yt-dlp 2.4.0

🎬️ A Rust library (with auto dependencies installation) for Youtube downloading
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
<h2 align="center">🎬️ A Rust library (with auto dependencies installation) for video downloading</h2>

<div align="center">This library is a Rust asynchronous wrapper around the yt-dlp command line tool, a feature-rich audio/video downloader supporting <strong>YouTube, Vimeo, TikTok, Instagram, Twitter, and more.</strong></div>
<div align="center">
  The crate is designed to download audio and video from various websites.
  You don't need to care about dependencies, yt-dlp and ffmpeg will be downloaded automatically.
</div>

<br>
<div align="center">⚠️ The project is still in development, so if you encounter any bugs or have any feature requests, please open an issue or a discussion.</div>
<br>

<div align="center">
  <a href="https://github.com/boul2gom/yt-dlp/issues/new/choose">Report a Bug</a>
  Β·
  <a href="https://github.com/boul2gom/yt-dlp/discussions/new?category=ideas">Request a Feature</a>
  Β·
  <a href="https://github.com/boul2gom/yt-dlp/discussions/new?category=q-a">Ask a Question</a>
</div>

---

<p align="center">
  <a href="https://github.com/boul2gom/yt-dlp/actions/workflows/ci-dev.yml">
    <img src="https://img.shields.io/github/actions/workflow/status/boul2gom/yt-dlp/ci-dev.yml?label=Develop%20CI&logo=Github" alt="Develop CI"/>
  </a>  
  <a href="https://crates.io/crates/yt-dlp">
    <img src="https://img.shields.io/github/v/release/boul2gom/yt-dlp?label=Release&logo=Rust" alt="Release"/>
  </a>
  <a href="https://crates.io/crates/yt-dlp">
    <img src="https://img.shields.io/crates/d/yt-dlp?label=Downloads&logo=Rust" alt="Downloads"/>
  </a>
  <a href="https://deepwiki.com/boul2gom/yt-dlp">
    <img src="https://deepwiki.com/badge.svg" alt="Ask DeepWiki">
  </a>
</p>
<p align="center">
  <a href="https://github.com/boul2gom/yt-dlp/discussions">
    <img src="https://img.shields.io/github/discussions/boul2gom/yt-dlp?label=Discussions&logo=Github" alt="Discussions">
  </a>
  <a href="https://github.com/boul2gom/yt-dlp/issues">
    <img src="https://img.shields.io/github/issues-raw/boul2gom/yt-dlp?label=Issues&logo=Github" alt="Issues">
  </a>
  <a href="https://github.com/boul2gom/yt-dlp/pulls">
    <img src="https://img.shields.io/github/issues-pr-raw/boul2gom/yt-dlp?label=Pull%20requests&logo=Github" alt="Pull%20requests">
  </a>
</p>
<p align="center">
  <a href="https://github.com/boul2gom/yt-dlp/blob/develop/LICENSE.md">
    <img src="https://img.shields.io/github/license/boul2gom/yt-dlp?label=License&logo=Github" alt="License">
  </a>
  <a href="https://github.com/boul2gom/yt-dlp/stargazers">
    <img src="https://img.shields.io/github/stars/boul2gom/yt-dlp?label=Stars&logo=Github" alt="Stars">
  </a>
  <a href="https://github.com/boul2gom/yt-dlp/fork">
    <img src="https://img.shields.io/github/forks/boul2gom/yt-dlp?label=Forks&logo=Github" alt="Forks">
  </a>
</p>  

<p align="center">
  <img src="https://repobeats.axiom.co/api/embed/81fed25250909bb618c0180c8092c143feae0616.svg" alt="Statistics" title="Repobeats analytics image" />
</p>

---

## πŸ’­οΈ Why use an external Python app?

Originally, to download videos from YouTube, I used the [```rustube```](https://crates.io/crates/rustube) crate, written in pure Rust and without any external dependencies.
However, I quickly realized that due to frequent breaking changes on the YouTube website, the crate was outdated and no longer functional.

After a few tests and research, I concluded that the python app [```yt-dlp```](https://github.com/yt-dlp/yt-dlp/) was the best compromise, thanks to its regular updates and massive community.
Its standalone binaries and its ability to output the fetched data in JSON format make it a perfect candidate for a Rust wrapper.

Using an external program is not ideal, but it is the most reliable and maintained solution for now.

## πŸ“₯ How to get it

Add the following to your `Cargo.toml` file:
```toml
[dependencies]
yt-dlp = "2.4.0"
```

A new release is automatically published every two weeks, to keep up to date with dependencies and features.
Make sure to check the [releases](https://github.com/boul2gom/yt-dlp/releases) page to see the latest version of the crate.

## πŸ”Œ Optional features

This library puts a lot of functionality behind optional features in order to optimize
compile time for the most common use cases. The following features are
available.

- πŸͺ **`hooks`** - Enables Rust hooks and callbacks for download events. Allows registering async functions that will be called when events occur.
- πŸ“‘ **`webhooks`** - Enables HTTP webhooks delivery for download events. Allows sending events to external HTTP endpoints with retry logic.
- πŸ“Š **`statistics`** - Enables real-time statistics and analytics on downloads and fetches. Exposes aggregate counters, averages, success rates, and a bounded history window.
- ⚑ **`cache-memory`** (enabled by default) β€” In-memory Moka cache (pulls in `moka`). Fast TTL-based eviction; no persistence.
- πŸ—ƒοΈ **`cache-json`** β€” JSON file-system backend. One `.json` file per entry.
- πŸ—„οΈ **`cache-redb`** β€” Embedded [redb]https://github.com/cberner/redb backend. Single-file, pure-Rust, ACID-compliant.
- 🌐 **`cache-redis`** β€” Distributed [Redis]https://redis.io/ backend. Native TTL via `SETEX`.
- πŸ”΄ **`live-recording`** - Enables live stream recording via HLS segment fetching (reqwest) or FFmpeg fallback. Pulls in `m3u8-rs` for HLS manifest parsing.
- πŸ”’ **`rustls`** - Enables the `rustls-tls` feature in the [```reqwest```]https://crates.io/crates/reqwest crate.
  This enables building the application without openssl or other system sourced SSL libraries.
- 🌍 **`hickory-dns`** - Enables async DNS resolution via [Hickory DNS]https://github.com/hickory-dns/hickory-dns (passes `reqwest/hickory-dns`). Replaces the default blocking system resolver with a fully async, pure-Rust resolver.

### πŸ—„οΈ Cache backends

The library includes a tiered metadata cache that avoids redundant yt-dlp subprocess calls for
video info, downloaded files, and playlists. The architecture uses an optional L1 in-memory layer
(Moka) and an optional L2 persistent layer, selected exclusively via Cargo features:

| Feature | Backend | Persistence | Notes |
|---|---|---|---|
| `cache-memory` *(default)* | In-memory Moka | ❌ No | TTL-based eviction, async-ready |
| `cache-json` | JSON files on disk | βœ… Yes | One `.json` file per entry in the cache directory |
| `cache-redb` | Embedded redb | βœ… Yes | Single-file, pure-Rust, ACID transactions |
| `cache-redis` | Redis | βœ… Yes | Distributed, native TTL via `SETEX` |

At most **one persistent backend** may be enabled at a time. `build.rs` enforces this with a
`compile_error!` if multiple persistent features (`cache-json`, `cache-redb`, `cache-redis`)
are active simultaneously. The `cache-memory` feature (Moka L1) can be combined with any persistent
backend for a tiered L1 + L2 setup.

**Default (in-memory Moka)** β€” no persistence, TTL-based eviction, useful for short-lived processes:
```toml
[dependencies]
yt-dlp = { version = "2.4.0", features = ["cache-memory"] }
```

**JSON** β€” persistent, file-system backed, no extra dependencies:
```toml
[dependencies]
yt-dlp = { version = "2.4.0", features = ["cache-json"] }
```

**Redb** β€” embedded, single-file, ACID-compliant, great for desktop/server apps:
```toml
[dependencies]
yt-dlp = { version = "2.4.0", features = ["cache-redb"] }
```

**Redis** β€” distributed, ideal for multi-node or cloud deployments:
```toml
[dependencies]
yt-dlp = { version = "2.4.0", features = ["cache-redis"] }
```

**Tiered (Moka L1 + persistent L2)** β€” best of both worlds:
```toml
[dependencies]
yt-dlp = { version = "2.4.0", features = ["cache-memory", "cache-redb"] }
```

#### CDN URL expiry and cache invalidation

When a `Video` is cached, its stream format URLs are valid for approximately **6 hours** (YouTube CDN lifetime). The library tracks this automatically via the `available_at` field on each `Format`.

On every `fetch_video_infos` call, the cache checks whether the format URLs are still fresh. If they have expired, the cached entry is **silently invalidated** and the video is re-fetched β€” so you never end up downloading with stale CDN URLs. The configured TTL (default 24 h) acts as an upper bound; the effective TTL is `min(configured_ttl, cdn_url_lifetime)`.

This behavior is transparent and requires no changes to your code. You can inspect the expiry yourself:
```rust,ignore
if !video.are_format_urls_fresh() {
    // URLs are stale β€” fetch_video_infos will re-fetch automatically
}
// Or get the earliest available_at timestamp across all downloadable formats:
if let Some(ts) = video.formats_available_at() {
    println!("Format URLs valid until approx. {} (unix)", ts + yt_dlp::model::FORMAT_URL_LIFETIME);
}
```

### πŸ” Observability & Tracing

This crate always includes the <img align="center" width="20" alt="Tracing" src="https://raw.githubusercontent.com/tokio-rs/tracing/refs/heads/master/assets/logo.svg" /> [`tracing`](https://crates.io/crates/tracing) crate. The library emits `debug` and `trace` span events throughout its internal operations (downloads, cache lookups, subprocess execution, etc.).

⚠️ **Important:** `tracing` macros are **pure no-ops** without a configured subscriber. If you don't add one, there is zero runtime overhead.

To capture logs, add a subscriber in your application:
```toml
[dependencies]
tracing-subscriber = "0.3"
```
```rust,ignore
use tracing::Level;
use tracing_subscriber::FmtSubscriber;

let subscriber = FmtSubscriber::builder()
        // all spans/events with a level higher than TRACE (e.g, debug, info, warn, etc.)
        // will be written to stdout.
        .with_max_level(Level::TRACE)
        // completes the builder.
        .finish();
tracing::subscriber::set_global_default(subscriber)
        .expect("setting default subscriber failed");
```

Refer to the [`tracing-subscriber` documentation](https://docs.rs/tracing-subscriber) for more advanced configuration (JSON output, log levels, targets, etc.).

---

## πŸ“– Documentation

The documentation is available on [docs.rs](https://docs.rs/yt-dlp).

## πŸ—οΈ Multi-Extractor Architecture

This library now supports downloading from **1,800+ websites** through a flexible extractor system:

- **`Downloader`** - Universal client supporting all sites via the extractors
- **`extractor::Youtube`** - Highly optimized YouTube extractor with platform-specific features:
  - Player client selection (Android, iOS, Web, TvEmbedded) for bypassing restrictions
  - Format presets (Best, Premium, High, Medium, Low, AudioOnly, ModernCodecs)
  - YouTube-specific methods: `search()`, `fetch_channel()`, `fetch_user()`, `fetch_playlist_paginated()`
- **`extractor::Generic`** - Universal extractor for all other sites with authentication support

### 🧩 Usage Patterns

- 🎬️ For YouTube with optimizations:
```rust,no_run
use yt_dlp::Downloader;
use yt_dlp::client::deps::Libraries;
use std::path::PathBuf;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries = Libraries::new(
        PathBuf::from("libs/yt-dlp"),
        PathBuf::from("libs/ffmpeg")
    );
    let downloader = Downloader::builder(libraries, "output")
        .build()
        .await?;

    // Access YouTube-specific features
    let youtube = downloader.youtube_extractor();
    let results = youtube.search("rust programming", 10).await?;
    let channel = youtube.fetch_channel("UCaYhcUwRBNscFNUKTjgPFiA").await?;

    Ok(())
}
```

- 🌐 For any website (YouTube, Vimeo, TikTok, etc.):
```rust,no_run
use yt_dlp::Downloader;
use yt_dlp::client::deps::Libraries;
use std::path::PathBuf;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries = Libraries::new(
        PathBuf::from("libs/yt-dlp"), 
        PathBuf::from("libs/ffmpeg")
    );
    let downloader = Downloader::builder(libraries, "output")
        .build()
        .await?;

    // Works with any supported site
    let video = downloader.fetch_video_infos("https://vimeo.com/123456789").await?;
    let video_path = downloader.download_video(
        &video,
        "output.mp4"
    ).await?;
    Ok(())
}
```

## πŸ“š Examples

- πŸ“¦ Installing the [```yt-dlp```]https://github.com/yt-dlp/yt-dlp/ and [```ffmpeg```]https://ffmpeg.org/ binaries:
```rust,no_run
use yt_dlp::Downloader;
use std::path::PathBuf;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let executables_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    // Create fetcher and install binaries
    let downloader = Downloader::with_new_binaries(
        executables_dir,
        output_dir
    ).await?.build().await?;
    
    Ok(())
}
```

- πŸ“¦ Installing the [```yt-dlp```]https://github.com/yt-dlp/yt-dlp/ binary only:
```rust,no_run
use yt_dlp::client::deps::LibraryInstaller;
use std::path::PathBuf;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let destination = PathBuf::from("libs");
    let installer = LibraryInstaller::new(destination);

    let youtube = installer.install_youtube(None).await.unwrap();
    Ok(())
}
```

- πŸ“¦ Installing the [```ffmpeg```]https://ffmpeg.org/ binary only:
```rust,no_run
use yt_dlp::client::deps::LibraryInstaller;
use std::path::PathBuf;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let destination = PathBuf::from("libs");
    let installer = LibraryInstaller::new(destination);
    
    let ffmpeg = installer.install_ffmpeg(None).await.unwrap();
    Ok(())
}
```

- πŸ”„ Updating the [```yt-dlp```]https://github.com/yt-dlp/yt-dlp/ binary:
```rust,no_run
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");
    
    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");
    
    let libraries = Libraries::new(youtube, ffmpeg);
    let downloader = Downloader::builder(libraries, output_dir)
        .build()
        .await?;

    downloader.update_downloader().await?;
    Ok(())
}
```

- πŸ“₯ Fetching a video (with its audio) and downloading it:
```rust,no_run
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");
    
    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");
    
    let libraries = Libraries::new(youtube, ffmpeg);
    let downloader = Downloader::builder(libraries, output_dir)
        .build()
        .await?;

    let url = String::from("https://www.youtube.com/watch?v=gXtp6C-3JKo");
    let video = downloader.fetch_video_infos(url).await?;
    let video_path = downloader.download_video(&video, "my-video.mp4").await?;
    Ok(())
}
```

- πŸ“ Downloading a video to a specific path (ignoring `output_dir`):
```rust,no_run
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");
    
    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");
    
    let libraries = Libraries::new(youtube, ffmpeg);
    let downloader = Downloader::builder(libraries, output_dir)
        .build()
        .await?;

    let url = String::from("https://www.youtube.com/watch?v=gXtp6C-3JKo");
    let video = downloader.fetch_video_infos(url).await?;
    
    // Download to an absolute path β€” the file is written directly to the given path,
    // bypassing the configured output_dir.
    let path = PathBuf::from("/Users/me/Videos/my-video.mp4");
    let video_path = downloader.download_video_to_path(&video, path).await?;
    Ok(())
}
```

- ✨ Using the fluent API with custom quality preferences:
```rust,no_run
use yt_dlp::Downloader;
use yt_dlp::model::selector::{VideoQuality, AudioQuality, VideoCodecPreference};
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");

    let libraries = Libraries::new(youtube, ffmpeg);
    let downloader = Downloader::builder(libraries, output_dir)
        .build()
        .await?;

    let url = String::from("https://www.youtube.com/watch?v=gXtp6C-3JKo");
    let video = downloader.fetch_video_infos(url).await?;

    // Use the fluent download builder API
    let video_path = downloader.download(&video, "my-video.mp4")
        .video_quality(VideoQuality::CustomHeight(1080))
        .video_codec(VideoCodecPreference::AVC1)
        .audio_quality(AudioQuality::Best)
        .execute()
        .await?;

    Ok(())
}
```

- 🎬 Fetching a video (without its audio) and downloading it:
```rust,no_run
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");

    let libraries = Libraries::new(youtube, ffmpeg);
    let downloader = Downloader::builder(libraries, output_dir)
        .build()
        .await?;

    let url = String::from("https://www.youtube.com/watch?v=gXtp6C-3JKo");
    let video = downloader.fetch_video_infos(url).await?;
    downloader.download_video_stream(&video, "video.mp4").await?;
    Ok(())
}
```

- 🎡 Fetching an audio and downloading it:
```rust,no_run
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");

    let libraries = Libraries::new(youtube, ffmpeg);
    let downloader = Downloader::builder(libraries, output_dir)
        .build()
        .await?;

    let url = String::from("https://www.youtube.com/watch?v=gXtp6C-3JKo");
    let video = downloader.fetch_video_infos(url).await?;
    downloader.download_audio_stream(&video, "audio.mp3").await?;
    Ok(())
}
```

- πŸ“œ Fetching a specific format and downloading it:
```rust,no_run
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;
use yt_dlp::VideoSelection;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");
    
    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");
    
    let libraries = Libraries::new(youtube, ffmpeg);
    let downloader = Downloader::builder(libraries, output_dir)
        .build()
        .await?;

    let url = String::from("https://www.youtube.com/watch?v=gXtp6C-3JKo");
    let video = downloader.fetch_video_infos(url).await?;
    println!("Video title: {}", video.title);

    let video_format = video.best_video_format().unwrap();
    let format_path = downloader.download_format(&video_format, "my-video-stream.mp4").await?;
    
    let audio_format = video.worst_audio_format().unwrap();
    let audio_path = downloader.download_format(&audio_format, "my-audio-stream.mp3").await?;
    
    Ok(())
}
```

- βš™οΈ Combining an audio and a video file into a single file:
```rust,no_run
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;
use yt_dlp::VideoSelection;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");
    
    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");
    
    let libraries = Libraries::new(youtube, ffmpeg);
    let downloader = Downloader::builder(libraries, output_dir)
        .build()
        .await?;

    let url = String::from("https://www.youtube.com/watch?v=gXtp6C-3JKo");
    let video = downloader.fetch_video_infos(url).await?;

    let audio_format = video.best_audio_format().unwrap();
    let audio_path = downloader.download_format(&audio_format, "audio-stream.mp3").await?;

    let video_format = video.worst_video_format().unwrap();
    let video_path = downloader.download_format(&video_format, "video-stream.mp4").await?;

    let output_path = downloader.combine_audio_and_video("audio-stream.mp3", "video-stream.mp4", "my-output.mp4").await?;
    Ok(())
}
```

- πŸ“Έ Fetching a thumbnail and downloading it:
```rust,no_run
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;
use yt_dlp::model::selector::ThumbnailQuality;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");
    
    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");
    
    let libraries = Libraries::new(youtube, ffmpeg);
    let downloader = Downloader::builder(libraries, output_dir)
        .build()
        .await?;

    let url = String::from("https://www.youtube.com/watch?v=gXtp6C-3JKo");
    let video = downloader.fetch_video_infos(url).await?;
    let thumbnail_path = downloader.download_thumbnail(&video, ThumbnailQuality::Best, "thumbnail.jpg").await?;
    Ok(())
}
```

- πŸ–ΌοΈ Selecting a thumbnail by minimum resolution and downloading it:
```rust,no_run
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries = Libraries::new(
        PathBuf::from("libs/yt-dlp"),
        PathBuf::from("libs/ffmpeg"),
    );
    let downloader = Downloader::builder(libraries, "output").build().await?;

    let url = "https://www.youtube.com/watch?v=gXtp6C-3JKo";
    let video = downloader.fetch_video_infos(url).await?;

    // Best thumbnail by area (width Γ— height)
    if let Some(thumb) = video.best_thumbnail() {
        println!("Best thumbnail: {} β€” {:?}", thumb.url, thumb.resolution);
    }

    // Smallest thumbnail that is at least 1280Γ—720
    if let Some(thumb) = video.thumbnail_for_size(1280, 720) {
        println!("HD thumbnail: {}", thumb.url);
    }

    Ok(())
}
```

- πŸ“ Downloading subtitles or automatic captions:
```rust,no_run
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries = Libraries::new(
        PathBuf::from("libs/yt-dlp"),
        PathBuf::from("libs/ffmpeg"),
    );
    let downloader = Downloader::builder(libraries, "output").build().await?;

    let url = "https://www.youtube.com/watch?v=gXtp6C-3JKo";
    let video = downloader.fetch_video_infos(url).await?;

    // Check available languages (merges subtitles + automatic captions)
    let langs = downloader.list_subtitle_languages(&video);
    println!("Available languages: {:?}", langs);

    // Download French subtitles (falls back to automatic captions if no manual ones)
    let sub_path = downloader.download_subtitle(&video, "fr", "subtitles.srt", true).await?;

    // Download all available subtitles/captions
    let paths = downloader.download_all_subtitles(&video, "subtitles/", true).await?;

    Ok(())
}
```

- 🎞️ Downloading storyboard preview frames:
```rust,no_run
use yt_dlp::Downloader;
use yt_dlp::model::StoryboardQuality;
use yt_dlp::VideoSelection;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries = Libraries::new(
        PathBuf::from("libs/yt-dlp"),
        PathBuf::from("libs/ffmpeg"),
    );
    let downloader = Downloader::builder(libraries, "output").build().await?;

    let url = "https://www.youtube.com/watch?v=gXtp6C-3JKo";
    let video = downloader.fetch_video_infos(url).await?;

    // Download the best (highest resolution) storyboard into a directory
    let frames = downloader
        .download_storyboard(&video, StoryboardQuality::Best, "storyboard/")
        .await?;
    println!("Downloaded {} MHTML fragment(s)", frames.len());

    // Or pick a specific storyboard format directly
    if let Some(format) = video.best_storyboard_format() {
        let frames = downloader.download_storyboard_format(format, "storyboard/").await?;
    }

    Ok(())
}
```

- πŸ“₯ Download with download manager and priority:
```rust,no_run
use yt_dlp::Downloader;
use yt_dlp::download::manager::{ManagerConfig, DownloadPriority};
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Custom download manager configuration using the typed builder
    let config = ManagerConfig::builder()
        .max_concurrent_downloads(5)        // Maximum 5 concurrent downloads
        .segment_size(1024 * 1024 * 10)    // 10 MB per segment
        .parallel_segments(8)               // 8 parallel segments per download
        .retry_attempts(5)                  // 5 retry attempts on failure
        .max_buffer_size(1024 * 1024 * 20) // 20 MB maximum buffer
        .build();

    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");

    let libraries = Libraries::new(youtube, ffmpeg);

    // Create a fetcher with custom configuration
    let downloader = Downloader::with_download_manager_config(libraries, output_dir, config)
        .build()
        .await?;

    // Download a video with high priority
    let url = String::from("https://www.youtube.com/watch?v=gXtp6C-3JKo");
    let video = downloader.fetch_video_infos(url).await?;

    let download_id = downloader.download_video_with_priority(
        &video,
        "video-high-priority.mp4",
        Some(DownloadPriority::High)
    ).await?;

    // Wait for download completion
    let status = downloader.wait_for_download(download_id).await;
    println!("Final download status: {:?}", status);

    Ok(())
}
```

- πŸ“Š Download with progress tracking:
```rust,no_run
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");
    
    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");
    
    let libraries = Libraries::new(youtube, ffmpeg);
    let downloader = Downloader::builder(libraries, output_dir)
        .build()
        .await?;

    let url = String::from("https://www.youtube.com/watch?v=gXtp6C-3JKo");
    let video = downloader.fetch_video_infos(url).await?;

    // Download with progress callback
    let download_id = downloader.download_video_with_progress(
        &video, 
        "video-with-progress.mp4", 
        |downloaded, total| {
            let percentage = if total > 0 {
                (downloaded as f64 / total as f64 * 100.0) as u64
            } else {
                0
            };
            println!("Progress: {}/{} bytes ({}%)", downloaded, total, percentage);
        }
    ).await?;

    // Wait for download completion
    downloader.wait_for_download(download_id).await;
    
    Ok(())
}
```

- πŸ›‘ Canceling a download:
```rust,no_run
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");
    
    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");
    
    let libraries = Libraries::new(youtube, ffmpeg);
    let downloader = Downloader::builder(libraries, output_dir)
        .build()
        .await?;

    let url = String::from("https://www.youtube.com/watch?v=gXtp6C-3JKo");
    let video = downloader.fetch_video_infos(url).await?;

    // Start a download
    let download_id = downloader.download_video_with_priority(
        &video, 
        "video-to-cancel.mp4", 
        None
    ).await?;

    // Check status
    let status = downloader.get_download_status(download_id).await;
    println!("Download status: {:?}", status);

    // Cancel the download
    let canceled = downloader.cancel_download(download_id).await;
    println!("Download canceled: {}", canceled);
    
    Ok(())
}
```

---

## πŸŽ›οΈ Format Selection

The library provides a powerful format selection system that allows you to download videos and audio with specific quality and codec preferences.

### 🎬 Video Quality Options

- `VideoQuality::Best` - Selects the highest quality video format available
- `VideoQuality::High` - Targets 1080p resolution
- `VideoQuality::Medium` - Targets 720p resolution
- `VideoQuality::Low` - Targets 480p resolution
- `VideoQuality::Worst` - Selects the lowest quality video format available
- `VideoQuality::CustomHeight(u32)` - Targets a specific height (e.g., `CustomHeight(1440)` for 1440p)
- `VideoQuality::CustomWidth(u32)` - Targets a specific width (e.g., `CustomWidth(1920)` for 1920px width)

### 🎡 Audio Quality Options

- `AudioQuality::Best` - Selects the highest quality audio format available
- `AudioQuality::High` - Targets 192kbps bitrate
- `AudioQuality::Medium` - Targets 128kbps bitrate
- `AudioQuality::Low` - Targets 96kbps bitrate
- `AudioQuality::Worst` - Selects the lowest quality audio format available
- `AudioQuality::CustomBitrate(u32)` - Targets a specific bitrate in kbps (e.g., `CustomBitrate(256)` for 256kbps)

### 🎞️ Codec Preferences

#### πŸ“Ή Video Codecs
- `VideoCodecPreference::VP9` - Prefer VP9 codec
- `VideoCodecPreference::AVC1` - Prefer AVC1/H.264 codec
- `VideoCodecPreference::AV1` - Prefer AV01/AV1 codec
- `VideoCodecPreference::Custom(String)` - Prefer a custom codec
- `VideoCodecPreference::Any` - No codec preference

#### πŸ”Š Audio Codecs
- `AudioCodecPreference::Opus` - Prefer Opus codec
- `AudioCodecPreference::AAC` - Prefer AAC codec
- `AudioCodecPreference::MP3` - Prefer MP3 codec
- `AudioCodecPreference::Custom(String)` - Prefer a custom codec
- `AudioCodecPreference::Any` - No codec preference

### πŸ§ͺ Example: Downloading with Quality and Codec Preferences

```rust,no_run
use yt_dlp::Downloader;
use yt_dlp::model::selector::{VideoQuality, VideoCodecPreference, AudioQuality, AudioCodecPreference};
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");
    
    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");
    
    let libraries = Libraries::new(youtube, ffmpeg);
    let downloader = Downloader::builder(libraries, output_dir)
        .build()
        .await?;

    let url = String::from("https://www.youtube.com/watch?v=gXtp6C-3JKo");
    let video = downloader.fetch_video_infos(url).await?;

    // Download a high quality video with VP9 codec and high quality audio with Opus codec
    let video_path = downloader.download_video_with_quality(
        &video,
        "complete-video.mp4",
        VideoQuality::High,
        VideoCodecPreference::VP9,
        AudioQuality::High,
        AudioCodecPreference::Opus
    ).await?;
    
    // Download just the video stream with medium quality and AVC1 codec
    let video_stream_path = downloader.download_video_stream_with_quality(
        &video,
        "video-only.mp4",
        VideoQuality::Medium,
        VideoCodecPreference::AVC1
    ).await?;
    
    // Download just the audio stream with high quality and AAC codec
    let audio_stream_path = downloader.download_audio_stream_with_quality(
        &video,
        "audio-only.m4a",
        AudioQuality::High,
        AudioCodecPreference::AAC
    ).await?;
    
    println!("Downloaded files:");
    println!("Complete video: {}", video_path.display());
    println!("Video stream: {}", video_stream_path.display());
    println!("Audio stream: {}", audio_stream_path.display());
    
    Ok(())
}
```

---

## πŸ“‹ Metadata
The project supports automatic addition of metadata to downloaded files in several formats:

- **MP3**: Title, artist, comment, genre (from tags), release year
- **M4A**: Title, artist, comment, genre (from tags), release year
- **MP4**: All basic metadata, plus technical information (resolution, FPS, video codec, video bitrate, audio codec, audio bitrate, audio channels, sample rate)
- **WebM**: All basic metadata (via Matroska format), plus technical information as with MP4
- **FLAC**: Title, artist, album, genre, date, description (via Vorbis comments through lofty), thumbnail embedding
- **OGG/Opus**: Title, artist, album, genre, date, description (via Vorbis comments through lofty)
- **WAV**: Title, artist, album, genre (via RIFF INFO through lofty)
- **AAC**: Title, artist, album, genre, date (via ID3v2 through lofty)
- **AIFF**: Title, artist, album, genre, date (via ID3v2 through lofty)
- **AVI/TS/FLV**: Basic metadata via FFmpeg fallback

Metadata is added automatically during download, without requiring any additional action from the user.

### 🧠 Intelligent Metadata Management
The system intelligently manages the application of metadata based on the file type and intended use:

- For standalone files (audio or audio+video), metadata is applied immediately during download.
- For separate audio and video streams that will be combined later, metadata is not applied to individual files to avoid redundant work.
- When combining audio and video streams with `combine_audio_and_video()`, complete metadata is applied to the final file, including information from both streams.

This optimized approach ensures that metadata is always present in the final file, while avoiding unnecessary processing of temporary files.

## πŸ“– Chapters

Videos may contain chapters that divide the content into logical segments. The library provides easy access to chapter information and **automatically embeds chapters into downloaded video files** (MP4/MKV/WebM):

- πŸ“– Accessing video chapters:
```rust,no_run
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");

    let libraries = Libraries::new(youtube, ffmpeg);
    let downloader = Downloader::builder(libraries, output_dir)
        .build()
        .await?;

    let url = String::from("https://www.youtube.com/watch?v=gXtp6C-3JKo");
    let video = downloader.fetch_video_infos(url).await?;

    // Check if video has chapters
    if video.has_chapters() {
        println!("Video has {} chapters", video.get_chapters().len());

        // Iterate over all chapters
        for chapter in video.get_chapters() {
            println!(
                "Chapter: {} ({:.2}s - {:.2}s)",
                chapter.title.as_deref().unwrap_or("Untitled"),
                chapter.start_time,
                chapter.end_time
            );
        }
    }

    Ok(())
}
```

- πŸ•’ Finding a chapter at a specific timestamp:
```rust,no_run
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");

    let libraries = Libraries::new(youtube, ffmpeg);
    let downloader = Downloader::builder(libraries, output_dir)
        .build()
        .await?;

    let url = String::from("https://www.youtube.com/watch?v=gXtp6C-3JKo");
    let video = downloader.fetch_video_infos(url).await?;

    // Find chapter at 120 seconds (2 minutes)
    if let Some(chapter) = video.get_chapter_at_time(120.0) {
        println!(
            "At 2:00, you're in chapter: {}",
            chapter.title.as_deref().unwrap_or("Untitled")
        );
        println!("Chapter duration: {:.2}s", chapter.duration());
    }

    Ok(())
}
```

**Note**: When downloading videos using `download_video()` or `download_video_from_url()`, chapters are **automatically embedded** into the video file metadata. Media players like VLC, MPV, and others will be able to navigate using the chapters!

## πŸ”₯ Heatmap

Heatmap data (also known as "Most Replayed" segments) shows viewer engagement across different parts of a video. This feature allows you to identify which segments are most popular:

- πŸ”₯ Accessing heatmap data:
```rust,no_run
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");

    let libraries = Libraries::new(youtube, ffmpeg);
    let downloader = Downloader::builder(libraries, output_dir)
        .build()
        .await?;

    let url = String::from("https://www.youtube.com/watch?v=gXtp6C-3JKo");
    let video = downloader.fetch_video_infos(url).await?;

    // Check if video has heatmap data
    if video.has_heatmap() {
        if let Some(heatmap) = video.get_heatmap() {
            println!("Video has {} heatmap segments", heatmap.points().len());

            // Find the most replayed segment
            if let Some(most_replayed) = heatmap.most_engaged_segment() {
                println!(
                    "Most replayed segment: {:.2}s - {:.2}s (engagement: {:.2})",
                    most_replayed.start_time,
                    most_replayed.end_time,
                    most_replayed.value
                );
            }
        }
    }

    Ok(())
}
```

- πŸ“Š Analyzing engagement by threshold:
```rust,no_run
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");

    let libraries = Libraries::new(youtube, ffmpeg);
    let downloader = Downloader::builder(libraries, output_dir)
        .build()
        .await?;

    let url = String::from("https://www.youtube.com/watch?v=gXtp6C-3JKo");
    let video = downloader.fetch_video_infos(url).await?;

    if let Some(heatmap) = video.get_heatmap() {
        // Get segments with high engagement (> 0.7)
        let highly_engaged = heatmap.get_highly_engaged_segments(0.7);
        println!("Found {} highly engaged segments", highly_engaged.len());

        for segment in highly_engaged {
            println!(
                "High engagement: {:.2}s - {:.2}s (value: {:.2})",
                segment.start_time,
                segment.end_time,
                segment.value
            );
        }

        // Get engagement at specific timestamp
        if let Some(point) = heatmap.get_point_at_time(120.0) {
            println!(
                "Engagement at 2:00 is {:.2}",
                point.value
            );
        }
    }

    Ok(())
}
```

## πŸ“ Subtitles

The library provides comprehensive subtitle support, including downloading, language selection, and embedding subtitles into videos:

- πŸ“‹ Listing available subtitle languages:
```rust,no_run
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");

    let libraries = Libraries::new(youtube, ffmpeg);
    let downloader = Downloader::builder(libraries, output_dir)
        .build()
        .await?;

    let url = String::from("https://www.youtube.com/watch?v=gXtp6C-3JKo");
    let video = downloader.fetch_video_infos(url).await?;

    // List all available subtitle languages
    let languages = downloader.list_subtitle_languages(&video);
    println!("Available subtitle languages: {:?}", languages);

    // Check if specific language is available
    if downloader.has_subtitle_language(&video, "en") {
        println!("English subtitles are available");
    }

    Ok(())
}
```

- πŸ“₯ Downloading a specific subtitle:
```rust,no_run
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");

    let libraries = Libraries::new(youtube, ffmpeg);
    let downloader = Downloader::builder(libraries, output_dir)
        .build()
        .await?;

    let url = String::from("https://www.youtube.com/watch?v=gXtp6C-3JKo");
    let video = downloader.fetch_video_infos(url).await?;

    // Download English subtitles
    let subtitle_path = downloader
        .download_subtitle(&video, "en", "subtitle_en.srt", true)
        .await?;
    println!("Subtitle downloaded to: {:?}", subtitle_path);

    Ok(())
}
```

- πŸ“₯ Downloading all available subtitles:
```rust,no_run
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");

    let libraries = Libraries::new(youtube, ffmpeg);
    let downloader = Downloader::builder(libraries, output_dir.clone())
        .build()
        .await?;

    let url = String::from("https://www.youtube.com/watch?v=gXtp6C-3JKo");
    let video = downloader.fetch_video_infos(url).await?;

    // Download all available subtitles
    let subtitle_paths = downloader
        .download_all_subtitles(&video, &output_dir, true)
        .await?;
    println!("Downloaded {} subtitle files", subtitle_paths.len());

    Ok(())
}
```

- 🎬 Embedding subtitles into a video:
```rust,no_run
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");

    let libraries = Libraries::new(youtube, ffmpeg);
    let downloader = Downloader::builder(libraries, output_dir)
        .build()
        .await?;

    let url = String::from("https://www.youtube.com/watch?v=gXtp6C-3JKo");
    let video = downloader.fetch_video_infos(url).await?;

    // Download video
    let video_path = downloader.download_video(&video, "video.mp4").await?;

    // Download subtitles
    let en_subtitle = downloader
        .download_subtitle(&video, "en", "subtitle_en.srt", true)
        .await?;
    let fr_subtitle = downloader
        .download_subtitle(&video, "fr", "subtitle_fr.srt", true)
        .await?;

    // Embed subtitles into video
    let video_with_subs = downloader
        .embed_subtitles_in_video(
            &video_path,
            &[en_subtitle, fr_subtitle],
            "video_with_subtitles.mp4",
        )
        .await?;
    println!("Video with embedded subtitles: {:?}", video_with_subs);

    Ok(())
}
```

- πŸ”„ Working with automatic captions:
```rust,no_run
use yt_dlp::Downloader;
use yt_dlp::model::caption::Subtitle;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");

    let libraries = Libraries::new(youtube, ffmpeg);
    let downloader = Downloader::builder(libraries, output_dir)
        .build()
        .await?;

    let url = String::from("https://www.youtube.com/watch?v=gXtp6C-3JKo");
    let video = downloader.fetch_video_infos(url).await?;

    // Iterate over subtitles and filter automatic ones
    for (lang_code, subtitles) in &video.subtitles {
        for subtitle in subtitles {
            if subtitle.is_automatic {
                println!(
                    "Auto-generated subtitle: {} ({})",
                    subtitle.language_name
                        .as_deref()
                        .unwrap_or(lang_code),
                    subtitle.file_extension()
                );
            }
        }
    }

    // Convert automatic captions to Subtitle struct
    for (lang_code, auto_captions) in &video.automatic_captions {
        if let Some(caption) = auto_captions.first() {
            let subtitle = Subtitle::from_automatic_caption(
                caption,
                lang_code.clone(),
            );
            println!("Converted: {}", subtitle);
        }
    }

    Ok(())
}
```

---

## πŸ“‚ Playlists

The library provides full playlist support, including fetching playlist metadata and downloading videos with various selection options:

- πŸ“‹ Fetching playlist information:
```rust,no_run
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");

    let libraries = Libraries::new(youtube, ffmpeg);
    let downloader = Downloader::builder(libraries, output_dir)
        .build()
        .await?;

    let playlist_url = String::from("https://www.youtube.com/playlist?list=PLrAXtmErZgOeiKm4sgNOknGvNjby9efdf");
    let playlist = downloader.fetch_playlist_infos(playlist_url).await?;

    println!("Playlist: {}", playlist.title);
    println!("Videos: {}", playlist.entry_count());
    println!("Uploader: {}", playlist.uploader.as_deref().unwrap_or("unknown"));

    // List all videos in the playlist
    for entry in &playlist.entries {
        println!(
            "[{}] {} ({})",
            entry.index.unwrap_or(0),
            entry.title,
            entry.id
        );
    }

    Ok(())
}
```

- πŸ“₯ Downloading entire playlist:
```rust,no_run
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");

    let libraries = Libraries::new(youtube, ffmpeg);
    let downloader = Downloader::builder(libraries, output_dir)
        .build()
        .await?;

    let playlist_url = String::from("https://www.youtube.com/playlist?list=PLrAXtmErZgOeiKm4sgNOknGvNjby9efdf");
    let playlist = downloader.fetch_playlist_infos(playlist_url).await?;

    // Download all videos with a pattern
    // Use %(playlist_index)s for index, %(title)s for title, %(id)s for video ID
    let video_paths = downloader
        .download_playlist(&playlist, "%(playlist_index)s - %(title)s.mp4")
        .await?;

    println!("Downloaded {} videos", video_paths.len());

    Ok(())
}
```

- 🎯 Downloading specific videos by index:
```rust,no_run
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");

    let libraries = Libraries::new(youtube, ffmpeg);
    let downloader = Downloader::builder(libraries, output_dir)
        .build()
        .await?;

    let playlist_url = String::from("https://www.youtube.com/playlist?list=PLrAXtmErZgOeiKm4sgNOknGvNjby9efdf");
    let playlist = downloader.fetch_playlist_infos(playlist_url).await?;

    // Download specific videos by index (0-based)
    let indices = vec![0, 2, 5, 10]; // Videos at positions 1, 3, 6, and 11
    let video_paths = downloader
        .download_playlist_items(&playlist, &indices, "%(playlist_index)s - %(title)s.mp4")
        .await?;

    println!("Downloaded {} specific videos", video_paths.len());

    Ok(())
}
```

- πŸ“Š Downloading a range of videos:
```rust,no_run
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");

    let libraries = Libraries::new(youtube, ffmpeg);
    let downloader = Downloader::builder(libraries, output_dir)
        .build()
        .await?;

    let playlist_url = String::from("https://www.youtube.com/playlist?list=PLrAXtmErZgOeiKm4sgNOknGvNjby9efdf");
    let playlist = downloader.fetch_playlist_infos(playlist_url).await?;

    // Download videos 5-15 (0-based, inclusive)
    let video_paths = downloader
        .download_playlist_range(&playlist, 5, 15, "%(playlist_index)s - %(title)s.mp4")
        .await?;

    println!("Downloaded {} videos from range", video_paths.len());

    Ok(())
}
```

- πŸ” Filtering and analyzing playlists:
```rust,no_run
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    let youtube = libraries_dir.join("yt-dlp");
    let ffmpeg = libraries_dir.join("ffmpeg");

    let libraries = Libraries::new(youtube, ffmpeg);
    let downloader = Downloader::builder(libraries, output_dir)
        .build()
        .await?;

    let playlist_url = String::from("https://www.youtube.com/playlist?list=PLrAXtmErZgOeiKm4sgNOknGvNjby9efdf");
    let playlist = downloader.fetch_playlist_infos(playlist_url).await?;

    // Check if playlist is complete
    if playlist.is_complete() {
        println!("All playlist videos have been fetched");
    }

    // Get only available videos
    let available = playlist.available_entries();
    println!("Available videos: {}/{}", available.len(), playlist.entry_count());

    // Get specific entry
    if let Some(first_video) = playlist.get_entry_by_index(0) {
        println!("First video: {}", first_video.title);
        if let Some(duration) = first_video.duration_minutes() {
            println!("Duration: {:.2} minutes", duration);
        }
    }

    // Get entries in a range
    let range = playlist.get_entries_in_range(0, 10);
    println!("First 11 videos: {}", range.len());

    Ok(())
}
```

---

## πŸ”” Events, Hooks & Webhooks

The library provides a comprehensive event system to monitor download lifecycle and react to events through Rust hooks or HTTP webhooks.

### ⚑ Event System

All download operations emit events that you can subscribe to:

- πŸ“‘ Subscribing to the event stream:
```rust,no_run
use yt_dlp::Downloader;
use tokio_stream::StreamExt;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    let libraries = Libraries::new(
        libraries_dir.join("yt-dlp"),
        libraries_dir.join("ffmpeg")
    );

    let downloader = Downloader::builder(libraries, output_dir).build().await?;
    let mut stream = downloader.event_stream();

    while let Some(Ok(event)) = stream.next().await {
        println!("Event: {} - {:?}", event.event_type(), event);
    }

    Ok(())
}
```

### βœ‰οΈ Available Events

The library emits **22 different event types** covering the entire download lifecycle:

**Download Lifecycle:**
- `VideoFetched` - Video metadata retrieved
- `DownloadQueued` - Download added to queue
- `DownloadStarted` - Download begins
- `DownloadProgress` - Progress updates (bytes downloaded, speed, ETA)
- `DownloadPaused` / `DownloadResumed` - Pause/resume events
- `DownloadCompleted` - Download finished successfully
- `DownloadFailed` - Download failed with error
- `DownloadCanceled` - Download was canceled

**Format & Metadata:**
- `FormatSelected` - Video/audio format chosen
- `MetadataApplied` - Metadata tags written
- `ChaptersEmbedded` - Chapters added to file

**Post-Processing:**
- `PostProcessStarted` / `PostProcessCompleted` / `PostProcessFailed` - FFmpeg operations

**Playlist Operations:**
- `PlaylistFetched` - Playlist metadata retrieved
- `PlaylistItemStarted` / `PlaylistItemCompleted` / `PlaylistItemFailed` - Per-item events
- `PlaylistCompleted` - Entire playlist finished

**Advanced:**
- `SegmentStarted` / `SegmentCompleted` - Parallel segment downloads

### πŸͺ Rust Hooks (Feature: `hooks`)

Register async functions to be called when events occur:

```toml
[dependencies]
yt-dlp = { version = "2.4.0", features = ["hooks"] }
```

- 🎣 Registering a hook for download events:
```rust,ignore
use yt_dlp::events::{EventHook, EventFilter, DownloadEvent, HookResult};
use async_trait::async_trait;
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[derive(Clone)]
struct MyHook;

#[async_trait]
impl EventHook for MyHook {
    async fn on_event(&self, event: &DownloadEvent) -> HookResult {
        match event {
            DownloadEvent::DownloadCompleted { download_id, output_path, .. } => {
                println!("Download {} completed: {:?}", download_id, output_path);
            }
            DownloadEvent::DownloadFailed { download_id, error, .. } => {
                eprintln!("Download {} failed: {}", download_id, error);
            }
            _ => {}
        }
        Ok(())
    }

    fn filter(&self) -> EventFilter {
        // Only receive terminal events (completed, failed, canceled)
        EventFilter::only_terminal()
    }
}

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    let libraries = Libraries::new(
        libraries_dir.join("yt-dlp"),
        libraries_dir.join("ffmpeg")
    );

    let mut downloader = Downloader::builder(libraries, output_dir).build().await?;
    downloader.register_hook(MyHook).await;

    Ok(())
}
```

**Hook Features:**
- Async execution
- Event filtering (by type, download ID, custom predicates)
- Parallel or sequential execution
- Automatic timeout protection (30s)
- Error isolation (hook failures don't stop downloads)

#### πŸ” Event Filters

```rust,no_run
use yt_dlp::events::EventFilter;

// Only completed downloads
EventFilter::only_completed();

// Only failed downloads
EventFilter::only_failed();

// Progress updates only
EventFilter::only_progress();

// Exclude progress events
EventFilter::all().exclude_progress();

// Specific download ID
EventFilter::download_id(123);

// Terminal events (completed, failed, canceled)
EventFilter::only_terminal();

// Chain filters
EventFilter::download_id(123).and_then(|e| e.is_terminal());

// Custom filter
EventFilter::all().and_then(|event| {
    // Your custom logic
    true
});
```

### πŸ“‘ HTTP Webhooks (Feature: `webhooks`)

Send events to external HTTP endpoints with automatic retry:

```toml
[dependencies]
yt-dlp = { version = "2.4.0", features = ["webhooks"] }
```

- πŸ“‘ Registering a webhook:
```rust,ignore
use yt_dlp::events::{WebhookConfig, WebhookMethod, EventFilter};
use std::time::Duration;
use yt_dlp::Downloader;
use std::path::PathBuf;
use yt_dlp::client::deps::Libraries;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    let libraries = Libraries::new(
        libraries_dir.join("yt-dlp"),
        libraries_dir.join("ffmpeg")
    );

    let webhook = WebhookConfig::new("https://example.com/webhook")
        .with_method(WebhookMethod::Post)
        .with_header("Authorization", "Bearer your-token")
        .with_filter(EventFilter::only_completed())
        .with_timeout(Duration::from_secs(10));

    let mut downloader = Downloader::builder(libraries, output_dir).build().await?;
    downloader.register_webhook(webhook).await;

    Ok(())
}
```

**Webhook Features:**
- HTTP POST/PUT/PATCH methods
- Custom headers (authentication, etc.)
- Event filtering (same as hooks)
- Automatic retry with exponential backoff (3 attempts by default)
- Configurable timeouts
- JSON payload with event data
- Environment variable configuration

**Environment Variables:**
```bash
export YTDLP_WEBHOOK_URL="https://example.com/webhook"
export YTDLP_WEBHOOK_METHOD="POST"  # Optional, default: POST
export YTDLP_WEBHOOK_TIMEOUT="10"   # Optional, default: 10 seconds
```

- πŸ”§ Loading a webhook from environment variables:
```rust,ignore
use yt_dlp::Downloader;
use yt_dlp::client::deps::Libraries;
use yt_dlp::events::WebhookConfig;
use std::path::PathBuf;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries = Libraries::new(
        PathBuf::from("libs/yt-dlp"),
        PathBuf::from("libs/ffmpeg")
    );
    let mut downloader = Downloader::builder(libraries, PathBuf::from("output")).build().await?;

    // Load webhook from environment variables
    if let Some(webhook) = WebhookConfig::from_env() {
        downloader.register_webhook(webhook).await;
    }

    Ok(())
}
```

**Webhook Payload:**
```json
{
  "event_type": "download_completed",
  "download_id": 123,
  "timestamp": "2025-01-21T10:30:00Z",
  "data": {
    "download_id": 123,
    "output_path": "/path/to/video.mp4",
    "duration": 45.2,
    "total_bytes": 104857600
  }
}
```

#### ♻️ Retry Strategy

- ♻️ Configuring a retry strategy:
```rust,ignore
use yt_dlp::events::RetryStrategy;
use std::time::Duration;

// Exponential backoff (default)
let strategy = RetryStrategy::exponential(
    3,                              // max attempts
    Duration::from_secs(1),         // initial delay
    Duration::from_secs(30)         // max delay
);

// Linear backoff
let strategy = RetryStrategy::linear(
    3,                              // max attempts
    Duration::from_secs(5)          // fixed delay
);

// No retries
let strategy = RetryStrategy::none();
```

### πŸ”— Combining Hooks and Webhooks

Use both hooks and webhooks together:

- πŸ”— Using hooks and webhooks simultaneously:
```rust,ignore
use yt_dlp::Downloader;
use yt_dlp::events::{EventHook, WebhookConfig, EventFilter};
use yt_dlp::client::deps::Libraries;
use std::path::PathBuf;

#[derive(Clone)]
struct MyLocalHook;

#[async_trait::async_trait]
impl EventHook for MyLocalHook {
    async fn on_event(&self, _event: &yt_dlp::events::DownloadEvent) -> yt_dlp::events::HookResult { Ok(()) }
    fn filter(&self) -> EventFilter { EventFilter::all() }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries = Libraries::new(PathBuf::from("libs/yt-dlp"), PathBuf::from("libs/ffmpeg"));

    let mut downloader = Downloader::builder(libraries, PathBuf::from("output")).build().await?;

    // Register Rust hook for immediate in-process handling
    downloader.register_hook(MyLocalHook).await;

    // Register webhook for external notifications
    let webhook = WebhookConfig::new("https://example.com/webhook")
        .with_filter(EventFilter::only_completed());
    downloader.register_webhook(webhook).await;

    // Start downloads - both hooks and webhooks will receive events
    let video = downloader.fetch_video_infos("https://youtube.com/watch?v=...".to_string()).await?;
    downloader.download_video(&video, "video.mp4").await?;

    Ok(())
}
```

## πŸ“Š Statistics & Analytics (Feature: `statistics`)

Enable real-time, aggregate metrics with zero manual bookkeeping:

```toml
[dependencies]
yt-dlp = { version = "2.4.0", features = ["statistics"] }
```

The [`StatisticsTracker`](https://docs.rs/yt-dlp/latest/yt_dlp/stats/struct.StatisticsTracker.html) subscribes to the internal event bus in a background task and continuously updates running counters. Call `snapshot()` at any time to obtain an atomic view of all metrics:

```rust,ignore
use yt_dlp::Downloader;
use yt_dlp::client::deps::Libraries;
use std::path::PathBuf;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries = Libraries::new(PathBuf::from("libs/yt-dlp"), PathBuf::from("libs/ffmpeg"));
    let downloader = Downloader::builder(libraries, "output").build().await?;

    // Perform some downloads and fetches ...
    let video = downloader.fetch_video_infos("https://youtube.com/watch?v=...".to_string()).await?;
    downloader.download_video(&video, "video.mp4").await?;

    let snapshot = downloader.statistics().snapshot().await;
    println!("Downloads completed:  {}", snapshot.downloads.completed);
    println!("Total bytes:          {}", snapshot.downloads.total_bytes);
    println!("Avg speed (B/s):      {:?}", snapshot.downloads.avg_speed_bytes_per_sec);
    println!("Download success %:   {:?}", snapshot.downloads.success_rate);
    println!("Fetch success %:      {:?}", snapshot.fetches.success_rate);
    println!("Post-process success: {:?}", snapshot.post_processing.success_rate);

    Ok(())
}
```

The snapshot exposes:
- **`downloads`** β€” attempted, completed, failed, canceled, total bytes, average speed, peak speed, success rate
- **`fetches`** β€” attempted, succeeded, failed, average duration, success rate (video + playlist fetches)
- **`post_processing`** β€” attempted, succeeded, failed, average duration
- **`playlists`** β€” playlists fetched, failed, per-item success rate
- **`recent_downloads`** β€” bounded history window of completed downloads with per-download details

## πŸš€ Advanced Features

### πŸ” Proxy Support

The library supports HTTP, HTTPS, and SOCKS5 proxies for both `yt-dlp` and `reqwest` downloads:

- πŸ” Configuring a proxy with authentication:
```rust,no_run
use yt_dlp::Downloader;
use yt_dlp::client::proxy::{ProxyConfig, ProxyType};
use yt_dlp::client::deps::Libraries;
use std::path::PathBuf;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    let libraries = Libraries::new(
        libraries_dir.join("yt-dlp"),
        libraries_dir.join("ffmpeg")
    );

    // Configure proxy with authentication
    let proxy = ProxyConfig::new(ProxyType::Http, "http://proxy.example.com:8080")
        .with_auth("username", "password")
        .with_no_proxy(vec!["localhost".to_string(), "127.0.0.1".to_string()]);

    // Build Downloader with proxy
    let downloader = Downloader::builder(libraries, output_dir)
        .with_proxy(proxy)
        .build()
        .await?;

    let url = String::from("https://www.youtube.com/watch?v=gXtp6C-3JKo");
    let video = downloader.fetch_video_infos(url).await?;

    // All downloads (video, audio, thumbnails) will use the proxy
    downloader.download_video(&video, "video.mp4").await?;

    Ok(())
}
```

Supported proxy types:
- **HTTP/HTTPS**: Standard HTTP proxies
- **SOCKS5**: SOCKS5 proxies for more flexibility
- **Authentication**: Username/password authentication
- **No-proxy list**: Exclude specific domains from proxying

### πŸ”‘ Authentication & Cookies

Many platforms (YouTube bot-protection, Twitch, age-restricted content, etc.) require authentication.
The library supports three authentication modes that are propagated to both metadata extraction and
all download operations automatically.

#### Cookie file (Netscape format)

```rust,no_run
use yt_dlp::Downloader;
use yt_dlp::client::deps::Libraries;
use std::path::PathBuf;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries = Libraries::new(
        PathBuf::from("libs/yt-dlp"),
        PathBuf::from("libs/ffmpeg"),
    );

    // Export cookies from your browser with a browser extension (e.g. "Get cookies.txt LOCALLY")
    let downloader = Downloader::builder(libraries, PathBuf::from("output"))
        .with_cookies("cookies.txt")
        .build()
        .await?;

    let video = downloader.fetch_video_infos("https://www.youtube.com/watch?v=gXtp6C-3JKo").await?;
    downloader.download_video(&video, "video.mp4").await?;

    Ok(())
}
```

#### Browser cookies

```rust,no_run
use yt_dlp::Downloader;
use yt_dlp::client::deps::Libraries;
use std::path::PathBuf;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries = Libraries::new(
        PathBuf::from("libs/yt-dlp"),
        PathBuf::from("libs/ffmpeg"),
    );

    // yt-dlp will read cookies directly from your browser's cookie store
    let downloader = Downloader::builder(libraries, PathBuf::from("output"))
        .with_cookies_from_browser("chrome") // or "firefox", "safari", "edge", …
        .build()
        .await?;

    let video = downloader.fetch_video_infos("https://www.youtube.com/watch?v=gXtp6C-3JKo").await?;
    downloader.download_video(&video, "video.mp4").await?;

    Ok(())
}
```

#### Runtime (after build)

```rust,no_run
use yt_dlp::Downloader;
use yt_dlp::client::deps::Libraries;
use std::path::PathBuf;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries = Libraries::new(
        PathBuf::from("libs/yt-dlp"),
        PathBuf::from("libs/ffmpeg"),
    );

    let mut downloader = Downloader::builder(libraries, PathBuf::from("output"))
        .build()
        .await?;

    // Apply cookies after build β€” propagates to both extractors and download args
    downloader.set_cookies("cookies.txt");
    // or: downloader.set_cookies_from_browser("chrome");
    // or: downloader.set_netrc();

    let video = downloader.fetch_video_infos("https://www.youtube.com/watch?v=gXtp6C-3JKo").await?;
    downloader.download_video(&video, "video.mp4").await?;

    Ok(())
}
```

#### .netrc

```rust,no_run
use yt_dlp::Downloader;
use yt_dlp::client::deps::Libraries;
use std::path::PathBuf;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries = Libraries::new(
        PathBuf::from("libs/yt-dlp"),
        PathBuf::from("libs/ffmpeg"),
    );

    let downloader = Downloader::builder(libraries, PathBuf::from("output"))
        .with_netrc()
        .build()
        .await?;

    let video = downloader.fetch_video_infos("https://www.youtube.com/watch?v=gXtp6C-3JKo").await?;
    downloader.download_video(&video, "video.mp4").await?;

    Ok(())
}
```

### βœ‚οΈ Clip extraction & chapter splitting

The library supports downloading a specific time range or a specific chapter from a video without fetching the whole file. Seeking is handled by [`media-seek`](crates/media-seek/README.md) β€” a pure Rust container index parser that translates timestamps into HTTP Range byte offsets.

- βœ‚οΈ Downloading a specific time range (seconds):
```rust,no_run
use yt_dlp::Downloader;
use yt_dlp::client::deps::Libraries;
use std::path::PathBuf;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries = Libraries::new(
        PathBuf::from("libs/yt-dlp"),
        PathBuf::from("libs/ffmpeg"),
    );
    let downloader = Downloader::builder(libraries, "output").build().await?;

    let url = "https://www.youtube.com/watch?v=gXtp6C-3JKo";
    let video = downloader.fetch_video_infos(url).await?;

    // Download seconds [60, 120] only β€” no re-encoding
    let clip_path = downloader
        .download(&video, "clip.mp4")
        .time_range(60.0, 120.0)?
        .execute()
        .await?;

    Ok(())
}
```

- πŸ“– Downloading a specific chapter by index range:
```rust,no_run
use yt_dlp::Downloader;
use yt_dlp::client::deps::Libraries;
use std::path::PathBuf;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries = Libraries::new(
        PathBuf::from("libs/yt-dlp"),
        PathBuf::from("libs/ffmpeg"),
    );
    let downloader = Downloader::builder(libraries, "output").build().await?;

    let url = "https://www.youtube.com/watch?v=gXtp6C-3JKo";
    let video = downloader.fetch_video_infos(url).await?;

    // Download chapters 0 through 2 (inclusive)
    let clip_path = downloader
        .download(&video, "chapters.mp4")
        .chapters(0, 2)?
        .execute()
        .await?;

    Ok(())
}
```

- πŸ”ͺ Splitting a downloaded video into one file per chapter:
```rust,no_run
use yt_dlp::Downloader;
use yt_dlp::client::deps::Libraries;
use std::path::PathBuf;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries = Libraries::new(
        PathBuf::from("libs/yt-dlp"),
        PathBuf::from("libs/ffmpeg"),
    );
    let downloader = Downloader::builder(libraries, "output").build().await?;

    let url = "https://www.youtube.com/watch?v=gXtp6C-3JKo";
    let video = downloader.fetch_video_infos(url).await?;

    // Download and split into one file per chapter β€” FFmpeg stream copy, no re-encoding
    let chapter_files: Vec<PathBuf> = downloader
        .split_by_chapters(&video, "output/chapters/")
        .await?;

    for path in &chapter_files {
        println!("Chapter file: {}", path.display());
    }

    Ok(())
}
```

### πŸ”΄ Live Stream Recording (Feature: `live-recording`)

Record live streams using either the pure-Rust reqwest engine or FFmpeg as a fallback.
Enable the feature in your `Cargo.toml`:

```toml
[dependencies]
yt-dlp = { version = "2.4.0", features = ["live-recording"] }
```

#### πŸ“₯ Basic live recording (reqwest engine)

```rust,ignore
use yt_dlp::Downloader;
use yt_dlp::client::deps::Libraries;
use std::path::PathBuf;
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries = Libraries::new(
        PathBuf::from("libs/yt-dlp"),
        PathBuf::from("libs/ffmpeg"),
    );
    let downloader = Downloader::builder(libraries, "output").build().await?;

    let video = downloader.fetch_video_infos("https://youtube.com/watch?v=LIVE_ID").await?;

    // Record for 1 hour maximum
    let result = downloader.record_live(&video, "live-recording.ts")
        .with_max_duration(Duration::from_secs(3600))
        .execute()
        .await?;

    println!("Recorded {} bytes in {:.1}s", result.total_bytes, result.total_duration.as_secs_f64());
    Ok(())
}
```

#### 🎬 FFmpeg fallback engine

```rust,ignore
use yt_dlp::Downloader;
use yt_dlp::events::RecordingMethod;
use yt_dlp::client::deps::Libraries;
use std::path::PathBuf;
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries = Libraries::new(
        PathBuf::from("libs/yt-dlp"),
        PathBuf::from("libs/ffmpeg"),
    );
    let downloader = Downloader::builder(libraries, "output").build().await?;

    let video = downloader.fetch_video_infos("https://youtube.com/watch?v=LIVE_ID").await?;

    let result = downloader.record_live(&video, "live-recording.ts")
        .with_method(RecordingMethod::Fallback)
        .with_max_duration(Duration::from_secs(600))
        .execute()
        .await?;

    Ok(())
}
```

**Implementation details:**
- **Reqwest engine** (default): Pure-Rust HLS segment fetcher. Polls the media playlist, downloads new segments, and writes them sequentially. Zero-copy `bytes::Bytes`, progress events throttled at 50 ms.
- **FFmpeg engine** (fallback): Spawns `ffmpeg -i <url> -c copy <output>`. Stops gracefully via stdin `q`. Useful for encrypted streams or complex HLS features.
- Recording stops on cancellation token, `#EXT-X-ENDLIST`, or max duration.
- Live events: `LiveRecordingStarted`, `LiveRecordingProgress`, `LiveRecordingStopped`, `LiveRecordingFailed`.

### 🎨 Post-Processing Options

Apply advanced post-processing to videos using FFmpeg:

#### πŸ”§ Basic codec conversion

- πŸ”§ Converting video codec and bitrate:
```rust,no_run
use yt_dlp::Downloader;
use yt_dlp::download::postprocess::{PostProcessConfig, VideoCodec, AudioCodec};
use yt_dlp::client::deps::Libraries;
use std::path::PathBuf;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    let libraries = Libraries::new(
        libraries_dir.join("yt-dlp"),
        libraries_dir.join("ffmpeg")
    );
    let downloader = Downloader::builder(libraries, output_dir).build().await?;

    // Configure post-processing
    let config = PostProcessConfig::new()
        .with_video_codec(VideoCodec::H264)
        .with_audio_codec(AudioCodec::AAC)
        .with_video_bitrate("2M")
        .with_audio_bitrate("192k");

    // Apply to existing video
    downloader.postprocess_video("input.mp4", "output.mp4", config).await?;

    Ok(())
}
```

#### πŸŽ›οΈ Advanced post-processing with filters

- πŸŽ›οΈ Applying resolution, framerate, and visual filters:
```rust,no_run
use yt_dlp::Downloader;
use yt_dlp::download::postprocess::{
    PostProcessConfig, VideoCodec, Resolution, EncodingPreset,
    FfmpegFilter, WatermarkPosition
};
use yt_dlp::client::deps::Libraries;
use std::path::PathBuf;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    let libraries = Libraries::new(
        libraries_dir.join("yt-dlp"),
        libraries_dir.join("ffmpeg")
    );
    let downloader = Downloader::builder(libraries, output_dir).build().await?;

    // Advanced configuration with filters
    let config = PostProcessConfig::new()
        .with_video_codec(VideoCodec::H265)
        .with_resolution(Resolution::HD)
        .with_framerate(30)
        .with_preset(EncodingPreset::Medium)
        .add_filter(FfmpegFilter::Brightness { value: 0.1 })
        .add_filter(FfmpegFilter::Contrast { value: 1.2 })
        .add_filter(FfmpegFilter::Watermark {
            path: "logo.png".to_string(),
            position: WatermarkPosition::BottomRight,
        });

    downloader.postprocess_video("input.mp4", "processed.mp4", config).await?;

    Ok(())
}
```

#### πŸ“‹ Available post-processing options

**Video Codecs:**
- H.264 (libx264) - Most compatible
- H.265 (libx265) - Better compression
- VP9 (libvpx-vp9) - Open format
- AV1 (libaom-av1) - Next-gen codec
- Copy - No re-encoding

**Audio Codecs:**
- AAC - High quality, widely supported
- MP3 (libmp3lame) - Universal compatibility
- Opus - Best quality/size ratio
- Vorbis - Open format
- Copy - No re-encoding

**Resolutions:**
- UHD8K (7680x4320)
- UHD4K (3840x2160)
- QHD (2560x1440)
- FullHD (1920x1080)
- HD (1280x720)
- SD (854x480)
- Low (640x360)
- Custom { width, height }

**Encoding Presets:**
- UltraFast, SuperFast, VeryFast, Fast
- Medium (balanced)
- Slow, Slower, VerySlow (best quality)

**Video Filters:**
- **Crop**: `Crop { width, height, x, y }`
- **Rotate**: `Rotate { angle }` (in degrees)
- **Watermark**: `Watermark { path, position }`
- **Brightness**: `Brightness { value }` (-1.0 to 1.0)
- **Contrast**: `Contrast { value }` (0.0 to 4.0)
- **Saturation**: `Saturation { value }` (0.0 to 3.0)
- **Blur**: `Blur { radius }`
- **FlipHorizontal**, **FlipVertical**
- **Denoise**, **Sharpen**
- **Custom**: `Custom { filter }` - Any FFmpeg filter string

### ⚑ Speed Profiles

The library includes an intelligent speed optimization system that automatically configures download parameters based on your internet connection speed. This feature significantly improves download performance for both individual videos and playlists.

#### πŸ“Š Available Speed Profiles

Three pre-configured profiles are available:

**🐒 Conservative** (for connections < 50 Mbps)
- 3 concurrent downloads
- 4-8 parallel segments per file
- 5 MB segment size
- 10 MB buffer
- 2 concurrent playlist downloads
- Best for: Standard internet, avoiding network congestion, limited bandwidth

**βš–οΈ Balanced** (for connections 50-500 Mbps) - **Default**
- 4 concurrent downloads
- 5–20 parallel segments per file
- 8 MB segment size
- 20 MB buffer
- 3 concurrent playlist downloads
- Best for: Most modern internet connections, general use

**πŸš€ Aggressive** (for connections > 500 Mbps)
- 6 concurrent downloads
- 6–24 parallel segments per file
- 10 MB segment size
- 30 MB buffer
- 5 concurrent playlist downloads
- Best for: High-bandwidth connections (fiber, gigabit), maximum speed

#### πŸš€ Using Speed Profiles

- πŸš€ Selecting a speed profile at build time:
```rust,no_run
use yt_dlp::Downloader;
use yt_dlp::download::SpeedProfile;
use yt_dlp::client::deps::Libraries;
use std::path::PathBuf;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    let libraries = Libraries::new(
        libraries_dir.join("yt-dlp"),
        libraries_dir.join("ffmpeg")
    );

    // Use the Aggressive profile for maximum speed
    let downloader = Downloader::builder(libraries, output_dir)
        .with_speed_profile(SpeedProfile::Aggressive)
        .build()
        .await?;

    // All downloads will now use optimized settings
    let url = String::from("https://www.youtube.com/watch?v=gXtp6C-3JKo");
    let video = downloader.fetch_video_infos(url).await?;
    downloader.download_video(&video, "video.mp4").await?;

    Ok(())
}
```

#### βš™οΈ Manual Configuration

- βš™οΈ Fine-grained control over download parameters:
```rust,no_run
use yt_dlp::Downloader;
use yt_dlp::download::ManagerConfig;
use yt_dlp::client::deps::Libraries;
use std::path::PathBuf;

#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries_dir = PathBuf::from("libs");
    let output_dir = PathBuf::from("output");

    let libraries = Libraries::new(
        libraries_dir.join("yt-dlp"),
        libraries_dir.join("ffmpeg")
    );

    // Create a custom configuration
    let config = ManagerConfig::builder()
        .max_concurrent_downloads(10)   // 10 concurrent downloads
        .segment_size(15 * 1024 * 1024) // 15 MB segments
        .parallel_segments(16)          // 16 parallel segments
        .build();

    let downloader = Downloader::builder(libraries, output_dir)
        .with_download_manager_config(config)
        .build()
        .await?;

    Ok(())
}
```

#### πŸ“ˆ Performance Improvements

The speed optimization system includes several advanced features:

- **HTTP/2 Support**: Automatically enabled for better connection multiplexing
- **Transparent Compression**: Responses are automatically decompressed (gzip, brotli) for faster transfers
- **TCP Nodelay**: Nagle's algorithm is disabled for lower latency on small writes
- **CDN-Friendly Range Probing**: Uses `GET` with `Range: bytes=0-0` instead of `HEAD` for better CDN compatibility
- **Progress Throttling**: Progress callbacks are throttled to 50 ms intervals to reduce overhead
- **Parallel Playlist Downloads**: Playlists are downloaded in parallel by default (previously sequential)
- **Dynamic Segment Allocation**: Automatically adjusts the number of parallel segments based on file size
- **Connection Pooling**: Reuses HTTP connections for better performance
- **Intelligent Buffering**: Optimized buffer sizes based on your profile
- **Async DNS** *(opt-in)*: Enable the `hickory-dns` feature for a fully async, pure-Rust DNS resolver

**Expected Performance Gains:**

For individual videos:
- Conservative: ~30% faster (HTTP/2)
- Balanced: ~100% faster (2x segments + HTTP/2)
- Aggressive: ~200% faster (3x segments + HTTP/2)

For playlists:
- Conservative: ~150% faster (2 videos in parallel)
- Balanced: ~200% faster (3 videos in parallel)
- Aggressive: ~400% faster (5 videos in parallel)

**Note**: Actual performance gains depend on your internet speed, server limitations, and network conditions.

## 🌍 Multi-Site Support

**This library supports all 1,800+ extractors from yt-dlp!**

While the examples focus on YouTube (the most common use case), the library works seamlessly with any site supported by yt-dlp. Simply pass the URL - yt-dlp automatically detects the correct extractor.

### πŸ—‚οΈ Supported Sites

- **Video platforms**: YouTube, Vimeo, Dailymotion, Twitch
- **Social media**: Instagram, TikTok, Twitter/X, Facebook
- **Streaming services**: Netflix, Disney+, Crunchyroll (may require authentication)
- **Music platforms**: Spotify, SoundCloud, Bandcamp
- **News outlets**: CNN, BBC, Fox News
- **And 1,800+ more...**

For the complete list, see [yt-dlp's supported sites](https://github.com/yt-dlp/yt-dlp/blob/master/supportedsites.md).

### 🧩 Examples

- 🎬 Downloading from Vimeo:
```rust,no_run
use yt_dlp::Downloader;
use yt_dlp::client::deps::Libraries;
use std::path::PathBuf;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries = Libraries::new(PathBuf::from("libs/yt-dlp"), PathBuf::from("libs/ffmpeg"));
    let downloader = Downloader::builder(libraries, PathBuf::from("output")).build().await?;

    let url = "https://vimeo.com/148751763".to_string();
    let video = downloader.fetch_video_infos(url).await?;
    downloader.download_video(&video, "vimeo-video.mp4").await?;

    Ok(())
}
```

- πŸ“± Downloading from TikTok:
```rust,no_run
use yt_dlp::Downloader;
use yt_dlp::client::deps::Libraries;
use std::path::PathBuf;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries = Libraries::new(PathBuf::from("libs/yt-dlp"), PathBuf::from("libs/ffmpeg"));
    let downloader = Downloader::builder(libraries, PathBuf::from("output")).build().await?;

    let url = "https://www.tiktok.com/@user/video/123".to_string();
    let video = downloader.fetch_video_infos(url).await?;
    downloader.download_video(&video, "tiktok-video.mp4").await?;

    Ok(())
}
```

- πŸ“Έ Downloading from Instagram (may require cookies for authentication):
```rust,no_run
use yt_dlp::Downloader;
use yt_dlp::client::deps::Libraries;
use std::path::PathBuf;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries = Libraries::new(PathBuf::from("libs/yt-dlp"), PathBuf::from("libs/ffmpeg"));
    let downloader = Downloader::builder(libraries, PathBuf::from("output")).build().await?;

    let url = "https://www.instagram.com/p/ABC123/".to_string();
    let video = downloader.fetch_video_infos(url).await?;

    Ok(())
}
```

- πŸ” Detecting which extractor handles a URL:
```rust,no_run
use yt_dlp::Downloader;
use yt_dlp::client::deps::Libraries;
use std::path::PathBuf;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let libraries = Libraries::new(
        PathBuf::from("libs/yt-dlp"),
        PathBuf::from("libs/ffmpeg")
    );
    let downloader = Downloader::builder(libraries, "output").build().await?;
    let extractor = downloader.detect_extractor("https://vimeo.com/123").await?;
    println!("This URL uses the '{}' extractor", extractor);
    Ok(())
}
```

For detailed documentation, examples, and authentication instructions, see the [`extractor`](https://docs.rs/yt-dlp/latest/yt_dlp/extractor/) module documentation.

## πŸ”¬ Profiling (Feature: `profiling`)

See [PROFILING.md](PROFILING.md) for the complete guide (flamegraph, samply, dhat-rs, heaptrack, Criterion, and the raw vs library comparison tool).

---

## 🏎️ Performances

The library fetches video metadata via `yt-dlp --dump-json`, then **downloads format streams
directly over HTTP using parallel segments** β€” bypassing yt-dlp's sequential download engine.
Run [`examples/compare.rs`](#-profiling-feature-profiling) with any public YouTube URL to
reproduce these numbers on your own connection:

```bash
cargo run --example compare --features profiling --release -- https://www.youtube.com/watch?v=gXtp6C-3JKo --cookies-from-browser safari --runs 10
```

> Results below are averages over 10 runs on a typical broadband connection.
>
> **Methodology**: raw `yt-dlp` re-fetches metadata on every download. The library fetches metadata
> **once**, caches it, and then downloads each format via parallel HTTP segments β€” this separation
> is the core optimisation reflected in the results below.

### 🎡 Audio streams

| Scenario | `yt-dlp` | Conservative | Balanced *(default)* | Aggressive |
|---|---|---|---|---|
| Audio 96 kbps (Low) | 8.26s | 1.27s | 1.47s | 1.27s |
| Audio 128 kbps (Medium) | 7.83s | 1.11s | 1.12s | 1.18s |
| Audio 192 kbps (High) | 8.53s | 1.38s | 1.26s | 1.19s |
| Audio best quality | 8.51s | 1.22s | 1.15s | 1.15s |

### 🎬 Video streams (no audio)

| Scenario | `yt-dlp` | Conservative | Balanced *(default)* | Aggressive |
|---|---|---|---|---|
| Video 480p | 8.59s | 2.39s | 2.11s | 2.58s |
| Video 720p | 9.84s | 3.67s | 3.86s | 3.89s |
| Video 1080p | 17.6s | 8.65s | 8.60s | 8.81s |
| Video best quality | 16.6s | 11.7s | 11.8s | 12.0s |

### πŸ“¦ Muxed streams β€” native (YouTube pre-muxed, no ffmpeg)

YouTube serves some formats already containing both video and audio tracks. No post-processing
is needed β€” the file is downloaded as-is.

| Scenario | `yt-dlp` | Conservative | Balanced *(default)* | Aggressive |
|---|---|---|---|---|
| Native 360p (mp4) | 9.69s | 2.11s | 2.00s | 2.16s |
| Native 720p (mp4) | 20.7s | 2.08s | 2.10s | 2.06s |

### πŸ“¦ Muxed streams β€” combined by ffmpeg

For higher-quality streams, YouTube only provides separate video and audio tracks. The library
downloads both in parallel, then ffmpeg merges them using **stream copy** (no re-encoding) when
the audio container is compatible with the output format (e.g. AAC/m4a β†’ mp4).

| Scenario | `yt-dlp` | Conservative | Balanced *(default)* | Aggressive |
|---|---|---|---|---|
| Muxed 480p | 9.41s | 3.51s | 3.48s | 3.34s |
| Muxed 720p | 10.4s | 4.95s | 4.92s | 4.97s |
| Muxed 1080p | 18.3s | 10.4s | 10.5s | 10.3s |
| Muxed best quality | 18.2s | 13.7s | 13.7s | 13.3s |

### πŸš€ Speed profiles

| Profile | Parallel segments | Segment size | Use case |
|---|---|---|---|
| `Conservative` | 1–16 | 5 MB | < 50 Mbps connections |
| `Balanced` *(default)* | 2–20 | 8 MB | Most modern connections |
| `Aggressive` | 3–24 | 10 MB | Fibre / gigabit |

See [PROFILING.md](PROFILING.md) for detailed micro-benchmarks.

---

## πŸ’‘Features coming soon
- [ ] Cargo profile configuration for optimized release builds
- [ ] Use `rust-ffmpeg` as safe bindings instead of commands, and keep Command fallback as a feature flag
- [ ] Full test suite, with fake server (due to anti-bot measures)
- [x] Clip extraction (download a specific time range)
- [ ] Bandwidth throttling (limit download speed)
- [x] Chapter-based splitting (split video into chapter files)
- [ ] Download queue persistence (resume queue across restarts)
- [ ] SponsorBlock integration (skip/mark sponsor segments)

---

## πŸ” The `media-seek` crate

This library uses [`media-seek`](crates/media-seek/README.md), a standalone sub-crate published independently on crates.io, for container index parsing. When you use clip extraction or chapter range downloads, `media-seek` parses the stream header to find the exact byte offsets β€” no subprocess, no FFmpeg involved for the seek step.

**Supported container formats**: MP4/M4A (fMP4 SIDX), WebM/MKV (EBML Cues), MP3 (Xing/VBRI TOC or CBR), OGG (granule bisection), FLAC (SEEKTABLE), WAV, AIFF, AAC/ADTS, FLV (AMF0 keyframes), AVI (`idx1`), MPEG-TS (PCR binary search).

You can also use `media-seek` directly in your own project:

```toml
[dependencies]
media-seek = "0.2.6"
```

See the [`media-seek` README](crates/media-seek/README.md) for the full API reference and usage examples.

---

## 🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.
Make sure to follow the [Contributing Guidelines](CONTRIBUTING.md).

## πŸ“„ License

This project is licensed under the [GPL-3.0 License](LICENSE.md).