<?php

declare(strict_types=1);

namespace Drupal\ffmpeg_media_streaming\Plugin\FFmpegOutput;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\ffmpeg_media\Plugin\FFmpegOutput\FFmpegOutputBase;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

/**
 * Base class for low-latency streaming output plugins (RTP/WHIP).
 *
 * Provides shared functionality for real-time streaming:
 * - Common low-latency encoding parameters
 * - Streaming output flag
 * - Codec-specific argument building (abstract)
 */
abstract class LowLatencyStreamingOutputBase extends FFmpegOutputBase implements ContainerFactoryPluginInterface {

  /**
   * Constructs a LowLatencyStreamingOutputBase object.
   *
   * @param array<string, mixed> $configuration
   *   Plugin configuration.
   * @param string $plugin_id
   *   Plugin ID.
   * @param mixed $plugin_definition
   *   Plugin definition.
   * @param \Drupal\Core\File\FileSystemInterface $fileSystem
   *   File system service.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
   *   Config factory.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    #[Autowire(service: 'file_system')]
    FileSystemInterface $fileSystem,
    protected readonly ConfigFactoryInterface $configFactory,
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $fileSystem);
  }

  /**
   * {@inheritdoc}
   */
  #[\Override]
  #[\NoDiscard]
  public function isStreamingOutput(): bool {
    return TRUE;
  }

  /**
   * Builds base low-latency encoding options shared by all streaming outputs.
   *
   * Subclasses should call this and append protocol-specific options.
   *
   * @return array<int, string>
   *   FFmpeg arguments for low-latency encoding.
   */
  #[\NoDiscard]
  protected function buildBaseLowLatencyOptions(): array {
    return [
      // Disable B-frames for lower latency.
      '-bf', '0',
      // Real-time encoding priority.
      '-preset', 'ultrafast',
      // Reduce GOP size for faster recovery.
      '-g', '30',
      // Disable scene change detection for consistent frame timing.
      '-sc_threshold', '0',
    ];
  }

  /**
   * Builds arguments for codec-specific optimizations.
   *
   * @param string $codecId
   *   The codec plugin ID.
   *
   * @return array<int, string>
   *   FFmpeg arguments for the specified codec.
   */
  #[\NoDiscard]
  abstract public function buildCodecSpecificArguments(string $codecId): array;

}
