diff --git a/ffplayout.py b/ffplayout.py index 7976c738..fb03b124 100755 --- a/ffplayout.py +++ b/ffplayout.py @@ -41,7 +41,7 @@ def main(): """ if stdin_args.mode: - output = locate('ffplayout.output.{}.output'.format(stdin_args.mode)) + output = locate(f'ffplayout.output.{stdin_args.mode}.output') output() else: @@ -54,7 +54,7 @@ def main(): mode = os.path.splitext(output)[0] if mode == _playout.mode: - output = locate('ffplayout.output.{}.output'.format(mode)) + output = locate(f'ffplayout.output.{mode}.output') output() diff --git a/ffplayout/filters/default.py b/ffplayout/filters/default.py index 168ff035..c85289a7 100644 --- a/ffplayout/filters/default.py +++ b/ffplayout/filters/default.py @@ -38,7 +38,7 @@ def text_filter(): if _text.add_text and _text.over_pre: if _text.fontfile and os.path.isfile(_text.fontfile): - font = ":fontfile='{}'".format(_text.fontfile) + font = f":fontfile='{_text.fontfile}'" filter_chain = [ "null,zmq=b=tcp\\\\://'{}',drawtext=text=''{}".format( _text.address.replace(':', '\\:'), font)] @@ -71,12 +71,10 @@ def pad_filter(probe): _pre.aspect, abs_tol=0.03): if probe.video[0]['aspect'] < _pre.aspect: filter_chain.append( - 'pad=ih*{}/{}/sar:ih:(ow-iw)/2:(oh-ih)/2'.format(_pre.w, - _pre.h)) + f'pad=ih*{_pre.w}/{_pre.h}/sar:ih:(ow-iw)/2:(oh-ih)/2') elif probe.video[0]['aspect'] > _pre.aspect: filter_chain.append( - 'pad=iw:iw*{}/{}/sar:(ow-iw)/2:(oh-ih)/2'.format(_pre.h, - _pre.w)) + f'pad=iw:iw*{_pre.h}/{_pre.w}/sar:(ow-iw)/2:(oh-ih)/2') return filter_chain @@ -88,7 +86,7 @@ def fps_filter(probe): filter_chain = [] if probe.video[0]['fps'] != _pre.fps: - filter_chain.append('fps={}'.format(_pre.fps)) + filter_chain.append(f'fps={_pre.fps}') return filter_chain @@ -102,11 +100,11 @@ def scale_filter(probe): if int(probe.video[0]['width']) != _pre.w or \ int(probe.video[0]['height']) != _pre.h: - filter_chain.append('scale={}:{}'.format(_pre.w, _pre.h)) + filter_chain.append(f'scale={_pre.w}:{_pre.h}') if not math.isclose(probe.video[0]['aspect'], _pre.aspect, abs_tol=0.03): - filter_chain.append('setdar=dar={}'.format(_pre.aspect)) + filter_chain.append(f'setdar=dar={_pre.aspect}') return filter_chain @@ -118,11 +116,10 @@ def fade_filter(duration, seek, out, track=''): filter_chain = [] if seek > 0.0: - filter_chain.append('{}fade=in:st=0:d=0.5'.format(track)) + filter_chain.append(f'{track}fade=in:st=0:d=0.5') if out != duration: - filter_chain.append('{}fade=out:st={}:d=1.0'.format(track, - out - seek - 1.0)) + filter_chain.append(f'{track}fade=out:st={out - seek - 1.0}:d=1.0') return filter_chain @@ -140,20 +137,18 @@ def overlay_filter(duration, ad, ad_last, ad_next): logo_chain = [] if _pre.logo_scale and \ re.match(r'\d+:-?\d+', _pre.logo_scale): - scale_filter = 'scale={},'.format(_pre.logo_scale) - logo_extras = 'format=rgba,{}colorchannelmixer=aa={}'.format( - scale_filter, _pre.logo_opacity) + scale_filter = f'scale={_pre.logo_scale},' + logo_extras = (f'format=rgba,{scale_filter}' + f'colorchannelmixer=aa={_pre.logo_opacity}') loop = 'loop=loop=-1:size=1:start=0' - logo_chain.append( - 'movie={},{},{}'.format(_pre.logo, loop, logo_extras)) + logo_chain.append(f'movie={_pre.logo},{loop},{logo_extras}') if ad_last: logo_chain.append('fade=in:st=0:d=1.0:alpha=1') if ad_next: - logo_chain.append('fade=out:st={}:d=1.0:alpha=1'.format( - duration - 1)) + logo_chain.append(f'fade=out:st={duration - 1}:d=1.0:alpha=1') - logo_filter = '{}[l];[v][l]{}:shortest=1'.format( - ','.join(logo_chain), _pre.logo_filter) + logo_filter = (f'{",".join(logo_chain)}[l];[v][l]' + f'{_pre.logo_filter}:shortest=1') return logo_filter @@ -165,10 +160,9 @@ def add_audio(probe, duration): line = [] if not probe.audio: - messenger.warning('Clip "{}" has no audio!'.format(probe.src)) - line = [ - 'aevalsrc=0:channel_layout=2:duration={}:sample_rate={}'.format( - duration, 48000)] + messenger.warning(f'Clip "{probe.src}" has no audio!') + line = [(f'aevalsrc=0:channel_layout=2:duration={duration}:' + f'sample_rate={48000}')] return line @@ -180,8 +174,8 @@ def add_loudnorm(probe): loud_filter = [] if probe.audio and _pre.add_loudnorm: - loud_filter = [('loudnorm=I={}:TP={}:LRA={}').format( - _pre.loud_i, _pre.loud_tp, _pre.loud_lra)] + loud_filter = [ + f'loudnorm=I={_pre.loud_i}:TP={_pre.loud_tp}:LRA={_pre.loud_lra}'] return loud_filter @@ -194,7 +188,7 @@ def extend_audio(probe, duration): if probe.audio and 'duration' in probe.audio[0] and \ duration > float(probe.audio[0]['duration']) + 0.1: - pad_filter.append('apad=whole_dur={}'.format(duration)) + pad_filter.append(f'apad=whole_dur={duration}') return pad_filter @@ -204,12 +198,11 @@ def extend_video(probe, duration, target_duration): check video duration, is it shorter then clip duration - pad it """ pad_filter = [] + vid_dur = probe.video[0].get('duration') - if 'duration' in probe.video[0] and \ - target_duration < duration > float( - probe.video[0]['duration']) + 0.1: - pad_filter.append('tpad=stop_mode=add:stop_duration={}'.format( - duration - float(probe.video[0]['duration']))) + if vid_dur and target_duration < duration > float(vid_dur) + 0.1: + pad_filter.append( + f'tpad=stop_mode=add:stop_duration={duration - float(vid_dur)}') return pad_filter @@ -218,34 +211,33 @@ def realtime_filter(duration, track=''): speed_filter = '' if _pre.realtime: - speed_filter = ',{}realtime=speed=1'.format(track) + speed_filter = f',{track}realtime=speed=1' if _global.time_delta < 0: speed = duration / (duration + _global.time_delta) if speed < 1.1: - speed_filter = ',{}realtime=speed={}'.format(track, speed) + speed_filter = f',{track}realtime=speed={speed}' return speed_filter def split_filter(filter_type): map_node = [] - filter_prefix = '' + prefix = '' _filter = '' if filter_type == 'a': - filter_prefix = 'a' + prefix = 'a' if _pre.output_count > 1: for num in range(_pre.output_count): - map_node.append('[{}out{}]'.format(filter_type, num + 1)) + map_node.append(f'[{filter_type}out{num + 1}]') - _filter = ',{}split={}{}'.format(filter_prefix, _pre.output_count, - ''.join(map_node)) + _filter = f',{prefix}split={_pre.output_count}{"".join(map_node)}' else: - _filter = '[{}out1]'.format(filter_type) + _filter = f'[{filter_type}out1]' return _filter @@ -307,7 +299,7 @@ def build_filtergraph(node, node_last, node_next, seek, probe): audio_chain += fade_filter(duration, seek, out, 'a') if video_chain: - video_filter = '{}[v]'.format(','.join(video_chain)) + video_filter = f'{",".join(video_chain)}[v]' else: video_filter = 'null[v]' @@ -316,15 +308,14 @@ def build_filtergraph(node, node_last, node_next, seek, probe): v_split = split_filter('v') video_map = ['-map', '[vout1]'] video_filter = [ - '-filter_complex', '[0:v]{};{}{}{}'.format( - video_filter, logo_filter, v_speed, v_split)] + '-filter_complex', + f'[0:v]{video_filter};{logo_filter}{v_speed}{v_split}'] a_speed = realtime_filter(out - seek, 'a') a_split = split_filter('a') audio_map = ['-map', '[aout1]'] audio_filter = [ - '-filter_complex', '{}{}{}'.format(','.join(audio_chain), - a_speed, a_split)] + '-filter_complex', f'{",".join(audio_chain)}{a_speed}{a_split}'] if probe.video[0]: return video_filter + audio_filter + video_map + audio_map diff --git a/ffplayout/folder.py b/ffplayout/folder.py index 82560182..05cdfcfa 100644 --- a/ffplayout/folder.py +++ b/ffplayout/folder.py @@ -52,7 +52,7 @@ class MediaStore: def fill(self): for ext in _storage.extensions: self.store.extend( - glob.glob(os.path.join(self.folder, '**', '*{}'.format(ext)), + glob.glob(os.path.join(self.folder, '**', f'*{ext}'), recursive=True)) if _storage.shuffle: @@ -84,7 +84,7 @@ class MediaWatcher: def __init__(self, media): self._media = media - self.extensions = ['*{}'.format(ext) for ext in _storage.extensions] + self.extensions = [f'*{ext}' for ext in _storage.extensions] self.event_handler = PatternMatchingEventHandler( patterns=self.extensions) @@ -107,14 +107,14 @@ class MediaWatcher: self._media.add(event.src_path) - messenger.info('Add file to media list: "{}"'.format(event.src_path)) + messenger.info(f'Add file to media list: "{event.src_path}"') def on_moved(self, event): self._media.remove(event.src_path) self._media.add(event.dest_path) - messenger.info('Move file from "{}" to "{}"'.format(event.src_path, - event.dest_path)) + messenger.info( + f'Move file from "{event.src_path}" to "{event.dest_path}"') if _current.clip == event.src_path: _ff.decoder.terminate() @@ -122,8 +122,7 @@ class MediaWatcher: def on_deleted(self, event): self._media.remove(event.src_path) - messenger.info( - 'Remove file from media list: "{}"'.format(event.src_path)) + messenger.info(f'Remove file from media list: "{event.src_path}"') if _current.clip == event.src_path: _ff.decoder.terminate() diff --git a/ffplayout/playlist.py b/ffplayout/playlist.py index 02e754cb..5b5190ec 100644 --- a/ffplayout/playlist.py +++ b/ffplayout/playlist.py @@ -191,7 +191,7 @@ class GetSourceFromPlaylist: if self.clip_nodes is None: self.eof_handling( - 'No valid playlist:\n{}'.format(self.json_file), True, 30) + f'No valid playlist:\n{self.json_file}', True, 30) yield self.src_cmd + self.filtergraph continue diff --git a/ffplayout/utils.py b/ffplayout/utils.py index b201c6c5..d45caef4 100644 --- a/ffplayout/utils.py +++ b/ffplayout/utils.py @@ -377,7 +377,7 @@ class Mailer: message['To'] = _mail.recip message['Subject'] = _mail.subject message['Date'] = formatdate(localtime=True) - message.attach(MIMEText('{} {}'.format(self.time, msg), 'plain')) + message.attach(MIMEText(f'{self.time} {msg}', 'plain')) text = message.as_string() try: @@ -463,7 +463,7 @@ def is_in_system(name): Check whether name is on PATH and marked as executable """ if which(name) is None: - messenger.error('{} is not found on system'.format(name)) + messenger.error(f'{name} is not found on system') sys.exit(1) @@ -483,7 +483,7 @@ def ffmpeg_libs(): info = check_output(cmd, stderr=STDOUT).decode('UTF-8') except CalledProcessError as err: messenger.error('ffmpeg - libs could not be readed!\n' - 'Processing is not possible. Error:\n{}'.format(err)) + f'Processing is not possible. Error:\n{err}') sys.exit(1) for line in info.split('\n'): @@ -550,8 +550,7 @@ class MediaProbe: try: info = json.loads(check_output(cmd).decode('UTF-8')) except CalledProcessError as err: - messenger.error('MediaProbe error in: "{}"\n {}'.format(self.src, - err)) + messenger.error(f'MediaProbe error in: "{self.src}"\n{err}') self.audio.append(None) self.video.append(None) @@ -564,12 +563,12 @@ class MediaProbe: self.audio.append(stream) if stream['codec_type'] == 'video': - if 'display_aspect_ratio' not in stream: - stream['aspect'] = float( - stream['width']) / float(stream['height']) - else: + if stream.get('display_aspect_ratio'): w, h = stream['display_aspect_ratio'].split(':') stream['aspect'] = float(w) / float(h) + else: + stream['aspect'] = float( + stream['width']) / float(stream['height']) a, b = stream['r_frame_rate'].split('/') stream['fps'] = float(a) / float(b) @@ -628,14 +627,11 @@ def ffmpeg_stderr_reader(std_errors, decoder): try: for line in std_errors: if _log.ff_level == 'INFO': - logger.info('{}{}'.format( - prefix, line.decode("utf-8").rstrip())) + logger.info(f'{prefix}{line.decode("utf-8").rstrip()}') elif _log.ff_level == 'WARNING': - logger.warning('{}{}'.format( - prefix, line.decode("utf-8").rstrip())) + logger.warning(f'{prefix}{line.decode("utf-8").rstrip()}') else: - logger.error('{}{}'.format( - prefix, line.decode("utf-8").rstrip())) + logger.error(f'{prefix}{line.decode("utf-8").rstrip()}') except ValueError: pass @@ -678,7 +674,7 @@ def is_int(value, default=False): def is_advertisement(node): - if 'category' in node and node["category"] == 'advertisement': + if node.get('category') == 'advertisement': return True @@ -690,7 +686,7 @@ def valid_json(file): json_object = json.load(file) return json_object except ValueError: - messenger.error("Playlist {} is not JSON conform".format(file)) + messenger.error(f'Playlist {file} is not JSON conform') return None @@ -705,8 +701,8 @@ def check_sync(delta): if _general.stop and abs(delta) > _general.threshold: messenger.error( - 'Sync tolerance value exceeded with {0:.2f} seconds,\n' - 'program terminated!'.format(delta)) + f'Sync tolerance value exceeded with {delta:.2f} seconds,\n' + 'program terminated!') terminate_processes() sys.exit(1) @@ -718,11 +714,9 @@ def check_length(total_play_time): if _playlist.length and total_play_time < _playlist.length - 5 \ and not stdin_args.loop: messenger.error( - 'Playlist ({}) is not long enough!\n' - 'Total play time is: {}, target length is: {}'.format( - get_date(True), - timedelta(seconds=total_play_time), - timedelta(seconds=_playlist.length)) + f'Playlist ({get_date(True)}) is not long enough!\n' + f'Total play time is: {timedelta(seconds=total_play_time)}, ' + f'target length is: {timedelta(seconds=_playlist.length)}' ) @@ -744,26 +738,26 @@ def validate_thread(clip_nodes): if probe.is_remote: if not probe.video[0]: - missing.append('Stream not exist: "{}"'.format(source)) + missing.append(f'Stream not exist: "{source}"') elif not os.path.isfile(source): - missing.append('File not exist: "{}"'.format(source)) + missing.append(f'File not exist: "{source}"') if is_float(node["in"]) and is_float(node["out"]): counter += node["out"] - node["in"] else: - missing.append('Missing Value in: "{}"'.format(node)) + missing.append(f'Missing Value in: "{node}"') if not is_float(node["duration"]): missing.append('No duration Value!') line = '\n'.join(missing) if line: - error += line + '\nIn line: {}\n\n'.format(node) + error += line + f'\nIn line: {node}\n\n' if error: messenger.error( 'Validation error, check JSON playlist, ' - 'values are missing:\n{}'.format(error) + f'values are missing:\n{error}' ) check_length(counter) @@ -796,9 +790,8 @@ def set_length(duration, seek, out): def loop_input(source, src_duration, target_duration): # loop filles n times loop_count = math.ceil(target_duration / src_duration) - messenger.info( - 'Loop "{0}" {1} times, total duration: {2:.2f}'.format( - source, loop_count, target_duration)) + messenger.info(f'Loop "{source}" {loop_count} times, ' + f'total duration: {target_duration:.2f}') return ['-stream_loop', str(loop_count), '-i', source, '-t', str(target_duration)] @@ -812,11 +805,9 @@ def gen_dummy(duration): # noise = 'noise=alls=50:allf=t+u,hue=s=0' return [ '-f', 'lavfi', '-i', - 'color=c={}:s={}x{}:d={}:r={},format=pix_fmts=yuv420p'.format( - color, _pre.w, _pre.h, duration, _pre.fps - ), - '-f', 'lavfi', '-i', 'anoisesrc=d={}:c=pink:r=48000:a=0.05'.format( - duration) + f'color=c={color}:s={_pre.w}x{_pre.h}:d={duration}:r={_pre.fps},' + 'format=pix_fmts=yuv420p', + '-f', 'lavfi', '-i', f'anoisesrc=d={duration}:c=pink:r=48000:a=0.05' ] @@ -828,12 +819,12 @@ def gen_filler(duration): probe.load(_storage.filler) if probe.format: - if 'duration' in probe.format: + if probe.format.get('duration'): filler_duration = float(probe.format['duration']) if filler_duration > duration: # cut filler messenger.info( - 'Generate filler with {0:.2f} seconds'.format(duration)) + f'Generate filler with {duration:.2f} seconds') return probe, ['-i', _storage.filler] + set_length( filler_duration, 0, duration) else: @@ -860,13 +851,13 @@ def src_or_dummy(probe, src, dur, seek, out): if probe.is_remote and probe.video[0]: if seek > 0.0: messenger.warning( - 'Seek in live source "{}" not supported!'.format(src)) + f'Seek in live source "{src}" not supported!') return ['-i', src] + set_length(86400.0, seek, out) elif src and os.path.isfile(src): if out > dur: if seek > 0.0: messenger.warning( - 'Seek in looped source "{}" not supported!'.format(src)) + f'Seek in looped source "{src}" not supported!') return ['-i', src] + set_length(dur, seek, out - seek) else: # FIXME: when list starts with looped clip, @@ -875,7 +866,7 @@ def src_or_dummy(probe, src, dur, seek, out): else: return seek_in(seek) + ['-i', src] + set_length(dur, seek, out) else: - messenger.error('Clip/URL not exist:\n{}'.format(src)) + messenger.error(f'Clip/URL not exist:\n{src}') return gen_dummy(out - seek) @@ -944,30 +935,27 @@ def handle_list_end(probe, new_length, src, begin, dur, seek, out): if new_out > dur: new_out = dur else: - messenger.info( - 'We are over time, new length is: {0:.2f}'.format(new_length)) + messenger.info(f'We are over time, new length is: {new_length:.2f}') missing_secs = abs(new_length - (dur - seek)) if dur > new_length > 1.5 and dur - seek >= new_length: src_cmd = src_or_dummy(probe, src, dur, seek, new_out) elif dur > new_length > 0.0: - messenger.info( - 'Last clip less then 1.5 second long, skip:\n{}'.format(src)) + messenger.info(f'Last clip less then 1.5 second long, skip:\n{src}') src_cmd = None if missing_secs > 2: new_playlist = False messenger.error( - 'Reach playlist end,\n{0:.2f} seconds needed.'.format( - missing_secs)) + f'Reach playlist end,\n{missing_secs:.2f} seconds needed.') else: new_out = out new_playlist = False src_cmd = src_or_dummy(probe, src, dur, seek, out) messenger.error( - 'Playlist is not long enough:' - '\n{0:.2f} seconds needed.'.format(missing_secs)) + f'Playlist is not long enough:\n{missing_secs:.2f} seconds needed.' + ) return src_cmd, seek, new_out, new_playlist @@ -987,14 +975,14 @@ def timed_source(probe, src, begin, dur, seek, out, first, last): return src_or_dummy(probe, src, dur, _seek, _out), \ _seek, _out, new_list else: - messenger.warning('Clip less then a second, skip:\n{}'.format(src)) + messenger.warning(f'Clip less then a second, skip:\n{src}') return None, 0, 0, True else: if not stdin_args.loop and _playlist.length: check_sync(current_delta) - messenger.debug('current_delta: {:f}'.format(current_delta)) - messenger.debug('total_delta: {:f}'.format(total_delta)) + messenger.debug(f'current_delta: {current_delta:f}') + messenger.debug(f'total_delta: {total_delta:f}') if (total_delta > out - seek and not last) \ or stdin_args.loop or not _playlist.length: @@ -1002,8 +990,7 @@ def timed_source(probe, src, begin, dur, seek, out, first, last): return src_or_dummy(probe, src, dur, seek, out), seek, out, False elif total_delta <= 0: - messenger.info( - 'Start time is over playtime, skip clip:\n{}'.format(src)) + messenger.info(f'Start time is over playtime, skip clip:\n{src}') return None, 0, 0, True elif total_delta < out - seek or last: