test_YoutubeDL.py 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401
  1. #!/usr/bin/env python3
  2. # Allow direct execution
  3. import os
  4. import sys
  5. import unittest
  6. from unittest.mock import patch
  7. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  8. import contextlib
  9. import copy
  10. import json
  11. from test.helper import FakeYDL, assertRegexpMatches, try_rm
  12. from yt_dlp import YoutubeDL
  13. from yt_dlp.compat import compat_os_name
  14. from yt_dlp.extractor import YoutubeIE
  15. from yt_dlp.extractor.common import InfoExtractor
  16. from yt_dlp.postprocessor.common import PostProcessor
  17. from yt_dlp.utils import (
  18. ExtractorError,
  19. LazyList,
  20. OnDemandPagedList,
  21. int_or_none,
  22. match_filter_func,
  23. )
  24. from yt_dlp.utils.traversal import traverse_obj
  25. TEST_URL = 'http://localhost/sample.mp4'
  26. class YDL(FakeYDL):
  27. def __init__(self, *args, **kwargs):
  28. super().__init__(*args, **kwargs)
  29. self.downloaded_info_dicts = []
  30. self.msgs = []
  31. def process_info(self, info_dict):
  32. self.downloaded_info_dicts.append(info_dict.copy())
  33. def to_screen(self, msg, *args, **kwargs):
  34. self.msgs.append(msg)
  35. def dl(self, *args, **kwargs):
  36. assert False, 'Downloader must not be invoked for test_YoutubeDL'
  37. def _make_result(formats, **kwargs):
  38. res = {
  39. 'formats': formats,
  40. 'id': 'testid',
  41. 'title': 'testttitle',
  42. 'extractor': 'testex',
  43. 'extractor_key': 'TestEx',
  44. 'webpage_url': 'http://example.com/watch?v=shenanigans',
  45. }
  46. res.update(**kwargs)
  47. return res
  48. class TestFormatSelection(unittest.TestCase):
  49. def test_prefer_free_formats(self):
  50. # Same resolution => download webm
  51. ydl = YDL()
  52. ydl.params['prefer_free_formats'] = True
  53. formats = [
  54. {'ext': 'webm', 'height': 460, 'url': TEST_URL},
  55. {'ext': 'mp4', 'height': 460, 'url': TEST_URL},
  56. ]
  57. info_dict = _make_result(formats)
  58. ydl.sort_formats(info_dict)
  59. ydl.process_ie_result(info_dict)
  60. downloaded = ydl.downloaded_info_dicts[0]
  61. self.assertEqual(downloaded['ext'], 'webm')
  62. # Different resolution => download best quality (mp4)
  63. ydl = YDL()
  64. ydl.params['prefer_free_formats'] = True
  65. formats = [
  66. {'ext': 'webm', 'height': 720, 'url': TEST_URL},
  67. {'ext': 'mp4', 'height': 1080, 'url': TEST_URL},
  68. ]
  69. info_dict['formats'] = formats
  70. ydl.sort_formats(info_dict)
  71. ydl.process_ie_result(info_dict)
  72. downloaded = ydl.downloaded_info_dicts[0]
  73. self.assertEqual(downloaded['ext'], 'mp4')
  74. # No prefer_free_formats => prefer mp4 and webm
  75. ydl = YDL()
  76. ydl.params['prefer_free_formats'] = False
  77. formats = [
  78. {'ext': 'webm', 'height': 720, 'url': TEST_URL},
  79. {'ext': 'mp4', 'height': 720, 'url': TEST_URL},
  80. {'ext': 'flv', 'height': 720, 'url': TEST_URL},
  81. ]
  82. info_dict['formats'] = formats
  83. ydl.sort_formats(info_dict)
  84. ydl.process_ie_result(info_dict)
  85. downloaded = ydl.downloaded_info_dicts[0]
  86. self.assertEqual(downloaded['ext'], 'mp4')
  87. ydl = YDL()
  88. ydl.params['prefer_free_formats'] = False
  89. formats = [
  90. {'ext': 'flv', 'height': 720, 'url': TEST_URL},
  91. {'ext': 'webm', 'height': 720, 'url': TEST_URL},
  92. ]
  93. info_dict['formats'] = formats
  94. ydl.sort_formats(info_dict)
  95. ydl.process_ie_result(info_dict)
  96. downloaded = ydl.downloaded_info_dicts[0]
  97. self.assertEqual(downloaded['ext'], 'webm')
  98. def test_format_selection(self):
  99. formats = [
  100. {'format_id': '35', 'ext': 'mp4', 'preference': 0, 'url': TEST_URL},
  101. {'format_id': 'example-with-dashes', 'ext': 'webm', 'preference': 1, 'url': TEST_URL},
  102. {'format_id': '45', 'ext': 'webm', 'preference': 2, 'url': TEST_URL},
  103. {'format_id': '47', 'ext': 'webm', 'preference': 3, 'url': TEST_URL},
  104. {'format_id': '2', 'ext': 'flv', 'preference': 4, 'url': TEST_URL},
  105. ]
  106. info_dict = _make_result(formats)
  107. def test(inp, *expected, multi=False):
  108. ydl = YDL({
  109. 'format': inp,
  110. 'allow_multiple_video_streams': multi,
  111. 'allow_multiple_audio_streams': multi,
  112. })
  113. ydl.process_ie_result(info_dict.copy())
  114. downloaded = [x['format_id'] for x in ydl.downloaded_info_dicts]
  115. self.assertEqual(downloaded, list(expected))
  116. test('20/47', '47')
  117. test('20/71/worst', '35')
  118. test(None, '2')
  119. test('webm/mp4', '47')
  120. test('3gp/40/mp4', '35')
  121. test('example-with-dashes', 'example-with-dashes')
  122. test('all', '2', '47', '45', 'example-with-dashes', '35')
  123. test('mergeall', '2+47+45+example-with-dashes+35', multi=True)
  124. # See: https://github.com/yt-dlp/yt-dlp/pulls/8797
  125. test('7_a/worst', '35')
  126. def test_format_selection_audio(self):
  127. formats = [
  128. {'format_id': 'audio-low', 'ext': 'webm', 'preference': 1, 'vcodec': 'none', 'url': TEST_URL},
  129. {'format_id': 'audio-mid', 'ext': 'webm', 'preference': 2, 'vcodec': 'none', 'url': TEST_URL},
  130. {'format_id': 'audio-high', 'ext': 'flv', 'preference': 3, 'vcodec': 'none', 'url': TEST_URL},
  131. {'format_id': 'vid', 'ext': 'mp4', 'preference': 4, 'url': TEST_URL},
  132. ]
  133. info_dict = _make_result(formats)
  134. ydl = YDL({'format': 'bestaudio'})
  135. ydl.process_ie_result(info_dict.copy())
  136. downloaded = ydl.downloaded_info_dicts[0]
  137. self.assertEqual(downloaded['format_id'], 'audio-high')
  138. ydl = YDL({'format': 'worstaudio'})
  139. ydl.process_ie_result(info_dict.copy())
  140. downloaded = ydl.downloaded_info_dicts[0]
  141. self.assertEqual(downloaded['format_id'], 'audio-low')
  142. formats = [
  143. {'format_id': 'vid-low', 'ext': 'mp4', 'preference': 1, 'url': TEST_URL},
  144. {'format_id': 'vid-high', 'ext': 'mp4', 'preference': 2, 'url': TEST_URL},
  145. ]
  146. info_dict = _make_result(formats)
  147. ydl = YDL({'format': 'bestaudio/worstaudio/best'})
  148. ydl.process_ie_result(info_dict.copy())
  149. downloaded = ydl.downloaded_info_dicts[0]
  150. self.assertEqual(downloaded['format_id'], 'vid-high')
  151. def test_format_selection_audio_exts(self):
  152. formats = [
  153. {'format_id': 'mp3-64', 'ext': 'mp3', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
  154. {'format_id': 'ogg-64', 'ext': 'ogg', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
  155. {'format_id': 'aac-64', 'ext': 'aac', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
  156. {'format_id': 'mp3-32', 'ext': 'mp3', 'abr': 32, 'url': 'http://_', 'vcodec': 'none'},
  157. {'format_id': 'aac-32', 'ext': 'aac', 'abr': 32, 'url': 'http://_', 'vcodec': 'none'},
  158. ]
  159. info_dict = _make_result(formats)
  160. ydl = YDL({'format': 'best', 'format_sort': ['abr', 'ext']})
  161. ydl.sort_formats(info_dict)
  162. ydl.process_ie_result(copy.deepcopy(info_dict))
  163. downloaded = ydl.downloaded_info_dicts[0]
  164. self.assertEqual(downloaded['format_id'], 'aac-64')
  165. ydl = YDL({'format': 'mp3'})
  166. ydl.sort_formats(info_dict)
  167. ydl.process_ie_result(copy.deepcopy(info_dict))
  168. downloaded = ydl.downloaded_info_dicts[0]
  169. self.assertEqual(downloaded['format_id'], 'mp3-64')
  170. ydl = YDL({'prefer_free_formats': True, 'format_sort': ['abr', 'ext']})
  171. ydl.sort_formats(info_dict)
  172. ydl.process_ie_result(copy.deepcopy(info_dict))
  173. downloaded = ydl.downloaded_info_dicts[0]
  174. self.assertEqual(downloaded['format_id'], 'ogg-64')
  175. def test_format_selection_video(self):
  176. formats = [
  177. {'format_id': 'dash-video-low', 'ext': 'mp4', 'preference': 1, 'acodec': 'none', 'url': TEST_URL},
  178. {'format_id': 'dash-video-high', 'ext': 'mp4', 'preference': 2, 'acodec': 'none', 'url': TEST_URL},
  179. {'format_id': 'vid', 'ext': 'mp4', 'preference': 3, 'url': TEST_URL},
  180. ]
  181. info_dict = _make_result(formats)
  182. ydl = YDL({'format': 'bestvideo'})
  183. ydl.process_ie_result(info_dict.copy())
  184. downloaded = ydl.downloaded_info_dicts[0]
  185. self.assertEqual(downloaded['format_id'], 'dash-video-high')
  186. ydl = YDL({'format': 'worstvideo'})
  187. ydl.process_ie_result(info_dict.copy())
  188. downloaded = ydl.downloaded_info_dicts[0]
  189. self.assertEqual(downloaded['format_id'], 'dash-video-low')
  190. ydl = YDL({'format': 'bestvideo[format_id^=dash][format_id$=low]'})
  191. ydl.process_ie_result(info_dict.copy())
  192. downloaded = ydl.downloaded_info_dicts[0]
  193. self.assertEqual(downloaded['format_id'], 'dash-video-low')
  194. formats = [
  195. {'format_id': 'vid-vcodec-dot', 'ext': 'mp4', 'preference': 1, 'vcodec': 'avc1.123456', 'acodec': 'none', 'url': TEST_URL},
  196. ]
  197. info_dict = _make_result(formats)
  198. ydl = YDL({'format': 'bestvideo[vcodec=avc1.123456]'})
  199. ydl.process_ie_result(info_dict.copy())
  200. downloaded = ydl.downloaded_info_dicts[0]
  201. self.assertEqual(downloaded['format_id'], 'vid-vcodec-dot')
  202. def test_format_selection_by_vcodec_sort(self):
  203. formats = [
  204. {'format_id': 'av1-format', 'ext': 'mp4', 'vcodec': 'av1', 'acodec': 'none', 'url': TEST_URL},
  205. {'format_id': 'vp9-hdr-format', 'ext': 'mp4', 'vcodec': 'vp09.02.50.10.01.09.18.09.00', 'acodec': 'none', 'url': TEST_URL},
  206. {'format_id': 'vp9-sdr-format', 'ext': 'mp4', 'vcodec': 'vp09.00.50.08', 'acodec': 'none', 'url': TEST_URL},
  207. {'format_id': 'h265-format', 'ext': 'mp4', 'vcodec': 'h265', 'acodec': 'none', 'url': TEST_URL},
  208. ]
  209. info_dict = _make_result(formats)
  210. ydl = YDL({'format': 'bestvideo', 'format_sort': ['vcodec:vp9.2']})
  211. ydl.process_ie_result(info_dict.copy())
  212. downloaded = ydl.downloaded_info_dicts[0]
  213. self.assertEqual(downloaded['format_id'], 'vp9-hdr-format')
  214. ydl = YDL({'format': 'bestvideo', 'format_sort': ['vcodec:vp9']})
  215. ydl.process_ie_result(info_dict.copy())
  216. downloaded = ydl.downloaded_info_dicts[0]
  217. self.assertEqual(downloaded['format_id'], 'vp9-sdr-format')
  218. ydl = YDL({'format': 'bestvideo', 'format_sort': ['+vcodec:vp9.2']})
  219. ydl.process_ie_result(info_dict.copy())
  220. downloaded = ydl.downloaded_info_dicts[0]
  221. self.assertEqual(downloaded['format_id'], 'vp9-hdr-format')
  222. ydl = YDL({'format': 'bestvideo', 'format_sort': ['+vcodec:vp9']})
  223. ydl.process_ie_result(info_dict.copy())
  224. downloaded = ydl.downloaded_info_dicts[0]
  225. self.assertEqual(downloaded['format_id'], 'vp9-sdr-format')
  226. def test_format_selection_string_ops(self):
  227. formats = [
  228. {'format_id': 'abc-cba', 'ext': 'mp4', 'url': TEST_URL},
  229. {'format_id': 'zxc-cxz', 'ext': 'webm', 'url': TEST_URL},
  230. ]
  231. info_dict = _make_result(formats)
  232. # equals (=)
  233. ydl = YDL({'format': '[format_id=abc-cba]'})
  234. ydl.process_ie_result(info_dict.copy())
  235. downloaded = ydl.downloaded_info_dicts[0]
  236. self.assertEqual(downloaded['format_id'], 'abc-cba')
  237. # does not equal (!=)
  238. ydl = YDL({'format': '[format_id!=abc-cba]'})
  239. ydl.process_ie_result(info_dict.copy())
  240. downloaded = ydl.downloaded_info_dicts[0]
  241. self.assertEqual(downloaded['format_id'], 'zxc-cxz')
  242. ydl = YDL({'format': '[format_id!=abc-cba][format_id!=zxc-cxz]'})
  243. self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
  244. # starts with (^=)
  245. ydl = YDL({'format': '[format_id^=abc]'})
  246. ydl.process_ie_result(info_dict.copy())
  247. downloaded = ydl.downloaded_info_dicts[0]
  248. self.assertEqual(downloaded['format_id'], 'abc-cba')
  249. # does not start with (!^=)
  250. ydl = YDL({'format': '[format_id!^=abc]'})
  251. ydl.process_ie_result(info_dict.copy())
  252. downloaded = ydl.downloaded_info_dicts[0]
  253. self.assertEqual(downloaded['format_id'], 'zxc-cxz')
  254. ydl = YDL({'format': '[format_id!^=abc][format_id!^=zxc]'})
  255. self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
  256. # ends with ($=)
  257. ydl = YDL({'format': '[format_id$=cba]'})
  258. ydl.process_ie_result(info_dict.copy())
  259. downloaded = ydl.downloaded_info_dicts[0]
  260. self.assertEqual(downloaded['format_id'], 'abc-cba')
  261. # does not end with (!$=)
  262. ydl = YDL({'format': '[format_id!$=cba]'})
  263. ydl.process_ie_result(info_dict.copy())
  264. downloaded = ydl.downloaded_info_dicts[0]
  265. self.assertEqual(downloaded['format_id'], 'zxc-cxz')
  266. ydl = YDL({'format': '[format_id!$=cba][format_id!$=cxz]'})
  267. self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
  268. # contains (*=)
  269. ydl = YDL({'format': '[format_id*=bc-cb]'})
  270. ydl.process_ie_result(info_dict.copy())
  271. downloaded = ydl.downloaded_info_dicts[0]
  272. self.assertEqual(downloaded['format_id'], 'abc-cba')
  273. # does not contain (!*=)
  274. ydl = YDL({'format': '[format_id!*=bc-cb]'})
  275. ydl.process_ie_result(info_dict.copy())
  276. downloaded = ydl.downloaded_info_dicts[0]
  277. self.assertEqual(downloaded['format_id'], 'zxc-cxz')
  278. ydl = YDL({'format': '[format_id!*=abc][format_id!*=zxc]'})
  279. self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
  280. ydl = YDL({'format': '[format_id!*=-]'})
  281. self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
  282. def test_youtube_format_selection(self):
  283. # FIXME: Rewrite in accordance with the new format sorting options
  284. return
  285. order = [
  286. '38', '37', '46', '22', '45', '35', '44', '18', '34', '43', '6', '5', '17', '36', '13',
  287. # Apple HTTP Live Streaming
  288. '96', '95', '94', '93', '92', '132', '151',
  289. # 3D
  290. '85', '84', '102', '83', '101', '82', '100',
  291. # Dash video
  292. '137', '248', '136', '247', '135', '246',
  293. '245', '244', '134', '243', '133', '242', '160',
  294. # Dash audio
  295. '141', '172', '140', '171', '139',
  296. ]
  297. def format_info(f_id):
  298. info = YoutubeIE._formats[f_id].copy()
  299. # XXX: In real cases InfoExtractor._parse_mpd_formats() fills up 'acodec'
  300. # and 'vcodec', while in tests such information is incomplete since
  301. # commit a6c2c24479e5f4827ceb06f64d855329c0a6f593
  302. # test_YoutubeDL.test_youtube_format_selection is broken without
  303. # this fix
  304. if 'acodec' in info and 'vcodec' not in info:
  305. info['vcodec'] = 'none'
  306. elif 'vcodec' in info and 'acodec' not in info:
  307. info['acodec'] = 'none'
  308. info['format_id'] = f_id
  309. info['url'] = 'url:' + f_id
  310. return info
  311. formats_order = [format_info(f_id) for f_id in order]
  312. info_dict = _make_result(list(formats_order), extractor='youtube')
  313. ydl = YDL({'format': 'bestvideo+bestaudio'})
  314. ydl.sort_formats(info_dict)
  315. ydl.process_ie_result(info_dict)
  316. downloaded = ydl.downloaded_info_dicts[0]
  317. self.assertEqual(downloaded['format_id'], '248+172')
  318. self.assertEqual(downloaded['ext'], 'mp4')
  319. info_dict = _make_result(list(formats_order), extractor='youtube')
  320. ydl = YDL({'format': 'bestvideo[height>=999999]+bestaudio/best'})
  321. ydl.sort_formats(info_dict)
  322. ydl.process_ie_result(info_dict)
  323. downloaded = ydl.downloaded_info_dicts[0]
  324. self.assertEqual(downloaded['format_id'], '38')
  325. info_dict = _make_result(list(formats_order), extractor='youtube')
  326. ydl = YDL({'format': 'bestvideo/best,bestaudio'})
  327. ydl.sort_formats(info_dict)
  328. ydl.process_ie_result(info_dict)
  329. downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
  330. self.assertEqual(downloaded_ids, ['137', '141'])
  331. info_dict = _make_result(list(formats_order), extractor='youtube')
  332. ydl = YDL({'format': '(bestvideo[ext=mp4],bestvideo[ext=webm])+bestaudio'})
  333. ydl.sort_formats(info_dict)
  334. ydl.process_ie_result(info_dict)
  335. downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
  336. self.assertEqual(downloaded_ids, ['137+141', '248+141'])
  337. info_dict = _make_result(list(formats_order), extractor='youtube')
  338. ydl = YDL({'format': '(bestvideo[ext=mp4],bestvideo[ext=webm])[height<=720]+bestaudio'})
  339. ydl.sort_formats(info_dict)
  340. ydl.process_ie_result(info_dict)
  341. downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
  342. self.assertEqual(downloaded_ids, ['136+141', '247+141'])
  343. info_dict = _make_result(list(formats_order), extractor='youtube')
  344. ydl = YDL({'format': '(bestvideo[ext=none]/bestvideo[ext=webm])+bestaudio'})
  345. ydl.sort_formats(info_dict)
  346. ydl.process_ie_result(info_dict)
  347. downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
  348. self.assertEqual(downloaded_ids, ['248+141'])
  349. for f1, f2 in zip(formats_order, formats_order[1:]):
  350. info_dict = _make_result([f1, f2], extractor='youtube')
  351. ydl = YDL({'format': 'best/bestvideo'})
  352. ydl.sort_formats(info_dict)
  353. ydl.process_ie_result(info_dict)
  354. downloaded = ydl.downloaded_info_dicts[0]
  355. self.assertEqual(downloaded['format_id'], f1['format_id'])
  356. info_dict = _make_result([f2, f1], extractor='youtube')
  357. ydl = YDL({'format': 'best/bestvideo'})
  358. ydl.sort_formats(info_dict)
  359. ydl.process_ie_result(info_dict)
  360. downloaded = ydl.downloaded_info_dicts[0]
  361. self.assertEqual(downloaded['format_id'], f1['format_id'])
  362. def test_audio_only_extractor_format_selection(self):
  363. # For extractors with incomplete formats (all formats are audio-only or
  364. # video-only) best and worst should fallback to corresponding best/worst
  365. # video-only or audio-only formats (as per
  366. # https://github.com/ytdl-org/youtube-dl/pull/5556)
  367. formats = [
  368. {'format_id': 'low', 'ext': 'mp3', 'preference': 1, 'vcodec': 'none', 'url': TEST_URL},
  369. {'format_id': 'high', 'ext': 'mp3', 'preference': 2, 'vcodec': 'none', 'url': TEST_URL},
  370. ]
  371. info_dict = _make_result(formats)
  372. ydl = YDL({'format': 'best'})
  373. ydl.process_ie_result(info_dict.copy())
  374. downloaded = ydl.downloaded_info_dicts[0]
  375. self.assertEqual(downloaded['format_id'], 'high')
  376. ydl = YDL({'format': 'worst'})
  377. ydl.process_ie_result(info_dict.copy())
  378. downloaded = ydl.downloaded_info_dicts[0]
  379. self.assertEqual(downloaded['format_id'], 'low')
  380. def test_format_not_available(self):
  381. formats = [
  382. {'format_id': 'regular', 'ext': 'mp4', 'height': 360, 'url': TEST_URL},
  383. {'format_id': 'video', 'ext': 'mp4', 'height': 720, 'acodec': 'none', 'url': TEST_URL},
  384. ]
  385. info_dict = _make_result(formats)
  386. # This must fail since complete video-audio format does not match filter
  387. # and extractor does not provide incomplete only formats (i.e. only
  388. # video-only or audio-only).
  389. ydl = YDL({'format': 'best[height>360]'})
  390. self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
  391. def test_format_selection_issue_10083(self):
  392. # See https://github.com/ytdl-org/youtube-dl/issues/10083
  393. formats = [
  394. {'format_id': 'regular', 'height': 360, 'url': TEST_URL},
  395. {'format_id': 'video', 'height': 720, 'acodec': 'none', 'url': TEST_URL},
  396. {'format_id': 'audio', 'vcodec': 'none', 'url': TEST_URL},
  397. ]
  398. info_dict = _make_result(formats)
  399. ydl = YDL({'format': 'best[height>360]/bestvideo[height>360]+bestaudio'})
  400. ydl.process_ie_result(info_dict.copy())
  401. self.assertEqual(ydl.downloaded_info_dicts[0]['format_id'], 'video+audio')
  402. def test_invalid_format_specs(self):
  403. def assert_syntax_error(format_spec):
  404. self.assertRaises(SyntaxError, YDL, {'format': format_spec})
  405. assert_syntax_error('bestvideo,,best')
  406. assert_syntax_error('+bestaudio')
  407. assert_syntax_error('bestvideo+')
  408. assert_syntax_error('/')
  409. assert_syntax_error('[720<height]')
  410. def test_format_filtering(self):
  411. formats = [
  412. {'format_id': 'A', 'filesize': 500, 'width': 1000},
  413. {'format_id': 'B', 'filesize': 1000, 'width': 500},
  414. {'format_id': 'C', 'filesize': 1000, 'width': 400},
  415. {'format_id': 'D', 'filesize': 2000, 'width': 600},
  416. {'format_id': 'E', 'filesize': 3000},
  417. {'format_id': 'F'},
  418. {'format_id': 'G', 'filesize': 1000000},
  419. ]
  420. for f in formats:
  421. f['url'] = 'http://_/'
  422. f['ext'] = 'unknown'
  423. info_dict = _make_result(formats, _format_sort_fields=('id', ))
  424. ydl = YDL({'format': 'best[filesize<3000]'})
  425. ydl.process_ie_result(info_dict)
  426. downloaded = ydl.downloaded_info_dicts[0]
  427. self.assertEqual(downloaded['format_id'], 'D')
  428. ydl = YDL({'format': 'best[filesize<=3000]'})
  429. ydl.process_ie_result(info_dict)
  430. downloaded = ydl.downloaded_info_dicts[0]
  431. self.assertEqual(downloaded['format_id'], 'E')
  432. ydl = YDL({'format': 'best[filesize <= ? 3000]'})
  433. ydl.process_ie_result(info_dict)
  434. downloaded = ydl.downloaded_info_dicts[0]
  435. self.assertEqual(downloaded['format_id'], 'F')
  436. ydl = YDL({'format': 'best [filesize = 1000] [width>450]'})
  437. ydl.process_ie_result(info_dict)
  438. downloaded = ydl.downloaded_info_dicts[0]
  439. self.assertEqual(downloaded['format_id'], 'B')
  440. ydl = YDL({'format': 'best [filesize = 1000] [width!=450]'})
  441. ydl.process_ie_result(info_dict)
  442. downloaded = ydl.downloaded_info_dicts[0]
  443. self.assertEqual(downloaded['format_id'], 'C')
  444. ydl = YDL({'format': '[filesize>?1]'})
  445. ydl.process_ie_result(info_dict)
  446. downloaded = ydl.downloaded_info_dicts[0]
  447. self.assertEqual(downloaded['format_id'], 'G')
  448. ydl = YDL({'format': '[filesize<1M]'})
  449. ydl.process_ie_result(info_dict)
  450. downloaded = ydl.downloaded_info_dicts[0]
  451. self.assertEqual(downloaded['format_id'], 'E')
  452. ydl = YDL({'format': '[filesize<1MiB]'})
  453. ydl.process_ie_result(info_dict)
  454. downloaded = ydl.downloaded_info_dicts[0]
  455. self.assertEqual(downloaded['format_id'], 'G')
  456. ydl = YDL({'format': 'all[width>=400][width<=600]'})
  457. ydl.process_ie_result(info_dict)
  458. downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
  459. self.assertEqual(downloaded_ids, ['D', 'C', 'B'])
  460. ydl = YDL({'format': 'best[height<40]'})
  461. with contextlib.suppress(ExtractorError):
  462. ydl.process_ie_result(info_dict)
  463. self.assertEqual(ydl.downloaded_info_dicts, [])
  464. @patch('yt_dlp.postprocessor.ffmpeg.FFmpegMergerPP.available', False)
  465. def test_default_format_spec_without_ffmpeg(self):
  466. ydl = YDL({})
  467. self.assertEqual(ydl._default_format_spec({}), 'best/bestvideo+bestaudio')
  468. ydl = YDL({'simulate': True})
  469. self.assertEqual(ydl._default_format_spec({}), 'best/bestvideo+bestaudio')
  470. ydl = YDL({})
  471. self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
  472. ydl = YDL({'simulate': True})
  473. self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
  474. ydl = YDL({'outtmpl': '-'})
  475. self.assertEqual(ydl._default_format_spec({}), 'best/bestvideo+bestaudio')
  476. ydl = YDL({})
  477. self.assertEqual(ydl._default_format_spec({}), 'best/bestvideo+bestaudio')
  478. self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
  479. @patch('yt_dlp.postprocessor.ffmpeg.FFmpegMergerPP.available', True)
  480. @patch('yt_dlp.postprocessor.ffmpeg.FFmpegMergerPP.can_merge', lambda _: True)
  481. def test_default_format_spec_with_ffmpeg(self):
  482. ydl = YDL({})
  483. self.assertEqual(ydl._default_format_spec({}), 'bestvideo*+bestaudio/best')
  484. ydl = YDL({'simulate': True})
  485. self.assertEqual(ydl._default_format_spec({}), 'bestvideo*+bestaudio/best')
  486. ydl = YDL({})
  487. self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
  488. ydl = YDL({'simulate': True})
  489. self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
  490. ydl = YDL({'outtmpl': '-'})
  491. self.assertEqual(ydl._default_format_spec({}), 'best/bestvideo+bestaudio')
  492. ydl = YDL({})
  493. self.assertEqual(ydl._default_format_spec({}), 'bestvideo*+bestaudio/best')
  494. self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
  495. class TestYoutubeDL(unittest.TestCase):
  496. def test_subtitles(self):
  497. def s_formats(lang, autocaption=False):
  498. return [{
  499. 'ext': ext,
  500. 'url': f'http://localhost/video.{lang}.{ext}',
  501. '_auto': autocaption,
  502. } for ext in ['vtt', 'srt', 'ass']]
  503. subtitles = {l: s_formats(l) for l in ['en', 'fr', 'es']}
  504. auto_captions = {l: s_formats(l, True) for l in ['it', 'pt', 'es']}
  505. info_dict = {
  506. 'id': 'test',
  507. 'title': 'Test',
  508. 'url': 'http://localhost/video.mp4',
  509. 'subtitles': subtitles,
  510. 'automatic_captions': auto_captions,
  511. 'extractor': 'TEST',
  512. 'webpage_url': 'http://example.com/watch?v=shenanigans',
  513. }
  514. def get_info(params={}):
  515. params.setdefault('simulate', True)
  516. ydl = YDL(params)
  517. ydl.report_warning = lambda *args, **kargs: None
  518. return ydl.process_video_result(info_dict, download=False)
  519. result = get_info()
  520. self.assertFalse(result.get('requested_subtitles'))
  521. self.assertEqual(result['subtitles'], subtitles)
  522. self.assertEqual(result['automatic_captions'], auto_captions)
  523. result = get_info({'writesubtitles': True})
  524. subs = result['requested_subtitles']
  525. self.assertTrue(subs)
  526. self.assertEqual(set(subs.keys()), {'en'})
  527. self.assertTrue(subs['en'].get('data') is None)
  528. self.assertEqual(subs['en']['ext'], 'ass')
  529. result = get_info({'writesubtitles': True, 'subtitlesformat': 'foo/srt'})
  530. subs = result['requested_subtitles']
  531. self.assertEqual(subs['en']['ext'], 'srt')
  532. result = get_info({'writesubtitles': True, 'subtitleslangs': ['es', 'fr', 'it']})
  533. subs = result['requested_subtitles']
  534. self.assertTrue(subs)
  535. self.assertEqual(set(subs.keys()), {'es', 'fr'})
  536. result = get_info({'writesubtitles': True, 'subtitleslangs': ['all', '-en']})
  537. subs = result['requested_subtitles']
  538. self.assertTrue(subs)
  539. self.assertEqual(set(subs.keys()), {'es', 'fr'})
  540. result = get_info({'writesubtitles': True, 'subtitleslangs': ['en', 'fr', '-en']})
  541. subs = result['requested_subtitles']
  542. self.assertTrue(subs)
  543. self.assertEqual(set(subs.keys()), {'fr'})
  544. result = get_info({'writesubtitles': True, 'subtitleslangs': ['-en', 'en']})
  545. subs = result['requested_subtitles']
  546. self.assertTrue(subs)
  547. self.assertEqual(set(subs.keys()), {'en'})
  548. result = get_info({'writesubtitles': True, 'subtitleslangs': ['e.+']})
  549. subs = result['requested_subtitles']
  550. self.assertTrue(subs)
  551. self.assertEqual(set(subs.keys()), {'es', 'en'})
  552. result = get_info({'writesubtitles': True, 'writeautomaticsub': True, 'subtitleslangs': ['es', 'pt']})
  553. subs = result['requested_subtitles']
  554. self.assertTrue(subs)
  555. self.assertEqual(set(subs.keys()), {'es', 'pt'})
  556. self.assertFalse(subs['es']['_auto'])
  557. self.assertTrue(subs['pt']['_auto'])
  558. result = get_info({'writeautomaticsub': True, 'subtitleslangs': ['es', 'pt']})
  559. subs = result['requested_subtitles']
  560. self.assertTrue(subs)
  561. self.assertEqual(set(subs.keys()), {'es', 'pt'})
  562. self.assertTrue(subs['es']['_auto'])
  563. self.assertTrue(subs['pt']['_auto'])
  564. def test_add_extra_info(self):
  565. test_dict = {
  566. 'extractor': 'Foo',
  567. }
  568. extra_info = {
  569. 'extractor': 'Bar',
  570. 'playlist': 'funny videos',
  571. }
  572. YDL.add_extra_info(test_dict, extra_info)
  573. self.assertEqual(test_dict['extractor'], 'Foo')
  574. self.assertEqual(test_dict['playlist'], 'funny videos')
  575. outtmpl_info = {
  576. 'id': '1234',
  577. 'ext': 'mp4',
  578. 'width': None,
  579. 'height': 1080,
  580. 'filesize': 1024,
  581. 'title1': '$PATH',
  582. 'title2': '%PATH%',
  583. 'title3': 'foo/bar\\test',
  584. 'title4': 'foo "bar" test',
  585. 'title5': 'áéí 𝐀',
  586. 'timestamp': 1618488000,
  587. 'duration': 100000,
  588. 'playlist_index': 1,
  589. 'playlist_autonumber': 2,
  590. '__last_playlist_index': 100,
  591. 'n_entries': 10,
  592. 'formats': [
  593. {'id': 'id 1', 'height': 1080, 'width': 1920},
  594. {'id': 'id 2', 'height': 720},
  595. {'id': 'id 3'},
  596. ],
  597. }
  598. def test_prepare_outtmpl_and_filename(self):
  599. def test(tmpl, expected, *, info=None, **params):
  600. params['outtmpl'] = tmpl
  601. ydl = FakeYDL(params)
  602. ydl._num_downloads = 1
  603. self.assertEqual(ydl.validate_outtmpl(tmpl), None)
  604. out = ydl.evaluate_outtmpl(tmpl, info or self.outtmpl_info)
  605. fname = ydl.prepare_filename(info or self.outtmpl_info)
  606. if not isinstance(expected, (list, tuple)):
  607. expected = (expected, expected)
  608. for (name, got), expect in zip((('outtmpl', out), ('filename', fname)), expected):
  609. if callable(expect):
  610. self.assertTrue(expect(got), f'Wrong {name} from {tmpl}')
  611. elif expect is not None:
  612. self.assertEqual(got, expect, f'Wrong {name} from {tmpl}')
  613. # Side-effects
  614. original_infodict = dict(self.outtmpl_info)
  615. test('foo.bar', 'foo.bar')
  616. original_infodict['epoch'] = self.outtmpl_info.get('epoch')
  617. self.assertTrue(isinstance(original_infodict['epoch'], int))
  618. test('%(epoch)d', int_or_none)
  619. self.assertEqual(original_infodict, self.outtmpl_info)
  620. # Auto-generated fields
  621. test('%(id)s.%(ext)s', '1234.mp4')
  622. test('%(duration_string)s', ('27:46:40', '27-46-40'))
  623. test('%(resolution)s', '1080p')
  624. test('%(playlist_index|)s', '001')
  625. test('%(playlist_index&{}!)s', '1!')
  626. test('%(playlist_autonumber)s', '02')
  627. test('%(autonumber)s', '00001')
  628. test('%(autonumber+2)03d', '005', autonumber_start=3)
  629. test('%(autonumber)s', '001', autonumber_size=3)
  630. # Escaping %
  631. test('%', '%')
  632. test('%%', '%')
  633. test('%%%%', '%%')
  634. test('%s', '%s')
  635. test('%%%s', '%%s')
  636. test('%d', '%d')
  637. test('%abc%', '%abc%')
  638. test('%%(width)06d.%(ext)s', '%(width)06d.mp4')
  639. test('%%%(height)s', '%1080')
  640. test('%(width)06d.%(ext)s', 'NA.mp4')
  641. test('%(width)06d.%%(ext)s', 'NA.%(ext)s')
  642. test('%%(width)06d.%(ext)s', '%(width)06d.mp4')
  643. # ID sanitization
  644. test('%(id)s', '_abcd', info={'id': '_abcd'})
  645. test('%(some_id)s', '_abcd', info={'some_id': '_abcd'})
  646. test('%(formats.0.id)s', '_abcd', info={'formats': [{'id': '_abcd'}]})
  647. test('%(id)s', '-abcd', info={'id': '-abcd'})
  648. test('%(id)s', '.abcd', info={'id': '.abcd'})
  649. test('%(id)s', 'ab__cd', info={'id': 'ab__cd'})
  650. test('%(id)s', ('ab:cd', 'ab:cd'), info={'id': 'ab:cd'})
  651. test('%(id.0)s', '-', info={'id': '--'})
  652. # Invalid templates
  653. self.assertTrue(isinstance(YoutubeDL.validate_outtmpl('%(title)'), ValueError))
  654. test('%(invalid@tmpl|def)s', 'none', outtmpl_na_placeholder='none')
  655. test('%(..)s', 'NA')
  656. test('%(formats.{id)s', 'NA')
  657. # Entire info_dict
  658. def expect_same_infodict(out):
  659. got_dict = json.loads(out)
  660. for info_field, expected in self.outtmpl_info.items():
  661. self.assertEqual(got_dict.get(info_field), expected, info_field)
  662. return True
  663. test('%()j', (expect_same_infodict, None))
  664. # NA placeholder
  665. NA_TEST_OUTTMPL = '%(uploader_date)s-%(width)d-%(x|def)s-%(id)s.%(ext)s'
  666. test(NA_TEST_OUTTMPL, 'NA-NA-def-1234.mp4')
  667. test(NA_TEST_OUTTMPL, 'none-none-def-1234.mp4', outtmpl_na_placeholder='none')
  668. test(NA_TEST_OUTTMPL, '--def-1234.mp4', outtmpl_na_placeholder='')
  669. test('%(non_existent.0)s', 'NA')
  670. # String formatting
  671. FMT_TEST_OUTTMPL = '%%(height)%s.%%(ext)s'
  672. test(FMT_TEST_OUTTMPL % 's', '1080.mp4')
  673. test(FMT_TEST_OUTTMPL % 'd', '1080.mp4')
  674. test(FMT_TEST_OUTTMPL % '6d', ' 1080.mp4')
  675. test(FMT_TEST_OUTTMPL % '-6d', '1080 .mp4')
  676. test(FMT_TEST_OUTTMPL % '06d', '001080.mp4')
  677. test(FMT_TEST_OUTTMPL % ' 06d', ' 01080.mp4')
  678. test(FMT_TEST_OUTTMPL % ' 06d', ' 01080.mp4')
  679. test(FMT_TEST_OUTTMPL % '0 6d', ' 01080.mp4')
  680. test(FMT_TEST_OUTTMPL % '0 6d', ' 01080.mp4')
  681. test(FMT_TEST_OUTTMPL % ' 0 6d', ' 01080.mp4')
  682. # Type casting
  683. test('%(id)d', '1234')
  684. test('%(height)c', '1')
  685. test('%(ext)c', 'm')
  686. test('%(id)d %(id)r', "1234 '1234'")
  687. test('%(id)r %(height)r', "'1234' 1080")
  688. test('%(title5)a %(height)a', (R"'\xe1\xe9\xed \U0001d400' 1080", None))
  689. test('%(ext)s-%(ext|def)d', 'mp4-def')
  690. test('%(width|0)04d', '0')
  691. test('a%(width|b)d', 'ab', outtmpl_na_placeholder='none')
  692. FORMATS = self.outtmpl_info['formats']
  693. # Custom type casting
  694. test('%(formats.:.id)l', 'id 1, id 2, id 3')
  695. test('%(formats.:.id)#l', ('id 1\nid 2\nid 3', 'id 1 id 2 id 3'))
  696. test('%(ext)l', 'mp4')
  697. test('%(formats.:.id) 18l', ' id 1, id 2, id 3')
  698. test('%(formats)j', (json.dumps(FORMATS), None))
  699. test('%(formats)#j', (
  700. json.dumps(FORMATS, indent=4),
  701. json.dumps(FORMATS, indent=4).replace(':', ':').replace('"', '"').replace('\n', ' '),
  702. ))
  703. test('%(title5).3B', 'á')
  704. test('%(title5)U', 'áéí 𝐀')
  705. test('%(title5)#U', 'a\u0301e\u0301i\u0301 𝐀')
  706. test('%(title5)+U', 'áéí A')
  707. test('%(title5)+#U', 'a\u0301e\u0301i\u0301 A')
  708. test('%(height)D', '1k')
  709. test('%(filesize)#D', '1Ki')
  710. test('%(height)5.2D', ' 1.08k')
  711. test('%(title4)#S', 'foo_bar_test')
  712. test('%(title4).10S', ('foo "bar" ', 'foo "bar"' + ('#' if compat_os_name == 'nt' else ' ')))
  713. if compat_os_name == 'nt':
  714. test('%(title4)q', ('"foo ""bar"" test"', None))
  715. test('%(formats.:.id)#q', ('"id 1" "id 2" "id 3"', None))
  716. test('%(formats.0.id)#q', ('"id 1"', None))
  717. else:
  718. test('%(title4)q', ('\'foo "bar" test\'', '\'foo "bar" test\''))
  719. test('%(formats.:.id)#q', "'id 1' 'id 2' 'id 3'")
  720. test('%(formats.0.id)#q', "'id 1'")
  721. # Internal formatting
  722. test('%(timestamp-1000>%H-%M-%S)s', '11-43-20')
  723. test('%(title|%)s %(title|%%)s', '% %%')
  724. test('%(id+1-height+3)05d', '00158')
  725. test('%(width+100)05d', 'NA')
  726. test('%(filesize*8)d', '8192')
  727. test('%(formats.0) 15s', ('% 15s' % FORMATS[0], None))
  728. test('%(formats.0)r', (repr(FORMATS[0]), None))
  729. test('%(height.0)03d', '001')
  730. test('%(-height.0)04d', '-001')
  731. test('%(formats.-1.id)s', FORMATS[-1]['id'])
  732. test('%(formats.0.id.-1)d', FORMATS[0]['id'][-1])
  733. test('%(formats.3)s', 'NA')
  734. test('%(formats.:2:-1)r', repr(FORMATS[:2:-1]))
  735. test('%(formats.0.id.-1+id)f', '1235.000000')
  736. test('%(formats.0.id.-1+formats.1.id.-1)d', '3')
  737. out = json.dumps([{'id': f['id'], 'height.:2': str(f['height'])[:2]}
  738. if 'height' in f else {'id': f['id']}
  739. for f in FORMATS])
  740. test('%(formats.:.{id,height.:2})j', (out, None))
  741. test('%(formats.:.{id,height}.id)l', ', '.join(f['id'] for f in FORMATS))
  742. test('%(.{id,title})j', ('{"id": "1234"}', '{"id": "1234"}'))
  743. # Alternates
  744. test('%(title,id)s', '1234')
  745. test('%(width-100,height+20|def)d', '1100')
  746. test('%(width-100,height+width|def)s', 'def')
  747. test('%(timestamp-x>%H\\,%M\\,%S,timestamp>%H\\,%M\\,%S)s', '12,00,00')
  748. # Replacement
  749. test('%(id&foo)s.bar', 'foo.bar')
  750. test('%(title&foo)s.bar', 'NA.bar')
  751. test('%(title&foo|baz)s.bar', 'baz.bar')
  752. test('%(x,id&foo|baz)s.bar', 'foo.bar')
  753. test('%(x,title&foo|baz)s.bar', 'baz.bar')
  754. test('%(id&a\nb|)s', ('a\nb', 'a b'))
  755. test('%(id&hi {:>10} {}|)s', 'hi 1234 1234')
  756. test(R'%(id&{0} {}|)s', 'NA')
  757. test(R'%(id&{0.1}|)s', 'NA')
  758. test('%(height&{:,d})S', '1,080')
  759. # Laziness
  760. def gen():
  761. yield from range(5)
  762. raise self.assertTrue(False, 'LazyList should not be evaluated till here')
  763. test('%(key.4)s', '4', info={'key': LazyList(gen())})
  764. # Empty filename
  765. test('%(foo|)s-%(bar|)s.%(ext)s', '-.mp4')
  766. # test('%(foo|)s.%(ext)s', ('.mp4', '_.mp4')) # FIXME: ?
  767. # test('%(foo|)s', ('', '_')) # FIXME: ?
  768. # Environment variable expansion for prepare_filename
  769. os.environ['__yt_dlp_var'] = 'expanded'
  770. envvar = '%__yt_dlp_var%' if compat_os_name == 'nt' else '$__yt_dlp_var'
  771. test(envvar, (envvar, 'expanded'))
  772. if compat_os_name == 'nt':
  773. test('%s%', ('%s%', '%s%'))
  774. os.environ['s'] = 'expanded'
  775. test('%s%', ('%s%', 'expanded')) # %s% should be expanded before escaping %s
  776. os.environ['(test)s'] = 'expanded'
  777. test('%(test)s%', ('NA%', 'expanded')) # Environment should take priority over template
  778. # Path expansion and escaping
  779. test('Hello %(title1)s', 'Hello $PATH')
  780. test('Hello %(title2)s', 'Hello %PATH%')
  781. test('%(title3)s', ('foo/bar\\test', 'foo⧸bar⧹test'))
  782. test('folder/%(title3)s', ('folder/foo/bar\\test', f'folder{os.path.sep}foo⧸bar⧹test'))
  783. def test_format_note(self):
  784. ydl = YoutubeDL()
  785. self.assertEqual(ydl._format_note({}), '')
  786. assertRegexpMatches(self, ydl._format_note({
  787. 'vbr': 10,
  788. }), r'^\s*10k$')
  789. assertRegexpMatches(self, ydl._format_note({
  790. 'fps': 30,
  791. }), r'^30fps$')
  792. def test_postprocessors(self):
  793. filename = 'post-processor-testfile.mp4'
  794. audiofile = filename + '.mp3'
  795. class SimplePP(PostProcessor):
  796. def run(self, info):
  797. with open(audiofile, 'w') as f:
  798. f.write('EXAMPLE')
  799. return [info['filepath']], info
  800. def run_pp(params, pp):
  801. with open(filename, 'w') as f:
  802. f.write('EXAMPLE')
  803. ydl = YoutubeDL(params)
  804. ydl.add_post_processor(pp())
  805. ydl.post_process(filename, {'filepath': filename})
  806. run_pp({'keepvideo': True}, SimplePP)
  807. self.assertTrue(os.path.exists(filename), f'{filename} doesn\'t exist')
  808. self.assertTrue(os.path.exists(audiofile), f'{audiofile} doesn\'t exist')
  809. os.unlink(filename)
  810. os.unlink(audiofile)
  811. run_pp({'keepvideo': False}, SimplePP)
  812. self.assertFalse(os.path.exists(filename), f'{filename} exists')
  813. self.assertTrue(os.path.exists(audiofile), f'{audiofile} doesn\'t exist')
  814. os.unlink(audiofile)
  815. class ModifierPP(PostProcessor):
  816. def run(self, info):
  817. with open(info['filepath'], 'w') as f:
  818. f.write('MODIFIED')
  819. return [], info
  820. run_pp({'keepvideo': False}, ModifierPP)
  821. self.assertTrue(os.path.exists(filename), f'{filename} doesn\'t exist')
  822. os.unlink(filename)
  823. def test_match_filter(self):
  824. first = {
  825. 'id': '1',
  826. 'url': TEST_URL,
  827. 'title': 'one',
  828. 'extractor': 'TEST',
  829. 'duration': 30,
  830. 'filesize': 10 * 1024,
  831. 'playlist_id': '42',
  832. 'uploader': '變態妍字幕版 太妍 тест',
  833. 'creator': "тест ' 123 ' тест--",
  834. 'webpage_url': 'http://example.com/watch?v=shenanigans',
  835. }
  836. second = {
  837. 'id': '2',
  838. 'url': TEST_URL,
  839. 'title': 'two',
  840. 'extractor': 'TEST',
  841. 'duration': 10,
  842. 'description': 'foo',
  843. 'filesize': 5 * 1024,
  844. 'playlist_id': '43',
  845. 'uploader': 'тест 123',
  846. 'webpage_url': 'http://example.com/watch?v=SHENANIGANS',
  847. }
  848. videos = [first, second]
  849. def get_videos(filter_=None):
  850. ydl = YDL({'match_filter': filter_, 'simulate': True})
  851. for v in videos:
  852. ydl.process_ie_result(v.copy(), download=True)
  853. return [v['id'] for v in ydl.downloaded_info_dicts]
  854. res = get_videos()
  855. self.assertEqual(res, ['1', '2'])
  856. def f(v, incomplete):
  857. if v['id'] == '1':
  858. return None
  859. else:
  860. return 'Video id is not 1'
  861. res = get_videos(f)
  862. self.assertEqual(res, ['1'])
  863. f = match_filter_func('duration < 30')
  864. res = get_videos(f)
  865. self.assertEqual(res, ['2'])
  866. f = match_filter_func('description = foo')
  867. res = get_videos(f)
  868. self.assertEqual(res, ['2'])
  869. f = match_filter_func('description =? foo')
  870. res = get_videos(f)
  871. self.assertEqual(res, ['1', '2'])
  872. f = match_filter_func('filesize > 5KiB')
  873. res = get_videos(f)
  874. self.assertEqual(res, ['1'])
  875. f = match_filter_func('playlist_id = 42')
  876. res = get_videos(f)
  877. self.assertEqual(res, ['1'])
  878. f = match_filter_func('uploader = "變態妍字幕版 太妍 тест"')
  879. res = get_videos(f)
  880. self.assertEqual(res, ['1'])
  881. f = match_filter_func('uploader != "變態妍字幕版 太妍 тест"')
  882. res = get_videos(f)
  883. self.assertEqual(res, ['2'])
  884. f = match_filter_func('creator = "тест \' 123 \' тест--"')
  885. res = get_videos(f)
  886. self.assertEqual(res, ['1'])
  887. f = match_filter_func("creator = 'тест \\' 123 \\' тест--'")
  888. res = get_videos(f)
  889. self.assertEqual(res, ['1'])
  890. f = match_filter_func(r"creator = 'тест \' 123 \' тест--' & duration > 30")
  891. res = get_videos(f)
  892. self.assertEqual(res, [])
  893. def test_playlist_items_selection(self):
  894. INDICES, PAGE_SIZE = list(range(1, 11)), 3
  895. def entry(i, evaluated):
  896. evaluated.append(i)
  897. return {
  898. 'id': str(i),
  899. 'title': str(i),
  900. 'url': TEST_URL,
  901. }
  902. def pagedlist_entries(evaluated):
  903. def page_func(n):
  904. start = PAGE_SIZE * n
  905. for i in INDICES[start: start + PAGE_SIZE]:
  906. yield entry(i, evaluated)
  907. return OnDemandPagedList(page_func, PAGE_SIZE)
  908. def page_num(i):
  909. return (i + PAGE_SIZE - 1) // PAGE_SIZE
  910. def generator_entries(evaluated):
  911. for i in INDICES:
  912. yield entry(i, evaluated)
  913. def list_entries(evaluated):
  914. return list(generator_entries(evaluated))
  915. def lazylist_entries(evaluated):
  916. return LazyList(generator_entries(evaluated))
  917. def get_downloaded_info_dicts(params, entries):
  918. ydl = YDL(params)
  919. ydl.process_ie_result({
  920. '_type': 'playlist',
  921. 'id': 'test',
  922. 'extractor': 'test:playlist',
  923. 'extractor_key': 'test:playlist',
  924. 'webpage_url': 'http://example.com',
  925. 'entries': entries,
  926. })
  927. return ydl.downloaded_info_dicts
  928. def test_selection(params, expected_ids, evaluate_all=False):
  929. expected_ids = list(expected_ids)
  930. if evaluate_all:
  931. generator_eval = pagedlist_eval = INDICES
  932. elif not expected_ids:
  933. generator_eval = pagedlist_eval = []
  934. else:
  935. generator_eval = INDICES[0: max(expected_ids)]
  936. pagedlist_eval = INDICES[PAGE_SIZE * page_num(min(expected_ids)) - PAGE_SIZE:
  937. PAGE_SIZE * page_num(max(expected_ids))]
  938. for name, func, expected_eval in (
  939. ('list', list_entries, INDICES),
  940. ('Generator', generator_entries, generator_eval),
  941. # ('LazyList', lazylist_entries, generator_eval), # Generator and LazyList follow the exact same code path
  942. ('PagedList', pagedlist_entries, pagedlist_eval),
  943. ):
  944. evaluated = []
  945. entries = func(evaluated)
  946. results = [(v['playlist_autonumber'] - 1, (int(v['id']), v['playlist_index']))
  947. for v in get_downloaded_info_dicts(params, entries)]
  948. self.assertEqual(results, list(enumerate(zip(expected_ids, expected_ids))), f'Entries of {name} for {params}')
  949. self.assertEqual(sorted(evaluated), expected_eval, f'Evaluation of {name} for {params}')
  950. test_selection({}, INDICES)
  951. test_selection({'playlistend': 20}, INDICES, True)
  952. test_selection({'playlistend': 2}, INDICES[:2])
  953. test_selection({'playliststart': 11}, [], True)
  954. test_selection({'playliststart': 2}, INDICES[1:])
  955. test_selection({'playlist_items': '2-4'}, INDICES[1:4])
  956. test_selection({'playlist_items': '2,4'}, [2, 4])
  957. test_selection({'playlist_items': '20'}, [], True)
  958. test_selection({'playlist_items': '0'}, [])
  959. # Tests for https://github.com/ytdl-org/youtube-dl/issues/10591
  960. test_selection({'playlist_items': '2-4,3-4,3'}, [2, 3, 4])
  961. test_selection({'playlist_items': '4,2'}, [4, 2])
  962. # Tests for https://github.com/yt-dlp/yt-dlp/issues/720
  963. # https://github.com/yt-dlp/yt-dlp/issues/302
  964. test_selection({'playlistreverse': True}, INDICES[::-1])
  965. test_selection({'playliststart': 2, 'playlistreverse': True}, INDICES[:0:-1])
  966. test_selection({'playlist_items': '2,4', 'playlistreverse': True}, [4, 2])
  967. test_selection({'playlist_items': '4,2'}, [4, 2])
  968. # Tests for --playlist-items start:end:step
  969. test_selection({'playlist_items': ':'}, INDICES, True)
  970. test_selection({'playlist_items': '::1'}, INDICES, True)
  971. test_selection({'playlist_items': '::-1'}, INDICES[::-1], True)
  972. test_selection({'playlist_items': ':6'}, INDICES[:6])
  973. test_selection({'playlist_items': ':-6'}, INDICES[:-5], True)
  974. test_selection({'playlist_items': '-1:6:-2'}, INDICES[:4:-2], True)
  975. test_selection({'playlist_items': '9:-6:-2'}, INDICES[8:3:-2], True)
  976. test_selection({'playlist_items': '1:inf:2'}, INDICES[::2], True)
  977. test_selection({'playlist_items': '-2:inf'}, INDICES[-2:], True)
  978. test_selection({'playlist_items': ':inf:-1'}, [], True)
  979. test_selection({'playlist_items': '0-2:2'}, [2])
  980. test_selection({'playlist_items': '1-:2'}, INDICES[::2], True)
  981. test_selection({'playlist_items': '0--2:2'}, INDICES[1:-1:2], True)
  982. test_selection({'playlist_items': '10::3'}, [10], True)
  983. test_selection({'playlist_items': '-1::3'}, [10], True)
  984. test_selection({'playlist_items': '11::3'}, [], True)
  985. test_selection({'playlist_items': '-15::2'}, INDICES[1::2], True)
  986. test_selection({'playlist_items': '-15::15'}, [], True)
  987. def test_do_not_override_ie_key_in_url_transparent(self):
  988. ydl = YDL()
  989. class Foo1IE(InfoExtractor):
  990. _VALID_URL = r'foo1:'
  991. def _real_extract(self, url):
  992. return {
  993. '_type': 'url_transparent',
  994. 'url': 'foo2:',
  995. 'ie_key': 'Foo2',
  996. 'title': 'foo1 title',
  997. 'id': 'foo1_id',
  998. }
  999. class Foo2IE(InfoExtractor):
  1000. _VALID_URL = r'foo2:'
  1001. def _real_extract(self, url):
  1002. return {
  1003. '_type': 'url',
  1004. 'url': 'foo3:',
  1005. 'ie_key': 'Foo3',
  1006. }
  1007. class Foo3IE(InfoExtractor):
  1008. _VALID_URL = r'foo3:'
  1009. def _real_extract(self, url):
  1010. return _make_result([{'url': TEST_URL}], title='foo3 title')
  1011. ydl.add_info_extractor(Foo1IE(ydl))
  1012. ydl.add_info_extractor(Foo2IE(ydl))
  1013. ydl.add_info_extractor(Foo3IE(ydl))
  1014. ydl.extract_info('foo1:')
  1015. downloaded = ydl.downloaded_info_dicts[0]
  1016. self.assertEqual(downloaded['url'], TEST_URL)
  1017. self.assertEqual(downloaded['title'], 'foo1 title')
  1018. self.assertEqual(downloaded['id'], 'testid')
  1019. self.assertEqual(downloaded['extractor'], 'testex')
  1020. self.assertEqual(downloaded['extractor_key'], 'TestEx')
  1021. # Test case for https://github.com/ytdl-org/youtube-dl/issues/27064
  1022. def test_ignoreerrors_for_playlist_with_url_transparent_iterable_entries(self):
  1023. class _YDL(YDL):
  1024. def __init__(self, *args, **kwargs):
  1025. super().__init__(*args, **kwargs)
  1026. def trouble(self, s, tb=None):
  1027. pass
  1028. ydl = _YDL({
  1029. 'format': 'extra',
  1030. 'ignoreerrors': True,
  1031. })
  1032. class VideoIE(InfoExtractor):
  1033. _VALID_URL = r'video:(?P<id>\d+)'
  1034. def _real_extract(self, url):
  1035. video_id = self._match_id(url)
  1036. formats = [{
  1037. 'format_id': 'default',
  1038. 'url': 'url:',
  1039. }]
  1040. if video_id == '0':
  1041. raise ExtractorError('foo')
  1042. if video_id == '2':
  1043. formats.append({
  1044. 'format_id': 'extra',
  1045. 'url': TEST_URL,
  1046. })
  1047. return {
  1048. 'id': video_id,
  1049. 'title': f'Video {video_id}',
  1050. 'formats': formats,
  1051. }
  1052. class PlaylistIE(InfoExtractor):
  1053. _VALID_URL = r'playlist:'
  1054. def _entries(self):
  1055. for n in range(3):
  1056. video_id = str(n)
  1057. yield {
  1058. '_type': 'url_transparent',
  1059. 'ie_key': VideoIE.ie_key(),
  1060. 'id': video_id,
  1061. 'url': f'video:{video_id}',
  1062. 'title': f'Video Transparent {video_id}',
  1063. }
  1064. def _real_extract(self, url):
  1065. return self.playlist_result(self._entries())
  1066. ydl.add_info_extractor(VideoIE(ydl))
  1067. ydl.add_info_extractor(PlaylistIE(ydl))
  1068. info = ydl.extract_info('playlist:')
  1069. entries = info['entries']
  1070. self.assertEqual(len(entries), 3)
  1071. self.assertTrue(entries[0] is None)
  1072. self.assertTrue(entries[1] is None)
  1073. self.assertEqual(len(ydl.downloaded_info_dicts), 1)
  1074. downloaded = ydl.downloaded_info_dicts[0]
  1075. entries[2].pop('requested_downloads', None)
  1076. self.assertEqual(entries[2], downloaded)
  1077. self.assertEqual(downloaded['url'], TEST_URL)
  1078. self.assertEqual(downloaded['title'], 'Video Transparent 2')
  1079. self.assertEqual(downloaded['id'], '2')
  1080. self.assertEqual(downloaded['extractor'], 'Video')
  1081. self.assertEqual(downloaded['extractor_key'], 'Video')
  1082. def test_header_cookies(self):
  1083. from http.cookiejar import Cookie
  1084. ydl = FakeYDL()
  1085. ydl.report_warning = lambda *_, **__: None
  1086. def cookie(name, value, version=None, domain='', path='', secure=False, expires=None):
  1087. return Cookie(
  1088. version or 0, name, value, None, False,
  1089. domain, bool(domain), bool(domain), path, bool(path),
  1090. secure, expires, False, None, None, rest={})
  1091. _test_url = 'https://yt.dlp/test'
  1092. def test(encoded_cookies, cookies, *, headers=False, round_trip=None, error_re=None):
  1093. def _test():
  1094. ydl.cookiejar.clear()
  1095. ydl._load_cookies(encoded_cookies, autoscope=headers)
  1096. if headers:
  1097. ydl._apply_header_cookies(_test_url)
  1098. data = {'url': _test_url}
  1099. ydl._calc_headers(data)
  1100. self.assertCountEqual(
  1101. map(vars, ydl.cookiejar), map(vars, cookies),
  1102. 'Extracted cookiejar.Cookie is not the same')
  1103. if not headers:
  1104. self.assertEqual(
  1105. data.get('cookies'), round_trip or encoded_cookies,
  1106. 'Cookie is not the same as round trip')
  1107. ydl.__dict__['_YoutubeDL__header_cookies'] = []
  1108. with self.subTest(msg=encoded_cookies):
  1109. if not error_re:
  1110. _test()
  1111. return
  1112. with self.assertRaisesRegex(Exception, error_re):
  1113. _test()
  1114. test('test=value; Domain=.yt.dlp', [cookie('test', 'value', domain='.yt.dlp')])
  1115. test('test=value', [cookie('test', 'value')], error_re=r'Unscoped cookies are not allowed')
  1116. test('cookie1=value1; Domain=.yt.dlp; Path=/test; cookie2=value2; Domain=.yt.dlp; Path=/', [
  1117. cookie('cookie1', 'value1', domain='.yt.dlp', path='/test'),
  1118. cookie('cookie2', 'value2', domain='.yt.dlp', path='/')])
  1119. test('test=value; Domain=.yt.dlp; Path=/test; Secure; Expires=9999999999', [
  1120. cookie('test', 'value', domain='.yt.dlp', path='/test', secure=True, expires=9999999999)])
  1121. test('test="value; "; path=/test; domain=.yt.dlp', [
  1122. cookie('test', 'value; ', domain='.yt.dlp', path='/test')],
  1123. round_trip='test="value\\073 "; Domain=.yt.dlp; Path=/test')
  1124. test('name=; Domain=.yt.dlp', [cookie('name', '', domain='.yt.dlp')],
  1125. round_trip='name=""; Domain=.yt.dlp')
  1126. test('test=value', [cookie('test', 'value', domain='.yt.dlp')], headers=True)
  1127. test('cookie1=value; Domain=.yt.dlp; cookie2=value', [], headers=True, error_re=r'Invalid syntax')
  1128. ydl.deprecated_feature = ydl.report_error
  1129. test('test=value', [], headers=True, error_re=r'Passing cookies as a header is a potential security risk')
  1130. def test_infojson_cookies(self):
  1131. TEST_FILE = 'test_infojson_cookies.info.json'
  1132. TEST_URL = 'https://example.com/example.mp4'
  1133. COOKIES = 'a=b; Domain=.example.com; c=d; Domain=.example.com'
  1134. COOKIE_HEADER = {'Cookie': 'a=b; c=d'}
  1135. ydl = FakeYDL()
  1136. ydl.process_info = lambda x: ydl._write_info_json('test', x, TEST_FILE)
  1137. def make_info(info_header_cookies=False, fmts_header_cookies=False, cookies_field=False):
  1138. fmt = {'url': TEST_URL}
  1139. if fmts_header_cookies:
  1140. fmt['http_headers'] = COOKIE_HEADER
  1141. if cookies_field:
  1142. fmt['cookies'] = COOKIES
  1143. return _make_result([fmt], http_headers=COOKIE_HEADER if info_header_cookies else None)
  1144. def test(initial_info, note):
  1145. result = {}
  1146. result['processed'] = ydl.process_ie_result(initial_info)
  1147. self.assertTrue(ydl.cookiejar.get_cookies_for_url(TEST_URL),
  1148. msg=f'No cookies set in cookiejar after initial process when {note}')
  1149. ydl.cookiejar.clear()
  1150. with open(TEST_FILE) as infojson:
  1151. result['loaded'] = ydl.sanitize_info(json.load(infojson), True)
  1152. result['final'] = ydl.process_ie_result(result['loaded'].copy(), download=False)
  1153. self.assertTrue(ydl.cookiejar.get_cookies_for_url(TEST_URL),
  1154. msg=f'No cookies set in cookiejar after final process when {note}')
  1155. ydl.cookiejar.clear()
  1156. for key in ('processed', 'loaded', 'final'):
  1157. info = result[key]
  1158. self.assertIsNone(
  1159. traverse_obj(info, ((None, ('formats', 0)), 'http_headers', 'Cookie'), casesense=False, get_all=False),
  1160. msg=f'Cookie header not removed in {key} result when {note}')
  1161. self.assertEqual(
  1162. traverse_obj(info, ((None, ('formats', 0)), 'cookies'), get_all=False), COOKIES,
  1163. msg=f'No cookies field found in {key} result when {note}')
  1164. test({'url': TEST_URL, 'http_headers': COOKIE_HEADER, 'id': '1', 'title': 'x'}, 'no formats field')
  1165. test(make_info(info_header_cookies=True), 'info_dict header cokies')
  1166. test(make_info(fmts_header_cookies=True), 'format header cookies')
  1167. test(make_info(info_header_cookies=True, fmts_header_cookies=True), 'info_dict and format header cookies')
  1168. test(make_info(info_header_cookies=True, fmts_header_cookies=True, cookies_field=True), 'all cookies fields')
  1169. test(make_info(cookies_field=True), 'cookies format field')
  1170. test({'url': TEST_URL, 'cookies': COOKIES, 'id': '1', 'title': 'x'}, 'info_dict cookies field only')
  1171. try_rm(TEST_FILE)
  1172. def test_add_headers_cookie(self):
  1173. def check_for_cookie_header(result):
  1174. return traverse_obj(result, ((None, ('formats', 0)), 'http_headers', 'Cookie'), casesense=False, get_all=False)
  1175. ydl = FakeYDL({'http_headers': {'Cookie': 'a=b'}})
  1176. ydl._apply_header_cookies(_make_result([])['webpage_url']) # Scope to input webpage URL: .example.com
  1177. fmt = {'url': 'https://example.com/video.mp4'}
  1178. result = ydl.process_ie_result(_make_result([fmt]), download=False)
  1179. self.assertIsNone(check_for_cookie_header(result), msg='http_headers cookies in result info_dict')
  1180. self.assertEqual(result.get('cookies'), 'a=b; Domain=.example.com', msg='No cookies were set in cookies field')
  1181. self.assertIn('a=b', ydl.cookiejar.get_cookie_header(fmt['url']), msg='No cookies were set in cookiejar')
  1182. fmt = {'url': 'https://wrong.com/video.mp4'}
  1183. result = ydl.process_ie_result(_make_result([fmt]), download=False)
  1184. self.assertIsNone(check_for_cookie_header(result), msg='http_headers cookies for wrong domain')
  1185. self.assertFalse(result.get('cookies'), msg='Cookies set in cookies field for wrong domain')
  1186. self.assertFalse(ydl.cookiejar.get_cookie_header(fmt['url']), msg='Cookies set in cookiejar for wrong domain')
  1187. if __name__ == '__main__':
  1188. unittest.main()