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.

109 lines
3.7 KiB

  1. from __future__ import unicode_literals
  2. import os
  3. import re
  4. import subprocess
  5. from ..postprocessor.ffmpeg import FFmpegPostProcessor
  6. from .common import FileDownloader
  7. from ..compat import (
  8. compat_urlparse,
  9. compat_urllib_request,
  10. )
  11. from ..utils import (
  12. check_executable,
  13. encodeFilename,
  14. )
  15. class HlsFD(FileDownloader):
  16. def real_download(self, filename, info_dict):
  17. url = info_dict['url']
  18. self.report_destination(filename)
  19. tmpfilename = self.temp_name(filename)
  20. args = [
  21. '-y', '-i', url, '-f', 'mp4', '-c', 'copy',
  22. '-bsf:a', 'aac_adtstoasc',
  23. encodeFilename(tmpfilename, for_subprocess=True)]
  24. for program in ['avconv', 'ffmpeg']:
  25. if check_executable(program, ['-version']):
  26. break
  27. else:
  28. self.report_error('m3u8 download detected but ffmpeg or avconv could not be found. Please install one.')
  29. return False
  30. cmd = [program] + args
  31. ffpp = FFmpegPostProcessor(downloader=self)
  32. ffpp.check_version()
  33. retval = subprocess.call(cmd)
  34. if retval == 0:
  35. fsize = os.path.getsize(encodeFilename(tmpfilename))
  36. self.to_screen('\r[%s] %s bytes' % (cmd[0], fsize))
  37. self.try_rename(tmpfilename, filename)
  38. self._hook_progress({
  39. 'downloaded_bytes': fsize,
  40. 'total_bytes': fsize,
  41. 'filename': filename,
  42. 'status': 'finished',
  43. })
  44. return True
  45. else:
  46. self.to_stderr('\n')
  47. self.report_error('%s exited with code %d' % (program, retval))
  48. return False
  49. class NativeHlsFD(FileDownloader):
  50. """ A more limited implementation that does not require ffmpeg """
  51. def real_download(self, filename, info_dict):
  52. url = info_dict['url']
  53. self.report_destination(filename)
  54. tmpfilename = self.temp_name(filename)
  55. self.to_screen(
  56. '[hlsnative] %s: Downloading m3u8 manifest' % info_dict['id'])
  57. data = self.ydl.urlopen(url).read()
  58. s = data.decode('utf-8', 'ignore')
  59. segment_urls = []
  60. for line in s.splitlines():
  61. line = line.strip()
  62. if line and not line.startswith('#'):
  63. segment_url = (
  64. line
  65. if re.match(r'^https?://', line)
  66. else compat_urlparse.urljoin(url, line))
  67. segment_urls.append(segment_url)
  68. is_test = self.params.get('test', False)
  69. remaining_bytes = self._TEST_FILE_SIZE if is_test else None
  70. byte_counter = 0
  71. with open(tmpfilename, 'wb') as outf:
  72. for i, segurl in enumerate(segment_urls):
  73. self.to_screen(
  74. '[hlsnative] %s: Downloading segment %d / %d' %
  75. (info_dict['id'], i + 1, len(segment_urls)))
  76. seg_req = compat_urllib_request.Request(segurl)
  77. if remaining_bytes is not None:
  78. seg_req.add_header('Range', 'bytes=0-%d' % (remaining_bytes - 1))
  79. segment = self.ydl.urlopen(seg_req).read()
  80. if remaining_bytes is not None:
  81. segment = segment[:remaining_bytes]
  82. remaining_bytes -= len(segment)
  83. outf.write(segment)
  84. byte_counter += len(segment)
  85. if remaining_bytes is not None and remaining_bytes <= 0:
  86. break
  87. self._hook_progress({
  88. 'downloaded_bytes': byte_counter,
  89. 'total_bytes': byte_counter,
  90. 'filename': filename,
  91. 'status': 'finished',
  92. })
  93. self.try_rename(tmpfilename, filename)
  94. return True