Newer
Older
if err:
return err
async def _build_blender_cmd(self, settings: Settings) -> typing.List[str]:
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
frame_start = settings.get('frame_start')
frame_end = settings.get('frame_end')
render_output = settings.get('render_output')
py_lines = [
"import bpy"
]
if frame_start is not None:
py_lines.append(f'bpy.context.scene.frame_start = {frame_start}')
if frame_end is not None:
py_lines.append(f'bpy.context.scene.frame_end = {frame_end}')
py_lines.append(f"bpy.ops.sound.mixdown(filepath={render_output!r}, "
f"codec='FLAC', container='FLAC', "
f"accuracy=128)")
py_lines.append('bpy.ops.wm.quit_blender()')
py_script = '\n'.join(py_lines)
return [
*settings['blender_cmd'],
'--enable-autoexec',
'-noaudio',
'--background',
settings['filepath'],
'--python-exit-code', '47',
'--python-expr', py_script
]
class AbstractFFmpegCommand(AbstractSubprocessCommand, abc.ABC):
index_file: typing.Optional[pathlib.Path] = None
def validate(self, settings: Settings) -> typing.Optional[str]:
# Check that FFmpeg can be found and shlex-split the string.
ffmpeg_cmd, err = self._setting(settings, 'ffmpeg_cmd', is_required=False, default='ffmpeg')
cmd = shlex.split(ffmpeg_cmd)
executable_path: typing.Optional[str] = shutil.which(cmd[0])
return f'FFmpeg command {ffmpeg_cmd!r} not found on $PATH'
settings['ffmpeg_cmd'] = cmd
self._log.debug('Found FFmpeg command at %r', executable_path)
return None
async def execute(self, settings: Settings) -> None:
cmd = self._build_ffmpeg_command(settings)
await self.subprocess(cmd)
if self.index_file is not None and self.index_file.exists():
try:
self.index_file.unlink()
except IOError:
msg = f'unable to unlink file {self.index_file}, ignoring'
await self.worker.register_log(msg)
self._log.warning(msg)
def _build_ffmpeg_command(self, settings: Settings) -> typing.List[str]:
assert isinstance(settings['ffmpeg_cmd'], list), \
'run validate() before _build_ffmpeg_command'
cmd = [
*settings['ffmpeg_cmd'],
*self.ffmpeg_args(settings),
]
return cmd
@abc.abstractmethod
def ffmpeg_args(self, settings: Settings) -> typing.List[str]:
"""Construct the FFmpeg arguments to execute.
Does not need to include the FFmpeg command itself, just
its arguments.
"""
pass
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
def create_index_file(self, input_files: pathlib.Path) -> pathlib.Path:
"""Construct a list of filenames for ffmpeg to process.
The filenames are stored in a file 'ffmpeg-input.txt' that sits in the
same directory as the input files.
It is assumed that 'input_files' contains a glob pattern in the file
name, and not in any directory parts.
The index file will be deleted after successful execution of the ffmpeg
command.
"""
# The index file needs to sit next to the input files, as
# ffmpeg checks for 'unsafe paths'.
self.index_file = input_files.absolute().with_name('ffmpeg-input.txt')
with self.index_file.open('w') as outfile:
for file_path in sorted(input_files.parent.glob(input_files.name)):
escaped = str(file_path.name).replace("'", "\\'")
print("file '%s'" % escaped, file=outfile)
return self.index_file
@command_executor('create_video')
class CreateVideoCommand(AbstractFFmpegCommand):
"""Create a video from individual frames.
Requires FFmpeg to be installed and available with the 'ffmpeg' command.
"""
codec_video = 'h264'
# Select some settings that are useful for scrubbing through the video.
constant_rate_factor = 23
keyframe_interval = 18 # GOP size
max_b_frames: typing.Optional[int] = 0
def validate(self, settings: Settings) -> typing.Optional[str]:
err = super().validate(settings)
if err:
return err
# Check that we know our input and output image files.
input_files, err = self._setting(settings, 'input_files', is_required=True)
if err:
return err
self._log.debug('Input files: %s', input_files)
output_file, err = self._setting(settings, 'output_file', is_required=True)
if err:
return err
self._log.debug('Output file: %s', output_file)
fps, err = self._setting(settings, 'fps', is_required=True, valtype=(int, float))
if err:
return err
self._log.debug('Frame rate: %r fps', fps)
return None
def ffmpeg_args(self, settings: Settings) -> typing.List[str]:
input_files = Path(settings['input_files'])
args = [
'-r', str(settings['fps']),
]
if platform.system() == 'Windows':
# FFMpeg on Windows doesn't support globbing, so we have to do
# that in Python instead.
index_file = self.create_index_file(input_files)
args += [
'-f', 'concat',
'-i', index_file.as_posix(),
]
else:
args += [
'-pattern_type', 'glob',
'-i', input_files.as_posix(),
]
args += [
'-c:v', self.codec_video,
'-crf', str(self.constant_rate_factor),
'-g', str(self.keyframe_interval),
]
if self.max_b_frames is not None:
args.extend(['-bf', str(self.max_b_frames)])
args += [
settings['output_file']
]
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
return args
@command_executor('concatenate_videos')
class ConcatenateVideosCommand(AbstractFFmpegCommand):
"""Create a video by concatenating other videos.
Requires FFmpeg to be installed and available with the 'ffmpeg' command.
"""
def validate(self, settings: Settings) -> typing.Optional[str]:
err = super().validate(settings)
if err:
return err
# Check that we know our input and output image files.
input_files, err = self._setting(settings, 'input_files', is_required=True)
if err:
return err
self._log.debug('Input files: %s', input_files)
output_file, err = self._setting(settings, 'output_file', is_required=True)
if err:
return err
self._log.debug('Output file: %s', output_file)
return None
def ffmpeg_args(self, settings: Settings) -> typing.List[str]:
index_file = self.create_index_file(Path(settings['input_files']))
output_file = Path(settings['output_file'])
self._log.debug('Output file: %s', output_file)
args = [
'-f', 'concat',
'-i', index_file.as_posix(),
'-c', 'copy',
'-y',
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
]
return args
@command_executor('mux_audio')
class MuxAudioCommand(AbstractFFmpegCommand):
def validate(self, settings: Settings) -> typing.Optional[str]:
err = super().validate(settings)
if err:
return err
# Check that we know our input and output image files.
audio_file, err = self._setting(settings, 'audio_file', is_required=True)
if err:
return err
if not Path(audio_file).exists():
return f'Audio file {audio_file} does not exist'
self._log.debug('Audio file: %s', audio_file)
video_file, err = self._setting(settings, 'video_file', is_required=True)
if err:
return err
if not Path(video_file).exists():
return f'Video file {video_file} does not exist'
self._log.debug('Video file: %s', video_file)
output_file, err = self._setting(settings, 'output_file', is_required=True)
if err:
return err
self._log.debug('Output file: %s', output_file)
return None
def ffmpeg_args(self, settings: Settings) -> typing.List[str]:
audio_file = Path(settings['audio_file']).absolute()
video_file = Path(settings['video_file']).absolute()
output_file = Path(settings['output_file']).absolute()
args = [
'-i', str(audio_file),
'-i', str(video_file),
'-c', 'copy',
'-y',
str(output_file),
]
return args
@command_executor('encode_audio')
class EncodeAudioCommand(AbstractFFmpegCommand):
def validate(self, settings: Settings) -> typing.Optional[str]:
err = super().validate(settings)
if err:
return err
# Check that we know our input and output image files.
input_file, err = self._setting(settings, 'input_file', is_required=True)
if err:
return err
if not Path(input_file).exists():
return f'Audio file {input_file} does not exist'
self._log.debug('Audio file: %s', input_file)
output_file, err = self._setting(settings, 'output_file', is_required=True)
if err:
return err
self._log.debug('Output file: %s', output_file)
_, err = self._setting(settings, 'bitrate', is_required=True)
if err:
return err
_, err = self._setting(settings, 'codec', is_required=True)
if err:
return err
return None
def ffmpeg_args(self, settings: Settings) -> typing.List[str]:
input_file = Path(settings['input_file']).absolute()
output_file = Path(settings['output_file']).absolute()
args = [
'-i', str(input_file),
'-c:a', settings['codec'],
'-b:a', settings['bitrate'],
'-y',
str(output_file),
]
return args
@command_executor('move_with_counter')
class MoveWithCounterCommand(AbstractCommand):
# Split '2018_12_06-spring.mkv' into a '2018_12_06' prefix and '-spring.mkv' suffix.
filename_parts = re.compile(r'(?P<prefix>^[0-9_]+)(?P<suffix>.*)$')
def validate(self, settings: Settings):
src, err = self._setting(settings, 'src', True)
if err:
return err
if not src:
return 'src may not be empty'
dest, err = self._setting(settings, 'dest', True)
if err:
return err
if not dest:
return 'dest may not be empty'
async def execute(self, settings: Settings):
src = Path(settings['src'])
if not src.exists():
raise CommandExecutionError('Path %s does not exist, unable to move' % src)
dest = Path(settings['dest'])
fname_parts = self.filename_parts.match(dest.name)
if fname_parts:
prefix = fname_parts.group('prefix') + '_'
suffix = fname_parts.group('suffix')
else:
prefix = dest.stem + '_'
suffix = dest.suffix
self._log.debug('Adding counter to output name between %r and %r', prefix, suffix)
dest = _numbered_path(dest.parent, prefix, suffix)
self._log.info('Moving %s to %s', src, dest)
await self.worker.register_log('%s: Moving %s to %s', self.command_name, src, dest)
await self._mkdir_if_not_exists(dest.parent)
shutil.move(str(src), str(dest))
self.worker.output_produced(dest)
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
@command_executor('create_python_file')
class CreatePythonFile(AbstractCommand):
def validate(self, settings: Settings):
filepath, err = self._setting(settings, 'filepath', True)
if err:
return err
if not filepath:
return 'filepath may not be empty'
if not filepath.endswith('.py'):
return 'filepath must end in .py'
dest, err = self._setting(settings, 'contents', True)
if err:
return err
async def execute(self, settings: Settings):
filepath = Path(settings['filepath'])
await self._mkdir_if_not_exists(filepath.parent)
if filepath.exists():
msg = f'Overwriting Python file {filepath}'
else:
msg = f'Creating Python file {filepath}'
self._log.info(msg)
await self.worker.register_log('%s: %s', self.command_name, msg)
await self.worker.register_log('%s: contents:\n%s', self.command_name, settings['contents'])
filepath.write_text(settings['contents'], encoding='utf-8')