test_YoutubeDL.py 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. from __future__ import unicode_literals
  4. # Allow direct execution
  5. import os
  6. import sys
  7. import unittest
  8. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  9. import copy
  10. from test.helper import FakeYDL, assertRegexpMatches
  11. from youtube_dl import YoutubeDL
  12. from youtube_dl.compat import compat_str, compat_urllib_error
  13. from youtube_dl.extractor import YoutubeIE
  14. from youtube_dl.extractor.common import InfoExtractor
  15. from youtube_dl.postprocessor.common import PostProcessor
  16. from youtube_dl.utils import ExtractorError, match_filter_func
  17. TEST_URL = 'http://localhost/sample.mp4'
  18. class YDL(FakeYDL):
  19. def __init__(self, *args, **kwargs):
  20. super(YDL, self).__init__(*args, **kwargs)
  21. self.downloaded_info_dicts = []
  22. self.msgs = []
  23. def process_info(self, info_dict):
  24. self.downloaded_info_dicts.append(info_dict)
  25. def to_screen(self, msg):
  26. self.msgs.append(msg)
  27. def _make_result(formats, **kwargs):
  28. res = {
  29. 'formats': formats,
  30. 'id': 'testid',
  31. 'title': 'testttitle',
  32. 'extractor': 'testex',
  33. 'extractor_key': 'TestEx',
  34. }
  35. res.update(**kwargs)
  36. return res
  37. class TestFormatSelection(unittest.TestCase):
  38. def test_prefer_free_formats(self):
  39. # Same resolution => download webm
  40. ydl = YDL()
  41. ydl.params['prefer_free_formats'] = True
  42. formats = [
  43. {'ext': 'webm', 'height': 460, 'url': TEST_URL},
  44. {'ext': 'mp4', 'height': 460, 'url': TEST_URL},
  45. ]
  46. info_dict = _make_result(formats)
  47. yie = YoutubeIE(ydl)
  48. yie._sort_formats(info_dict['formats'])
  49. ydl.process_ie_result(info_dict)
  50. downloaded = ydl.downloaded_info_dicts[0]
  51. self.assertEqual(downloaded['ext'], 'webm')
  52. # Different resolution => download best quality (mp4)
  53. ydl = YDL()
  54. ydl.params['prefer_free_formats'] = True
  55. formats = [
  56. {'ext': 'webm', 'height': 720, 'url': TEST_URL},
  57. {'ext': 'mp4', 'height': 1080, 'url': TEST_URL},
  58. ]
  59. info_dict['formats'] = formats
  60. yie = YoutubeIE(ydl)
  61. yie._sort_formats(info_dict['formats'])
  62. ydl.process_ie_result(info_dict)
  63. downloaded = ydl.downloaded_info_dicts[0]
  64. self.assertEqual(downloaded['ext'], 'mp4')
  65. # No prefer_free_formats => prefer mp4 and flv for greater compatibility
  66. ydl = YDL()
  67. ydl.params['prefer_free_formats'] = False
  68. formats = [
  69. {'ext': 'webm', 'height': 720, 'url': TEST_URL},
  70. {'ext': 'mp4', 'height': 720, 'url': TEST_URL},
  71. {'ext': 'flv', 'height': 720, 'url': TEST_URL},
  72. ]
  73. info_dict['formats'] = formats
  74. yie = YoutubeIE(ydl)
  75. yie._sort_formats(info_dict['formats'])
  76. ydl.process_ie_result(info_dict)
  77. downloaded = ydl.downloaded_info_dicts[0]
  78. self.assertEqual(downloaded['ext'], 'mp4')
  79. ydl = YDL()
  80. ydl.params['prefer_free_formats'] = False
  81. formats = [
  82. {'ext': 'flv', 'height': 720, 'url': TEST_URL},
  83. {'ext': 'webm', 'height': 720, 'url': TEST_URL},
  84. ]
  85. info_dict['formats'] = formats
  86. yie = YoutubeIE(ydl)
  87. yie._sort_formats(info_dict['formats'])
  88. ydl.process_ie_result(info_dict)
  89. downloaded = ydl.downloaded_info_dicts[0]
  90. self.assertEqual(downloaded['ext'], 'flv')
  91. def test_format_selection(self):
  92. formats = [
  93. {'format_id': '35', 'ext': 'mp4', 'preference': 1, 'url': TEST_URL},
  94. {'format_id': 'example-with-dashes', 'ext': 'webm', 'preference': 1, 'url': TEST_URL},
  95. {'format_id': '45', 'ext': 'webm', 'preference': 2, 'url': TEST_URL},
  96. {'format_id': '47', 'ext': 'webm', 'preference': 3, 'url': TEST_URL},
  97. {'format_id': '2', 'ext': 'flv', 'preference': 4, 'url': TEST_URL},
  98. ]
  99. info_dict = _make_result(formats)
  100. ydl = YDL({'format': '20/47'})
  101. ydl.process_ie_result(info_dict.copy())
  102. downloaded = ydl.downloaded_info_dicts[0]
  103. self.assertEqual(downloaded['format_id'], '47')
  104. ydl = YDL({'format': '20/71/worst'})
  105. ydl.process_ie_result(info_dict.copy())
  106. downloaded = ydl.downloaded_info_dicts[0]
  107. self.assertEqual(downloaded['format_id'], '35')
  108. ydl = YDL()
  109. ydl.process_ie_result(info_dict.copy())
  110. downloaded = ydl.downloaded_info_dicts[0]
  111. self.assertEqual(downloaded['format_id'], '2')
  112. ydl = YDL({'format': 'webm/mp4'})
  113. ydl.process_ie_result(info_dict.copy())
  114. downloaded = ydl.downloaded_info_dicts[0]
  115. self.assertEqual(downloaded['format_id'], '47')
  116. ydl = YDL({'format': '3gp/40/mp4'})
  117. ydl.process_ie_result(info_dict.copy())
  118. downloaded = ydl.downloaded_info_dicts[0]
  119. self.assertEqual(downloaded['format_id'], '35')
  120. ydl = YDL({'format': 'example-with-dashes'})
  121. ydl.process_ie_result(info_dict.copy())
  122. downloaded = ydl.downloaded_info_dicts[0]
  123. self.assertEqual(downloaded['format_id'], 'example-with-dashes')
  124. def test_format_selection_audio(self):
  125. formats = [
  126. {'format_id': 'audio-low', 'ext': 'webm', 'preference': 1, 'vcodec': 'none', 'url': TEST_URL},
  127. {'format_id': 'audio-mid', 'ext': 'webm', 'preference': 2, 'vcodec': 'none', 'url': TEST_URL},
  128. {'format_id': 'audio-high', 'ext': 'flv', 'preference': 3, 'vcodec': 'none', 'url': TEST_URL},
  129. {'format_id': 'vid', 'ext': 'mp4', 'preference': 4, 'url': TEST_URL},
  130. ]
  131. info_dict = _make_result(formats)
  132. ydl = YDL({'format': 'bestaudio'})
  133. ydl.process_ie_result(info_dict.copy())
  134. downloaded = ydl.downloaded_info_dicts[0]
  135. self.assertEqual(downloaded['format_id'], 'audio-high')
  136. ydl = YDL({'format': 'worstaudio'})
  137. ydl.process_ie_result(info_dict.copy())
  138. downloaded = ydl.downloaded_info_dicts[0]
  139. self.assertEqual(downloaded['format_id'], 'audio-low')
  140. formats = [
  141. {'format_id': 'vid-low', 'ext': 'mp4', 'preference': 1, 'url': TEST_URL},
  142. {'format_id': 'vid-high', 'ext': 'mp4', 'preference': 2, 'url': TEST_URL},
  143. ]
  144. info_dict = _make_result(formats)
  145. ydl = YDL({'format': 'bestaudio/worstaudio/best'})
  146. ydl.process_ie_result(info_dict.copy())
  147. downloaded = ydl.downloaded_info_dicts[0]
  148. self.assertEqual(downloaded['format_id'], 'vid-high')
  149. def test_format_selection_audio_exts(self):
  150. formats = [
  151. {'format_id': 'mp3-64', 'ext': 'mp3', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
  152. {'format_id': 'ogg-64', 'ext': 'ogg', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
  153. {'format_id': 'aac-64', 'ext': 'aac', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
  154. {'format_id': 'mp3-32', 'ext': 'mp3', 'abr': 32, 'url': 'http://_', 'vcodec': 'none'},
  155. {'format_id': 'aac-32', 'ext': 'aac', 'abr': 32, 'url': 'http://_', 'vcodec': 'none'},
  156. ]
  157. info_dict = _make_result(formats)
  158. ydl = YDL({'format': 'best'})
  159. ie = YoutubeIE(ydl)
  160. ie._sort_formats(info_dict['formats'])
  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. ie = YoutubeIE(ydl)
  166. ie._sort_formats(info_dict['formats'])
  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})
  171. ie = YoutubeIE(ydl)
  172. ie._sort_formats(info_dict['formats'])
  173. ydl.process_ie_result(copy.deepcopy(info_dict))
  174. downloaded = ydl.downloaded_info_dicts[0]
  175. self.assertEqual(downloaded['format_id'], 'ogg-64')
  176. def test_format_selection_video(self):
  177. formats = [
  178. {'format_id': 'dash-video-low', 'ext': 'mp4', 'preference': 1, 'acodec': 'none', 'url': TEST_URL},
  179. {'format_id': 'dash-video-high', 'ext': 'mp4', 'preference': 2, 'acodec': 'none', 'url': TEST_URL},
  180. {'format_id': 'vid', 'ext': 'mp4', 'preference': 3, 'url': TEST_URL},
  181. ]
  182. info_dict = _make_result(formats)
  183. ydl = YDL({'format': 'bestvideo'})
  184. ydl.process_ie_result(info_dict.copy())
  185. downloaded = ydl.downloaded_info_dicts[0]
  186. self.assertEqual(downloaded['format_id'], 'dash-video-high')
  187. ydl = YDL({'format': 'worstvideo'})
  188. ydl.process_ie_result(info_dict.copy())
  189. downloaded = ydl.downloaded_info_dicts[0]
  190. self.assertEqual(downloaded['format_id'], 'dash-video-low')
  191. ydl = YDL({'format': 'bestvideo[format_id^=dash][format_id$=low]'})
  192. ydl.process_ie_result(info_dict.copy())
  193. downloaded = ydl.downloaded_info_dicts[0]
  194. self.assertEqual(downloaded['format_id'], 'dash-video-low')
  195. formats = [
  196. {'format_id': 'vid-vcodec-dot', 'ext': 'mp4', 'preference': 1, 'vcodec': 'avc1.123456', 'acodec': 'none', 'url': TEST_URL},
  197. ]
  198. info_dict = _make_result(formats)
  199. ydl = YDL({'format': 'bestvideo[vcodec=avc1.123456]'})
  200. ydl.process_ie_result(info_dict.copy())
  201. downloaded = ydl.downloaded_info_dicts[0]
  202. self.assertEqual(downloaded['format_id'], 'vid-vcodec-dot')
  203. def test_format_selection_string_ops(self):
  204. formats = [
  205. {'format_id': 'abc-cba', 'ext': 'mp4', 'url': TEST_URL},
  206. {'format_id': 'zxc-cxz', 'ext': 'webm', 'url': TEST_URL},
  207. ]
  208. info_dict = _make_result(formats)
  209. # equals (=)
  210. ydl = YDL({'format': '[format_id=abc-cba]'})
  211. ydl.process_ie_result(info_dict.copy())
  212. downloaded = ydl.downloaded_info_dicts[0]
  213. self.assertEqual(downloaded['format_id'], 'abc-cba')
  214. # does not equal (!=)
  215. ydl = YDL({'format': '[format_id!=abc-cba]'})
  216. ydl.process_ie_result(info_dict.copy())
  217. downloaded = ydl.downloaded_info_dicts[0]
  218. self.assertEqual(downloaded['format_id'], 'zxc-cxz')
  219. ydl = YDL({'format': '[format_id!=abc-cba][format_id!=zxc-cxz]'})
  220. self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
  221. # starts with (^=)
  222. ydl = YDL({'format': '[format_id^=abc]'})
  223. ydl.process_ie_result(info_dict.copy())
  224. downloaded = ydl.downloaded_info_dicts[0]
  225. self.assertEqual(downloaded['format_id'], 'abc-cba')
  226. # does not start with (!^=)
  227. ydl = YDL({'format': '[format_id!^=abc]'})
  228. ydl.process_ie_result(info_dict.copy())
  229. downloaded = ydl.downloaded_info_dicts[0]
  230. self.assertEqual(downloaded['format_id'], 'zxc-cxz')
  231. ydl = YDL({'format': '[format_id!^=abc][format_id!^=zxc]'})
  232. self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
  233. # ends with ($=)
  234. ydl = YDL({'format': '[format_id$=cba]'})
  235. ydl.process_ie_result(info_dict.copy())
  236. downloaded = ydl.downloaded_info_dicts[0]
  237. self.assertEqual(downloaded['format_id'], 'abc-cba')
  238. # does not end with (!$=)
  239. ydl = YDL({'format': '[format_id!$=cba]'})
  240. ydl.process_ie_result(info_dict.copy())
  241. downloaded = ydl.downloaded_info_dicts[0]
  242. self.assertEqual(downloaded['format_id'], 'zxc-cxz')
  243. ydl = YDL({'format': '[format_id!$=cba][format_id!$=cxz]'})
  244. self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
  245. # contains (*=)
  246. ydl = YDL({'format': '[format_id*=bc-cb]'})
  247. ydl.process_ie_result(info_dict.copy())
  248. downloaded = ydl.downloaded_info_dicts[0]
  249. self.assertEqual(downloaded['format_id'], 'abc-cba')
  250. # does not contain (!*=)
  251. ydl = YDL({'format': '[format_id!*=bc-cb]'})
  252. ydl.process_ie_result(info_dict.copy())
  253. downloaded = ydl.downloaded_info_dicts[0]
  254. self.assertEqual(downloaded['format_id'], 'zxc-cxz')
  255. ydl = YDL({'format': '[format_id!*=abc][format_id!*=zxc]'})
  256. self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
  257. ydl = YDL({'format': '[format_id!*=-]'})
  258. self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
  259. def test_youtube_format_selection(self):
  260. order = [
  261. '38', '37', '46', '22', '45', '35', '44', '18', '34', '43', '6', '5', '17', '36', '13',
  262. # Apple HTTP Live Streaming
  263. '96', '95', '94', '93', '92', '132', '151',
  264. # 3D
  265. '85', '84', '102', '83', '101', '82', '100',
  266. # Dash video
  267. '137', '248', '136', '247', '135', '246',
  268. '245', '244', '134', '243', '133', '242', '160',
  269. # Dash audio
  270. '141', '172', '140', '171', '139',
  271. ]
  272. def format_info(f_id):
  273. info = YoutubeIE._formats[f_id].copy()
  274. # XXX: In real cases InfoExtractor._parse_mpd_formats() fills up 'acodec'
  275. # and 'vcodec', while in tests such information is incomplete since
  276. # commit a6c2c24479e5f4827ceb06f64d855329c0a6f593
  277. # test_YoutubeDL.test_youtube_format_selection is broken without
  278. # this fix
  279. if 'acodec' in info and 'vcodec' not in info:
  280. info['vcodec'] = 'none'
  281. elif 'vcodec' in info and 'acodec' not in info:
  282. info['acodec'] = 'none'
  283. info['format_id'] = f_id
  284. info['url'] = 'url:' + f_id
  285. return info
  286. formats_order = [format_info(f_id) for f_id in order]
  287. info_dict = _make_result(list(formats_order), extractor='youtube')
  288. ydl = YDL({'format': 'bestvideo+bestaudio'})
  289. yie = YoutubeIE(ydl)
  290. yie._sort_formats(info_dict['formats'])
  291. ydl.process_ie_result(info_dict)
  292. downloaded = ydl.downloaded_info_dicts[0]
  293. self.assertEqual(downloaded['format_id'], '137+141')
  294. self.assertEqual(downloaded['ext'], 'mp4')
  295. info_dict = _make_result(list(formats_order), extractor='youtube')
  296. ydl = YDL({'format': 'bestvideo[height>=999999]+bestaudio/best'})
  297. yie = YoutubeIE(ydl)
  298. yie._sort_formats(info_dict['formats'])
  299. ydl.process_ie_result(info_dict)
  300. downloaded = ydl.downloaded_info_dicts[0]
  301. self.assertEqual(downloaded['format_id'], '38')
  302. info_dict = _make_result(list(formats_order), extractor='youtube')
  303. ydl = YDL({'format': 'bestvideo/best,bestaudio'})
  304. yie = YoutubeIE(ydl)
  305. yie._sort_formats(info_dict['formats'])
  306. ydl.process_ie_result(info_dict)
  307. downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
  308. self.assertEqual(downloaded_ids, ['137', '141'])
  309. info_dict = _make_result(list(formats_order), extractor='youtube')
  310. ydl = YDL({'format': '(bestvideo[ext=mp4],bestvideo[ext=webm])+bestaudio'})
  311. yie = YoutubeIE(ydl)
  312. yie._sort_formats(info_dict['formats'])
  313. ydl.process_ie_result(info_dict)
  314. downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
  315. self.assertEqual(downloaded_ids, ['137+141', '248+141'])
  316. info_dict = _make_result(list(formats_order), extractor='youtube')
  317. ydl = YDL({'format': '(bestvideo[ext=mp4],bestvideo[ext=webm])[height<=720]+bestaudio'})
  318. yie = YoutubeIE(ydl)
  319. yie._sort_formats(info_dict['formats'])
  320. ydl.process_ie_result(info_dict)
  321. downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
  322. self.assertEqual(downloaded_ids, ['136+141', '247+141'])
  323. info_dict = _make_result(list(formats_order), extractor='youtube')
  324. ydl = YDL({'format': '(bestvideo[ext=none]/bestvideo[ext=webm])+bestaudio'})
  325. yie = YoutubeIE(ydl)
  326. yie._sort_formats(info_dict['formats'])
  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, ['248+141'])
  330. for f1, f2 in zip(formats_order, formats_order[1:]):
  331. info_dict = _make_result([f1, f2], extractor='youtube')
  332. ydl = YDL({'format': 'best/bestvideo'})
  333. yie = YoutubeIE(ydl)
  334. yie._sort_formats(info_dict['formats'])
  335. ydl.process_ie_result(info_dict)
  336. downloaded = ydl.downloaded_info_dicts[0]
  337. self.assertEqual(downloaded['format_id'], f1['format_id'])
  338. info_dict = _make_result([f2, f1], extractor='youtube')
  339. ydl = YDL({'format': 'best/bestvideo'})
  340. yie = YoutubeIE(ydl)
  341. yie._sort_formats(info_dict['formats'])
  342. ydl.process_ie_result(info_dict)
  343. downloaded = ydl.downloaded_info_dicts[0]
  344. self.assertEqual(downloaded['format_id'], f1['format_id'])
  345. def test_audio_only_extractor_format_selection(self):
  346. # For extractors with incomplete formats (all formats are audio-only or
  347. # video-only) best and worst should fallback to corresponding best/worst
  348. # video-only or audio-only formats (as per
  349. # https://github.com/ytdl-org/youtube-dl/pull/5556)
  350. formats = [
  351. {'format_id': 'low', 'ext': 'mp3', 'preference': 1, 'vcodec': 'none', 'url': TEST_URL},
  352. {'format_id': 'high', 'ext': 'mp3', 'preference': 2, 'vcodec': 'none', 'url': TEST_URL},
  353. ]
  354. info_dict = _make_result(formats)
  355. ydl = YDL({'format': 'best'})
  356. ydl.process_ie_result(info_dict.copy())
  357. downloaded = ydl.downloaded_info_dicts[0]
  358. self.assertEqual(downloaded['format_id'], 'high')
  359. ydl = YDL({'format': 'worst'})
  360. ydl.process_ie_result(info_dict.copy())
  361. downloaded = ydl.downloaded_info_dicts[0]
  362. self.assertEqual(downloaded['format_id'], 'low')
  363. def test_format_not_available(self):
  364. formats = [
  365. {'format_id': 'regular', 'ext': 'mp4', 'height': 360, 'url': TEST_URL},
  366. {'format_id': 'video', 'ext': 'mp4', 'height': 720, 'acodec': 'none', 'url': TEST_URL},
  367. ]
  368. info_dict = _make_result(formats)
  369. # This must fail since complete video-audio format does not match filter
  370. # and extractor does not provide incomplete only formats (i.e. only
  371. # video-only or audio-only).
  372. ydl = YDL({'format': 'best[height>360]'})
  373. self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
  374. def test_format_selection_issue_10083(self):
  375. # See https://github.com/ytdl-org/youtube-dl/issues/10083
  376. formats = [
  377. {'format_id': 'regular', 'height': 360, 'url': TEST_URL},
  378. {'format_id': 'video', 'height': 720, 'acodec': 'none', 'url': TEST_URL},
  379. {'format_id': 'audio', 'vcodec': 'none', 'url': TEST_URL},
  380. ]
  381. info_dict = _make_result(formats)
  382. ydl = YDL({'format': 'best[height>360]/bestvideo[height>360]+bestaudio'})
  383. ydl.process_ie_result(info_dict.copy())
  384. self.assertEqual(ydl.downloaded_info_dicts[0]['format_id'], 'video+audio')
  385. def test_invalid_format_specs(self):
  386. def assert_syntax_error(format_spec):
  387. ydl = YDL({'format': format_spec})
  388. info_dict = _make_result([{'format_id': 'foo', 'url': TEST_URL}])
  389. self.assertRaises(SyntaxError, ydl.process_ie_result, info_dict)
  390. assert_syntax_error('bestvideo,,best')
  391. assert_syntax_error('+bestaudio')
  392. assert_syntax_error('bestvideo+')
  393. assert_syntax_error('/')
  394. assert_syntax_error('bestvideo+bestvideo+bestaudio')
  395. def test_format_filtering(self):
  396. formats = [
  397. {'format_id': 'A', 'filesize': 500, 'width': 1000},
  398. {'format_id': 'B', 'filesize': 1000, 'width': 500},
  399. {'format_id': 'C', 'filesize': 1000, 'width': 400},
  400. {'format_id': 'D', 'filesize': 2000, 'width': 600},
  401. {'format_id': 'E', 'filesize': 3000},
  402. {'format_id': 'F'},
  403. {'format_id': 'G', 'filesize': 1000000},
  404. ]
  405. for f in formats:
  406. f['url'] = 'http://_/'
  407. f['ext'] = 'unknown'
  408. info_dict = _make_result(formats)
  409. ydl = YDL({'format': 'best[filesize<3000]'})
  410. ydl.process_ie_result(info_dict)
  411. downloaded = ydl.downloaded_info_dicts[0]
  412. self.assertEqual(downloaded['format_id'], 'D')
  413. ydl = YDL({'format': 'best[filesize<=3000]'})
  414. ydl.process_ie_result(info_dict)
  415. downloaded = ydl.downloaded_info_dicts[0]
  416. self.assertEqual(downloaded['format_id'], 'E')
  417. ydl = YDL({'format': 'best[filesize <= ? 3000]'})
  418. ydl.process_ie_result(info_dict)
  419. downloaded = ydl.downloaded_info_dicts[0]
  420. self.assertEqual(downloaded['format_id'], 'F')
  421. ydl = YDL({'format': 'best [filesize = 1000] [width>450]'})
  422. ydl.process_ie_result(info_dict)
  423. downloaded = ydl.downloaded_info_dicts[0]
  424. self.assertEqual(downloaded['format_id'], 'B')
  425. ydl = YDL({'format': 'best [filesize = 1000] [width!=450]'})
  426. ydl.process_ie_result(info_dict)
  427. downloaded = ydl.downloaded_info_dicts[0]
  428. self.assertEqual(downloaded['format_id'], 'C')
  429. ydl = YDL({'format': '[filesize>?1]'})
  430. ydl.process_ie_result(info_dict)
  431. downloaded = ydl.downloaded_info_dicts[0]
  432. self.assertEqual(downloaded['format_id'], 'G')
  433. ydl = YDL({'format': '[filesize<1M]'})
  434. ydl.process_ie_result(info_dict)
  435. downloaded = ydl.downloaded_info_dicts[0]
  436. self.assertEqual(downloaded['format_id'], 'E')
  437. ydl = YDL({'format': '[filesize<1MiB]'})
  438. ydl.process_ie_result(info_dict)
  439. downloaded = ydl.downloaded_info_dicts[0]
  440. self.assertEqual(downloaded['format_id'], 'G')
  441. ydl = YDL({'format': 'all[width>=400][width<=600]'})
  442. ydl.process_ie_result(info_dict)
  443. downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
  444. self.assertEqual(downloaded_ids, ['B', 'C', 'D'])
  445. ydl = YDL({'format': 'best[height<40]'})
  446. try:
  447. ydl.process_ie_result(info_dict)
  448. except ExtractorError:
  449. pass
  450. self.assertEqual(ydl.downloaded_info_dicts, [])
  451. def test_default_format_spec(self):
  452. ydl = YDL({'simulate': True})
  453. self.assertEqual(ydl._default_format_spec({}), 'bestvideo+bestaudio/best')
  454. ydl = YDL({})
  455. self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
  456. ydl = YDL({'simulate': True})
  457. self.assertEqual(ydl._default_format_spec({'is_live': True}), 'bestvideo+bestaudio/best')
  458. ydl = YDL({'outtmpl': '-'})
  459. self.assertEqual(ydl._default_format_spec({}), 'best/bestvideo+bestaudio')
  460. ydl = YDL({})
  461. self.assertEqual(ydl._default_format_spec({}, download=False), 'bestvideo+bestaudio/best')
  462. self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
  463. class TestYoutubeDL(unittest.TestCase):
  464. def test_subtitles(self):
  465. def s_formats(lang, autocaption=False):
  466. return [{
  467. 'ext': ext,
  468. 'url': 'http://localhost/video.%s.%s' % (lang, ext),
  469. '_auto': autocaption,
  470. } for ext in ['vtt', 'srt', 'ass']]
  471. subtitles = dict((l, s_formats(l)) for l in ['en', 'fr', 'es'])
  472. auto_captions = dict((l, s_formats(l, True)) for l in ['it', 'pt', 'es'])
  473. info_dict = {
  474. 'id': 'test',
  475. 'title': 'Test',
  476. 'url': 'http://localhost/video.mp4',
  477. 'subtitles': subtitles,
  478. 'automatic_captions': auto_captions,
  479. 'extractor': 'TEST',
  480. }
  481. def get_info(params={}):
  482. params.setdefault('simulate', True)
  483. ydl = YDL(params)
  484. ydl.report_warning = lambda *args, **kargs: None
  485. return ydl.process_video_result(info_dict, download=False)
  486. result = get_info()
  487. self.assertFalse(result.get('requested_subtitles'))
  488. self.assertEqual(result['subtitles'], subtitles)
  489. self.assertEqual(result['automatic_captions'], auto_captions)
  490. result = get_info({'writesubtitles': True})
  491. subs = result['requested_subtitles']
  492. self.assertTrue(subs)
  493. self.assertEqual(set(subs.keys()), set(['en']))
  494. self.assertTrue(subs['en'].get('data') is None)
  495. self.assertEqual(subs['en']['ext'], 'ass')
  496. result = get_info({'writesubtitles': True, 'subtitlesformat': 'foo/srt'})
  497. subs = result['requested_subtitles']
  498. self.assertEqual(subs['en']['ext'], 'srt')
  499. result = get_info({'writesubtitles': True, 'subtitleslangs': ['es', 'fr', 'it']})
  500. subs = result['requested_subtitles']
  501. self.assertTrue(subs)
  502. self.assertEqual(set(subs.keys()), set(['es', 'fr']))
  503. result = get_info({'writesubtitles': True, 'writeautomaticsub': True, 'subtitleslangs': ['es', 'pt']})
  504. subs = result['requested_subtitles']
  505. self.assertTrue(subs)
  506. self.assertEqual(set(subs.keys()), set(['es', 'pt']))
  507. self.assertFalse(subs['es']['_auto'])
  508. self.assertTrue(subs['pt']['_auto'])
  509. result = get_info({'writeautomaticsub': True, 'subtitleslangs': ['es', 'pt']})
  510. subs = result['requested_subtitles']
  511. self.assertTrue(subs)
  512. self.assertEqual(set(subs.keys()), set(['es', 'pt']))
  513. self.assertTrue(subs['es']['_auto'])
  514. self.assertTrue(subs['pt']['_auto'])
  515. def test_add_extra_info(self):
  516. test_dict = {
  517. 'extractor': 'Foo',
  518. }
  519. extra_info = {
  520. 'extractor': 'Bar',
  521. 'playlist': 'funny videos',
  522. }
  523. YDL.add_extra_info(test_dict, extra_info)
  524. self.assertEqual(test_dict['extractor'], 'Foo')
  525. self.assertEqual(test_dict['playlist'], 'funny videos')
  526. def test_prepare_filename(self):
  527. info = {
  528. 'id': '1234',
  529. 'ext': 'mp4',
  530. 'width': None,
  531. 'height': 1080,
  532. 'title1': '$PATH',
  533. 'title2': '%PATH%',
  534. }
  535. def fname(templ, na_placeholder='NA'):
  536. params = {'outtmpl': templ}
  537. if na_placeholder != 'NA':
  538. params['outtmpl_na_placeholder'] = na_placeholder
  539. ydl = YoutubeDL(params)
  540. return ydl.prepare_filename(info)
  541. self.assertEqual(fname('%(id)s.%(ext)s'), '1234.mp4')
  542. self.assertEqual(fname('%(id)s-%(width)s.%(ext)s'), '1234-NA.mp4')
  543. NA_TEST_OUTTMPL = '%(uploader_date)s-%(width)d-%(id)s.%(ext)s'
  544. # Replace missing fields with 'NA' by default
  545. self.assertEqual(fname(NA_TEST_OUTTMPL), 'NA-NA-1234.mp4')
  546. # Or by provided placeholder
  547. self.assertEqual(fname(NA_TEST_OUTTMPL, na_placeholder='none'), 'none-none-1234.mp4')
  548. self.assertEqual(fname(NA_TEST_OUTTMPL, na_placeholder=''), '--1234.mp4')
  549. self.assertEqual(fname('%(height)d.%(ext)s'), '1080.mp4')
  550. self.assertEqual(fname('%(height)6d.%(ext)s'), ' 1080.mp4')
  551. self.assertEqual(fname('%(height)-6d.%(ext)s'), '1080 .mp4')
  552. self.assertEqual(fname('%(height)06d.%(ext)s'), '001080.mp4')
  553. self.assertEqual(fname('%(height) 06d.%(ext)s'), ' 01080.mp4')
  554. self.assertEqual(fname('%(height) 06d.%(ext)s'), ' 01080.mp4')
  555. self.assertEqual(fname('%(height)0 6d.%(ext)s'), ' 01080.mp4')
  556. self.assertEqual(fname('%(height)0 6d.%(ext)s'), ' 01080.mp4')
  557. self.assertEqual(fname('%(height) 0 6d.%(ext)s'), ' 01080.mp4')
  558. self.assertEqual(fname('%%'), '%')
  559. self.assertEqual(fname('%%%%'), '%%')
  560. self.assertEqual(fname('%%(height)06d.%(ext)s'), '%(height)06d.mp4')
  561. self.assertEqual(fname('%(width)06d.%(ext)s'), 'NA.mp4')
  562. self.assertEqual(fname('%(width)06d.%%(ext)s'), 'NA.%(ext)s')
  563. self.assertEqual(fname('%%(width)06d.%(ext)s'), '%(width)06d.mp4')
  564. self.assertEqual(fname('Hello %(title1)s'), 'Hello $PATH')
  565. self.assertEqual(fname('Hello %(title2)s'), 'Hello %PATH%')
  566. def test_format_note(self):
  567. ydl = YoutubeDL()
  568. self.assertEqual(ydl._format_note({}), '')
  569. assertRegexpMatches(self, ydl._format_note({
  570. 'vbr': 10,
  571. }), r'^\s*10k$')
  572. assertRegexpMatches(self, ydl._format_note({
  573. 'fps': 30,
  574. }), r'^30fps$')
  575. def test_postprocessors(self):
  576. filename = 'post-processor-testfile.mp4'
  577. audiofile = filename + '.mp3'
  578. class SimplePP(PostProcessor):
  579. def run(self, info):
  580. with open(audiofile, 'wt') as f:
  581. f.write('EXAMPLE')
  582. return [info['filepath']], info
  583. def run_pp(params, PP):
  584. with open(filename, 'wt') as f:
  585. f.write('EXAMPLE')
  586. ydl = YoutubeDL(params)
  587. ydl.add_post_processor(PP())
  588. ydl.post_process(filename, {'filepath': filename})
  589. run_pp({'keepvideo': True}, SimplePP)
  590. self.assertTrue(os.path.exists(filename), '%s doesn\'t exist' % filename)
  591. self.assertTrue(os.path.exists(audiofile), '%s doesn\'t exist' % audiofile)
  592. os.unlink(filename)
  593. os.unlink(audiofile)
  594. run_pp({'keepvideo': False}, SimplePP)
  595. self.assertFalse(os.path.exists(filename), '%s exists' % filename)
  596. self.assertTrue(os.path.exists(audiofile), '%s doesn\'t exist' % audiofile)
  597. os.unlink(audiofile)
  598. class ModifierPP(PostProcessor):
  599. def run(self, info):
  600. with open(info['filepath'], 'wt') as f:
  601. f.write('MODIFIED')
  602. return [], info
  603. run_pp({'keepvideo': False}, ModifierPP)
  604. self.assertTrue(os.path.exists(filename), '%s doesn\'t exist' % filename)
  605. os.unlink(filename)
  606. def test_match_filter(self):
  607. class FilterYDL(YDL):
  608. def __init__(self, *args, **kwargs):
  609. super(FilterYDL, self).__init__(*args, **kwargs)
  610. self.params['simulate'] = True
  611. def process_info(self, info_dict):
  612. super(YDL, self).process_info(info_dict)
  613. def _match_entry(self, info_dict, incomplete):
  614. res = super(FilterYDL, self)._match_entry(info_dict, incomplete)
  615. if res is None:
  616. self.downloaded_info_dicts.append(info_dict)
  617. return res
  618. first = {
  619. 'id': '1',
  620. 'url': TEST_URL,
  621. 'title': 'one',
  622. 'extractor': 'TEST',
  623. 'duration': 30,
  624. 'filesize': 10 * 1024,
  625. 'playlist_id': '42',
  626. 'uploader': "變態妍字幕版 太妍 тест",
  627. 'creator': "тест ' 123 ' тест--",
  628. }
  629. second = {
  630. 'id': '2',
  631. 'url': TEST_URL,
  632. 'title': 'two',
  633. 'extractor': 'TEST',
  634. 'duration': 10,
  635. 'description': 'foo',
  636. 'filesize': 5 * 1024,
  637. 'playlist_id': '43',
  638. 'uploader': "тест 123",
  639. }
  640. videos = [first, second]
  641. def get_videos(filter_=None):
  642. ydl = FilterYDL({'match_filter': filter_})
  643. for v in videos:
  644. ydl.process_ie_result(v, download=True)
  645. return [v['id'] for v in ydl.downloaded_info_dicts]
  646. res = get_videos()
  647. self.assertEqual(res, ['1', '2'])
  648. def f(v):
  649. if v['id'] == '1':
  650. return None
  651. else:
  652. return 'Video id is not 1'
  653. res = get_videos(f)
  654. self.assertEqual(res, ['1'])
  655. f = match_filter_func('duration < 30')
  656. res = get_videos(f)
  657. self.assertEqual(res, ['2'])
  658. f = match_filter_func('description = foo')
  659. res = get_videos(f)
  660. self.assertEqual(res, ['2'])
  661. f = match_filter_func('description =? foo')
  662. res = get_videos(f)
  663. self.assertEqual(res, ['1', '2'])
  664. f = match_filter_func('filesize > 5KiB')
  665. res = get_videos(f)
  666. self.assertEqual(res, ['1'])
  667. f = match_filter_func('playlist_id = 42')
  668. res = get_videos(f)
  669. self.assertEqual(res, ['1'])
  670. f = match_filter_func('uploader = "變態妍字幕版 太妍 тест"')
  671. res = get_videos(f)
  672. self.assertEqual(res, ['1'])
  673. f = match_filter_func('uploader != "變態妍字幕版 太妍 тест"')
  674. res = get_videos(f)
  675. self.assertEqual(res, ['2'])
  676. f = match_filter_func('creator = "тест \' 123 \' тест--"')
  677. res = get_videos(f)
  678. self.assertEqual(res, ['1'])
  679. f = match_filter_func("creator = 'тест \\' 123 \\' тест--'")
  680. res = get_videos(f)
  681. self.assertEqual(res, ['1'])
  682. f = match_filter_func(r"creator = 'тест \' 123 \' тест--' & duration > 30")
  683. res = get_videos(f)
  684. self.assertEqual(res, [])
  685. def test_playlist_items_selection(self):
  686. entries = [{
  687. 'id': compat_str(i),
  688. 'title': compat_str(i),
  689. 'url': TEST_URL,
  690. } for i in range(1, 5)]
  691. playlist = {
  692. '_type': 'playlist',
  693. 'id': 'test',
  694. 'entries': entries,
  695. 'extractor': 'test:playlist',
  696. 'extractor_key': 'test:playlist',
  697. 'webpage_url': 'http://example.com',
  698. }
  699. def get_downloaded_info_dicts(params):
  700. ydl = YDL(params)
  701. # make a deep copy because the dictionary and nested entries
  702. # can be modified
  703. ydl.process_ie_result(copy.deepcopy(playlist))
  704. return ydl.downloaded_info_dicts
  705. def get_ids(params):
  706. return [int(v['id']) for v in get_downloaded_info_dicts(params)]
  707. result = get_ids({})
  708. self.assertEqual(result, [1, 2, 3, 4])
  709. result = get_ids({'playlistend': 10})
  710. self.assertEqual(result, [1, 2, 3, 4])
  711. result = get_ids({'playlistend': 2})
  712. self.assertEqual(result, [1, 2])
  713. result = get_ids({'playliststart': 10})
  714. self.assertEqual(result, [])
  715. result = get_ids({'playliststart': 2})
  716. self.assertEqual(result, [2, 3, 4])
  717. result = get_ids({'playlist_items': '2-4'})
  718. self.assertEqual(result, [2, 3, 4])
  719. result = get_ids({'playlist_items': '2,4'})
  720. self.assertEqual(result, [2, 4])
  721. result = get_ids({'playlist_items': '10'})
  722. self.assertEqual(result, [])
  723. result = get_ids({'playlist_items': '3-10'})
  724. self.assertEqual(result, [3, 4])
  725. result = get_ids({'playlist_items': '2-4,3-4,3'})
  726. self.assertEqual(result, [2, 3, 4])
  727. # Tests for https://github.com/ytdl-org/youtube-dl/issues/10591
  728. # @{
  729. result = get_downloaded_info_dicts({'playlist_items': '2-4,3-4,3'})
  730. self.assertEqual(result[0]['playlist_index'], 2)
  731. self.assertEqual(result[1]['playlist_index'], 3)
  732. result = get_downloaded_info_dicts({'playlist_items': '2-4,3-4,3'})
  733. self.assertEqual(result[0]['playlist_index'], 2)
  734. self.assertEqual(result[1]['playlist_index'], 3)
  735. self.assertEqual(result[2]['playlist_index'], 4)
  736. result = get_downloaded_info_dicts({'playlist_items': '4,2'})
  737. self.assertEqual(result[0]['playlist_index'], 4)
  738. self.assertEqual(result[1]['playlist_index'], 2)
  739. # @}
  740. def test_urlopen_no_file_protocol(self):
  741. # see https://github.com/ytdl-org/youtube-dl/issues/8227
  742. ydl = YDL()
  743. self.assertRaises(compat_urllib_error.URLError, ydl.urlopen, 'file:///etc/passwd')
  744. def test_do_not_override_ie_key_in_url_transparent(self):
  745. ydl = YDL()
  746. class Foo1IE(InfoExtractor):
  747. _VALID_URL = r'foo1:'
  748. def _real_extract(self, url):
  749. return {
  750. '_type': 'url_transparent',
  751. 'url': 'foo2:',
  752. 'ie_key': 'Foo2',
  753. 'title': 'foo1 title',
  754. 'id': 'foo1_id',
  755. }
  756. class Foo2IE(InfoExtractor):
  757. _VALID_URL = r'foo2:'
  758. def _real_extract(self, url):
  759. return {
  760. '_type': 'url',
  761. 'url': 'foo3:',
  762. 'ie_key': 'Foo3',
  763. }
  764. class Foo3IE(InfoExtractor):
  765. _VALID_URL = r'foo3:'
  766. def _real_extract(self, url):
  767. return _make_result([{'url': TEST_URL}], title='foo3 title')
  768. ydl.add_info_extractor(Foo1IE(ydl))
  769. ydl.add_info_extractor(Foo2IE(ydl))
  770. ydl.add_info_extractor(Foo3IE(ydl))
  771. ydl.extract_info('foo1:')
  772. downloaded = ydl.downloaded_info_dicts[0]
  773. self.assertEqual(downloaded['url'], TEST_URL)
  774. self.assertEqual(downloaded['title'], 'foo1 title')
  775. self.assertEqual(downloaded['id'], 'testid')
  776. self.assertEqual(downloaded['extractor'], 'testex')
  777. self.assertEqual(downloaded['extractor_key'], 'TestEx')
  778. # Test case for https://github.com/ytdl-org/youtube-dl/issues/27064
  779. def test_ignoreerrors_for_playlist_with_url_transparent_iterable_entries(self):
  780. class _YDL(YDL):
  781. def __init__(self, *args, **kwargs):
  782. super(_YDL, self).__init__(*args, **kwargs)
  783. def trouble(self, s, tb=None):
  784. pass
  785. ydl = _YDL({
  786. 'format': 'extra',
  787. 'ignoreerrors': True,
  788. })
  789. class VideoIE(InfoExtractor):
  790. _VALID_URL = r'video:(?P<id>\d+)'
  791. def _real_extract(self, url):
  792. video_id = self._match_id(url)
  793. formats = [{
  794. 'format_id': 'default',
  795. 'url': 'url:',
  796. }]
  797. if video_id == '0':
  798. raise ExtractorError('foo')
  799. if video_id == '2':
  800. formats.append({
  801. 'format_id': 'extra',
  802. 'url': TEST_URL,
  803. })
  804. return {
  805. 'id': video_id,
  806. 'title': 'Video %s' % video_id,
  807. 'formats': formats,
  808. }
  809. class PlaylistIE(InfoExtractor):
  810. _VALID_URL = r'playlist:'
  811. def _entries(self):
  812. for n in range(3):
  813. video_id = compat_str(n)
  814. yield {
  815. '_type': 'url_transparent',
  816. 'ie_key': VideoIE.ie_key(),
  817. 'id': video_id,
  818. 'url': 'video:%s' % video_id,
  819. 'title': 'Video Transparent %s' % video_id,
  820. }
  821. def _real_extract(self, url):
  822. return self.playlist_result(self._entries())
  823. ydl.add_info_extractor(VideoIE(ydl))
  824. ydl.add_info_extractor(PlaylistIE(ydl))
  825. info = ydl.extract_info('playlist:')
  826. entries = info['entries']
  827. self.assertEqual(len(entries), 3)
  828. self.assertTrue(entries[0] is None)
  829. self.assertTrue(entries[1] is None)
  830. self.assertEqual(len(ydl.downloaded_info_dicts), 1)
  831. downloaded = ydl.downloaded_info_dicts[0]
  832. self.assertEqual(entries[2], downloaded)
  833. self.assertEqual(downloaded['url'], TEST_URL)
  834. self.assertEqual(downloaded['title'], 'Video Transparent 2')
  835. self.assertEqual(downloaded['id'], '2')
  836. self.assertEqual(downloaded['extractor'], 'Video')
  837. self.assertEqual(downloaded['extractor_key'], 'Video')
  838. def test_default_times(self):
  839. """Test addition of missing upload/release/_date from /release_/timestamp"""
  840. info = {
  841. 'id': '1234',
  842. 'url': TEST_URL,
  843. 'title': 'Title',
  844. 'ext': 'mp4',
  845. 'timestamp': 1631352900,
  846. 'release_timestamp': 1632995931,
  847. }
  848. params = {'simulate': True, }
  849. ydl = FakeYDL(params)
  850. out_info = ydl.process_ie_result(info)
  851. self.assertTrue(isinstance(out_info['upload_date'], compat_str))
  852. self.assertEqual(out_info['upload_date'], '20210911')
  853. self.assertTrue(isinstance(out_info['release_date'], compat_str))
  854. self.assertEqual(out_info['release_date'], '20210930')
  855. if __name__ == '__main__':
  856. unittest.main()