or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

audio.mdcodecs.mdcontainers.mdfilters.mdindex.mdstreams.mdvideo.md

containers.mddocs/

0

# Container Operations

1

2

Core functionality for opening, reading, and writing media files. PyAV containers provide access to media formats, streams, and metadata through FFmpeg's libavformat.

3

4

## Capabilities

5

6

### Opening Containers

7

8

Open media files for reading or writing with automatic format detection and comprehensive options.

9

10

```python { .api }

11

def open(file, mode='r', format=None, options=None, container_options=None,

12

stream_options=None, metadata_encoding='utf-8', metadata_errors='strict',

13

buffer_size=32768, timeout=None, io_open=None, hwaccel=None):

14

"""

15

Open a media container.

16

17

Parameters:

18

- file: str | file-like | bytes - File path, file object, or bytes

19

- mode: str - 'r' for input, 'w' for output

20

- format: str - Container format name (auto-detected if None)

21

- options: dict - General options

22

- container_options: dict - Container-specific options

23

- stream_options: list[dict] - Per-stream options

24

- metadata_encoding: str - Metadata encoding

25

- metadata_errors: str - Error handling for metadata

26

- buffer_size: int - I/O buffer size in bytes

27

- timeout: float - Operation timeout in seconds

28

- io_open: callable - Custom I/O opener

29

- hwaccel: str - Hardware acceleration device

30

31

Returns:

32

InputContainer | OutputContainer

33

"""

34

```

35

36

### Input Containers

37

38

Read and decode media from files, streams, or network sources.

39

40

```python { .api }

41

class InputContainer:

42

"""Container for reading media files."""

43

44

# Properties

45

streams: StreamContainer

46

metadata: dict[str, str]

47

format: ContainerFormat

48

duration: int | None # Duration in AV_TIME_BASE units

49

start_time: int # Start time in AV_TIME_BASE units

50

bit_rate: int # Overall bitrate

51

size: int # File size in bytes

52

53

def close(self) -> None:

54

"""Close the container and release resources."""

55

56

def demux(self, *streams, video=None, audio=None, subtitles=None, data=None) -> Iterator[Packet]:

57

"""

58

Demux packets from streams.

59

60

Parameters:

61

- *streams: Specific streams to demux

62

- video: int | VideoStream - Video stream index or object

63

- audio: int | AudioStream - Audio stream index or object

64

- subtitles: int | SubtitleStream - Subtitle stream index or object

65

- data: int | DataStream - Data stream index or object

66

67

Yields:

68

Packet objects from the specified streams

69

"""

70

71

def decode(self, *args, **kwargs) -> Iterator[AudioFrame | VideoFrame | SubtitleSet]:

72

"""

73

Decode frames from streams.

74

75

Parameters: Same as demux()

76

77

Yields:

78

Decoded frames based on stream type

79

"""

80

81

def seek(self, offset, *, backward=True, any_frame=False, stream=None) -> None:

82

"""

83

Seek to a specific position.

84

85

Parameters:

86

- offset: int - Target position in stream time_base units

87

- backward: bool - Allow seeking backward

88

- any_frame: bool - Seek to any frame (not just keyframes)

89

- stream: Stream - Reference stream for offset units

90

"""

91

92

def flush_buffers(self) -> None:

93

"""Flush internal decode buffers."""

94

```

95

96

### Output Containers

97

98

Write and encode media to files with format control and stream management.

99

100

```python { .api }

101

class OutputContainer:

102

"""Container for writing media files."""

103

104

# Properties

105

streams: StreamContainer

106

metadata: dict[str, str]

107

format: ContainerFormat

108

default_video_codec: str

109

default_audio_codec: str

110

default_subtitle_codec: str

111

supported_codecs: set[str]

112

113

def add_stream(self, codec=None, rate=None, **kwargs) -> AudioStream | VideoStream:

114

"""

115

Add a stream to the container.

116

117

Parameters:

118

- codec: str | Codec - Codec name or object

119

- rate: int | Fraction - Frame rate for video, sample rate for audio

120

- **kwargs: Additional codec parameters

121

122

Returns:

123

Stream object for the new stream

124

"""

125

126

def add_stream_from_template(self, stream, **kwargs) -> Stream:

127

"""

128

Add stream using another stream as template.

129

130

Parameters:

131

- stream: Stream - Template stream

132

- **kwargs: Override parameters

133

134

Returns:

135

New stream object

136

"""

137

138

def add_data_stream(self, codec=None) -> DataStream:

139

"""Add a data stream."""

140

141

def start_encoding(self) -> None:

142

"""Begin encoding process - must be called before muxing packets."""

143

144

def mux(self, packet) -> None:

145

"""

146

Multiplex a packet into the container.

147

148

Parameters:

149

- packet: Packet - Encoded packet to write

150

"""

151

152

def mux_one(self, packet) -> None:

153

"""Multiplex exactly one packet."""

154

155

def close(self) -> None:

156

"""Close container and finalize file."""

157

```

158

159

### Container Flags

160

161

```python { .api }

162

class Flags(Flag):

163

"""Container behavior flags."""

164

gen_pts = 1 # Generate missing PTS

165

ign_idx = 2 # Ignore index

166

non_block = 4 # Non-blocking mode

167

ign_dts = 8 # Ignore DTS

168

no_fillin = 16 # Do not fill in missing values

169

no_parse = 32 # Do not use packet parsing

170

no_buffer = 64 # Do not buffer

171

custom_io = 128 # Custom I/O

172

discard_corrupt = 256 # Discard corrupt packets

173

flush_packets = 512 # Flush output packets

174

bitexact = 1024 # Bitexact mode

175

sort_dts = 2048 # Sort DTS

176

fast_seek = 4096 # Fast seeking

177

shortest = 8192 # Stop at shortest stream

178

auto_bsf = 16384 # Automatic bitstream filtering

179

```

180

181

### Stream Container

182

183

```python { .api }

184

class StreamContainer:

185

"""Container managing streams in a media file."""

186

187

# Stream collections by type

188

video: tuple[VideoStream, ...]

189

audio: tuple[AudioStream, ...]

190

subtitles: tuple[SubtitleStream, ...]

191

attachments: tuple[AttachmentStream, ...]

192

data: tuple[DataStream, ...]

193

other: tuple[Stream, ...]

194

195

def __len__(self) -> int:

196

"""Total number of streams."""

197

198

def __iter__(self) -> Iterator[Stream]:

199

"""Iterate over all streams."""

200

201

def __getitem__(self, index: int) -> Stream:

202

"""Get stream by index."""

203

204

def get(self, *, video=None, audio=None, subtitles=None, data=None) -> list[Stream]:

205

"""

206

Get streams by type and criteria.

207

208

Parameters:

209

- video: int | tuple - Video stream selection

210

- audio: int | tuple - Audio stream selection

211

- subtitles: int | tuple - Subtitle stream selection

212

- data: int | tuple - Data stream selection

213

214

Returns:

215

List of matching streams

216

"""

217

218

def best(self, kind) -> Stream | None:

219

"""

220

Get the best stream of a given type.

221

222

Parameters:

223

- kind: str - Stream type ('video', 'audio', 'subtitle')

224

225

Returns:

226

Best stream of the specified type or None

227

"""

228

```

229

230

### Container Formats

231

232

```python { .api }

233

class ContainerFormat:

234

"""Media container format information."""

235

236

name: str # Format name

237

long_name: str # Descriptive name

238

extensions: set[str] # File extensions

239

is_input: bool # Can read this format

240

is_output: bool # Can write this format

241

flags: int # Format flags

242

no_file: bool # Format doesn't need files

243

```

244

245

## Usage Examples

246

247

### Reading Media Files

248

249

```python

250

import av

251

252

# Open container

253

container = av.open('video.mp4')

254

255

# Get basic information

256

print(f"Duration: {container.duration / av.time_base}")

257

print(f"Bitrate: {container.bit_rate}")

258

print(f"Video streams: {len(container.streams.video)}")

259

print(f"Audio streams: {len(container.streams.audio)}")

260

261

# Access metadata

262

for key, value in container.metadata.items():

263

print(f"{key}: {value}")

264

265

# Get best streams

266

video_stream = container.streams.video[0]

267

audio_stream = container.streams.audio[0]

268

269

# Decode frames

270

for frame in container.decode(video_stream):

271

print(f"Video frame: {frame.width}x{frame.height} at {frame.time}")

272

273

for frame in container.decode(audio_stream):

274

print(f"Audio frame: {frame.samples} samples at {frame.time}")

275

276

container.close()

277

```

278

279

### Writing Media Files

280

281

```python

282

import av

283

import numpy as np

284

285

# Create output container

286

output = av.open('output.mp4', 'w')

287

288

# Add video stream

289

video_stream = output.add_stream('h264', rate=30)

290

video_stream.width = 1280

291

video_stream.height = 720

292

video_stream.pix_fmt = 'yuv420p'

293

294

# Add audio stream

295

audio_stream = output.add_stream('aac', rate=44100)

296

audio_stream.channels = 2

297

audio_stream.layout = 'stereo'

298

299

# Start encoding

300

output.start_encoding()

301

302

# Generate and encode frames

303

for i in range(150): # 5 seconds

304

# Create video frame

305

frame = av.VideoFrame.from_ndarray(

306

np.random.randint(0, 255, (720, 1280, 3), dtype=np.uint8),

307

format='rgb24'

308

)

309

frame.pts = i

310

frame.time_base = video_stream.time_base

311

312

# Encode and mux

313

for packet in video_stream.encode(frame):

314

output.mux(packet)

315

316

# Flush encoders

317

for packet in video_stream.encode():

318

output.mux(packet)

319

for packet in audio_stream.encode():

320

output.mux(packet)

321

322

output.close()

323

```

324

325

### Network Streaming

326

327

```python

328

import av

329

330

# Open network stream

331

container = av.open('rtmp://example.com/stream', options={

332

'timeout': '5000000', # 5 second timeout

333

'user_agent': 'PyAV Client'

334

})

335

336

# Read packets

337

for packet in container.demux():

338

if packet.stream.type == 'video':

339

for frame in packet.decode():

340

print(f"Video frame: {frame.width}x{frame.height}")

341

elif packet.stream.type == 'audio':

342

for frame in packet.decode():

343

print(f"Audio frame: {frame.samples} samples")

344

345

container.close()

346

```