or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

captions.mdcollections.mdexceptions.mdindex.mdstream-management.mdvideo-downloads.md

stream-management.mddocs/

0

# Stream Management and Filtering

1

2

Advanced stream selection and filtering capabilities for choosing specific video qualities, formats, and codecs from available YouTube video and audio streams.

3

4

## Capabilities

5

6

### Stream Class

7

8

Represents an individual downloadable video or audio stream with specific quality, format, and codec characteristics.

9

10

```python { .api }

11

class Stream:

12

def __init__(self, stream: Dict, monostate: Monostate):

13

"""

14

Initialize a Stream object.

15

16

Args:

17

stream (dict): Stream metadata dictionary

18

monostate (Monostate): Shared state object for callbacks

19

"""

20

```

21

22

### Basic Stream Properties

23

24

Access fundamental stream characteristics including URL, format, and technical specifications.

25

26

```python { .api }

27

@property

28

def url(self) -> str:

29

"""Get the direct download URL for the stream."""

30

31

@property

32

def itag(self) -> int:

33

"""Get the YouTube internal stream identifier."""

34

35

@property

36

def mime_type(self) -> str:

37

"""Get the MIME type (e.g., 'video/mp4', 'audio/webm')."""

38

39

@property

40

def type(self) -> str:

41

"""Get the media type (e.g., 'video', 'audio')."""

42

43

@property

44

def subtype(self) -> str:

45

"""Get the media subtype (e.g., 'mp4', 'webm')."""

46

47

@property

48

def codecs(self) -> List[str]:

49

"""Get the list of codecs used in the stream."""

50

51

@property

52

def video_codec(self) -> Optional[str]:

53

"""Get the video codec (e.g., 'avc1.640028')."""

54

55

@property

56

def audio_codec(self) -> Optional[str]:

57

"""Get the audio codec (e.g., 'mp4a.40.2')."""

58

```

59

60

### File Size Information

61

62

Access stream file size in various units.

63

64

```python { .api }

65

@property

66

def filesize(self) -> int:

67

"""Get the file size in bytes."""

68

69

@property

70

def filesize_kb(self) -> float:

71

"""Get the file size in kilobytes."""

72

73

@property

74

def filesize_mb(self) -> float:

75

"""Get the file size in megabytes."""

76

77

@property

78

def filesize_gb(self) -> float:

79

"""Get the file size in gigabytes."""

80

81

@property

82

def filesize_approx(self) -> int:

83

"""Get the approximate file size in bytes."""

84

```

85

86

### Stream Type Classification

87

88

Determine stream characteristics and content types.

89

90

```python { .api }

91

@property

92

def is_progressive(self) -> bool:

93

"""Check if stream contains both audio and video."""

94

95

@property

96

def is_adaptive(self) -> bool:

97

"""Check if stream is DASH (audio or video only)."""

98

99

@property

100

def includes_audio_track(self) -> bool:

101

"""Check if stream contains audio."""

102

103

@property

104

def includes_video_track(self) -> bool:

105

"""Check if stream contains video."""

106

107

@property

108

def is_dash(self) -> bool:

109

"""Check if stream uses DASH protocol."""

110

111

@property

112

def is_otf(self) -> bool:

113

"""Check if stream is On-The-Fly generated."""

114

```

115

116

### Video Stream Properties

117

118

Properties specific to video streams.

119

120

```python { .api }

121

@property

122

def resolution(self) -> str:

123

"""Get the video resolution (e.g., '720p', '1080p')."""

124

125

@property

126

def fps(self) -> int:

127

"""Get the frames per second for video streams."""

128

129

@property

130

def is_3d(self) -> bool:

131

"""Check if the video stream is 3D."""

132

133

@property

134

def is_hdr(self) -> bool:

135

"""Check if the video stream supports HDR."""

136

137

@property

138

def is_live(self) -> bool:

139

"""Check if the stream is from a live broadcast."""

140

```

141

142

### Audio Stream Properties

143

144

Properties specific to audio streams.

145

146

```python { .api }

147

@property

148

def abr(self) -> str:

149

"""Get the audio bitrate (e.g., '128kbps')."""

150

151

@property

152

def bitrate(self) -> Optional[int]:

153

"""Get the bitrate in bits per second."""

154

```

155

156

### File Operations

157

158

Download and file management operations.

159

160

```python { .api }

161

def download(

162

self,

163

output_path: Optional[str] = None,

164

filename: Optional[str] = None,

165

filename_prefix: Optional[str] = None,

166

skip_existing: bool = True,

167

timeout: Optional[int] = None,

168

max_retries: Optional[int] = 0

169

) -> str:

170

"""

171

Download the stream to a file.

172

173

Args:

174

output_path (str, optional): Directory to save the file

175

filename (str, optional): Custom filename (without extension)

176

filename_prefix (str, optional): Prefix to add to filename

177

skip_existing (bool): Skip download if file already exists

178

timeout (int, optional): Request timeout in seconds

179

max_retries (int, optional): Maximum number of retry attempts

180

181

Returns:

182

str: Path to the downloaded file

183

"""

184

185

def stream_to_buffer(self, buffer: BinaryIO) -> None:

186

"""

187

Stream content directly to a buffer.

188

189

Args:

190

buffer (BinaryIO): Buffer to write stream content to

191

"""

192

193

def get_file_path(

194

self,

195

filename: Optional[str] = None,

196

output_path: Optional[str] = None,

197

filename_prefix: Optional[str] = None

198

) -> str:

199

"""

200

Get the full file path for the download.

201

202

Args:

203

filename (str, optional): Custom filename

204

output_path (str, optional): Directory path

205

filename_prefix (str, optional): Filename prefix

206

207

Returns:

208

str: Complete file path

209

"""

210

211

@property

212

def default_filename(self) -> str:

213

"""Get the auto-generated filename for the stream."""

214

215

def exists_at_path(self, file_path: str) -> bool:

216

"""

217

Check if file exists at the specified path.

218

219

Args:

220

file_path (str): Path to check

221

222

Returns:

223

bool: True if file exists

224

"""

225

```

226

227

### Stream Metadata

228

229

Additional stream information and metadata.

230

231

```python { .api }

232

@property

233

def title(self) -> str:

234

"""Get the video title associated with this stream."""

235

236

@property

237

def expiration(self) -> datetime:

238

"""Get the stream URL expiration datetime."""

239

```

240

241

### StreamQuery Class

242

243

Query and filtering interface for stream collections with chainable methods for advanced stream selection.

244

245

```python { .api }

246

class StreamQuery:

247

def __init__(self, fmt_streams: List[Stream]):

248

"""

249

Initialize StreamQuery with a list of streams.

250

251

Args:

252

fmt_streams (List[Stream]): List of available streams

253

"""

254

```

255

256

### Stream Filtering

257

258

Filter streams by various criteria with chainable methods.

259

260

```python { .api }

261

def filter(

262

self,

263

fps=None,

264

res=None,

265

resolution=None,

266

mime_type=None,

267

type=None,

268

subtype=None,

269

file_extension=None,

270

abr=None,

271

bitrate=None,

272

video_codec=None,

273

audio_codec=None,

274

only_audio=None,

275

only_video=None,

276

progressive=None,

277

adaptive=None,

278

is_dash=None,

279

custom_filter_functions=None

280

) -> StreamQuery:

281

"""

282

Filter streams by multiple criteria.

283

284

Args:

285

fps (int, optional): Frames per second

286

res (str, optional): Resolution (e.g., '720p')

287

resolution (str, optional): Alias for res

288

mime_type (str, optional): MIME type filter

289

type (str, optional): Media type ('video', 'audio')

290

subtype (str, optional): Media subtype ('mp4', 'webm')

291

file_extension (str, optional): File extension filter

292

abr (str, optional): Audio bitrate

293

bitrate (int, optional): Bitrate filter

294

video_codec (str, optional): Video codec filter

295

audio_codec (str, optional): Audio codec filter

296

only_audio (bool, optional): Audio-only streams

297

only_video (bool, optional): Video-only streams

298

progressive (bool, optional): Progressive streams

299

adaptive (bool, optional): Adaptive (DASH) streams

300

is_dash (bool, optional): DASH protocol streams

301

custom_filter_functions (List[callable], optional): Custom filter functions

302

303

Returns:

304

StreamQuery: Filtered stream query object

305

"""

306

307

def otf(self, is_otf: bool = False) -> StreamQuery:

308

"""

309

Filter streams by On-The-Fly generation status.

310

311

Args:

312

is_otf (bool): Filter for OTF streams

313

314

Returns:

315

StreamQuery: Filtered stream query

316

"""

317

```

318

319

### Stream Ordering

320

321

Sort and order streams by attributes.

322

323

```python { .api }

324

def order_by(self, attribute_name: str) -> StreamQuery:

325

"""

326

Order streams by a specific attribute.

327

328

Args:

329

attribute_name (str): Stream attribute to order by

330

331

Returns:

332

StreamQuery: Ordered stream query

333

"""

334

335

def desc(self) -> StreamQuery:

336

"""

337

Order streams in descending order.

338

339

Returns:

340

StreamQuery: Stream query with descending order

341

"""

342

343

def asc(self) -> StreamQuery:

344

"""

345

Order streams in ascending order.

346

347

Returns:

348

StreamQuery: Stream query with ascending order

349

"""

350

```

351

352

### Stream Selection

353

354

Get specific streams from the filtered results.

355

356

```python { .api }

357

def get_by_itag(self, itag: int) -> Optional[Stream]:

358

"""

359

Get stream by YouTube itag identifier.

360

361

Args:

362

itag (int): YouTube itag identifier

363

364

Returns:

365

Stream or None: Stream with matching itag

366

"""

367

368

def get_by_resolution(self, resolution: str) -> Optional[Stream]:

369

"""

370

Get stream by resolution.

371

372

Args:

373

resolution (str): Target resolution (e.g., '720p')

374

375

Returns:

376

Stream or None: Stream with matching resolution

377

"""

378

379

def get_highest_resolution(self) -> Optional[Stream]:

380

"""

381

Get the stream with the highest resolution.

382

383

Returns:

384

Stream or None: Highest resolution stream

385

"""

386

387

def get_lowest_resolution(self) -> Optional[Stream]:

388

"""

389

Get the stream with the lowest resolution.

390

391

Returns:

392

Stream or None: Lowest resolution stream

393

"""

394

395

def get_audio_only(self, subtype: str = "mp4") -> Optional[Stream]:

396

"""

397

Get an audio-only stream.

398

399

Args:

400

subtype (str): Preferred audio format

401

402

Returns:

403

Stream or None: Audio-only stream

404

"""

405

406

def first(self) -> Optional[Stream]:

407

"""

408

Get the first stream in the filtered results.

409

410

Returns:

411

Stream or None: First stream

412

"""

413

414

def last(self) -> Optional[Stream]:

415

"""

416

Get the last stream in the filtered results.

417

418

Returns:

419

Stream or None: Last stream

420

"""

421

```

422

423

### Sequence Operations

424

425

Access streams using sequence operations.

426

427

```python { .api }

428

def __getitem__(self, i: Union[slice, int]) -> Union[Stream, List[Stream]]:

429

"""

430

Get stream(s) by index or slice.

431

432

Args:

433

i (int or slice): Index or slice object

434

435

Returns:

436

Stream or List[Stream]: Stream(s) at specified index/slice

437

"""

438

439

def __len__(self) -> int:

440

"""

441

Get the number of streams in the query.

442

443

Returns:

444

int: Number of streams

445

"""

446

447

### Deprecated Methods

448

449

Legacy methods maintained for backward compatibility.

450

451

```python { .api }

452

def count(self, value: Optional[str] = None) -> int:

453

"""

454

Get the count of items in the list.

455

456

**DEPRECATED**: Use len() directly on the StreamQuery object instead.

457

458

Args:

459

value (str, optional): Specific value to count

460

461

Returns:

462

int: Count of streams or specific value occurrences

463

"""

464

465

def all(self) -> List[Stream]:

466

"""

467

Get all the results represented by this query as a list.

468

469

**DEPRECATED**: StreamQuery can be treated as a list directly.

470

471

Returns:

472

List[Stream]: All streams in the query

473

"""

474

```

475

476

## Usage Examples

477

478

### Basic Stream Selection

479

480

```python

481

from pytube import YouTube

482

483

yt = YouTube('https://www.youtube.com/watch?v=9bZkp7q19f0')

484

485

# Get all available streams

486

streams = yt.streams

487

488

# Get highest resolution progressive stream

489

best_stream = streams.get_highest_resolution()

490

print(f"Best quality: {best_stream.resolution} - {best_stream.filesize_mb:.1f}MB")

491

492

# Get audio-only stream

493

audio_stream = streams.get_audio_only()

494

print(f"Audio: {audio_stream.abr} - {audio_stream.filesize_mb:.1f}MB")

495

```

496

497

### Advanced Filtering

498

499

```python

500

from pytube import YouTube

501

502

yt = YouTube('https://www.youtube.com/watch?v=9bZkp7q19f0')

503

504

# Filter by multiple criteria

505

hd_mp4_streams = yt.streams.filter(

506

resolution='720p',

507

file_extension='mp4',

508

progressive=True

509

)

510

511

# Custom filtering with lambda functions

512

large_files = yt.streams.filter(

513

custom_filter_functions=[lambda s: s.filesize > 100_000_000] # > 100MB

514

)

515

516

# Chain filters and ordering

517

best_audio = (yt.streams

518

.filter(only_audio=True, file_extension='mp4')

519

.order_by('abr')

520

.desc()

521

.first())

522

```

523

524

### Stream Information Analysis

525

526

```python

527

from pytube import YouTube

528

529

yt = YouTube('https://www.youtube.com/watch?v=9bZkp7q19f0')

530

531

# Analyze all available streams

532

for stream in yt.streams:

533

print(f"itag: {stream.itag}")

534

print(f"Type: {stream.type}")

535

print(f"Quality: {stream.resolution or stream.abr}")

536

print(f"Format: {stream.mime_type}")

537

print(f"Size: {stream.filesize_mb:.1f}MB")

538

print(f"Progressive: {stream.is_progressive}")

539

print("---")

540

```

541

542

### Custom Download Locations

543

544

```python

545

from pytube import YouTube

546

import os

547

548

yt = YouTube('https://www.youtube.com/watch?v=9bZkp7q19f0')

549

550

# Download to specific directory with custom filename

551

output_dir = "/path/to/downloads"

552

custom_filename = "my_video"

553

554

stream = yt.streams.get_highest_resolution()

555

file_path = stream.download(

556

output_path=output_dir,

557

filename=custom_filename

558

)

559

560

print(f"Downloaded to: {file_path}")

561

```

562

563

### Streaming to Buffer

564

565

```python

566

from pytube import YouTube

567

from io import BytesIO

568

569

yt = YouTube('https://www.youtube.com/watch?v=9bZkp7q19f0')

570

stream = yt.streams.get_audio_only()

571

572

# Stream directly to memory buffer

573

buffer = BytesIO()

574

stream.stream_to_buffer(buffer)

575

576

# Process buffer content

577

buffer.seek(0)

578

audio_data = buffer.read()

579

print(f"Audio data size: {len(audio_data)} bytes")

580

```

581

582

## Types

583

584

```python { .api }

585

from typing import List, Optional, Union, BinaryIO, Callable, Dict, Any

586

from datetime import datetime

587

588

# Custom filter function type

589

CustomFilterFunction = Callable[[Stream], bool]

590

591

# Stream filtering parameter types

592

FilterValue = Union[str, int, bool, None]

593

```