2017-08-21 23:30:13 +00:00
|
|
|
#!/usr/bin/env python3
|
2017-02-10 19:18:22 +00:00
|
|
|
# Copyright © 2017 Kristof Toth <mrtoth@strongds.hu>
|
|
|
|
# This program is free software. It comes without any warranty, to the extent
|
|
|
|
# permitted by applicable law. You can redistribute it and/or modify it under the
|
|
|
|
# terms of the Do What The Fuck You Want To Public License, Version 2,
|
|
|
|
# as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
|
|
|
|
|
2017-10-30 10:47:41 +00:00
|
|
|
from subprocess import call, Popen, PIPE, DEVNULL
|
2017-01-15 20:29:09 +00:00
|
|
|
from os import listdir, remove
|
2017-02-06 11:25:48 +00:00
|
|
|
from os.path import splitext, exists, join
|
2017-01-15 17:26:07 +00:00
|
|
|
from re import match
|
2017-01-15 19:18:07 +00:00
|
|
|
from enum import Enum
|
2017-01-15 19:49:27 +00:00
|
|
|
from datetime import timedelta
|
2017-02-04 15:27:26 +00:00
|
|
|
from math import floor
|
2017-01-15 23:09:49 +00:00
|
|
|
from argparse import ArgumentParser
|
2017-02-15 17:27:33 +00:00
|
|
|
from signal import signal, SIGINT
|
2017-08-21 20:51:05 +00:00
|
|
|
from sys import exit
|
2017-09-02 18:47:01 +00:00
|
|
|
from copy import deepcopy
|
2017-10-30 13:45:11 +00:00
|
|
|
from collections import namedtuple
|
2017-09-02 17:25:35 +00:00
|
|
|
import utility
|
2017-10-30 10:47:41 +00:00
|
|
|
from utility import call_verbose, print_opt, get_output, temporary_directory, yes_no_question, check_dependencies
|
2017-01-15 19:06:19 +00:00
|
|
|
|
|
|
|
|
2017-01-15 19:18:07 +00:00
|
|
|
class Stream(Enum):
|
|
|
|
AUDIO = 1
|
|
|
|
VIDEO = 2
|
|
|
|
|
2017-01-15 20:53:36 +00:00
|
|
|
class File(Enum):
|
|
|
|
LIST = 1
|
|
|
|
LOOP = 2
|
2017-02-04 15:27:26 +00:00
|
|
|
FRACTION = 3
|
|
|
|
OUTPUT = 4
|
2017-01-15 20:53:36 +00:00
|
|
|
|
2017-02-04 21:16:55 +00:00
|
|
|
|
2017-10-30 10:54:33 +00:00
|
|
|
class DownloadFailure(RuntimeError):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
2017-10-29 19:25:01 +00:00
|
|
|
class coub_dl:
|
|
|
|
default_files = {Stream.AUDIO: 'audio', Stream.VIDEO: 'video',
|
|
|
|
File.LIST: 'list.txt', File.LOOP: 'loop', File.FRACTION: 'fraction',
|
|
|
|
File.OUTPUT: 'out'}
|
|
|
|
output_files = {File.OUTPUT}
|
2017-08-21 23:25:52 +00:00
|
|
|
|
|
|
|
|
2017-09-02 15:58:41 +00:00
|
|
|
def __init__(self, url, files_dict, directory):
|
|
|
|
self._url = url
|
|
|
|
self._files_dict = files_dict
|
|
|
|
self._directory = directory
|
2017-10-30 13:45:11 +00:00
|
|
|
self._loopdata = namedtuple('loopdata', ('base', 'fraction', 'time', 'file'))
|
2017-09-02 15:58:41 +00:00
|
|
|
|
|
|
|
|
|
|
|
def __call__(self):
|
|
|
|
# download streams and update FILE dict with extensions
|
|
|
|
self.download_audio_stream()
|
|
|
|
self.download_video_stream()
|
|
|
|
self.read_extensions()
|
2017-10-30 10:54:33 +00:00
|
|
|
self.check_downloads()
|
2017-10-27 00:10:59 +00:00
|
|
|
self.fix_video_stream()
|
2017-09-02 15:58:41 +00:00
|
|
|
|
|
|
|
# write concat helper file for ffmpeg
|
2017-10-30 13:54:05 +00:00
|
|
|
self.calculate_loops()
|
|
|
|
self.write_concat_helper()
|
2017-09-02 15:58:41 +00:00
|
|
|
|
|
|
|
# loop & mux streams
|
2017-10-30 13:45:11 +00:00
|
|
|
self.loop_shorter_stream()
|
2017-09-02 15:58:41 +00:00
|
|
|
self.mux_streams()
|
|
|
|
|
|
|
|
|
|
|
|
def download_audio_stream(self):
|
|
|
|
call(('youtube-dl', '--ignore-config',
|
|
|
|
'--extract-audio',
|
|
|
|
'--output', '{}.%(ext)s'.format(self._files_dict[Stream.AUDIO]),
|
|
|
|
self._url),
|
|
|
|
stdout=DEVNULL, stderr=DEVNULL)
|
|
|
|
|
|
|
|
|
|
|
|
def download_video_stream(self):
|
|
|
|
call(('youtube-dl', '--ignore-config',
|
|
|
|
'--output', '{}.%(ext)s'.format(self._files_dict[Stream.VIDEO]),
|
2017-10-27 00:10:59 +00:00
|
|
|
self._url),
|
2017-09-02 15:58:41 +00:00
|
|
|
stdout=DEVNULL, stderr=DEVNULL)
|
|
|
|
|
|
|
|
|
|
|
|
def read_extensions(self):
|
|
|
|
for file in listdir(self._directory):
|
|
|
|
for filename in self._files_dict:
|
|
|
|
fullname = join(self._directory, file)
|
2017-10-27 00:12:28 +00:00
|
|
|
if match('^{}\..+$'.format(self._files_dict[filename]), fullname):
|
2017-09-02 15:58:41 +00:00
|
|
|
self._files_dict[filename] = fullname
|
|
|
|
|
|
|
|
|
2017-10-30 10:34:35 +00:00
|
|
|
def check_downloads(self):
|
|
|
|
check = {Stream.VIDEO, Stream.AUDIO}
|
|
|
|
if not all({exists(self._files_dict[item]) for item in check}):
|
2017-10-30 10:54:33 +00:00
|
|
|
raise DownloadFailure()
|
2017-10-30 10:34:35 +00:00
|
|
|
|
|
|
|
|
2017-10-27 00:10:59 +00:00
|
|
|
def fix_video_stream(self):
|
|
|
|
""" magic fix for videos served by coub. see https://github.com/rg3/youtube-dl/issues/13754 """
|
|
|
|
with open(self._files_dict[Stream.VIDEO], 'r+b') as f:
|
|
|
|
f.seek(0)
|
|
|
|
f.write(bytes(2))
|
|
|
|
|
|
|
|
|
2017-10-30 13:45:11 +00:00
|
|
|
def calculate_loops(self):
|
|
|
|
audioLen = coub_dl.get_length(self._files_dict[Stream.AUDIO])
|
|
|
|
videoLen = coub_dl.get_length(self._files_dict[Stream.VIDEO])
|
|
|
|
|
|
|
|
longer = audioLen if audioLen > videoLen else videoLen
|
|
|
|
self._loopdata.time = audioLen if audioLen < videoLen else videoLen
|
|
|
|
self._loopdata.file = self._files_dict[Stream.AUDIO] if audioLen < videoLen else self._files_dict[Stream.VIDEO]
|
|
|
|
self._files_dict[File.LOOP] += splitext(self._loopdata.file)[1]
|
|
|
|
self._files_dict[File.FRACTION] += splitext(self._loopdata.file)[1]
|
|
|
|
|
|
|
|
times = longer.total_seconds() / self._loopdata.time.total_seconds()
|
|
|
|
self._loopdata.base = int(floor(times))
|
|
|
|
self._loopdata.fraction = times % 1
|
|
|
|
|
|
|
|
|
2017-10-30 13:54:05 +00:00
|
|
|
def write_concat_helper(self):
|
|
|
|
with open(self._files_dict[File.LIST], 'w') as f:
|
|
|
|
for i in range(self._loopdata.base):
|
|
|
|
f.write("file '{}'\n".format(self._loopdata.file))
|
|
|
|
f.write("file '{}'\n".format(self._files_dict[File.FRACTION]))
|
|
|
|
|
|
|
|
|
2017-10-30 13:45:11 +00:00
|
|
|
def loop_shorter_stream(self):
|
2017-09-02 15:58:41 +00:00
|
|
|
# prepare last fractional loop
|
2017-10-30 13:45:11 +00:00
|
|
|
call(('ffmpeg', '-i', self._loopdata.file, '-t', str(self._loopdata.fraction *
|
|
|
|
self._loopdata.time.total_seconds()),
|
2017-09-02 15:58:41 +00:00
|
|
|
self._files_dict[File.FRACTION]),
|
|
|
|
stdout=DEVNULL, stderr=DEVNULL)
|
|
|
|
|
|
|
|
# concat them
|
|
|
|
call(('ffmpeg', '-f', 'concat', '-safe', '0', '-i', self._files_dict[File.LIST],
|
|
|
|
'-c', 'copy', self._files_dict[File.LOOP]),
|
|
|
|
stdout=DEVNULL, stderr=DEVNULL)
|
|
|
|
|
|
|
|
|
|
|
|
def mux_streams(self):
|
|
|
|
call(('ffmpeg', '-i', self._files_dict[File.LOOP],
|
|
|
|
'-i', self._files_dict[Stream.AUDIO],
|
|
|
|
'-map', '0:v:0', '-map', '1:a:0',
|
|
|
|
'-c', 'copy', self._files_dict[File.OUTPUT]),
|
|
|
|
stdout=DEVNULL, stderr=DEVNULL)
|
|
|
|
|
|
|
|
|
2017-09-02 17:25:35 +00:00
|
|
|
@staticmethod
|
|
|
|
def get_length(file):
|
|
|
|
data = coub_dl.get_duration(coub_dl.get_command_stderr(('ffprobe', file))).split(':')
|
|
|
|
return timedelta(hours=float(data[0]), minutes=float(data[1]), seconds=float(data[2]))
|
2017-08-21 20:51:05 +00:00
|
|
|
|
|
|
|
|
2017-09-02 17:25:35 +00:00
|
|
|
@staticmethod
|
|
|
|
def get_command_stderr(command):
|
|
|
|
process = Popen(command, stderr=PIPE, stdout=PIPE)
|
|
|
|
out, err = process.communicate()
|
|
|
|
return err
|
2017-02-09 11:16:38 +00:00
|
|
|
|
|
|
|
|
2017-09-02 17:25:35 +00:00
|
|
|
@staticmethod
|
|
|
|
def get_duration(ffprobe_output):
|
|
|
|
durationPattern = r'.*Duration:\s(.+),\sstart.*'
|
|
|
|
regex = match(durationPattern, str(ffprobe_output))
|
|
|
|
duration = regex.groups()[0] if regex else None
|
|
|
|
if not duration:
|
|
|
|
raise ValueError('Cannot process ffprobe output!')
|
|
|
|
return duration
|
2017-02-10 19:11:08 +00:00
|
|
|
|
|
|
|
|
2017-09-02 17:25:35 +00:00
|
|
|
@staticmethod
|
|
|
|
def get_title(url):
|
|
|
|
return get_output(('youtube-dl', '--get-title', url))
|
2017-01-15 19:06:19 +00:00
|
|
|
|
2017-02-06 14:43:04 +00:00
|
|
|
|
2017-09-02 18:47:01 +00:00
|
|
|
def run(URL, output, extension):
|
2017-02-06 12:10:47 +00:00
|
|
|
# create dict that contains files used
|
2017-10-29 19:25:01 +00:00
|
|
|
FILES = deepcopy(coub_dl.default_files)
|
2017-09-02 18:47:01 +00:00
|
|
|
determine_output_filename(URL, output, extension, FILES)
|
2017-02-05 21:53:08 +00:00
|
|
|
|
|
|
|
# ask what to do if output exists
|
|
|
|
if exists(FILES[File.OUTPUT]):
|
|
|
|
answer = yes_no_question('A file named "{}" already exists! Overwrite?'.format(FILES[File.OUTPUT]),
|
|
|
|
default='no')
|
|
|
|
if not answer:
|
|
|
|
print_opt('Exiting!')
|
|
|
|
exit()
|
|
|
|
else:
|
|
|
|
remove(FILES[File.OUTPUT])
|
|
|
|
|
2017-02-06 12:10:47 +00:00
|
|
|
# create temporary directory to work in
|
2017-02-06 14:43:04 +00:00
|
|
|
with temporary_directory() as dir:
|
2017-02-06 11:25:48 +00:00
|
|
|
# update temporary file locations in FILES dict
|
2017-10-29 19:25:01 +00:00
|
|
|
for key in {key: FILES[key] for key in FILES if key not in coub_dl.output_files}:
|
2017-02-06 12:10:47 +00:00
|
|
|
FILES[key] = join(dir, FILES[key])
|
2017-02-05 21:53:08 +00:00
|
|
|
|
2017-09-02 15:58:41 +00:00
|
|
|
coub_dl(URL, FILES, dir)()
|
2017-09-02 17:25:35 +00:00
|
|
|
|
|
|
|
|
|
|
|
def determine_output_filename(url, user_supplied, extension, files_dict):
|
|
|
|
if user_supplied is None:
|
|
|
|
files_dict[File.OUTPUT] = coub_dl.get_title(url)
|
|
|
|
else:
|
|
|
|
files_dict[File.OUTPUT] = user_supplied
|
|
|
|
files_dict[File.OUTPUT] += extension
|
|
|
|
|
|
|
|
|
|
|
|
def parse_cmd_arguments():
|
|
|
|
parser = ArgumentParser(description='Download player-looped videos with youtube-dl & ffmpeg.')
|
|
|
|
parser.add_argument('-nv', '--nonverbose', action='store_true', help='Turn off non-critical messages to user')
|
|
|
|
parser.add_argument('-o', '--output', default=None, help='Specify name of the output file (use -e for extension)')
|
|
|
|
parser.add_argument('-e', '--extension', default='mp4', help='Set the container to use for the output')
|
2017-09-02 18:47:01 +00:00
|
|
|
parser.add_argument('URLs', type=str, nargs='+', help='The URLs of the sites containing the videos to download')
|
2017-09-02 17:25:35 +00:00
|
|
|
|
|
|
|
args = parser.parse_args()
|
|
|
|
args.extension = '.' + args.extension
|
|
|
|
|
|
|
|
return args
|
|
|
|
|
|
|
|
|
2017-10-30 12:06:27 +00:00
|
|
|
def decorate_coubdl_uimsgs(*args):
|
|
|
|
for item in args:
|
|
|
|
setattr(coub_dl, item[0],
|
|
|
|
call_verbose(**item[1])(getattr(coub_dl, item[0])))
|
|
|
|
|
|
|
|
|
2017-09-02 17:25:35 +00:00
|
|
|
if __name__ == '__main__':
|
|
|
|
signal(SIGINT, lambda a, b: exit('\nExiting!'))
|
|
|
|
args = parse_cmd_arguments()
|
|
|
|
utility.VERBOSE = False if args.nonverbose else True
|
2017-10-30 12:06:27 +00:00
|
|
|
decorate_coubdl_uimsgs(('download_audio_stream', {'before_message': 'Downloading audio stream... '}),
|
|
|
|
('download_video_stream', {'before_message': 'Downloading video stream... '}),
|
|
|
|
('loop_shorter_stream', {'before_message': 'Looping shorter stream... '}),
|
|
|
|
('mux_streams', {'before_message': 'Muxing streams... '}))
|
2017-09-02 17:25:35 +00:00
|
|
|
|
2017-10-30 10:47:41 +00:00
|
|
|
check_dependencies((('youtube-dl', '--version'), ('ffmpeg', '-version')))
|
2017-09-02 18:47:01 +00:00
|
|
|
|
|
|
|
for url in set(args.URLs):
|
|
|
|
print_opt('\nCreating video from {}'.format(url))
|
2017-10-30 10:54:33 +00:00
|
|
|
try: run(url, args.output, args.extension)
|
|
|
|
except DownloadFailure: exit('Failed to download streams! This usually happens when Coub changes something.')
|