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.

625 lines
25 KiB

11 years ago
11 years ago
11 years ago
  1. import math
  2. import os
  3. import re
  4. import subprocess
  5. import sys
  6. import time
  7. from .utils import (
  8. compat_urllib_error,
  9. compat_urllib_request,
  10. ContentTooShortError,
  11. determine_ext,
  12. encodeFilename,
  13. sanitize_open,
  14. timeconvert,
  15. )
  16. class FileDownloader(object):
  17. """File Downloader class.
  18. File downloader objects are the ones responsible of downloading the
  19. actual video file and writing it to disk.
  20. File downloaders accept a lot of parameters. In order not to saturate
  21. the object constructor with arguments, it receives a dictionary of
  22. options instead.
  23. Available options:
  24. verbose: Print additional info to stdout.
  25. quiet: Do not print messages to stdout.
  26. ratelimit: Download speed limit, in bytes/sec.
  27. retries: Number of times to retry for HTTP error 5xx
  28. buffersize: Size of download buffer in bytes.
  29. noresizebuffer: Do not automatically resize the download buffer.
  30. continuedl: Try to continue downloads if possible.
  31. noprogress: Do not print the progress bar.
  32. logtostderr: Log messages to stderr instead of stdout.
  33. consoletitle: Display progress in console window's titlebar.
  34. nopart: Do not use temporary .part files.
  35. updatetime: Use the Last-modified header to set output file timestamps.
  36. test: Download only first bytes to test the downloader.
  37. min_filesize: Skip files smaller than this size
  38. max_filesize: Skip files larger than this size
  39. """
  40. params = None
  41. def __init__(self, ydl, params):
  42. """Create a FileDownloader object with the given options."""
  43. self.ydl = ydl
  44. self._progress_hooks = []
  45. self.params = params
  46. @staticmethod
  47. def format_bytes(bytes):
  48. if bytes is None:
  49. return 'N/A'
  50. if type(bytes) is str:
  51. bytes = float(bytes)
  52. if bytes == 0.0:
  53. exponent = 0
  54. else:
  55. exponent = int(math.log(bytes, 1024.0))
  56. suffix = ['B','KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB'][exponent]
  57. converted = float(bytes) / float(1024 ** exponent)
  58. return '%.2f%s' % (converted, suffix)
  59. @staticmethod
  60. def format_seconds(seconds):
  61. (mins, secs) = divmod(seconds, 60)
  62. (hours, mins) = divmod(mins, 60)
  63. if hours > 99:
  64. return '--:--:--'
  65. if hours == 0:
  66. return '%02d:%02d' % (mins, secs)
  67. else:
  68. return '%02d:%02d:%02d' % (hours, mins, secs)
  69. @staticmethod
  70. def calc_percent(byte_counter, data_len):
  71. if data_len is None:
  72. return None
  73. return float(byte_counter) / float(data_len) * 100.0
  74. @staticmethod
  75. def format_percent(percent):
  76. if percent is None:
  77. return '---.-%'
  78. return '%6s' % ('%3.1f%%' % percent)
  79. @staticmethod
  80. def calc_eta(start, now, total, current):
  81. if total is None:
  82. return None
  83. dif = now - start
  84. if current == 0 or dif < 0.001: # One millisecond
  85. return None
  86. rate = float(current) / dif
  87. return int((float(total) - float(current)) / rate)
  88. @staticmethod
  89. def format_eta(eta):
  90. if eta is None:
  91. return '--:--'
  92. return FileDownloader.format_seconds(eta)
  93. @staticmethod
  94. def calc_speed(start, now, bytes):
  95. dif = now - start
  96. if bytes == 0 or dif < 0.001: # One millisecond
  97. return None
  98. return float(bytes) / dif
  99. @staticmethod
  100. def format_speed(speed):
  101. if speed is None:
  102. return '%10s' % '---b/s'
  103. return '%10s' % ('%s/s' % FileDownloader.format_bytes(speed))
  104. @staticmethod
  105. def best_block_size(elapsed_time, bytes):
  106. new_min = max(bytes / 2.0, 1.0)
  107. new_max = min(max(bytes * 2.0, 1.0), 4194304) # Do not surpass 4 MB
  108. if elapsed_time < 0.001:
  109. return int(new_max)
  110. rate = bytes / elapsed_time
  111. if rate > new_max:
  112. return int(new_max)
  113. if rate < new_min:
  114. return int(new_min)
  115. return int(rate)
  116. @staticmethod
  117. def parse_bytes(bytestr):
  118. """Parse a string indicating a byte quantity into an integer."""
  119. matchobj = re.match(r'(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$', bytestr)
  120. if matchobj is None:
  121. return None
  122. number = float(matchobj.group(1))
  123. multiplier = 1024.0 ** 'bkmgtpezy'.index(matchobj.group(2).lower())
  124. return int(round(number * multiplier))
  125. def to_screen(self, *args, **kargs):
  126. self.ydl.to_screen(*args, **kargs)
  127. def to_stderr(self, message):
  128. self.ydl.to_screen(message)
  129. def to_console_title(self, message):
  130. self.ydl.to_console_title(message)
  131. def trouble(self, *args, **kargs):
  132. self.ydl.trouble(*args, **kargs)
  133. def report_warning(self, *args, **kargs):
  134. self.ydl.report_warning(*args, **kargs)
  135. def report_error(self, *args, **kargs):
  136. self.ydl.report_error(*args, **kargs)
  137. def slow_down(self, start_time, byte_counter):
  138. """Sleep if the download speed is over the rate limit."""
  139. rate_limit = self.params.get('ratelimit', None)
  140. if rate_limit is None or byte_counter == 0:
  141. return
  142. now = time.time()
  143. elapsed = now - start_time
  144. if elapsed <= 0.0:
  145. return
  146. speed = float(byte_counter) / elapsed
  147. if speed > rate_limit:
  148. time.sleep((byte_counter - rate_limit * (now - start_time)) / rate_limit)
  149. def temp_name(self, filename):
  150. """Returns a temporary filename for the given filename."""
  151. if self.params.get('nopart', False) or filename == u'-' or \
  152. (os.path.exists(encodeFilename(filename)) and not os.path.isfile(encodeFilename(filename))):
  153. return filename
  154. return filename + u'.part'
  155. def undo_temp_name(self, filename):
  156. if filename.endswith(u'.part'):
  157. return filename[:-len(u'.part')]
  158. return filename
  159. def try_rename(self, old_filename, new_filename):
  160. try:
  161. if old_filename == new_filename:
  162. return
  163. os.rename(encodeFilename(old_filename), encodeFilename(new_filename))
  164. except (IOError, OSError):
  165. self.report_error(u'unable to rename file')
  166. def try_utime(self, filename, last_modified_hdr):
  167. """Try to set the last-modified time of the given file."""
  168. if last_modified_hdr is None:
  169. return
  170. if not os.path.isfile(encodeFilename(filename)):
  171. return
  172. timestr = last_modified_hdr
  173. if timestr is None:
  174. return
  175. filetime = timeconvert(timestr)
  176. if filetime is None:
  177. return filetime
  178. # Ignore obviously invalid dates
  179. if filetime == 0:
  180. return
  181. try:
  182. os.utime(filename, (time.time(), filetime))
  183. except:
  184. pass
  185. return filetime
  186. def report_destination(self, filename):
  187. """Report destination filename."""
  188. self.to_screen(u'[download] Destination: ' + filename)
  189. def report_progress(self, percent, data_len_str, speed, eta):
  190. """Report download progress."""
  191. if self.params.get('noprogress', False):
  192. return
  193. clear_line = (u'\x1b[K' if sys.stderr.isatty() and os.name != 'nt' else u'')
  194. if eta is not None:
  195. eta_str = self.format_eta(eta)
  196. else:
  197. eta_str = 'Unknown ETA'
  198. if percent is not None:
  199. percent_str = self.format_percent(percent)
  200. else:
  201. percent_str = 'Unknown %'
  202. speed_str = self.format_speed(speed)
  203. if self.params.get('progress_with_newline', False):
  204. self.to_screen(u'[download] %s of %s at %s ETA %s' %
  205. (percent_str, data_len_str, speed_str, eta_str))
  206. else:
  207. self.to_screen(u'\r%s[download] %s of %s at %s ETA %s' %
  208. (clear_line, percent_str, data_len_str, speed_str, eta_str), skip_eol=True)
  209. self.to_console_title(u'youtube-dl - %s of %s at %s ETA %s' %
  210. (percent_str.strip(), data_len_str.strip(), speed_str.strip(), eta_str.strip()))
  211. def report_resuming_byte(self, resume_len):
  212. """Report attempt to resume at given byte."""
  213. self.to_screen(u'[download] Resuming download at byte %s' % resume_len)
  214. def report_retry(self, count, retries):
  215. """Report retry in case of HTTP error 5xx"""
  216. self.to_screen(u'[download] Got server HTTP error. Retrying (attempt %d of %d)...' % (count, retries))
  217. def report_file_already_downloaded(self, file_name):
  218. """Report file has already been fully downloaded."""
  219. try:
  220. self.to_screen(u'[download] %s has already been downloaded' % file_name)
  221. except UnicodeEncodeError:
  222. self.to_screen(u'[download] The file has already been downloaded')
  223. def report_unable_to_resume(self):
  224. """Report it was impossible to resume download."""
  225. self.to_screen(u'[download] Unable to resume')
  226. def report_finish(self, data_len_str, tot_time):
  227. """Report download finished."""
  228. if self.params.get('noprogress', False):
  229. self.to_screen(u'[download] Download completed')
  230. else:
  231. clear_line = (u'\x1b[K' if sys.stderr.isatty() and os.name != 'nt' else u'')
  232. self.to_screen(u'\r%s[download] 100%% of %s in %s' %
  233. (clear_line, data_len_str, self.format_seconds(tot_time)))
  234. def _download_with_rtmpdump(self, filename, url, player_url, page_url, play_path, tc_url, live):
  235. self.report_destination(filename)
  236. tmpfilename = self.temp_name(filename)
  237. test = self.params.get('test', False)
  238. # Check for rtmpdump first
  239. try:
  240. subprocess.call(['rtmpdump', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  241. except (OSError, IOError):
  242. self.report_error(u'RTMP download detected but "rtmpdump" could not be run')
  243. return False
  244. verbosity_option = '--verbose' if self.params.get('verbose', False) else '--quiet'
  245. # Download using rtmpdump. rtmpdump returns exit code 2 when
  246. # the connection was interrumpted and resuming appears to be
  247. # possible. This is part of rtmpdump's normal usage, AFAIK.
  248. basic_args = ['rtmpdump', verbosity_option, '-r', url, '-o', tmpfilename]
  249. if player_url is not None:
  250. basic_args += ['--swfVfy', player_url]
  251. if page_url is not None:
  252. basic_args += ['--pageUrl', page_url]
  253. if play_path is not None:
  254. basic_args += ['--playpath', play_path]
  255. if tc_url is not None:
  256. basic_args += ['--tcUrl', url]
  257. if test:
  258. basic_args += ['--stop', '1']
  259. if live:
  260. basic_args += ['--live']
  261. args = basic_args + [[], ['--resume', '--skip', '1']][self.params.get('continuedl', False)]
  262. if self.params.get('verbose', False):
  263. try:
  264. import pipes
  265. shell_quote = lambda args: ' '.join(map(pipes.quote, args))
  266. except ImportError:
  267. shell_quote = repr
  268. self.to_screen(u'[debug] rtmpdump command line: ' + shell_quote(args))
  269. retval = subprocess.call(args)
  270. while (retval == 2 or retval == 1) and not test:
  271. prevsize = os.path.getsize(encodeFilename(tmpfilename))
  272. self.to_screen(u'\r[rtmpdump] %s bytes' % prevsize, skip_eol=True)
  273. time.sleep(5.0) # This seems to be needed
  274. retval = subprocess.call(basic_args + ['-e'] + [[], ['-k', '1']][retval == 1])
  275. cursize = os.path.getsize(encodeFilename(tmpfilename))
  276. if prevsize == cursize and retval == 1:
  277. break
  278. # Some rtmp streams seem abort after ~ 99.8%. Don't complain for those
  279. if prevsize == cursize and retval == 2 and cursize > 1024:
  280. self.to_screen(u'\r[rtmpdump] Could not download the whole video. This can happen for some advertisements.')
  281. retval = 0
  282. break
  283. if retval == 0 or (test and retval == 2):
  284. fsize = os.path.getsize(encodeFilename(tmpfilename))
  285. self.to_screen(u'\r[rtmpdump] %s bytes' % fsize)
  286. self.try_rename(tmpfilename, filename)
  287. self._hook_progress({
  288. 'downloaded_bytes': fsize,
  289. 'total_bytes': fsize,
  290. 'filename': filename,
  291. 'status': 'finished',
  292. })
  293. return True
  294. else:
  295. self.to_stderr(u"\n")
  296. self.report_error(u'rtmpdump exited with code %d' % retval)
  297. return False
  298. def _download_with_mplayer(self, filename, url):
  299. self.report_destination(filename)
  300. tmpfilename = self.temp_name(filename)
  301. args = ['mplayer', '-really-quiet', '-vo', 'null', '-vc', 'dummy', '-dumpstream', '-dumpfile', tmpfilename, url]
  302. # Check for mplayer first
  303. try:
  304. subprocess.call(['mplayer', '-h'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  305. except (OSError, IOError):
  306. self.report_error(u'MMS or RTSP download detected but "%s" could not be run' % args[0] )
  307. return False
  308. # Download using mplayer.
  309. retval = subprocess.call(args)
  310. if retval == 0:
  311. fsize = os.path.getsize(encodeFilename(tmpfilename))
  312. self.to_screen(u'\r[%s] %s bytes' % (args[0], fsize))
  313. self.try_rename(tmpfilename, filename)
  314. self._hook_progress({
  315. 'downloaded_bytes': fsize,
  316. 'total_bytes': fsize,
  317. 'filename': filename,
  318. 'status': 'finished',
  319. })
  320. return True
  321. else:
  322. self.to_stderr(u"\n")
  323. self.report_error(u'mplayer exited with code %d' % retval)
  324. return False
  325. def _download_m3u8_with_ffmpeg(self, filename, url):
  326. self.report_destination(filename)
  327. tmpfilename = self.temp_name(filename)
  328. args = ['-y', '-i', url, '-f', 'mp4', '-c', 'copy',
  329. '-bsf:a', 'aac_adtstoasc', tmpfilename]
  330. for program in ['avconv', 'ffmpeg']:
  331. try:
  332. subprocess.call([program, '-version'], stdout=(open(os.path.devnull, 'w')), stderr=subprocess.STDOUT)
  333. break
  334. except (OSError, IOError):
  335. pass
  336. else:
  337. self.report_error(u'm3u8 download detected but ffmpeg or avconv could not be found')
  338. cmd = [program] + args
  339. retval = subprocess.call(cmd)
  340. if retval == 0:
  341. fsize = os.path.getsize(encodeFilename(tmpfilename))
  342. self.to_screen(u'\r[%s] %s bytes' % (args[0], fsize))
  343. self.try_rename(tmpfilename, filename)
  344. self._hook_progress({
  345. 'downloaded_bytes': fsize,
  346. 'total_bytes': fsize,
  347. 'filename': filename,
  348. 'status': 'finished',
  349. })
  350. return True
  351. else:
  352. self.to_stderr(u"\n")
  353. self.report_error(u'ffmpeg exited with code %d' % retval)
  354. return False
  355. def _do_download(self, filename, info_dict):
  356. url = info_dict['url']
  357. # Check file already present
  358. if self.params.get('continuedl', False) and os.path.isfile(encodeFilename(filename)) and not self.params.get('nopart', False):
  359. self.report_file_already_downloaded(filename)
  360. self._hook_progress({
  361. 'filename': filename,
  362. 'status': 'finished',
  363. 'total_bytes': os.path.getsize(encodeFilename(filename)),
  364. })
  365. return True
  366. # Attempt to download using rtmpdump
  367. if url.startswith('rtmp'):
  368. return self._download_with_rtmpdump(filename, url,
  369. info_dict.get('player_url', None),
  370. info_dict.get('page_url', None),
  371. info_dict.get('play_path', None),
  372. info_dict.get('tc_url', None),
  373. info_dict.get('rtmp_live', False))
  374. # Attempt to download using mplayer
  375. if url.startswith('mms') or url.startswith('rtsp'):
  376. return self._download_with_mplayer(filename, url)
  377. # m3u8 manifest are downloaded with ffmpeg
  378. if determine_ext(url) == u'm3u8':
  379. return self._download_m3u8_with_ffmpeg(filename, url)
  380. tmpfilename = self.temp_name(filename)
  381. stream = None
  382. # Do not include the Accept-Encoding header
  383. headers = {'Youtubedl-no-compression': 'True'}
  384. if 'user_agent' in info_dict:
  385. headers['Youtubedl-user-agent'] = info_dict['user_agent']
  386. basic_request = compat_urllib_request.Request(url, None, headers)
  387. request = compat_urllib_request.Request(url, None, headers)
  388. if self.params.get('test', False):
  389. request.add_header('Range','bytes=0-10240')
  390. # Establish possible resume length
  391. if os.path.isfile(encodeFilename(tmpfilename)):
  392. resume_len = os.path.getsize(encodeFilename(tmpfilename))
  393. else:
  394. resume_len = 0
  395. open_mode = 'wb'
  396. if resume_len != 0:
  397. if self.params.get('continuedl', False):
  398. self.report_resuming_byte(resume_len)
  399. request.add_header('Range','bytes=%d-' % resume_len)
  400. open_mode = 'ab'
  401. else:
  402. resume_len = 0
  403. count = 0
  404. retries = self.params.get('retries', 0)
  405. while count <= retries:
  406. # Establish connection
  407. try:
  408. if count == 0 and 'urlhandle' in info_dict:
  409. data = info_dict['urlhandle']
  410. data = compat_urllib_request.urlopen(request)
  411. break
  412. except (compat_urllib_error.HTTPError, ) as err:
  413. if (err.code < 500 or err.code >= 600) and err.code != 416:
  414. # Unexpected HTTP error
  415. raise
  416. elif err.code == 416:
  417. # Unable to resume (requested range not satisfiable)
  418. try:
  419. # Open the connection again without the range header
  420. data = compat_urllib_request.urlopen(basic_request)
  421. content_length = data.info()['Content-Length']
  422. except (compat_urllib_error.HTTPError, ) as err:
  423. if err.code < 500 or err.code >= 600:
  424. raise
  425. else:
  426. # Examine the reported length
  427. if (content_length is not None and
  428. (resume_len - 100 < int(content_length) < resume_len + 100)):
  429. # The file had already been fully downloaded.
  430. # Explanation to the above condition: in issue #175 it was revealed that
  431. # YouTube sometimes adds or removes a few bytes from the end of the file,
  432. # changing the file size slightly and causing problems for some users. So
  433. # I decided to implement a suggested change and consider the file
  434. # completely downloaded if the file size differs less than 100 bytes from
  435. # the one in the hard drive.
  436. self.report_file_already_downloaded(filename)
  437. self.try_rename(tmpfilename, filename)
  438. self._hook_progress({
  439. 'filename': filename,
  440. 'status': 'finished',
  441. })
  442. return True
  443. else:
  444. # The length does not match, we start the download over
  445. self.report_unable_to_resume()
  446. open_mode = 'wb'
  447. break
  448. # Retry
  449. count += 1
  450. if count <= retries:
  451. self.report_retry(count, retries)
  452. if count > retries:
  453. self.report_error(u'giving up after %s retries' % retries)
  454. return False
  455. data_len = data.info().get('Content-length', None)
  456. if data_len is not None:
  457. data_len = int(data_len) + resume_len
  458. min_data_len = self.params.get("min_filesize", None)
  459. max_data_len = self.params.get("max_filesize", None)
  460. if min_data_len is not None and data_len < min_data_len:
  461. self.to_screen(u'\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len))
  462. return False
  463. if max_data_len is not None and data_len > max_data_len:
  464. self.to_screen(u'\r[download] File is larger than max-filesize (%s bytes > %s bytes). Aborting.' % (data_len, max_data_len))
  465. return False
  466. data_len_str = self.format_bytes(data_len)
  467. byte_counter = 0 + resume_len
  468. block_size = self.params.get('buffersize', 1024)
  469. start = time.time()
  470. while True:
  471. # Download and write
  472. before = time.time()
  473. data_block = data.read(block_size)
  474. after = time.time()
  475. if len(data_block) == 0:
  476. break
  477. byte_counter += len(data_block)
  478. # Open file just in time
  479. if stream is None:
  480. try:
  481. (stream, tmpfilename) = sanitize_open(tmpfilename, open_mode)
  482. assert stream is not None
  483. filename = self.undo_temp_name(tmpfilename)
  484. self.report_destination(filename)
  485. except (OSError, IOError) as err:
  486. self.report_error(u'unable to open for writing: %s' % str(err))
  487. return False
  488. try:
  489. stream.write(data_block)
  490. except (IOError, OSError) as err:
  491. self.to_stderr(u"\n")
  492. self.report_error(u'unable to write data: %s' % str(err))
  493. return False
  494. if not self.params.get('noresizebuffer', False):
  495. block_size = self.best_block_size(after - before, len(data_block))
  496. # Progress message
  497. speed = self.calc_speed(start, time.time(), byte_counter - resume_len)
  498. if data_len is None:
  499. eta = percent = None
  500. else:
  501. percent = self.calc_percent(byte_counter, data_len)
  502. eta = self.calc_eta(start, time.time(), data_len - resume_len, byte_counter - resume_len)
  503. self.report_progress(percent, data_len_str, speed, eta)
  504. self._hook_progress({
  505. 'downloaded_bytes': byte_counter,
  506. 'total_bytes': data_len,
  507. 'tmpfilename': tmpfilename,
  508. 'filename': filename,
  509. 'status': 'downloading',
  510. 'eta': eta,
  511. 'speed': speed,
  512. })
  513. # Apply rate limit
  514. self.slow_down(start, byte_counter - resume_len)
  515. if stream is None:
  516. self.to_stderr(u"\n")
  517. self.report_error(u'Did not get any data blocks')
  518. return False
  519. stream.close()
  520. self.report_finish(data_len_str, (time.time() - start))
  521. if data_len is not None and byte_counter != data_len:
  522. raise ContentTooShortError(byte_counter, int(data_len))
  523. self.try_rename(tmpfilename, filename)
  524. # Update file modification time
  525. if self.params.get('updatetime', True):
  526. info_dict['filetime'] = self.try_utime(filename, data.info().get('last-modified', None))
  527. self._hook_progress({
  528. 'downloaded_bytes': byte_counter,
  529. 'total_bytes': byte_counter,
  530. 'filename': filename,
  531. 'status': 'finished',
  532. })
  533. return True
  534. def _hook_progress(self, status):
  535. for ph in self._progress_hooks:
  536. ph(status)
  537. def add_progress_hook(self, ph):
  538. """ ph gets called on download progress, with a dictionary with the entries
  539. * filename: The final filename
  540. * status: One of "downloading" and "finished"
  541. It can also have some of the following entries:
  542. * downloaded_bytes: Bytes on disks
  543. * total_bytes: Total bytes, None if unknown
  544. * tmpfilename: The filename we're currently writing to
  545. * eta: The estimated time in seconds, None if unknown
  546. * speed: The download speed in bytes/second, None if unknown
  547. Hooks are guaranteed to be called at least once (with status "finished")
  548. if the download is successful.
  549. """
  550. self._progress_hooks.append(ph)