You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

536 lines
20 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
  1. #!/usr/bin/env python
  2. from __future__ import unicode_literals
  3. # Allow direct execution
  4. import os
  5. import sys
  6. import unittest
  7. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  8. import copy
  9. from test.helper import FakeYDL, assertRegexpMatches
  10. from youtube_dl import YoutubeDL
  11. from youtube_dl.extractor import YoutubeIE
  12. from youtube_dl.postprocessor.common import PostProcessor
  13. from youtube_dl.utils import match_filter_func
  14. TEST_URL = 'http://localhost/sample.mp4'
  15. class YDL(FakeYDL):
  16. def __init__(self, *args, **kwargs):
  17. super(YDL, self).__init__(*args, **kwargs)
  18. self.downloaded_info_dicts = []
  19. self.msgs = []
  20. def process_info(self, info_dict):
  21. self.downloaded_info_dicts.append(info_dict)
  22. def to_screen(self, msg):
  23. self.msgs.append(msg)
  24. def _make_result(formats, **kwargs):
  25. res = {
  26. 'formats': formats,
  27. 'id': 'testid',
  28. 'title': 'testttitle',
  29. 'extractor': 'testex',
  30. }
  31. res.update(**kwargs)
  32. return res
  33. class TestFormatSelection(unittest.TestCase):
  34. def test_prefer_free_formats(self):
  35. # Same resolution => download webm
  36. ydl = YDL()
  37. ydl.params['prefer_free_formats'] = True
  38. formats = [
  39. {'ext': 'webm', 'height': 460, 'url': TEST_URL},
  40. {'ext': 'mp4', 'height': 460, 'url': TEST_URL},
  41. ]
  42. info_dict = _make_result(formats)
  43. yie = YoutubeIE(ydl)
  44. yie._sort_formats(info_dict['formats'])
  45. ydl.process_ie_result(info_dict)
  46. downloaded = ydl.downloaded_info_dicts[0]
  47. self.assertEqual(downloaded['ext'], 'webm')
  48. # Different resolution => download best quality (mp4)
  49. ydl = YDL()
  50. ydl.params['prefer_free_formats'] = True
  51. formats = [
  52. {'ext': 'webm', 'height': 720, 'url': TEST_URL},
  53. {'ext': 'mp4', 'height': 1080, 'url': TEST_URL},
  54. ]
  55. info_dict['formats'] = formats
  56. yie = YoutubeIE(ydl)
  57. yie._sort_formats(info_dict['formats'])
  58. ydl.process_ie_result(info_dict)
  59. downloaded = ydl.downloaded_info_dicts[0]
  60. self.assertEqual(downloaded['ext'], 'mp4')
  61. # No prefer_free_formats => prefer mp4 and flv for greater compatibility
  62. ydl = YDL()
  63. ydl.params['prefer_free_formats'] = False
  64. formats = [
  65. {'ext': 'webm', 'height': 720, 'url': TEST_URL},
  66. {'ext': 'mp4', 'height': 720, 'url': TEST_URL},
  67. {'ext': 'flv', 'height': 720, 'url': TEST_URL},
  68. ]
  69. info_dict['formats'] = formats
  70. yie = YoutubeIE(ydl)
  71. yie._sort_formats(info_dict['formats'])
  72. ydl.process_ie_result(info_dict)
  73. downloaded = ydl.downloaded_info_dicts[0]
  74. self.assertEqual(downloaded['ext'], 'mp4')
  75. ydl = YDL()
  76. ydl.params['prefer_free_formats'] = False
  77. formats = [
  78. {'ext': 'flv', 'height': 720, 'url': TEST_URL},
  79. {'ext': 'webm', 'height': 720, 'url': TEST_URL},
  80. ]
  81. info_dict['formats'] = formats
  82. yie = YoutubeIE(ydl)
  83. yie._sort_formats(info_dict['formats'])
  84. ydl.process_ie_result(info_dict)
  85. downloaded = ydl.downloaded_info_dicts[0]
  86. self.assertEqual(downloaded['ext'], 'flv')
  87. def test_format_limit(self):
  88. formats = [
  89. {'format_id': 'meh', 'url': 'http://example.com/meh', 'preference': 1},
  90. {'format_id': 'good', 'url': 'http://example.com/good', 'preference': 2},
  91. {'format_id': 'great', 'url': 'http://example.com/great', 'preference': 3},
  92. {'format_id': 'excellent', 'url': 'http://example.com/exc', 'preference': 4},
  93. ]
  94. info_dict = _make_result(formats)
  95. ydl = YDL()
  96. ydl.process_ie_result(info_dict)
  97. downloaded = ydl.downloaded_info_dicts[0]
  98. self.assertEqual(downloaded['format_id'], 'excellent')
  99. ydl = YDL({'format_limit': 'good'})
  100. assert ydl.params['format_limit'] == 'good'
  101. ydl.process_ie_result(info_dict.copy())
  102. downloaded = ydl.downloaded_info_dicts[0]
  103. self.assertEqual(downloaded['format_id'], 'good')
  104. ydl = YDL({'format_limit': 'great', 'format': 'all'})
  105. ydl.process_ie_result(info_dict.copy())
  106. self.assertEqual(ydl.downloaded_info_dicts[0]['format_id'], 'meh')
  107. self.assertEqual(ydl.downloaded_info_dicts[1]['format_id'], 'good')
  108. self.assertEqual(ydl.downloaded_info_dicts[2]['format_id'], 'great')
  109. self.assertTrue('3' in ydl.msgs[0])
  110. ydl = YDL()
  111. ydl.params['format_limit'] = 'excellent'
  112. ydl.process_ie_result(info_dict.copy())
  113. downloaded = ydl.downloaded_info_dicts[0]
  114. self.assertEqual(downloaded['format_id'], 'excellent')
  115. def test_format_selection(self):
  116. formats = [
  117. {'format_id': '35', 'ext': 'mp4', 'preference': 1, 'url': TEST_URL},
  118. {'format_id': '45', 'ext': 'webm', 'preference': 2, 'url': TEST_URL},
  119. {'format_id': '47', 'ext': 'webm', 'preference': 3, 'url': TEST_URL},
  120. {'format_id': '2', 'ext': 'flv', 'preference': 4, 'url': TEST_URL},
  121. ]
  122. info_dict = _make_result(formats)
  123. ydl = YDL({'format': '20/47'})
  124. ydl.process_ie_result(info_dict.copy())
  125. downloaded = ydl.downloaded_info_dicts[0]
  126. self.assertEqual(downloaded['format_id'], '47')
  127. ydl = YDL({'format': '20/71/worst'})
  128. ydl.process_ie_result(info_dict.copy())
  129. downloaded = ydl.downloaded_info_dicts[0]
  130. self.assertEqual(downloaded['format_id'], '35')
  131. ydl = YDL()
  132. ydl.process_ie_result(info_dict.copy())
  133. downloaded = ydl.downloaded_info_dicts[0]
  134. self.assertEqual(downloaded['format_id'], '2')
  135. ydl = YDL({'format': 'webm/mp4'})
  136. ydl.process_ie_result(info_dict.copy())
  137. downloaded = ydl.downloaded_info_dicts[0]
  138. self.assertEqual(downloaded['format_id'], '47')
  139. ydl = YDL({'format': '3gp/40/mp4'})
  140. ydl.process_ie_result(info_dict.copy())
  141. downloaded = ydl.downloaded_info_dicts[0]
  142. self.assertEqual(downloaded['format_id'], '35')
  143. def test_format_selection_audio(self):
  144. formats = [
  145. {'format_id': 'audio-low', 'ext': 'webm', 'preference': 1, 'vcodec': 'none', 'url': TEST_URL},
  146. {'format_id': 'audio-mid', 'ext': 'webm', 'preference': 2, 'vcodec': 'none', 'url': TEST_URL},
  147. {'format_id': 'audio-high', 'ext': 'flv', 'preference': 3, 'vcodec': 'none', 'url': TEST_URL},
  148. {'format_id': 'vid', 'ext': 'mp4', 'preference': 4, 'url': TEST_URL},
  149. ]
  150. info_dict = _make_result(formats)
  151. ydl = YDL({'format': 'bestaudio'})
  152. ydl.process_ie_result(info_dict.copy())
  153. downloaded = ydl.downloaded_info_dicts[0]
  154. self.assertEqual(downloaded['format_id'], 'audio-high')
  155. ydl = YDL({'format': 'worstaudio'})
  156. ydl.process_ie_result(info_dict.copy())
  157. downloaded = ydl.downloaded_info_dicts[0]
  158. self.assertEqual(downloaded['format_id'], 'audio-low')
  159. formats = [
  160. {'format_id': 'vid-low', 'ext': 'mp4', 'preference': 1, 'url': TEST_URL},
  161. {'format_id': 'vid-high', 'ext': 'mp4', 'preference': 2, 'url': TEST_URL},
  162. ]
  163. info_dict = _make_result(formats)
  164. ydl = YDL({'format': 'bestaudio/worstaudio/best'})
  165. ydl.process_ie_result(info_dict.copy())
  166. downloaded = ydl.downloaded_info_dicts[0]
  167. self.assertEqual(downloaded['format_id'], 'vid-high')
  168. def test_format_selection_audio_exts(self):
  169. formats = [
  170. {'format_id': 'mp3-64', 'ext': 'mp3', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
  171. {'format_id': 'ogg-64', 'ext': 'ogg', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
  172. {'format_id': 'aac-64', 'ext': 'aac', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
  173. {'format_id': 'mp3-32', 'ext': 'mp3', 'abr': 32, 'url': 'http://_', 'vcodec': 'none'},
  174. {'format_id': 'aac-32', 'ext': 'aac', 'abr': 32, 'url': 'http://_', 'vcodec': 'none'},
  175. ]
  176. info_dict = _make_result(formats)
  177. ydl = YDL({'format': 'best'})
  178. ie = YoutubeIE(ydl)
  179. ie._sort_formats(info_dict['formats'])
  180. ydl.process_ie_result(copy.deepcopy(info_dict))
  181. downloaded = ydl.downloaded_info_dicts[0]
  182. self.assertEqual(downloaded['format_id'], 'aac-64')
  183. ydl = YDL({'format': 'mp3'})
  184. ie = YoutubeIE(ydl)
  185. ie._sort_formats(info_dict['formats'])
  186. ydl.process_ie_result(copy.deepcopy(info_dict))
  187. downloaded = ydl.downloaded_info_dicts[0]
  188. self.assertEqual(downloaded['format_id'], 'mp3-64')
  189. ydl = YDL({'prefer_free_formats': True})
  190. ie = YoutubeIE(ydl)
  191. ie._sort_formats(info_dict['formats'])
  192. ydl.process_ie_result(copy.deepcopy(info_dict))
  193. downloaded = ydl.downloaded_info_dicts[0]
  194. self.assertEqual(downloaded['format_id'], 'ogg-64')
  195. def test_format_selection_video(self):
  196. formats = [
  197. {'format_id': 'dash-video-low', 'ext': 'mp4', 'preference': 1, 'acodec': 'none', 'url': TEST_URL},
  198. {'format_id': 'dash-video-high', 'ext': 'mp4', 'preference': 2, 'acodec': 'none', 'url': TEST_URL},
  199. {'format_id': 'vid', 'ext': 'mp4', 'preference': 3, 'url': TEST_URL},
  200. ]
  201. info_dict = _make_result(formats)
  202. ydl = YDL({'format': 'bestvideo'})
  203. ydl.process_ie_result(info_dict.copy())
  204. downloaded = ydl.downloaded_info_dicts[0]
  205. self.assertEqual(downloaded['format_id'], 'dash-video-high')
  206. ydl = YDL({'format': 'worstvideo'})
  207. ydl.process_ie_result(info_dict.copy())
  208. downloaded = ydl.downloaded_info_dicts[0]
  209. self.assertEqual(downloaded['format_id'], 'dash-video-low')
  210. def test_youtube_format_selection(self):
  211. order = [
  212. '38', '37', '46', '22', '45', '35', '44', '18', '34', '43', '6', '5', '36', '17', '13',
  213. # Apple HTTP Live Streaming
  214. '96', '95', '94', '93', '92', '132', '151',
  215. # 3D
  216. '85', '84', '102', '83', '101', '82', '100',
  217. # Dash video
  218. '137', '248', '136', '247', '135', '246',
  219. '245', '244', '134', '243', '133', '242', '160',
  220. # Dash audio
  221. '141', '172', '140', '171', '139',
  222. ]
  223. for f1id, f2id in zip(order, order[1:]):
  224. f1 = YoutubeIE._formats[f1id].copy()
  225. f1['format_id'] = f1id
  226. f1['url'] = 'url:' + f1id
  227. f2 = YoutubeIE._formats[f2id].copy()
  228. f2['format_id'] = f2id
  229. f2['url'] = 'url:' + f2id
  230. info_dict = _make_result([f1, f2], extractor='youtube')
  231. ydl = YDL()
  232. yie = YoutubeIE(ydl)
  233. yie._sort_formats(info_dict['formats'])
  234. ydl.process_ie_result(info_dict)
  235. downloaded = ydl.downloaded_info_dicts[0]
  236. self.assertEqual(downloaded['format_id'], f1id)
  237. info_dict = _make_result([f2, f1], extractor='youtube')
  238. ydl = YDL()
  239. yie = YoutubeIE(ydl)
  240. yie._sort_formats(info_dict['formats'])
  241. ydl.process_ie_result(info_dict)
  242. downloaded = ydl.downloaded_info_dicts[0]
  243. self.assertEqual(downloaded['format_id'], f1id)
  244. def test_format_filtering(self):
  245. formats = [
  246. {'format_id': 'A', 'filesize': 500, 'width': 1000},
  247. {'format_id': 'B', 'filesize': 1000, 'width': 500},
  248. {'format_id': 'C', 'filesize': 1000, 'width': 400},
  249. {'format_id': 'D', 'filesize': 2000, 'width': 600},
  250. {'format_id': 'E', 'filesize': 3000},
  251. {'format_id': 'F'},
  252. {'format_id': 'G', 'filesize': 1000000},
  253. ]
  254. for f in formats:
  255. f['url'] = 'http://_/'
  256. f['ext'] = 'unknown'
  257. info_dict = _make_result(formats)
  258. ydl = YDL({'format': 'best[filesize<3000]'})
  259. ydl.process_ie_result(info_dict)
  260. downloaded = ydl.downloaded_info_dicts[0]
  261. self.assertEqual(downloaded['format_id'], 'D')
  262. ydl = YDL({'format': 'best[filesize<=3000]'})
  263. ydl.process_ie_result(info_dict)
  264. downloaded = ydl.downloaded_info_dicts[0]
  265. self.assertEqual(downloaded['format_id'], 'E')
  266. ydl = YDL({'format': 'best[filesize <= ? 3000]'})
  267. ydl.process_ie_result(info_dict)
  268. downloaded = ydl.downloaded_info_dicts[0]
  269. self.assertEqual(downloaded['format_id'], 'F')
  270. ydl = YDL({'format': 'best [filesize = 1000] [width>450]'})
  271. ydl.process_ie_result(info_dict)
  272. downloaded = ydl.downloaded_info_dicts[0]
  273. self.assertEqual(downloaded['format_id'], 'B')
  274. ydl = YDL({'format': 'best [filesize = 1000] [width!=450]'})
  275. ydl.process_ie_result(info_dict)
  276. downloaded = ydl.downloaded_info_dicts[0]
  277. self.assertEqual(downloaded['format_id'], 'C')
  278. ydl = YDL({'format': '[filesize>?1]'})
  279. ydl.process_ie_result(info_dict)
  280. downloaded = ydl.downloaded_info_dicts[0]
  281. self.assertEqual(downloaded['format_id'], 'G')
  282. ydl = YDL({'format': '[filesize<1M]'})
  283. ydl.process_ie_result(info_dict)
  284. downloaded = ydl.downloaded_info_dicts[0]
  285. self.assertEqual(downloaded['format_id'], 'E')
  286. ydl = YDL({'format': '[filesize<1MiB]'})
  287. ydl.process_ie_result(info_dict)
  288. downloaded = ydl.downloaded_info_dicts[0]
  289. self.assertEqual(downloaded['format_id'], 'G')
  290. class TestYoutubeDL(unittest.TestCase):
  291. def test_subtitles(self):
  292. def s_formats(lang, autocaption=False):
  293. return [{
  294. 'ext': ext,
  295. 'url': 'http://localhost/video.%s.%s' % (lang, ext),
  296. '_auto': autocaption,
  297. } for ext in ['vtt', 'srt', 'ass']]
  298. subtitles = dict((l, s_formats(l)) for l in ['en', 'fr', 'es'])
  299. auto_captions = dict((l, s_formats(l, True)) for l in ['it', 'pt', 'es'])
  300. info_dict = {
  301. 'id': 'test',
  302. 'title': 'Test',
  303. 'url': 'http://localhost/video.mp4',
  304. 'subtitles': subtitles,
  305. 'automatic_captions': auto_captions,
  306. 'extractor': 'TEST',
  307. }
  308. def get_info(params={}):
  309. params.setdefault('simulate', True)
  310. ydl = YDL(params)
  311. ydl.report_warning = lambda *args, **kargs: None
  312. return ydl.process_video_result(info_dict, download=False)
  313. result = get_info()
  314. self.assertFalse(result.get('requested_subtitles'))
  315. self.assertEqual(result['subtitles'], subtitles)
  316. self.assertEqual(result['automatic_captions'], auto_captions)
  317. result = get_info({'writesubtitles': True})
  318. subs = result['requested_subtitles']
  319. self.assertTrue(subs)
  320. self.assertEqual(set(subs.keys()), set(['en']))
  321. self.assertTrue(subs['en'].get('data') is None)
  322. self.assertEqual(subs['en']['ext'], 'ass')
  323. result = get_info({'writesubtitles': True, 'subtitlesformat': 'foo/srt'})
  324. subs = result['requested_subtitles']
  325. self.assertEqual(subs['en']['ext'], 'srt')
  326. result = get_info({'writesubtitles': True, 'subtitleslangs': ['es', 'fr', 'it']})
  327. subs = result['requested_subtitles']
  328. self.assertTrue(subs)
  329. self.assertEqual(set(subs.keys()), set(['es', 'fr']))
  330. result = get_info({'writesubtitles': True, 'writeautomaticsub': True, 'subtitleslangs': ['es', 'pt']})
  331. subs = result['requested_subtitles']
  332. self.assertTrue(subs)
  333. self.assertEqual(set(subs.keys()), set(['es', 'pt']))
  334. self.assertFalse(subs['es']['_auto'])
  335. self.assertTrue(subs['pt']['_auto'])
  336. result = get_info({'writeautomaticsub': True, 'subtitleslangs': ['es', 'pt']})
  337. subs = result['requested_subtitles']
  338. self.assertTrue(subs)
  339. self.assertEqual(set(subs.keys()), set(['es', 'pt']))
  340. self.assertTrue(subs['es']['_auto'])
  341. self.assertTrue(subs['pt']['_auto'])
  342. def test_add_extra_info(self):
  343. test_dict = {
  344. 'extractor': 'Foo',
  345. }
  346. extra_info = {
  347. 'extractor': 'Bar',
  348. 'playlist': 'funny videos',
  349. }
  350. YDL.add_extra_info(test_dict, extra_info)
  351. self.assertEqual(test_dict['extractor'], 'Foo')
  352. self.assertEqual(test_dict['playlist'], 'funny videos')
  353. def test_prepare_filename(self):
  354. info = {
  355. 'id': '1234',
  356. 'ext': 'mp4',
  357. 'width': None,
  358. }
  359. def fname(templ):
  360. ydl = YoutubeDL({'outtmpl': templ})
  361. return ydl.prepare_filename(info)
  362. self.assertEqual(fname('%(id)s.%(ext)s'), '1234.mp4')
  363. self.assertEqual(fname('%(id)s-%(width)s.%(ext)s'), '1234-NA.mp4')
  364. # Replace missing fields with 'NA'
  365. self.assertEqual(fname('%(uploader_date)s-%(id)s.%(ext)s'), 'NA-1234.mp4')
  366. def test_format_note(self):
  367. ydl = YoutubeDL()
  368. self.assertEqual(ydl._format_note({}), '')
  369. assertRegexpMatches(self, ydl._format_note({
  370. 'vbr': 10,
  371. }), '^\s*10k$')
  372. def test_postprocessors(self):
  373. filename = 'post-processor-testfile.mp4'
  374. audiofile = filename + '.mp3'
  375. class SimplePP(PostProcessor):
  376. def run(self, info):
  377. with open(audiofile, 'wt') as f:
  378. f.write('EXAMPLE')
  379. info['filepath']
  380. return False, info
  381. def run_pp(params):
  382. with open(filename, 'wt') as f:
  383. f.write('EXAMPLE')
  384. ydl = YoutubeDL(params)
  385. ydl.add_post_processor(SimplePP())
  386. ydl.post_process(filename, {'filepath': filename})
  387. run_pp({'keepvideo': True})
  388. self.assertTrue(os.path.exists(filename), '%s doesn\'t exist' % filename)
  389. self.assertTrue(os.path.exists(audiofile), '%s doesn\'t exist' % audiofile)
  390. os.unlink(filename)
  391. os.unlink(audiofile)
  392. run_pp({'keepvideo': False})
  393. self.assertFalse(os.path.exists(filename), '%s exists' % filename)
  394. self.assertTrue(os.path.exists(audiofile), '%s doesn\'t exist' % audiofile)
  395. os.unlink(audiofile)
  396. def test_match_filter(self):
  397. class FilterYDL(YDL):
  398. def __init__(self, *args, **kwargs):
  399. super(FilterYDL, self).__init__(*args, **kwargs)
  400. self.params['simulate'] = True
  401. def process_info(self, info_dict):
  402. super(YDL, self).process_info(info_dict)
  403. def _match_entry(self, info_dict, incomplete):
  404. res = super(FilterYDL, self)._match_entry(info_dict, incomplete)
  405. if res is None:
  406. self.downloaded_info_dicts.append(info_dict)
  407. return res
  408. first = {
  409. 'id': '1',
  410. 'url': TEST_URL,
  411. 'title': 'one',
  412. 'extractor': 'TEST',
  413. 'duration': 30,
  414. 'filesize': 10 * 1024,
  415. }
  416. second = {
  417. 'id': '2',
  418. 'url': TEST_URL,
  419. 'title': 'two',
  420. 'extractor': 'TEST',
  421. 'duration': 10,
  422. 'description': 'foo',
  423. 'filesize': 5 * 1024,
  424. }
  425. videos = [first, second]
  426. def get_videos(filter_=None):
  427. ydl = FilterYDL({'match_filter': filter_})
  428. for v in videos:
  429. ydl.process_ie_result(v, download=True)
  430. return [v['id'] for v in ydl.downloaded_info_dicts]
  431. res = get_videos()
  432. self.assertEqual(res, ['1', '2'])
  433. def f(v):
  434. if v['id'] == '1':
  435. return None
  436. else:
  437. return 'Video id is not 1'
  438. res = get_videos(f)
  439. self.assertEqual(res, ['1'])
  440. f = match_filter_func('duration < 30')
  441. res = get_videos(f)
  442. self.assertEqual(res, ['2'])
  443. f = match_filter_func('description = foo')
  444. res = get_videos(f)
  445. self.assertEqual(res, ['2'])
  446. f = match_filter_func('description =? foo')
  447. res = get_videos(f)
  448. self.assertEqual(res, ['1', '2'])
  449. f = match_filter_func('filesize > 5KiB')
  450. res = get_videos(f)
  451. self.assertEqual(res, ['1'])
  452. if __name__ == '__main__':
  453. unittest.main()