# # Rip a disc's main title with HandBrake. # # The command and the retry come from homesvr/ripserver/listener.py # perform_rip. Episode selection is not here: a later step will show a # model suggestion and wait for a person to confirm it. # import asyncio import logging import time from pathlib import Path _LOGGER = logging.getLogger(__name__) # flatpak's HandBrake, not a bare HandBrakeCLI on PATH. _HANDBRAKE = ('flatpak', 'run', '--command=HandBrakeCLI', 'fr.handbrake.ghb') # A real main-title encode takes longer, and writes more, than this. # A shorter or smaller file is retried once without libdvdnav. _MIN_DURATION = 120 _MIN_SIZE = 1_000_000 def main_feature_cmd(disc_dir, output, no_dvdnav=False): "Argv for the main title of DISC_DIR, written to OUTPUT." cmd = [ *_HANDBRAKE, '-i', str(disc_dir), '-o', str(output), '--main-feature', '-N', 'eng', '--native-dub', '--preset', 'Very Fast 480p30', # DVD; no need to go above 480 '--quality', '21', '--encoder', 'x264', '--deinterlace', 'bob', '--markers', ] if no_dvdnav: cmd.append('--no-dvdnav') return cmd async def _encode(cmd, output): "Run one encode. 'ok', 'small' when the file is too short or too small, or 'failed'." started = time.time() proc = await asyncio.create_subprocess_exec( *cmd, stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL, ) rc = await proc.wait() if rc != 0: _LOGGER.error(f'HandBrake failed ({rc}) for {output}') return 'failed' duration = time.time() - started # One stat of the file just written. It does not block the loop for long. size = Path(output).stat().st_size # noqa: ASYNC240 if duration < _MIN_DURATION or size < _MIN_SIZE: _LOGGER.warning( f'HandBrake result for {output} is {duration:.0f}s and {size} bytes' ) return 'small' return 'ok' async def rip_main(disc_dir): "Rip the main title to DISC_DIR/dirname.mkv. The watcher records the file." disc_dir = Path(disc_dir) output = disc_dir / f'{disc_dir.name}.mkv' _LOGGER.info(f'Rip main title of {disc_dir} to {output}') cmd = main_feature_cmd(disc_dir, output) # A non-zero exit is a failure. A finished file that is too short or # too small is the case the old rip retried without libdvdnav. result = await _encode(cmd, output) if result == 'small': _LOGGER.info(f'Retrying {output} with --no-dvdnav') cmd = main_feature_cmd(disc_dir, output, no_dvdnav=True) result = await _encode(cmd, output) if result == 'ok': return output _LOGGER.error(f'Rip failed for {disc_dir}') return None