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.

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