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.

92 lines
3.0 KiB

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