"""Keep the selected database media on screen using a fullscreen FFplay process.""" import argparse import json import logging import os from pathlib import Path import shutil import signal import sqlite3 import subprocess import time from urllib.parse import urlsplit LOGGER = logging.getLogger(__name__) POLL_INTERVAL = 2 def select_media(db): """Return (ID, URI), preferring active rows and using the lowest ID to break ties.""" return db.execute(""" SELECT media_id, media_uri FROM media WHERE media_active = 1 OR media_default = 1 ORDER BY CASE WHEN media_active = 1 THEN 0 ELSE 1 END, media_id LIMIT 1 """).fetchone() def resolve_media_uri(uri, directory): if not uri or not uri.strip(): return None # Preserve network/FFmpeg protocol URLs; anchor legacy relative file paths to config.json. if urlsplit(uri).scheme: return uri return str((Path(directory) / uri).resolve()) class Player: def __init__(self, directory, error_log, executable='ffplay'): self.directory = Path(directory) self.error_log = error_log self.executable = executable self.process = None self.selection = object() # Distinct from the initial blank-screen selection. def update(self, media): uri = resolve_media_uri(media[1], self.directory) if media else None selection = (media[0], uri) if media else None if selection == self.selection and self.process is not None and self.process.poll() is None: return self.stop() command = [self.executable, '-hide_banner', '-loglevel', 'error', '-nostats', '-fs'] if uri is None: # Keep a real fullscreen black window open instead of exposing the desktop. command += ['-f', 'lavfi', '-i', 'color=c=black:s=1920x1080:r=1'] else: command += ['-i', uri] self.process = subprocess.Popen( command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=self.error_log, env={**os.environ, 'AV_LOG_FORCE_NOCOLOR': '1'} ) self.selection = selection LOGGER.info('Displaying %s', uri if uri is not None else 'a blank screen') def stop(self): if self.process is None: return if self.process.poll() is None: self.process.terminate() try: self.process.wait(timeout=2) except subprocess.TimeoutExpired: self.process.kill() self.process.wait() else: self.process.wait() self.process = None def request_shutdown(signum, frame): raise KeyboardInterrupt def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--config', type=Path, default=Path(__file__).with_name('config.json')) parser.add_argument('--log-file', type=Path, help='FFplay error log (default: ffplay.log beside config.json)') args = parser.parse_args() config_path = args.config.resolve() with config_path.open() as config_file: config = json.load(config_file) if config['database']['type'].casefold() != 'sqlite': parser.error('The player currently supports only SQLite') database = (config_path.parent / config['database']['name']).resolve() if not database.is_file(): parser.error('Database does not exist; run sc_database_generator.py first') executable = shutil.which('ffplay') if executable is None: parser.error('ffplay must be installed and available on PATH') log_path = args.log_file or config_path.parent / 'ffplay.log' logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s') # Read-only mode prevents accidentally modifying the catalog or creating an empty DB. db = sqlite3.connect(database.as_uri() + '?mode=ro', uri=True, timeout=1) previous_handler = signal.signal(signal.SIGTERM, request_shutdown) try: with log_path.open('ab') as error_log: player = Player(config_path.parent, error_log, executable) try: while True: try: player.update(select_media(db)) except (sqlite3.Error, OSError, ValueError): LOGGER.exception('Unable to update playback; retrying in two seconds') time.sleep(POLL_INTERVAL) finally: player.stop() except KeyboardInterrupt: LOGGER.info('Player stopped') finally: db.close() signal.signal(signal.SIGTERM, previous_handler) if __name__ == '__main__': main()