test_YoutubeDL.py 58 KB

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