2017-01-15 22:43:21 +00:00
|
|
|
from subprocess import call, Popen, PIPE, check_output, DEVNULL
|
2017-01-15 20:29:09 +00:00
|
|
|
from os import listdir, remove
|
2017-01-15 22:43:21 +00:00
|
|
|
from os.path import splitext, exists
|
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-05 16:00:08 +00:00
|
|
|
from functools import wraps, partial
|
2017-02-04 21:38:19 +00:00
|
|
|
from atexit import register
|
2017-01-15 17:26:07 +00:00
|
|
|
|
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-02-04 17:38:08 +00:00
|
|
|
def call_verbose(before_message='', after_message='Done!'):
|
|
|
|
def tag(f):
|
2017-02-04 17:00:20 +00:00
|
|
|
@wraps(f)
|
|
|
|
def wrapper(*args, **kwargs):
|
2017-02-04 17:38:08 +00:00
|
|
|
print_opt(before_message, end='', flush=True)
|
2017-02-04 17:00:20 +00:00
|
|
|
f(*args, **kwargs)
|
2017-02-04 17:38:08 +00:00
|
|
|
print_opt(after_message)
|
2017-02-04 17:00:20 +00:00
|
|
|
return wrapper
|
2017-02-04 17:38:08 +00:00
|
|
|
return tag
|
2017-02-04 17:00:20 +00:00
|
|
|
|
2017-02-04 21:16:55 +00:00
|
|
|
|
2017-01-15 22:53:48 +00:00
|
|
|
def print_opt(*args, **kwargs):
|
|
|
|
if VERBOSE:
|
|
|
|
print(*args, **kwargs)
|
|
|
|
|
2017-02-04 21:16:55 +00:00
|
|
|
|
2017-02-04 22:15:33 +00:00
|
|
|
def get_command_stderr(command):
|
2017-01-15 19:06:19 +00:00
|
|
|
process = Popen(command, stderr=PIPE, stdout=PIPE)
|
|
|
|
out, err = process.communicate()
|
|
|
|
return err
|
|
|
|
|
2017-02-04 21:16:55 +00:00
|
|
|
|
2017-02-04 22:15:33 +00:00
|
|
|
def get_duration(ffprobe_output):
|
2017-01-15 19:06:19 +00:00
|
|
|
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-04 21:16:55 +00:00
|
|
|
|
2017-02-04 17:38:08 +00:00
|
|
|
@call_verbose(before_message='Downloading audio stream... ')
|
2017-02-05 16:00:08 +00:00
|
|
|
def download_audio_stream(url, file_dict):
|
2017-02-03 21:54:09 +00:00
|
|
|
call(('youtube-dl', '--ignore-config',
|
|
|
|
'--extract-audio',
|
2017-02-05 16:00:08 +00:00
|
|
|
'--output', '{}.%(ext)s'.format(file_dict[Stream.AUDIO]),
|
|
|
|
url),
|
2017-01-15 22:43:21 +00:00
|
|
|
stdout=DEVNULL, stderr=DEVNULL)
|
2017-02-04 17:00:20 +00:00
|
|
|
|
2017-02-04 21:16:55 +00:00
|
|
|
|
2017-02-04 17:38:08 +00:00
|
|
|
@call_verbose(before_message='Downloading video stream... ')
|
2017-02-05 16:00:08 +00:00
|
|
|
def download_video_stream(url, file_dict):
|
2017-02-03 21:54:09 +00:00
|
|
|
call(('youtube-dl', '--ignore-config',
|
2017-02-05 16:00:08 +00:00
|
|
|
'--output', '{}.%(ext)s'.format(file_dict[Stream.VIDEO]),
|
|
|
|
url),
|
2017-01-15 22:43:21 +00:00
|
|
|
stdout=DEVNULL, stderr=DEVNULL)
|
2017-01-15 21:28:37 +00:00
|
|
|
|
2017-02-04 21:16:55 +00:00
|
|
|
|
2017-02-05 16:00:08 +00:00
|
|
|
def read_extensions(file_dict):
|
2017-01-15 21:28:37 +00:00
|
|
|
for file in listdir():
|
2017-02-05 16:00:08 +00:00
|
|
|
for filename in file_dict:
|
|
|
|
if match('^{}.*'.format(file_dict[filename]), file):
|
|
|
|
file_dict[filename] = file
|
2017-01-15 21:28:37 +00:00
|
|
|
|
2017-02-04 21:16:55 +00:00
|
|
|
|
|
|
|
@call_verbose(before_message='Looping shorter stream... ')
|
2017-02-05 16:00:08 +00:00
|
|
|
def loop_shorter_stream(file_dict, shorter, shorter_file, loop_fraction):
|
|
|
|
# prepare last fractional loop
|
|
|
|
call(('ffmpeg', '-i', shorter_file, '-t', str(loop_fraction * shorter.total_seconds()), file_dict[File.FRACTION]),
|
2017-02-04 21:16:55 +00:00
|
|
|
stdout=DEVNULL, stderr=DEVNULL)
|
|
|
|
|
2017-02-05 16:00:08 +00:00
|
|
|
# concat them
|
|
|
|
call(('ffmpeg', '-f', 'concat', '-i', file_dict[File.LIST],
|
|
|
|
'-c', 'copy', file_dict[File.LOOP]),
|
2017-02-04 21:16:55 +00:00
|
|
|
stdout=DEVNULL, stderr=DEVNULL)
|
|
|
|
|
|
|
|
|
|
|
|
@call_verbose(before_message='Muxing streams... ')
|
2017-02-05 16:00:08 +00:00
|
|
|
def mux_streams(file_dict):
|
|
|
|
call(('ffmpeg', '-i', file_dict[File.LOOP],
|
|
|
|
'-i', file_dict[Stream.AUDIO],
|
2017-02-04 21:16:55 +00:00
|
|
|
'-map', '0:v:0', '-map', '1:a:0',
|
2017-02-05 16:00:08 +00:00
|
|
|
'-c', 'copy', file_dict[File.OUTPUT]),
|
2017-02-04 21:16:55 +00:00
|
|
|
stdout=DEVNULL, stderr=DEVNULL)
|
|
|
|
|
|
|
|
|
2017-02-05 16:00:08 +00:00
|
|
|
def cleanup(file_dict, outputs):
|
|
|
|
for key in file_dict:
|
|
|
|
if key not in outputs:
|
2017-02-04 23:15:41 +00:00
|
|
|
try:
|
2017-02-05 16:00:08 +00:00
|
|
|
remove(file_dict[key])
|
2017-02-04 23:15:41 +00:00
|
|
|
except FileNotFoundError:
|
|
|
|
pass
|
2017-02-04 21:38:19 +00:00
|
|
|
|
|
|
|
|
2017-01-15 22:43:21 +00:00
|
|
|
def yes_no_question(question, default):
|
|
|
|
valid = {"yes": True, "y": True, "ye": True,
|
|
|
|
"no": False, "n": False}
|
|
|
|
if default is None:
|
|
|
|
prompt = " [y/n] "
|
|
|
|
elif default == "yes":
|
|
|
|
prompt = " [Y/n] "
|
|
|
|
elif default == "no":
|
|
|
|
prompt = " [y/N] "
|
|
|
|
else:
|
|
|
|
raise ValueError("Invalid default answer: {}!".format(default))
|
|
|
|
|
|
|
|
while True:
|
|
|
|
print(question + prompt)
|
|
|
|
choice = input().lower()
|
|
|
|
if default is not None and choice == '':
|
|
|
|
return valid[default]
|
|
|
|
elif choice in valid:
|
|
|
|
return valid[choice]
|
|
|
|
else:
|
|
|
|
print("Please respond with 'yes'(y) or 'no'(n)!")
|
|
|
|
|
2017-01-15 19:06:19 +00:00
|
|
|
|
2017-02-04 21:16:55 +00:00
|
|
|
|
|
|
|
# parse 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.')
|
|
|
|
parser.add_argument('url', type=str, help='The URL of the site containing the video to download.')
|
|
|
|
|
|
|
|
args = parser.parse_args()
|
|
|
|
args.extension = '.' + args.extension
|
|
|
|
VERBOSE = False if args.nonverbose else True
|
|
|
|
|
|
|
|
|
2017-01-15 20:53:36 +00:00
|
|
|
FILES = {Stream.AUDIO: 'audio', Stream.VIDEO: 'video',
|
2017-02-04 15:27:26 +00:00
|
|
|
File.LIST: 'list.txt', File.LOOP: 'loop', File.FRACTION: 'fraction',
|
|
|
|
File.OUTPUT: 'output'+args.extension}
|
2017-01-15 20:53:36 +00:00
|
|
|
OUTPUT_KEYS = [File.OUTPUT]
|
2017-01-15 23:09:49 +00:00
|
|
|
URL = args.url
|
2017-01-15 17:26:07 +00:00
|
|
|
|
2017-01-15 19:14:01 +00:00
|
|
|
|
2017-02-05 16:00:08 +00:00
|
|
|
# clean up on exit
|
|
|
|
register(partial(cleanup, FILES, OUTPUT_KEYS))
|
|
|
|
|
|
|
|
|
2017-02-04 13:40:10 +00:00
|
|
|
# fetch video title if no filename was specified
|
|
|
|
if args.output is None:
|
|
|
|
FILES[File.OUTPUT] = check_output(('youtube-dl', '--get-title', args.url)).decode('utf-8').strip()
|
|
|
|
else:
|
|
|
|
FILES[File.OUTPUT] = args.output
|
|
|
|
FILES[File.OUTPUT] += args.extension
|
2017-01-15 22:43:21 +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:
|
2017-01-15 22:53:48 +00:00
|
|
|
print_opt('Exiting!')
|
2017-01-15 22:43:21 +00:00
|
|
|
exit()
|
|
|
|
else:
|
|
|
|
remove(FILES[File.OUTPUT])
|
|
|
|
|
|
|
|
# download streams and update FILE dict with extensions
|
2017-02-05 16:00:08 +00:00
|
|
|
download_audio_stream(URL, FILES)
|
|
|
|
download_video_stream(URL, FILES)
|
|
|
|
read_extensions(FILES)
|
2017-01-15 19:06:19 +00:00
|
|
|
|
2017-01-15 21:28:37 +00:00
|
|
|
# get stream lengths via ffprobe
|
2017-02-04 22:15:33 +00:00
|
|
|
audioData= get_duration(get_command_stderr(('ffprobe', FILES[Stream.AUDIO]))).split(':')
|
|
|
|
videoData = get_duration(get_command_stderr(('ffprobe', FILES[Stream.VIDEO]))).split(':')
|
2017-01-15 19:49:27 +00:00
|
|
|
|
|
|
|
audioLen = timedelta(hours=float(audioData[0]), minutes=float(audioData[1]), seconds=float(audioData[2]))
|
|
|
|
videoLen = timedelta(hours=float(videoData[0]), minutes=float(videoData[1]), seconds=float(videoData[2]))
|
2017-01-15 19:06:19 +00:00
|
|
|
|
2017-01-15 21:28:37 +00:00
|
|
|
# decide which stream needs some looping
|
2017-01-15 19:49:27 +00:00
|
|
|
longer = audioLen if audioLen > videoLen else videoLen
|
|
|
|
shorter = audioLen if audioLen < videoLen else videoLen
|
2017-01-15 19:59:53 +00:00
|
|
|
shorterFile = FILES[Stream.AUDIO] if audioLen < videoLen else FILES[Stream.VIDEO]
|
2017-01-15 20:53:36 +00:00
|
|
|
FILES[File.LOOP] += splitext(shorterFile)[1]
|
2017-02-04 15:27:26 +00:00
|
|
|
FILES[File.FRACTION] += splitext(shorterFile)[1]
|
2017-01-15 19:49:27 +00:00
|
|
|
|
2017-02-04 15:27:26 +00:00
|
|
|
times = longer.total_seconds() / shorter.total_seconds()
|
|
|
|
timesLoop_base = floor(times)
|
|
|
|
timesLoop_fraction = times % 1
|
2017-01-15 19:49:27 +00:00
|
|
|
|
2017-01-15 21:28:37 +00:00
|
|
|
# write concat helper file for ffmpeg
|
2017-01-15 20:53:36 +00:00
|
|
|
with open(FILES[File.LIST], 'w') as f:
|
2017-02-04 15:27:26 +00:00
|
|
|
for i in range(timesLoop_base):
|
2017-01-15 20:18:10 +00:00
|
|
|
print("file '{}'".format(shorterFile), file=f)
|
2017-02-04 15:27:26 +00:00
|
|
|
print("file '{}'".format(FILES[File.FRACTION]), file=f)
|
|
|
|
|
2017-02-05 16:00:08 +00:00
|
|
|
loop_shorter_stream(FILES, shorter, shorterFile, timesLoop_fraction)
|
|
|
|
mux_streams(FILES)
|