0
# Video Recording and Encoding
1
2
Video recording capabilities with support for multiple encoders, various output formats, and hardware acceleration. The encoding system provides both simple recording methods and advanced encoder management for complex applications.
3
4
## Capabilities
5
6
### Recording Control
7
8
High-level recording interface for common video capture scenarios.
9
10
```python { .api }
11
def start_recording(
12
self,
13
encoder: Encoder,
14
output: Output,
15
pts: str = None,
16
config: CameraConfiguration = None,
17
quality: Quality = None,
18
name: str = "main"
19
):
20
"""
21
Start video recording with specified encoder and output.
22
23
Parameters:
24
- encoder: Encoder instance (H264Encoder, MJPEGEncoder, etc.)
25
- output: Output instance (FileOutput, CircularOutput, etc.)
26
- pts: str, PTS file path for timestamp logging
27
- config: CameraConfiguration, configuration to apply before recording
28
- quality: Quality enum value for encoding quality
29
- name: str, stream name to encode
30
31
Raises:
32
- RuntimeError: If encoder fails to start or configuration invalid
33
"""
34
35
def stop_recording(self):
36
"""
37
Stop all active recording and encoding operations.
38
39
Stops all encoders and outputs, finalizes files, and releases resources.
40
"""
41
42
def start_and_record_video(
43
self,
44
output: str,
45
encoder: Encoder = None,
46
config: CameraConfiguration = None,
47
quality: Quality = None,
48
duration: float = None,
49
show_preview: bool = None,
50
audio: bool = False
51
):
52
"""
53
Convenience method to start camera and record video.
54
55
Parameters:
56
- output: str, output file path
57
- encoder: Encoder instance (default: H264Encoder)
58
- config: CameraConfiguration (default: video configuration)
59
- quality: Quality enum value
60
- duration: float, recording duration in seconds (None for indefinite)
61
- show_preview: bool, show preview during recording
62
- audio: bool, enable audio recording
63
"""
64
```
65
66
### Encoder Management
67
68
Low-level encoder control for advanced recording scenarios.
69
70
```python { .api }
71
def start_encoder(
72
self,
73
encoder: Encoder,
74
output: Output,
75
pts: str = None,
76
quality: Quality = None,
77
name: str = "main"
78
):
79
"""
80
Start individual encoder without stopping existing encoders.
81
82
Parameters:
83
- encoder: Encoder instance
84
- output: Output instance
85
- pts: str, PTS file path
86
- quality: Quality enum value
87
- name: str, stream name to encode
88
89
Returns:
90
Encoder instance that was started
91
"""
92
93
def stop_encoder(self, encoders: list[Encoder] = None):
94
"""
95
Stop specific encoders.
96
97
Parameters:
98
- encoders: list of Encoder instances to stop (None = stop all)
99
"""
100
```
101
102
### Encoder Classes
103
104
Base encoder class and available encoder implementations.
105
106
```python { .api }
107
class Encoder:
108
"""Base class for video encoders."""
109
110
# Properties
111
running: bool # Whether encoder is active
112
width: int # Frame width
113
height: int # Frame height
114
size: tuple[int, int] # Frame dimensions
115
stride: int # Row stride
116
format: str # Input pixel format
117
output: Output # Output destination(s)
118
name: str # Encoder name
119
120
# Audio properties
121
audio: bool # Enable audio encoding
122
audio_input: dict # Audio input parameters
123
audio_output: dict # Audio output parameters
124
audio_sync: int # Audio sync offset
125
126
def encode(self, stream: str, request: CompletedRequest):
127
"""
128
Encode frame from request (abstract method).
129
130
Parameters:
131
- stream: str, stream name
132
- request: CompletedRequest with frame data
133
"""
134
135
def start(self, quality: Quality = None):
136
"""
137
Start encoding process.
138
139
Parameters:
140
- quality: Quality enum value
141
"""
142
143
def stop(self):
144
"""Stop encoding and finalize output."""
145
146
def outputframe(
147
self,
148
frame: bytes,
149
keyframe: bool = False,
150
timestamp: int = None,
151
packet: bytes = None,
152
audio: bytes = None
153
):
154
"""
155
Output encoded frame to destination.
156
157
Parameters:
158
- frame: bytes, encoded frame data
159
- keyframe: bool, whether frame is a keyframe
160
- timestamp: int, frame timestamp
161
- packet: bytes, packet data
162
- audio: bytes, audio data
163
"""
164
165
class Quality(Enum):
166
"""Encoding quality levels."""
167
VERY_LOW = 1
168
LOW = 2
169
MEDIUM = 3
170
HIGH = 4
171
VERY_HIGH = 5
172
```
173
174
### Concrete Encoder Implementations
175
176
Available encoder types for different formats and use cases.
177
178
```python { .api }
179
class H264Encoder(Encoder):
180
"""
181
H.264 video encoder with hardware acceleration when available.
182
183
Parameters:
184
- bitrate: int, target bitrate in bits/second
185
- framerate: float, target framerate
186
- repeat: bool, repeat sequence parameter sets
187
- iperiod: int, I-frame period (keyframe interval)
188
- profile: str, H.264 profile ("baseline", "main", "high")
189
- level: str, H.264 level ("3.1", "4.0", "4.1", etc.)
190
- intra_refresh: str, intra refresh mode
191
"""
192
193
class MJPEGEncoder(Encoder):
194
"""
195
MJPEG video encoder for high-quality sequential JPEG frames.
196
197
Parameters:
198
- q: int, JPEG quality (1-100)
199
"""
200
201
class JpegEncoder(Encoder):
202
"""
203
JPEG still image encoder for single frame capture.
204
205
Parameters:
206
- q: int, JPEG quality (1-100)
207
"""
208
209
class LibavH264Encoder(Encoder):
210
"""
211
H.264 encoder using libav/FFmpeg backend.
212
213
Parameters:
214
- preset: str, encoding preset ("ultrafast", "fast", "medium", etc.)
215
- crf: int, constant rate factor (0-51, lower = better quality)
216
- bitrate: int, target bitrate
217
"""
218
219
class LibavMjpegEncoder(Encoder):
220
"""MJPEG encoder using libav/FFmpeg backend."""
221
222
class MultiEncoder(Encoder):
223
"""
224
Composite encoder that manages multiple encoders simultaneously.
225
226
Allows encoding the same stream to multiple formats/outputs.
227
"""
228
```
229
230
### Output Classes
231
232
Output destinations for encoded video data.
233
234
```python { .api }
235
class Output:
236
"""Base class for encoder outputs."""
237
238
recording: bool # Whether currently recording
239
pts_output: str # PTS timestamp file path
240
needs_pacing: bool # Whether output needs frame pacing
241
242
def start(self):
243
"""Start recording to output."""
244
245
def stop(self):
246
"""Stop recording and finalize output."""
247
248
def output_frame(
249
self,
250
frame: bytes,
251
keyframe: bool = False,
252
timestamp: int = None,
253
packet: bytes = None,
254
audio: bytes = None
255
):
256
"""Output encoded frame (abstract method)."""
257
258
def output_timestamp(self, timestamp: int):
259
"""Output timestamp to PTS file."""
260
261
class FileOutput(Output):
262
"""
263
Output to file with automatic format detection.
264
265
Parameters:
266
- filename: str, output file path
267
- pts: str, PTS file path for timestamps
268
"""
269
270
class FfmpegOutput(Output):
271
"""
272
Output via FFmpeg process for complex formats and streaming.
273
274
Parameters:
275
- cmd: list, FFmpeg command line arguments
276
- audio: bool, enable audio passthrough
277
"""
278
279
class CircularOutput(Output):
280
"""
281
Circular buffer output for continuous recording with size limit.
282
283
Parameters:
284
- filename: str, output file path
285
- buffersize: int, buffer size in seconds
286
- outputtofile: bool, write to file when buffer full
287
"""
288
289
class SplittableOutput(Output):
290
"""
291
Output that can split recording into multiple files.
292
293
Parameters:
294
- filename_template: str, filename template with placeholders
295
- split_size: int, split size in MB or seconds
296
"""
297
```
298
299
## Usage Examples
300
301
### Basic Video Recording
302
303
```python
304
from picamera2 import Picamera2
305
from picamera2.encoders import H264Encoder
306
from picamera2.outputs import FileOutput
307
import time
308
309
picam2 = Picamera2()
310
video_config = picam2.create_video_configuration()
311
picam2.configure(video_config)
312
picam2.start()
313
314
# Create encoder and output
315
encoder = H264Encoder(bitrate=10000000) # 10 Mbps
316
output = FileOutput("video.h264")
317
318
# Start recording
319
picam2.start_recording(encoder, output)
320
321
# Record for 10 seconds
322
time.sleep(10)
323
324
# Stop recording
325
picam2.stop_recording()
326
picam2.close()
327
```
328
329
### High-Quality Recording
330
331
```python
332
from picamera2 import Picamera2
333
from picamera2.encoders import H264Encoder, Quality
334
from picamera2.outputs import FileOutput
335
336
picam2 = Picamera2()
337
338
# High-resolution video configuration
339
video_config = picam2.create_video_configuration(
340
main={"size": (1920, 1080), "format": "YUV420"}
341
)
342
picam2.configure(video_config)
343
picam2.start()
344
345
# High-quality encoder
346
encoder = H264Encoder(
347
bitrate=20000000, # 20 Mbps
348
framerate=30,
349
profile="high",
350
level="4.1"
351
)
352
353
output = FileOutput("high_quality.h264")
354
355
# Record with high quality setting
356
picam2.start_recording(encoder, output, quality=Quality.VERY_HIGH)
357
358
time.sleep(30) # 30 second recording
359
picam2.stop_recording()
360
picam2.close()
361
```
362
363
### Multiple Encoder Recording
364
365
```python
366
from picamera2 import Picamera2
367
from picamera2.encoders import H264Encoder, MJPEGEncoder
368
from picamera2.outputs import FileOutput
369
370
picam2 = Picamera2()
371
video_config = picam2.create_video_configuration()
372
picam2.configure(video_config)
373
picam2.start()
374
375
# Multiple encoders for same stream
376
h264_encoder = H264Encoder(bitrate=10000000)
377
mjpeg_encoder = MJPEGEncoder(q=85)
378
379
h264_output = FileOutput("video.h264")
380
mjpeg_output = FileOutput("video.mjpeg")
381
382
# Start both encoders
383
picam2.start_encoder(h264_encoder, h264_output)
384
picam2.start_encoder(mjpeg_encoder, mjpeg_output)
385
386
time.sleep(15)
387
388
# Stop all encoders
389
picam2.stop_recording()
390
picam2.close()
391
```
392
393
### Circular Buffer Recording
394
395
```python
396
from picamera2 import Picamera2
397
from picamera2.encoders import H264Encoder
398
from picamera2.outputs import CircularOutput
399
400
picam2 = Picamera2()
401
video_config = picam2.create_video_configuration()
402
picam2.configure(video_config)
403
picam2.start()
404
405
encoder = H264Encoder()
406
# Keep last 30 seconds in buffer
407
circular_output = CircularOutput("buffer.h264", buffersize=30)
408
409
picam2.start_recording(encoder, circular_output)
410
411
# Record continuously - only last 30s kept in memory
412
# On motion detection or trigger, save buffer to file
413
input("Press Enter to save buffer and stop...")
414
415
# Save buffer content
416
circular_output.outputtofile = True
417
picam2.stop_recording()
418
picam2.close()
419
```
420
421
### Streaming with FFmpeg
422
423
```python
424
from picamera2 import Picamera2
425
from picamera2.encoders import H264Encoder
426
from picamera2.outputs import FfmpegOutput
427
428
picam2 = Picamera2()
429
video_config = picam2.create_video_configuration()
430
picam2.configure(video_config)
431
picam2.start()
432
433
encoder = H264Encoder()
434
435
# Stream to RTMP server
436
ffmpeg_output = FfmpegOutput([
437
"-f", "h264",
438
"-i", "-",
439
"-c:v", "copy",
440
"-f", "flv",
441
"rtmp://localhost/live/stream"
442
])
443
444
picam2.start_recording(encoder, ffmpeg_output)
445
446
# Stream indefinitely
447
try:
448
while True:
449
time.sleep(1)
450
except KeyboardInterrupt:
451
picam2.stop_recording()
452
453
picam2.close()
454
```
455
456
### Convenience Recording
457
458
```python
459
from picamera2 import Picamera2
460
from picamera2.encoders import H264Encoder, Quality
461
462
picam2 = Picamera2()
463
464
# All-in-one recording method
465
picam2.start_and_record_video(
466
"recording.h264",
467
duration=60, # 60 seconds
468
quality=Quality.HIGH,
469
show_preview=True
470
)
471
472
# Camera automatically starts, records, and stops
473
print("Recording complete")
474
```
475
476
### Audio Recording
477
478
```python
479
from picamera2 import Picamera2
480
from picamera2.encoders import H264Encoder
481
from picamera2.outputs import FfmpegOutput
482
483
picam2 = Picamera2()
484
video_config = picam2.create_video_configuration()
485
picam2.configure(video_config)
486
picam2.start()
487
488
# Encoder with audio support
489
encoder = H264Encoder(bitrate=10000000)
490
encoder.audio = True
491
492
# Output with audio muxing
493
output = FfmpegOutput([
494
"-f", "h264", "-i", "-",
495
"-f", "alsa", "-i", "hw:1", # Audio input
496
"-c:v", "copy",
497
"-c:a", "aac",
498
"video_with_audio.mp4"
499
])
500
501
picam2.start_recording(encoder, output)
502
time.sleep(30)
503
picam2.stop_recording()
504
picam2.close()
505
```
506
507
### Quality Control
508
509
```python
510
from picamera2 import Picamera2
511
from picamera2.encoders import H264Encoder, Quality
512
from picamera2.outputs import FileOutput
513
514
picam2 = Picamera2()
515
video_config = picam2.create_video_configuration()
516
picam2.configure(video_config)
517
picam2.start()
518
519
# Test different quality levels
520
qualities = [Quality.VERY_LOW, Quality.LOW, Quality.MEDIUM,
521
Quality.HIGH, Quality.VERY_HIGH]
522
523
for i, quality in enumerate(qualities):
524
encoder = H264Encoder()
525
output = FileOutput(f"test_quality_{i}.h264")
526
527
picam2.start_recording(encoder, output, quality=quality)
528
time.sleep(5) # 5 second clips
529
picam2.stop_recording()
530
531
picam2.close()
532
```