#include "media/boundary_encode.hpp"
#include "core/json.hpp"
#include "media/rpu_injector.hpp"
#include "media/ffmpeg_raii.hpp"
#include "media/sei_injector.hpp"
#include "media/video_frame_index.hpp"
#include "media/video_stream_selection.hpp"

#include <sstream>
#include <filesystem>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <iomanip>
#include <limits>
#include <optional>
#include <span>
#include <stdexcept>
#include <string_view>
#include <unordered_map>
#include <vector>

#ifdef SMARTCUT_HAS_FFMPEG
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/error.h>
#include <libavutil/hdr_dynamic_metadata.h>
#include <libavutil/opt.h>
#include <libavutil/pixdesc.h>
#include <libavutil/mastering_display_metadata.h>
}
#endif

namespace smartcut::media {
namespace {

template <typename Callback>
class ScopeExit final {
 public:
  explicit ScopeExit(Callback& callback) noexcept : callback_(&callback) {}
  ScopeExit(const ScopeExit&) = delete;
  ScopeExit& operator=(const ScopeExit&) = delete;
  ~ScopeExit() noexcept { (*callback_)(); }

 private:
  Callback* callback_;
};

template <typename Callback>
ScopeExit(Callback&) -> ScopeExit<Callback>;

enum class BoundaryPathRelation {
  distinct,
  same_file,
  indeterminate,
};

struct BoundaryPathCheck {
  BoundaryPathRelation relation{BoundaryPathRelation::distinct};
  std::string detail;
};

BoundaryPathCheck boundary_path_relation(const std::string& input,
                                         const std::string& output) {
  const std::filesystem::path input_path(input);
  const std::filesystem::path output_path(output);
  std::error_code equivalent_error;
  if (std::filesystem::equivalent(input_path, output_path, equivalent_error))
    return {BoundaryPathRelation::same_file, {}};
  if (!equivalent_error) return {};

  // A not-yet-created output is the normal case. Resolve both paths through
  // existing parent components so a lexical alias is still rejected without
  // requiring the output to exist.
  if (equivalent_error != std::errc::no_such_file_or_directory)
    return {BoundaryPathRelation::indeterminate, equivalent_error.message()};
  std::error_code input_error;
  std::error_code output_error;
  const auto canonical_input = std::filesystem::weakly_canonical(input_path, input_error);
  const auto canonical_output = std::filesystem::weakly_canonical(output_path, output_error);
  if (input_error)
    return {BoundaryPathRelation::indeterminate, input_error.message()};
  if (output_error)
    return {BoundaryPathRelation::indeterminate, output_error.message()};
  return {canonical_input == canonical_output ? BoundaryPathRelation::same_file
                                               : BoundaryPathRelation::distinct,
          {}};
}

std::string boundary_public_error(const char* error, const char* phase,
                                  std::uint64_t first_frame,
                                  std::uint64_t end_frame,
                                  const std::string& detail = {}) {
  std::ostringstream report;
  report << "{\"schema\":\"boundary-encode-error-v1\",\"error\":\""
         << smartcut::core::json_escape(error) << "\",\"phase\":\""
         << smartcut::core::json_escape(phase) << "\",\"ffmpeg_error_code\":-1,"
         << "\"ffmpeg_error\":\"\",\"first_frame\":" << first_frame
         << ",\"end_frame\":" << end_frame;
  if (!detail.empty())
    report << ",\"detail\":\"" << smartcut::core::json_escape(detail) << '"';
  report << '}';
  return report.str();
}

#ifdef SMARTCUT_HAS_FFMPEG
bool boundary_exception_injection_enabled() {
#ifdef _MSC_VER
  char* value = nullptr;
  std::size_t length = 0;
  if (_dupenv_s(&value, &length, "SMARTCUT_TEST_BOUNDARY_EXCEPTION") != 0 || !value)
    return false;
  const bool enabled = std::string_view(value) == "1";
  std::free(value);
  return enabled;
#else
  const char* value = std::getenv("SMARTCUT_TEST_BOUNDARY_EXCEPTION");
  return value && std::string_view(value) == "1";
#endif
}
#endif

}  // namespace

#ifdef SMARTCUT_HAS_FFMPEG
static int find_video_stream(AVFormatContext* context) {
  std::vector<VideoStreamRole> roles;
  roles.reserve(context->nb_streams);
  for (unsigned index = 0; index < context->nb_streams; ++index) {
    const auto* stream = context->streams[index];
    roles.push_back(stream->codecpar->codec_type != AVMEDIA_TYPE_VIDEO
                        ? VideoStreamRole::other
                        : (stream->disposition & AV_DISPOSITION_ATTACHED_PIC) != 0
                              ? VideoStreamRole::attached_picture
                              : VideoStreamRole::program_video);
  }
  const auto selected = first_program_video_stream(roles);
  return selected ? static_cast<int>(*selected) : -1;
}
static bool constant_frame_timing(const AVStream* stream, AVRational& frame_rate,
                                  std::int64_t& first_pts) {
  if (!stream || stream->r_frame_rate.num <= 0 || stream->r_frame_rate.den <= 0 ||
      stream->avg_frame_rate.num <= 0 || stream->avg_frame_rate.den <= 0 ||
      av_cmp_q(stream->r_frame_rate, stream->avg_frame_rate) != 0 ||
      stream->time_base.num <= 0 || stream->time_base.den <= 0 ||
      stream->start_time == AV_NOPTS_VALUE) return false;
  frame_rate = stream->avg_frame_rate;
  first_pts = stream->start_time;
  return true;
}
static std::optional<std::uint64_t> frame_for_pts(std::int64_t pts, const AVStream* stream,
                                                   AVRational frame_rate,
                                                   std::int64_t first_pts) {
  if (pts == AV_NOPTS_VALUE || pts < first_pts) return std::nullopt;
  const auto frame = av_rescale_q_rnd(pts - first_pts, stream->time_base,
                                     AVRational{frame_rate.den, frame_rate.num},
                                     AV_ROUND_NEAR_INF);
  return frame < 0 ? std::nullopt : std::optional<std::uint64_t>(static_cast<std::uint64_t>(frame));
}
static std::vector<std::uint8_t> codec_parameter_set_prefix(const AVCodecParameters* parameters) {
  std::vector<std::uint8_t> prefix;
  if (!parameters || !parameters->extradata || parameters->extradata_size < 7 || parameters->extradata[0] != 1) return prefix;
  const auto* data = reinterpret_cast<const std::uint8_t*>(parameters->extradata);
  const auto size = static_cast<std::size_t>(parameters->extradata_size);
  if (parameters->codec_id == AV_CODEC_ID_H264) {
    const auto length_size = static_cast<std::size_t>((data[4] & 3U) + 1U);
    std::size_t cursor = 6;
    const auto append = [&](std::size_t bytes) {
      for (std::size_t shift = length_size; shift > 0; --shift)
        prefix.push_back(static_cast<std::uint8_t>((bytes >> (8U * (shift - 1U))) & 0xffU));
      prefix.insert(prefix.end(), data + cursor, data + cursor + bytes);
    };
    auto count = static_cast<unsigned>(data[5] & 0x1fU);
    for (unsigned item = 0; item < count; ++item) {
      if (cursor + 2 > size) return {};
      const auto bytes = static_cast<std::size_t>((data[cursor] << 8U) | data[cursor + 1]); cursor += 2;
      if (cursor + bytes > size) return {};
      append(bytes); cursor += bytes;
    }
    if (cursor >= size) return prefix;
    count = data[cursor++];
    for (unsigned item = 0; item < count; ++item) {
      if (cursor + 2 > size) return {};
      const auto bytes = static_cast<std::size_t>((data[cursor] << 8U) | data[cursor + 1]); cursor += 2;
      if (cursor + bytes > size) return {};
      append(bytes); cursor += bytes;
    }
    return prefix;
  }
  if (parameters->codec_id != AV_CODEC_ID_HEVC || size < 23) return prefix;
  const auto length_size = static_cast<std::size_t>((data[21] & 3U) + 1U);
  std::size_t cursor = 23;
  const auto arrays = static_cast<unsigned>(data[22]);
  for (unsigned array = 0; array < arrays && cursor + 3 <= size; ++array) {
    const unsigned nal_type = data[cursor++] & 0x3fU;
    const auto count = static_cast<unsigned>((data[cursor] << 8U) | data[cursor + 1]); cursor += 2;
    for (unsigned item = 0; item < count && cursor + 2 <= size; ++item) {
      const auto bytes = static_cast<std::size_t>((data[cursor] << 8U) | data[cursor + 1]); cursor += 2;
      if (cursor + bytes > size) return {};
      if (nal_type >= 32U && nal_type <= 34U) {
        for (std::size_t shift = length_size; shift > 0; --shift) prefix.push_back(static_cast<std::uint8_t>((bytes >> (8U * (shift - 1U))) & 0xffU));
        prefix.insert(prefix.end(), data + cursor, data + cursor + bytes);
      }
      cursor += bytes;
    }
  }
  return prefix;
}
static bool packet_exact_or_hevc_parameter_prefixed(const AVPacket* expected,
                                                     const AVPacket* actual,
                                                     const std::vector<std::uint8_t>& allowed_prefix) {
  if (!expected || !actual) return false;
  if (expected->size == actual->size &&
      std::memcmp(expected->data, actual->data, static_cast<std::size_t>(expected->size)) == 0) return true;
  if (allowed_prefix.empty() || actual->size != expected->size + static_cast<int>(allowed_prefix.size())) return false;
  return std::memcmp(actual->data, allowed_prefix.data(), allowed_prefix.size()) == 0 &&
         std::memcmp(expected->data, actual->data + allowed_prefix.size(),
                     static_cast<std::size_t>(expected->size)) == 0;
}
static std::string hdr10_x265_params(const std::string& input_path) {
  AVFormatContext* format = nullptr; AVCodecContext* decoder = nullptr; AVPacket* packet = av_packet_alloc(); AVFrame* frame = av_frame_alloc(); std::string result;
  auto cleanup = [&] { av_frame_free(&frame); av_packet_free(&packet); avcodec_free_context(&decoder); avformat_close_input(&format); };
  if (!packet || !frame || avformat_open_input(&format, input_path.c_str(), nullptr, nullptr) < 0 || avformat_find_stream_info(format, nullptr) < 0) { cleanup(); return {}; }
  const int stream_index = find_video_stream(format); if (stream_index < 0) { cleanup(); return {}; }
  const auto* codec = ffmpeg::preferred_video_decoder(format->streams[stream_index]->codecpar->codec_id); decoder = avcodec_alloc_context3(codec);
  if (!codec || !decoder || avcodec_parameters_to_context(decoder, format->streams[stream_index]->codecpar) < 0 || avcodec_open2(decoder, codec, nullptr) < 0) { cleanup(); return {}; }
  bool done = false;
  while (!done && av_read_frame(format, packet) >= 0) {
    if (packet->stream_index == stream_index && avcodec_send_packet(decoder, packet) >= 0) {
      while (!done && avcodec_receive_frame(decoder, frame) >= 0) {
        const auto* mastering_side = av_frame_get_side_data(frame, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA);
        const auto* light_side = av_frame_get_side_data(frame, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL);
        const auto* mastering = mastering_side ? reinterpret_cast<const AVMasteringDisplayMetadata*>(mastering_side->data) : nullptr;
        const auto* light = light_side ? reinterpret_cast<const AVContentLightMetadata*>(light_side->data) : nullptr;
        if (mastering && mastering->has_primaries && mastering->has_luminance) {
          const auto chroma = [](AVRational value) { return static_cast<long long>(std::llround(av_q2d(value) * 50000.0)); };
          const auto luminance = [](AVRational value) { return static_cast<long long>(std::llround(av_q2d(value) * 10000.0)); };
          std::ostringstream parameters;
          parameters << "master-display=G(" << chroma(mastering->display_primaries[1][0]) << ',' << chroma(mastering->display_primaries[1][1])
                     << ")B(" << chroma(mastering->display_primaries[2][0]) << ',' << chroma(mastering->display_primaries[2][1])
                     << ")R(" << chroma(mastering->display_primaries[0][0]) << ',' << chroma(mastering->display_primaries[0][1])
                     << ")WP(" << chroma(mastering->white_point[0]) << ',' << chroma(mastering->white_point[1])
                     << ")L(" << luminance(mastering->max_luminance) << ',' << luminance(mastering->min_luminance) << ')';
          if (light) parameters << ":max-cll=" << light->MaxCLL << ',' << light->MaxFALL;
          parameters << ":hdr10=1"; result = parameters.str();
        }
        done = true;
      }
    }
    av_packet_unref(packet);
  }
  cleanup(); return result;
}

static const char* h264_profile_for_format(AVPixelFormat format, int source_profile) {
  const auto* descriptor = av_pix_fmt_desc_get(format);
  if (!descriptor) return nullptr;
  const int depth = descriptor->comp[0].depth;
  const bool chroma_444 = descriptor->log2_chroma_w == 0 && descriptor->log2_chroma_h == 0;
  const bool chroma_422 = descriptor->log2_chroma_w == 1 && descriptor->log2_chroma_h == 0;
  if (chroma_444) return "high444";
  if (chroma_422) return "high422";
  if (depth > 8) return "high10";
  switch (source_profile) {
    case AV_PROFILE_H264_BASELINE:
    case AV_PROFILE_H264_CONSTRAINED_BASELINE: return "baseline";
    case AV_PROFILE_H264_MAIN: return "main";
    case AV_PROFILE_H264_HIGH: return "high";
    default: return nullptr;
  }
}

static const char* hevc_profile_for_format(AVPixelFormat format) {
  const auto* descriptor = av_pix_fmt_desc_get(format);
  if (!descriptor) return nullptr;
  const int depth = descriptor->comp[0].depth;
  const bool chroma_444 = descriptor->log2_chroma_w == 0 && descriptor->log2_chroma_h == 0;
  const bool chroma_422 = descriptor->log2_chroma_w == 1 && descriptor->log2_chroma_h == 0;
  if (chroma_444) return depth > 8 ? "main444-10" : "main444-8";
  if (chroma_422) return "main422-10";
  return depth > 8 ? "main10" : "main";
}

static std::string x265_colour_params(const AVCodecContext* decoder,
                                      const std::string& hdr_parameters) {
  std::ostringstream parameters;
  parameters << "repeat-headers=1";
  if (decoder->color_primaries != AVCOL_PRI_UNSPECIFIED)
    parameters << ":colorprim=" << static_cast<int>(decoder->color_primaries);
  if (decoder->color_trc != AVCOL_TRC_UNSPECIFIED)
    parameters << ":transfer=" << static_cast<int>(decoder->color_trc);
  if (decoder->colorspace != AVCOL_SPC_UNSPECIFIED)
    parameters << ":colormatrix=" << static_cast<int>(decoder->colorspace);
  if (decoder->color_range != AVCOL_RANGE_UNSPECIFIED)
    parameters << ":range=" << (decoder->color_range == AVCOL_RANGE_JPEG ? "full" : "limited");
  if (!hdr_parameters.empty()) parameters << ':' << hdr_parameters;
  return parameters.str();
}

static std::vector<std::uint8_t> hdr10plus_nal_from_frame(const AVFrame* frame) {
  const auto* side = frame ? av_frame_get_side_data(frame, AV_FRAME_DATA_DYNAMIC_HDR_PLUS) : nullptr;
  if (!side || side->size < sizeof(AVDynamicHDRPlus)) return {};
  std::uint8_t* t35 = nullptr;
  std::size_t t35_size = 0;
  std::vector<std::uint8_t> nal;
  const auto* metadata = reinterpret_cast<const AVDynamicHDRPlus*>(side->data);
  if (av_dynamic_hdr_plus_to_t35(metadata, &t35, &t35_size) >= 0)
    nal = make_hevc_prefix_sei_t35(std::span<const std::uint8_t>(t35, t35_size));
  av_free(t35);
  return nal;
}

static std::vector<std::vector<std::uint8_t>> read_hdr10plus_sequence(const std::string& input_path) {
  std::vector<std::vector<std::uint8_t>> sequence;
  AVFormatContext* format = nullptr;
  AVCodecContext* decoder = nullptr;
  AVPacket* packet = av_packet_alloc();
  AVFrame* frame = av_frame_alloc();
  auto cleanup = [&] {
    av_frame_free(&frame); av_packet_free(&packet); avcodec_free_context(&decoder);
    avformat_close_input(&format);
  };
  if (!packet || !frame || avformat_open_input(&format, input_path.c_str(), nullptr, nullptr) < 0 ||
      avformat_find_stream_info(format, nullptr) < 0) { cleanup(); return sequence; }
  const int stream_index = find_video_stream(format);
  const AVCodec* codec = stream_index >= 0
      ? ffmpeg::preferred_video_decoder(format->streams[stream_index]->codecpar->codec_id) : nullptr;
  decoder = codec ? avcodec_alloc_context3(codec) : nullptr;
  if (!decoder || avcodec_parameters_to_context(decoder, format->streams[stream_index]->codecpar) < 0 ||
      avcodec_open2(decoder, codec, nullptr) < 0) { cleanup(); return sequence; }
  auto drain = [&] {
    while (avcodec_receive_frame(decoder, frame) >= 0) {
      sequence.push_back(hdr10plus_nal_from_frame(frame));
      av_frame_unref(frame);
    }
  };
  while (av_read_frame(format, packet) >= 0) {
    if (packet->stream_index == stream_index && avcodec_send_packet(decoder, packet) >= 0) drain();
    av_packet_unref(packet);
  }
  avcodec_send_packet(decoder, nullptr); drain(); cleanup(); return sequence;
}
static std::vector<std::uint8_t> selected_nal_from_packet(const AVPacket* packet, unsigned wanted_type, int wanted_sei_payload = -1) {
  std::vector<std::uint8_t> result;
  if (!packet || packet->size < 4) return result;
  const auto* bytes = reinterpret_cast<const std::uint8_t*>(packet->data); const auto size = static_cast<std::size_t>(packet->size);
  auto capture = [&](std::size_t nal_start, std::size_t nal_end) {
    if (nal_start + 2 > nal_end || ((bytes[nal_start] >> 1U) & 0x3fU) != wanted_type ||
        (wanted_sei_payload >= 0 && (nal_start + 3 > nal_end || bytes[nal_start + 2] != static_cast<std::uint8_t>(wanted_sei_payload)))) return;
    result = {0, 0, 0, 1}; result.insert(result.end(), bytes + nal_start, bytes + nal_end);
  };
  bool annex_b = false;
  for (std::size_t i = 0; i + 3 < size; ++i) if (bytes[i] == 0 && bytes[i + 1] == 0 && (bytes[i + 2] == 1 || (bytes[i + 2] == 0 && bytes[i + 3] == 1))) { annex_b = true; break; }
  if (annex_b) {
    for (std::size_t cursor = 0; cursor + 3 < size && result.empty();) {
      if (!(bytes[cursor] == 0 && bytes[cursor + 1] == 0 && (bytes[cursor + 2] == 1 || (bytes[cursor + 2] == 0 && bytes[cursor + 3] == 1)))) { ++cursor; continue; }
      const auto nal_start = cursor + (bytes[cursor + 2] == 1 ? 3U : 4U); auto nal_end = nal_start;
      while (nal_end + 3 < size && !(bytes[nal_end] == 0 && bytes[nal_end + 1] == 0 && (bytes[nal_end + 2] == 1 || (bytes[nal_end + 2] == 0 && bytes[nal_end + 3] == 1)))) ++nal_end;
      if (nal_end + 3 >= size) nal_end = size;
      capture(nal_start, nal_end); cursor = nal_end;
    }
  } else {
    for (std::size_t cursor = 0; cursor + 4 <= size && result.empty();) {
      const auto length = (static_cast<std::size_t>(bytes[cursor]) << 24U) | (static_cast<std::size_t>(bytes[cursor + 1]) << 16U) | (static_cast<std::size_t>(bytes[cursor + 2]) << 8U) | bytes[cursor + 3]; cursor += 4;
      if (length < 3 || cursor + length > size) break;
      capture(cursor, cursor + length); cursor += length;
    }
  }
  return result;
}
static std::vector<std::vector<std::uint8_t>> read_nal_sequence(const std::string& input_path, unsigned nal_type, int sei_payload = -1,
                                                                std::size_t max_video_packets = std::numeric_limits<std::size_t>::max()) {
  std::vector<std::vector<std::uint8_t>> sequence; AVFormatContext* format = nullptr; AVPacket* packet = av_packet_alloc();
  if (!packet || avformat_open_input(&format, input_path.c_str(), nullptr, nullptr) < 0 || avformat_find_stream_info(format, nullptr) < 0) { av_packet_free(&packet); avformat_close_input(&format); return sequence; }
  const int stream = find_video_stream(format);
  while (stream >= 0 && sequence.size() < max_video_packets && av_read_frame(format, packet) >= 0) { if (packet->stream_index == stream) sequence.push_back(selected_nal_from_packet(packet, nal_type, sei_payload)); av_packet_unref(packet); }
  av_packet_free(&packet); avformat_close_input(&format); return sequence;
}
static std::string payload_hash(const std::vector<std::uint8_t>& payload) {
  if (payload.empty()) return {};
  std::uint64_t hash = 14695981039346656037ULL; for (const auto byte : payload) { hash ^= byte; hash *= 1099511628211ULL; }
  std::ostringstream output; output << std::hex << std::setfill('0') << std::setw(16) << hash; return output.str();
}
#endif
std::string hdr10plus_sequence_report(const std::string& input) {
#ifndef SMARTCUT_HAS_FFMPEG
  (void)input; return "{\"schema\":\"hdr10plus-sequence-v1\",\"status\":\"FAILED\",\"error\":\"FFmpeg support is not enabled\"}";
#else
  const auto sequence = read_hdr10plus_sequence(input); std::size_t coverage = 0; std::ostringstream output;
  output << "{\"schema\":\"hdr10plus-sequence-v1\",\"status\":\"PASSED\",\"video_packets\":" << sequence.size() << ",\"payloads\":[";
  for (std::size_t i = 0; i < sequence.size(); ++i) { if (i) output << ','; if (!sequence[i].empty()) ++coverage; output << "{\"packet\":" << i << ",\"hash\":\"" << payload_hash(sequence[i]) << "\",\"bytes\":" << sequence[i].size() << '}'; }
  output << "],\"coverage\":" << coverage << '}'; return output.str();
#endif
}
std::string dovi_rpu_sequence_report(const std::string& input) {
#ifndef SMARTCUT_HAS_FFMPEG
  (void)input; return "{\"schema\":\"dovi-rpu-sequence-v1\",\"status\":\"FAILED\",\"error\":\"FFmpeg support is not enabled\"}";
#else
  const auto sequence = read_nal_sequence(input, 62); std::size_t coverage = 0; std::ostringstream output;
  output << "{\"schema\":\"dovi-rpu-sequence-v1\",\"status\":\"PASSED\",\"video_packets\":" << sequence.size() << ",\"payloads\":[";
  for (std::size_t i = 0; i < sequence.size(); ++i) { if (i) output << ','; if (!sequence[i].empty()) ++coverage; output << "{\"packet\":" << i << ",\"hash\":\"" << payload_hash(sequence[i]) << "\",\"bytes\":" << sequence[i].size() << '}'; }
  output << "],\"coverage\":" << coverage << '}'; return output.str();
#endif
}
std::string codec_capabilities_report() {
#ifndef SMARTCUT_HAS_FFMPEG
  return "{\"schema\":\"codec-capabilities-v1\",\"status\":\"FAILED\",\"error\":\"FFmpeg support is not enabled\"}";
#else
  struct Check { const char* name; AVCodecID codec_id; AVPixelFormat pixel_format; int profile; };
  const Check checks[] = {
      {"hevc-main-8", AV_CODEC_ID_HEVC, AV_PIX_FMT_YUV420P, AV_PROFILE_HEVC_MAIN},
      {"hevc-main10", AV_CODEC_ID_HEVC, AV_PIX_FMT_YUV420P10LE, AV_PROFILE_HEVC_MAIN_10},
      {"av1-main-8", AV_CODEC_ID_AV1, AV_PIX_FMT_YUV420P, AV_PROFILE_AV1_MAIN},
      {"av1-main10", AV_CODEC_ID_AV1, AV_PIX_FMT_YUV420P10LE, AV_PROFILE_AV1_MAIN},
      {"vp9-profile0", AV_CODEC_ID_VP9, AV_PIX_FMT_YUV420P, AV_PROFILE_VP9_0},
      {"vp9-profile2", AV_CODEC_ID_VP9, AV_PIX_FMT_YUV420P10LE, AV_PROFILE_VP9_2},
  };
  bool passed = true; std::ostringstream output;
  output << "{\"schema\":\"codec-capabilities-v1\",\"capabilities\":[";
  for (std::size_t i = 0; i < sizeof(checks) / sizeof(checks[0]); ++i) {
    const auto& check = checks[i];
    const auto* decoder_codec = ffmpeg::preferred_video_decoder(check.codec_id);
    const auto* encoder_codec = ffmpeg::matching_boundary_encoder(check.codec_id);
    AVCodecContext* encoder = encoder_codec ? avcodec_alloc_context3(encoder_codec) : nullptr;
    int open_result = AVERROR_ENCODER_NOT_FOUND;
    if (encoder) {
      encoder->width = 64; encoder->height = 64; encoder->time_base = AVRational{1, 25}; encoder->framerate = AVRational{25, 1};
      encoder->pix_fmt = check.pixel_format; encoder->sample_aspect_ratio = AVRational{1, 1}; encoder->bit_rate = 1'000'000;
      encoder->gop_size = 25; encoder->max_b_frames = 0; encoder->profile = check.profile; encoder->thread_count = 1;
      open_result = avcodec_open2(encoder, encoder_codec, nullptr);
    }
    const bool available = decoder_codec && encoder_codec && open_result >= 0;
    passed = passed && available;
    if (i) output << ',';
    output << "{\"name\":\"" << check.name << "\",\"decoder\":\"" << (decoder_codec ? decoder_codec->name : "")
           << "\",\"encoder\":\"" << (encoder_codec ? encoder_codec->name : "") << "\",\"pixel_format\":\""
           << (av_get_pix_fmt_name(check.pixel_format) ? av_get_pix_fmt_name(check.pixel_format) : "unknown")
           << "\",\"encoder_open_result\":" << open_result << ",\"available\":" << (available ? "true" : "false") << '}';
    avcodec_free_context(&encoder);
  }
  output << "],\"status\":\"" << (passed ? "PASSED" : "FAILED") << "\"}";
  return output.str();
#endif
}
static std::string encode_mkv_boundary_once(const std::string& input, const std::string& output,
                                            std::uint64_t first_frame,
                                            std::uint64_t end_frame,
                                            bool allow_index_seek,
                                            bool mapping_retry) {
#ifndef SMARTCUT_HAS_FFMPEG
  (void)input; (void)output; (void)first_frame; (void)end_frame;
  (void)allow_index_seek; (void)mapping_retry;
  return "{\"schema\":\"boundary-encode-error-v1\",\"error\":\"FFmpeg support is not enabled; configure with SMARTCUT_MEDIA_ROOT\",\"phase\":\"ffmpeg-unavailable\",\"ffmpeg_error_code\":-1,\"ffmpeg_error\":\"\",\"first_frame\":" +
         std::to_string(first_frame) + ",\"end_frame\":" + std::to_string(end_frame) + "}";
#else
  const std::filesystem::path output_path(output);
  AVFormatContext* source = nullptr;
  AVFormatContext* destination = nullptr;
  AVCodecContext* decoder = nullptr;
  AVCodecContext* encoder = nullptr;
  AVPacket* packet = nullptr;
  AVFrame* frame = nullptr;
  bool completed = false;
  bool output_created = false;
  bool cleanup_ran = false;
  auto cleanup = [&]() noexcept {
    if (cleanup_ran) return;
    cleanup_ran = true;
    av_frame_free(&frame);
    av_packet_free(&packet);
    avcodec_free_context(&decoder);
    avcodec_free_context(&encoder);
    if (destination && destination->pb) avio_closep(&destination->pb);
    avformat_free_context(destination);
    avformat_close_input(&source);
    if (!completed && output_created) {
      std::error_code ignored;
      std::filesystem::remove(output_path, ignored);
    }
  };
  ScopeExit cleanup_on_exit(cleanup);
  packet = av_packet_alloc();
  frame = av_frame_alloc();
  int result = 0;
  int video_stream = -1;
  std::size_t indexed_video_stream = 0;
  bool source_has_audio = false;
  bool dovi_first_rpu_rewritten = false;
  std::string dovi_rewrite_error;
  std::string failure_phase;
  std::string failure_detail;
  std::uint64_t decoded_frame = 0;
  std::uint64_t decoded_frames = 0;
  std::uint64_t video_packets_read = 0;
  std::uint64_t encoded_frames = 0;
  std::uint64_t encoded_packets = 0;
  std::uint64_t hdr10plus_packets = 0;
  std::uint64_t dovi_rpu_packets = 0;
  std::uint64_t last_mapped_frame = 0;
  std::uint64_t failure_source_frame = 0;
  bool have_last_mapped_frame = false;
  bool have_failure_source_frame = false;
  bool decoder_flush_submitted = false;
  bool decoder_eof_reached = false;
  bool seeked_to_preroll = false;
  bool seek_fallback = mapping_retry;
  int seek_fallback_error = mapping_retry ? AVERROR_INVALIDDATA : 0;
  const char* seek_fallback_reason = mapping_retry ? "index-mapping-incomplete" : "none";
  std::int64_t last_source_pts = AV_NOPTS_VALUE;
  std::int64_t failure_source_pts = AV_NOPTS_VALUE;
  std::int64_t failure_packet_pts = AV_NOPTS_VALUE;
  std::int64_t failure_packet_dts = AV_NOPTS_VALUE;
  std::vector<std::vector<std::uint8_t>> source_dovi_rpu;
  std::vector<std::vector<std::uint8_t>> pending_hdr10plus;
  std::vector<std::vector<std::uint8_t>> pending_dovi_rpu;
  std::unordered_map<std::int64_t, std::vector<std::uint8_t>> dovi_rpu_by_pts;

  auto append_nullable_i64 = [](std::ostringstream& report, std::int64_t value) {
    if (value == AV_NOPTS_VALUE) report << "null";
    else report << value;
  };
  auto failure_report = [&](const char* error, const char* phase, int code) {
    char error_text[AV_ERROR_MAX_STRING_SIZE]{};
    if (code < 0) av_strerror(code, error_text, sizeof(error_text));
    std::ostringstream report;
    report << "{\"schema\":\"boundary-encode-error-v1\",\"error\":\""
           << smartcut::core::json_escape(error) << "\",\"phase\":\""
           << smartcut::core::json_escape(phase ? phase : "unknown")
           << "\",\"ffmpeg_error_code\":" << code << ",\"ffmpeg_error\":\""
           << smartcut::core::json_escape(code < 0 ? error_text : "")
           << "\",\"first_frame\":" << first_frame << ",\"end_frame\":" << end_frame
           << ",\"video_packets_read\":" << video_packets_read << ",\"decoded_frames\":"
           << decoded_frames << ",\"encoded_frames\":" << encoded_frames
           << ",\"encoded_packets\":" << encoded_packets << ",\"last_mapped_frame\":";
    if (have_last_mapped_frame) report << last_mapped_frame;
    else report << "null";
    report << ",\"last_source_pts\":";
    append_nullable_i64(report, last_source_pts);
    report << ",\"failure_source_frame\":";
    if (have_failure_source_frame) report << failure_source_frame;
    else report << "null";
    report << ",\"failure_source_pts\":";
    append_nullable_i64(report, failure_source_pts);
    report << ",\"failure_packet_pts\":";
    append_nullable_i64(report, failure_packet_pts);
    report << ",\"failure_packet_dts\":";
    append_nullable_i64(report, failure_packet_dts);
    report << ",\"decoder_flush_submitted\":" << (decoder_flush_submitted ? "true" : "false")
           << ",\"decoder_eof_reached\":" << (decoder_eof_reached ? "true" : "false")
           << ",\"frame_mapping\":\""
           << (seeked_to_preroll ? "exact-index" : "decode-from-start")
           << "\",\"seek_fallback\":" << (seek_fallback ? "true" : "false")
           << ",\"seek_fallback_reason\":\"" << seek_fallback_reason << '"';
    if (!failure_detail.empty())
      report << ",\"detail\":\"" << smartcut::core::json_escape(failure_detail) << '"';
    report << '}';
    return report.str();
  };
  auto fail = [&](const char* phase, int code, std::optional<std::uint64_t> source_frame = {},
                  std::int64_t source_pts = AV_NOPTS_VALUE,
                  std::int64_t packet_pts = AV_NOPTS_VALUE,
                  std::int64_t packet_dts = AV_NOPTS_VALUE) {
    if (result < 0) return;
    result = code < 0 ? code : AVERROR_UNKNOWN;
    failure_phase = phase;
    if (source_frame) {
      failure_source_frame = *source_frame;
      have_failure_source_frame = true;
    }
    failure_source_pts = source_pts;
    failure_packet_pts = packet_pts;
    failure_packet_dts = packet_dts;
  };

  if (end_frame <= first_frame) {
    const auto report = failure_report("end frame must be greater than first frame",
                                       "range-validation", AVERROR(EINVAL));
    cleanup();
    return report;
  }

  if (!packet || !frame) {
    const auto report = failure_report("codec context setup failed", "frame-packet-allocation",
                                       AVERROR(ENOMEM));
    cleanup();
    return report;
  }
  int operation = avformat_open_input(&source, input.c_str(), nullptr, nullptr);
  if (operation < 0) {
    const auto report = failure_report("input open failed", "input-open", operation);
    cleanup();
    return report;
  }
  operation = avformat_find_stream_info(source, nullptr);
  if (operation < 0) {
    const auto report = failure_report("input open failed", "stream-info", operation);
    cleanup();
    return report;
  }
  std::size_t video_stream_ordinal = 0;
  for (unsigned i = 0; i < source->nb_streams; ++i) {
    if (source->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
      if ((source->streams[i]->disposition & AV_DISPOSITION_ATTACHED_PIC) == 0 &&
          video_stream < 0) {
        video_stream = static_cast<int>(i);
        indexed_video_stream = video_stream_ordinal;
      }
      ++video_stream_ordinal;
    }
    if (source->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) source_has_audio = true;
  }
  if (video_stream < 0) {
    const auto report = failure_report("video stream not found", "video-stream-selection",
                                       AVERROR_STREAM_NOT_FOUND);
    cleanup();
    return report;
  }
  const AVStream* input_stream = source->streams[video_stream];
  AVRational source_frame_rate{}; std::int64_t source_first_pts = AV_NOPTS_VALUE;
  const bool seekable_cfr = constant_frame_timing(input_stream, source_frame_rate, source_first_pts);
  constexpr std::uint64_t seek_preroll_frames = 512;
  const auto seek_preroll_frame = first_frame > seek_preroll_frames
                                      ? first_frame - seek_preroll_frames
                                      : std::uint64_t{0};
  const auto indexed_seek_pts = allow_index_seek && first_frame > seek_preroll_frames
                                    ? indexed_frame_pts_range(input, seek_preroll_frame, end_frame,
                                                              indexed_video_stream)
                                    : std::nullopt;
  if (allow_index_seek && first_frame > seek_preroll_frames && !indexed_seek_pts) {
    seek_fallback = true;
    seek_fallback_reason = "index-unavailable-or-unsafe";
  }
  std::unordered_map<std::int64_t, std::uint64_t> indexed_frame_by_pts;
  if (indexed_seek_pts) {
    indexed_frame_by_pts.reserve(indexed_seek_pts->pts.size());
    for (std::size_t offset = 0; offset < indexed_seek_pts->pts.size(); ++offset)
      indexed_frame_by_pts.emplace(indexed_seek_pts->pts[offset],
                                   indexed_seek_pts->first_frame + offset);
  }
  const AVCodec* decoder_codec = ffmpeg::preferred_video_decoder(input_stream->codecpar->codec_id);
  const AVCodec* encoder_codec = ffmpeg::matching_boundary_encoder(input_stream->codecpar->codec_id);
  if (!decoder_codec || !encoder_codec) {
    const bool decoder_missing = decoder_codec == nullptr;
    const auto report = failure_report(
        "required decoder or matching boundary encoder not found",
        decoder_missing ? "decoder-selection" : "boundary-encoder-selection",
        decoder_missing ? AVERROR_DECODER_NOT_FOUND : AVERROR_ENCODER_NOT_FOUND);
    cleanup();
    return report;
  }
  if (input_stream->codecpar->codec_id == AV_CODEC_ID_HEVC && !seekable_cfr) {
    source_dovi_rpu = read_nal_sequence(input, 62, -1, static_cast<std::size_t>(end_frame));
  }
  decoder = avcodec_alloc_context3(decoder_codec);
  encoder = avcodec_alloc_context3(encoder_codec);
  if (!decoder || !encoder) {
    const auto report = failure_report("codec context setup failed", "codec-context-allocation",
                                       AVERROR(ENOMEM));
    cleanup();
    return report;
  }
  operation = avcodec_parameters_to_context(decoder, input_stream->codecpar);
  if (operation < 0) {
    const auto report =
        failure_report("codec context setup failed", "decoder-parameters", operation);
    cleanup();
    return report;
  }
  operation = avcodec_open2(decoder, decoder_codec, nullptr);
  if (operation < 0) {
    const auto report = failure_report("decoder open failed", "decoder-open", operation);
    cleanup();
    return report;
  }
  operation = avformat_alloc_output_context2(&destination, nullptr, "matroska", output.c_str());
  if (operation < 0 || !destination) {
    const auto report = failure_report("output context failed", "output-context",
                                       operation < 0 ? operation : AVERROR(ENOMEM));
    cleanup();
    return report;
  }
  encoder->width = decoder->width; encoder->height = decoder->height; encoder->pix_fmt = decoder->pix_fmt; encoder->framerate = input_stream->avg_frame_rate.num > 0 ? input_stream->avg_frame_rate : AVRational{25, 1}; encoder->time_base = av_inv_q(encoder->framerate); encoder->sample_aspect_ratio = decoder->sample_aspect_ratio; encoder->color_range = decoder->color_range; encoder->color_primaries = decoder->color_primaries; encoder->color_trc = decoder->color_trc; encoder->colorspace = decoder->colorspace; encoder->chroma_sample_location = decoder->chroma_sample_location; encoder->bit_rate = input_stream->codecpar->bit_rate > 0 ? input_stream->codecpar->bit_rate : (source->bit_rate > 0 ? source->bit_rate : 8'000'000); encoder->profile = input_stream->codecpar->profile; encoder->level = input_stream->codecpar->level; encoder->gop_size = static_cast<int>(std::max<std::uint64_t>(end_frame - first_frame, 2)); encoder->max_b_frames = input_stream->codecpar->codec_id == AV_CODEC_ID_H264 ? std::max(input_stream->codecpar->video_delay, 0) : 0; if (destination->oformat->flags & AVFMT_GLOBALHEADER) encoder->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  const auto hdr10_parameters = hdr10_x265_params(input);
  const auto x265_parameters = x265_colour_params(decoder, hdr10_parameters);
  if (input_stream->codecpar->codec_id == AV_CODEC_ID_HEVC)
    av_opt_set(encoder->priv_data, "x265-params", x265_parameters.c_str(), 0);
  if (input_stream->codecpar->codec_id == AV_CODEC_ID_HEVC)
    av_opt_set(encoder->priv_data, "preset", "ultrafast", 0);
  else if (input_stream->codecpar->codec_id == AV_CODEC_ID_H264)
    av_opt_set(encoder->priv_data, "preset", "veryfast", 0);
  if (input_stream->codecpar->codec_id == AV_CODEC_ID_HEVC) {
    if (const auto* profile = hevc_profile_for_format(decoder->pix_fmt))
      av_opt_set(encoder->priv_data, "profile", profile, 0);
    // libx265 disables A/53 passthrough by default. Decoder frame side data is
    // deliberately retained and this option writes it back into the encoded
    // boundary access units.
    av_opt_set(encoder->priv_data, "a53cc", "1", 0);
  }
  else if (input_stream->codecpar->codec_id == AV_CODEC_ID_H264) {
    const char* profile = h264_profile_for_format(decoder->pix_fmt, input_stream->codecpar->profile);
    if (profile) av_opt_set(encoder->priv_data, "profile", profile, 0);
    av_opt_set(encoder->priv_data, "a53cc", "1", 0);
  }
  else if (input_stream->codecpar->codec_id == AV_CODEC_ID_AV1) {
    av_opt_set(encoder->priv_data, "cpu-used", "8", 0);
    av_opt_set(encoder->priv_data, "row-mt", "1", 0);
    av_opt_set(encoder->priv_data, "lag-in-frames", "0", 0);
  } else if (input_stream->codecpar->codec_id == AV_CODEC_ID_VP9) {
    av_opt_set(encoder->priv_data, "deadline", "realtime", 0);
    av_opt_set(encoder->priv_data, "cpu-used", "8", 0);
    av_opt_set(encoder->priv_data, "row-mt", "1", 0);
    av_opt_set(encoder->priv_data, "lag-in-frames", "0", 0);
    av_opt_set(encoder->priv_data, "auto-alt-ref", "0", 0);
  }
  operation = avcodec_open2(encoder, encoder_codec, nullptr);
  if (operation < 0) {
    const auto report =
        failure_report("boundary encoder open failed", "boundary-encoder-open", operation);
    cleanup();
    return report;
  }
  AVStream* output_stream = avformat_new_stream(destination, nullptr);
  if (!output_stream) {
    const auto report =
        failure_report("output stream setup failed", "output-stream-create", AVERROR(ENOMEM));
    cleanup();
    return report;
  }
  operation = avcodec_parameters_from_context(output_stream->codecpar, encoder);
  if (operation < 0) {
    const auto report =
        failure_report("output stream setup failed", "output-stream-parameters", operation);
    cleanup();
    return report;
  }
  output_stream->time_base = encoder->time_base;
  if (const auto* dovi_config = av_packet_side_data_get(input_stream->codecpar->coded_side_data, input_stream->codecpar->nb_coded_side_data, AV_PKT_DATA_DOVI_CONF)) {
    if (auto* copied = av_packet_side_data_new(&output_stream->codecpar->coded_side_data, &output_stream->codecpar->nb_coded_side_data, AV_PKT_DATA_DOVI_CONF, dovi_config->size, 0)) std::memcpy(copied->data, dovi_config->data, dovi_config->size);
  }
  if (!(destination->oformat->flags & AVFMT_NOFILE)) {
    operation = avio_open(&destination->pb, output.c_str(), AVIO_FLAG_WRITE);
    if (operation < 0) {
      const auto report = failure_report("output open failed", "output-open", operation);
      cleanup();
      return report;
    }
    output_created = true;
    if (boundary_exception_injection_enabled())
      throw std::runtime_error("injected boundary exception after output open");
  }
  operation = avformat_write_header(destination, nullptr);
  if (operation < 0) {
    const auto report = failure_report("output header failed", "output-header-write", operation);
    cleanup();
    return report;
  }

  auto write_encoded = [&](bool flush) {
    if (flush) {
      const int send = avcodec_send_frame(encoder, nullptr);
      if (send < 0 && send != AVERROR_EOF) {
        fail("encoder-flush-submit", send,
             have_last_mapped_frame ? std::optional<std::uint64_t>(last_mapped_frame)
                                    : std::nullopt,
             last_source_pts);
        return false;
      }
    }
    while (true) {
      const int receive = avcodec_receive_packet(encoder, packet);
      if (receive == AVERROR(EAGAIN) || receive == AVERROR_EOF) return true;
      if (receive < 0) {
        fail("encoder-receive-packet", receive,
             have_last_mapped_frame ? std::optional<std::uint64_t>(last_mapped_frame)
                                    : std::nullopt,
             last_source_pts);
        return false;
      }
      if (encoded_packets < pending_hdr10plus.size() &&
          !pending_hdr10plus[encoded_packets].empty()) {
        const auto& sei = pending_hdr10plus[encoded_packets];
        const int old_size = packet->size;
        const int grow = av_grow_packet(packet, static_cast<int>(sei.size()));
        if (grow < 0) {
          fail("hdr10plus-packet-grow", grow,
               have_last_mapped_frame ? std::optional<std::uint64_t>(last_mapped_frame)
                                      : std::nullopt,
               last_source_pts, packet->pts, packet->dts);
          return false;
        }
        std::memmove(packet->data + sei.size(), packet->data, static_cast<std::size_t>(old_size));
        std::memcpy(packet->data, sei.data(), sei.size());
        ++hdr10plus_packets;
      }
      if (encoded_packets < pending_dovi_rpu.size() &&
          !pending_dovi_rpu[encoded_packets].empty()) {
        const auto& rpu = pending_dovi_rpu[encoded_packets];
        const int old_size = packet->size;
        const int grow = av_grow_packet(packet, static_cast<int>(rpu.size()));
        if (grow < 0) {
          fail("dovi-rpu-packet-grow", grow,
               have_last_mapped_frame ? std::optional<std::uint64_t>(last_mapped_frame)
                                      : std::nullopt,
               last_source_pts, packet->pts, packet->dts);
          return false;
        }
        std::memmove(packet->data + rpu.size(), packet->data, static_cast<std::size_t>(old_size));
        std::memcpy(packet->data, rpu.data(), rpu.size());
        ++dovi_rpu_packets;
      }
      packet->stream_index = output_stream->index;
      av_packet_rescale_ts(packet, encoder->time_base, output_stream->time_base);
      const auto packet_pts = packet->pts;
      const auto packet_dts = packet->dts;
      const int write = av_interleaved_write_frame(destination, packet);
      if (write < 0) {
        fail("boundary-packet-write", write,
             have_last_mapped_frame ? std::optional<std::uint64_t>(last_mapped_frame)
                                    : std::nullopt,
             last_source_pts, packet_pts, packet_dts);
        return false;
      }
      ++encoded_packets;
      av_packet_unref(packet);
    }
  };
  auto encode_selected = [&](AVFrame* selected, std::uint64_t source_frame,
                             std::int64_t source_pts) {
    auto hdr10plus = hdr10plus_nal_from_frame(selected);
    selected->pts = static_cast<std::int64_t>(encoded_frames);
    selected->pict_type = encoded_frames == 0 ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_NONE;
    std::vector<std::uint8_t> rpu;
    if (seekable_cfr) {
      if (const auto found = dovi_rpu_by_pts.find(source_pts); found != dovi_rpu_by_pts.end())
        rpu = found->second;
    } else if (source_frame < source_dovi_rpu.size()) {
      rpu = source_dovi_rpu[source_frame];
    }
    pending_hdr10plus.push_back(std::move(hdr10plus));
    if (encoded_frames == 0 && !rpu.empty()) {
      std::vector<std::uint8_t> rewritten;
      if (!rewrite_dovi_rpu_as_scene_refresh(rpu, rewritten, dovi_rewrite_error)) {
        failure_detail = dovi_rewrite_error;
        fail("dovi-rpu-rewrite", AVERROR_INVALIDDATA, source_frame, source_pts);
        return false;
      }
      rpu = std::move(rewritten);
      dovi_first_rpu_rewritten = true;
    }
    pending_dovi_rpu.push_back(std::move(rpu));
    const int send = avcodec_send_frame(encoder, selected);
    if (send < 0) {
      fail("encoder-send-frame", send, source_frame, source_pts);
      return false;
    }
    ++encoded_frames;
    return write_encoded(false);
  };
  seeked_to_preroll = indexed_seek_pts.has_value();
  if (seeked_to_preroll) {
    // MPEG-TS seeks can land at the following GOP despite AVSEEK_FLAG_BACKWARD.
    // Use the compact exact index's actual timestamp rather than assuming nominal
    // frame-rate continuity. Every decoded frame is mapped through the same
    // exact index below.
    const auto target_pts = indexed_seek_pts->pts.front();
    operation = av_seek_frame(source, video_stream, target_pts, AVSEEK_FLAG_BACKWARD);
    if (operation < 0) {
      // Some demuxers are sequentially decodable but cannot honour timestamp
      // seeks. Reopen from byte zero and retain the safe pre-1.0.3 behaviour.
      seek_fallback = true;
      seek_fallback_error = operation;
      seek_fallback_reason = "input-seek-failed";
      seeked_to_preroll = false;
      avformat_close_input(&source);
      operation = avformat_open_input(&source, input.c_str(), nullptr, nullptr);
      if (operation >= 0) operation = avformat_find_stream_info(source, nullptr);
      if (operation < 0) {
        const auto report = failure_report("input reopen after boundary seek failed",
                                           "input-reopen-after-seek", operation);
        cleanup();
        return report;
      }
      video_stream = find_video_stream(source);
      if (video_stream < 0 ||
          source->streams[video_stream]->codecpar->codec_id != decoder_codec->id) {
        const auto report = failure_report("video stream changed after boundary seek fallback",
                                           "input-reopen-stream-selection",
                                           AVERROR_STREAM_NOT_FOUND);
        cleanup();
        return report;
      }
      input_stream = source->streams[video_stream];
      avcodec_flush_buffers(decoder);
    } else {
      avformat_flush(source);
      avcodec_flush_buffers(decoder);
    }
  }
  bool reached_end = false;
  auto process_decoded_frame = [&] {
    ++decoded_frames;
    const auto source_pts = frame->best_effort_timestamp != AV_NOPTS_VALUE
                                ? frame->best_effort_timestamp
                                : frame->pts;
    last_source_pts = source_pts;
    auto source_frame = decoded_frame;
    if (seeked_to_preroll) {
      const auto mapped = indexed_frame_by_pts.find(source_pts);
      if (mapped == indexed_frame_by_pts.end()) return true;
      source_frame = mapped->second;
    }
    last_mapped_frame = source_frame;
    have_last_mapped_frame = true;
    if (source_frame >= first_frame && source_frame < end_frame &&
        !encode_selected(frame, source_frame, source_pts))
      return false;
    decoded_frame = source_frame + 1;
    reached_end = source_frame + 1 >= end_frame;
    return true;
  };
  auto receive_decoded_frames = [&] {
    while (result == 0 && !reached_end) {
      const int receive = avcodec_receive_frame(decoder, frame);
      if (receive == AVERROR(EAGAIN) || receive == AVERROR_EOF) return receive;
      if (receive < 0) {
        fail("decoder-receive-frame", receive,
             have_last_mapped_frame ? std::optional<std::uint64_t>(last_mapped_frame)
                                    : std::nullopt,
             last_source_pts);
        return receive;
      }
      const bool processed = process_decoded_frame();
      av_frame_unref(frame);
      if (!processed) return result;
    }
    return 0;
  };

  int read_result = 0;
  while (result == 0 && !reached_end) {
    read_result = av_read_frame(source, packet);
    if (read_result < 0) break;
    if (packet->stream_index == video_stream) {
      ++video_packets_read;
      const auto packet_pts = packet->pts != AV_NOPTS_VALUE ? packet->pts : packet->dts;
      if (seekable_cfr && input_stream->codecpar->codec_id == AV_CODEC_ID_HEVC &&
          packet_pts != AV_NOPTS_VALUE)
        dovi_rpu_by_pts[packet_pts] = selected_nal_from_packet(packet, 62);
      const int send = avcodec_send_packet(decoder, packet);
      if (send < 0) {
        fail("decoder-send-packet", send, {}, AV_NOPTS_VALUE, packet->pts, packet->dts);
      } else {
        receive_decoded_frames();
      }
    }
    av_packet_unref(packet);
  }
  if (result == 0 && !reached_end) {
    if (read_result < 0 && read_result != AVERROR_EOF) {
      fail("input-read-packet", read_result);
    } else {
      const int flush = avcodec_send_packet(decoder, nullptr);
      if (flush == 0) {
        decoder_flush_submitted = true;
        const int drain = receive_decoded_frames();
        decoder_eof_reached = drain == AVERROR_EOF;
      } else if (flush == AVERROR_EOF) {
        decoder_flush_submitted = true;
        decoder_eof_reached = true;
      } else {
        fail("decoder-flush-submit", flush,
             have_last_mapped_frame ? std::optional<std::uint64_t>(last_mapped_frame)
                                    : std::nullopt,
             last_source_pts);
      }
    }
  }
  const bool incomplete = result == 0 && encoded_frames != end_frame - first_frame;
  if (result == 0 && !incomplete) write_encoded(true);
  if (result == 0 && !incomplete) {
    const int trailer = av_write_trailer(destination);
    if (trailer < 0)
      fail("output-trailer-write", trailer,
           have_last_mapped_frame ? std::optional<std::uint64_t>(last_mapped_frame)
                                  : std::nullopt,
           last_source_pts);
  }
  if (result == 0 && !incomplete && destination && destination->pb) {
    const int close_result = avio_closep(&destination->pb);
    if (close_result < 0)
      fail("output-close", close_result,
           have_last_mapped_frame ? std::optional<std::uint64_t>(last_mapped_frame)
                                  : std::nullopt,
           last_source_pts);
  }
  if (result == 0 && !incomplete) completed = true;
  const auto* pixel_name_value = decoder ? av_get_pix_fmt_name(decoder->pix_fmt) : nullptr;
  const std::string pixel_name = pixel_name_value ? pixel_name_value : "unknown";
  const bool hlg = decoder && decoder->color_trc == AVCOL_TRC_ARIB_STD_B67;
  cleanup();
  if (incomplete) {
    std::ostringstream detail;
    detail << "expected " << (end_frame - first_frame) << " frames but encoded "
           << encoded_frames;
    failure_detail = detail.str();
    return failure_report("requested boundary range was not fully decoded", "range-incomplete",
                          AVERROR_EOF);
  }
  if (result < 0)
    return failure_report("boundary encode failed", failure_phase.c_str(), result);
  std::ostringstream report; report << "{\"schema\":\"boundary-encode-report-v5\",\"first_frame\":" << first_frame << ",\"end_frame\":" << end_frame << ",\"encoded_frames\":" << encoded_frames << ",\"encoded_packets\":" << encoded_packets << ",\"frame_mapping\":\"" << (seeked_to_preroll ? "exact-index" : "decode-from-start") << "\",\"seek_fallback\":" << (seek_fallback ? "true" : "false") << ",\"seek_fallback_reason\":\"" << seek_fallback_reason << "\",\"seek_fallback_ffmpeg_error_code\":" << seek_fallback_error << ",\"pixel_format\":\"" << pixel_name << "\",\"hlg_preserved\":" << (hlg ? "true" : "false") << ",\"a53_caption_policy\":\"frame-side-data-passthrough\",\"hdr10plus_packets\":" << hdr10plus_packets << ",\"dovi_rpu_packets\":" << dovi_rpu_packets << ",\"dovi_first_rpu_scene_refresh\":" << (dovi_first_rpu_rewritten ? "true" : "false") << ",\"independent_gop\":true,\"audio_policy\":\"" << (source_has_audio ? "video-only-boundary-segment; source-audio-not-copied" : "source-has-no-audio") << "\",\"validation\":\"pending-output-audit\"}"; return report.str();
#endif
}

std::string encode_mkv_boundary(const std::string& input, const std::string& output,
                                std::uint64_t first_frame, std::uint64_t end_frame) {
  try {
    const auto path_check = boundary_path_relation(input, output);
    if (path_check.relation == BoundaryPathRelation::same_file)
      return boundary_public_error("input and output paths refer to the same file",
                                   "path-validation", first_frame, end_frame);
    if (path_check.relation == BoundaryPathRelation::indeterminate)
      return boundary_public_error("input and output paths could not be compared safely",
                                   "path-validation", first_frame, end_frame,
                                   path_check.detail);

    const auto indexed =
        encode_mkv_boundary_once(input, output, first_frame, end_frame, true, false);
    if (indexed.find("\"phase\":\"range-incomplete\"") != std::string::npos &&
        indexed.find("\"frame_mapping\":\"exact-index\"") != std::string::npos)
      return encode_mkv_boundary_once(input, output, first_frame, end_frame, false, true);
    return indexed;
  } catch (const std::filesystem::filesystem_error& error) {
    return boundary_public_error("boundary encode filesystem or cache operation failed",
                                 "filesystem-cache", first_frame, end_frame, error.what());
  } catch (const std::exception& error) {
    return boundary_public_error("boundary encode operation raised an exception",
                                 "boundary-exception", first_frame, end_frame, error.what());
  } catch (...) {
    return boundary_public_error("boundary encode operation raised an unknown exception",
                                 "boundary-exception", first_frame, end_frame);
  }
}

std::string validate_mkv_boundary(const std::string& source_path, const std::string& output, std::uint64_t expected_frames) {
#ifndef SMARTCUT_HAS_FFMPEG
  (void)source_path; (void)output; (void)expected_frames; return "{\"error\":\"FFmpeg support is not enabled; configure with SMARTCUT_MEDIA_ROOT\"}";
#else
  AVFormatContext* source = nullptr; AVFormatContext* input = nullptr; AVCodecContext* decoder = nullptr; AVPacket* packet = av_packet_alloc(); AVFrame* frame = av_frame_alloc(); int source_video_stream = -1; int video_stream = -1; std::uint64_t packets = 0; std::uint64_t decoded_frames = 0; std::uint64_t timing_violations = 0; bool first_is_key = false; bool color_match = false; bool codec_match = false; bool seen_nonnegative_dts = false; std::vector<std::int64_t> last_dts; auto cleanup = [&] { av_frame_free(&frame); av_packet_free(&packet); avcodec_free_context(&decoder); avformat_close_input(&source); avformat_close_input(&input); };
  if (avformat_open_input(&source, source_path.c_str(), nullptr, nullptr) < 0 || avformat_find_stream_info(source, nullptr) < 0 || avformat_open_input(&input, output.c_str(), nullptr, nullptr) < 0 || avformat_find_stream_info(input, nullptr) < 0) { cleanup(); return "{\"error\":\"boundary source or output open failed\"}"; }
  source_video_stream = find_video_stream(source);
  video_stream = find_video_stream(input);
  if (video_stream < 0 || source_video_stream < 0) { cleanup(); return "{\"error\":\"boundary video stream not found\"}"; }
  const auto* source_codec = source->streams[source_video_stream]->codecpar; const auto* output_codec = input->streams[video_stream]->codecpar;
  const bool h264_baseline_equivalent = source_codec->codec_id == AV_CODEC_ID_H264 &&
      ((source_codec->profile == AV_PROFILE_H264_BASELINE && output_codec->profile == AV_PROFILE_H264_CONSTRAINED_BASELINE) ||
       (source_codec->profile == AV_PROFILE_H264_CONSTRAINED_BASELINE && output_codec->profile == AV_PROFILE_H264_BASELINE));
  codec_match = source_codec->codec_id == output_codec->codec_id &&
      (source_codec->profile < 0 || output_codec->profile < 0 || source_codec->profile == output_codec->profile || h264_baseline_equivalent);
  const auto* source_format = av_pix_fmt_desc_get(static_cast<AVPixelFormat>(source_codec->format));
  const bool chroma_location_is_signalled = source_format &&
      source_format->log2_chroma_w == 1 && source_format->log2_chroma_h == 1;
  const bool chroma_match = !chroma_location_is_signalled ||
      source_codec->chroma_location == AVCHROMA_LOC_UNSPECIFIED ||
      source_codec->chroma_location == output_codec->chroma_location;
  color_match = source_codec->width == output_codec->width && source_codec->height == output_codec->height && source_codec->format == output_codec->format && source_codec->color_range == output_codec->color_range && source_codec->color_primaries == output_codec->color_primaries && source_codec->color_trc == output_codec->color_trc && source_codec->color_space == output_codec->color_space && chroma_match && av_cmp_q(source_codec->sample_aspect_ratio, output_codec->sample_aspect_ratio) == 0;
  const AVCodec* codec = ffmpeg::preferred_video_decoder(input->streams[video_stream]->codecpar->codec_id); decoder = avcodec_alloc_context3(codec); if (!codec || !decoder || avcodec_parameters_to_context(decoder, input->streams[video_stream]->codecpar) < 0 || avcodec_open2(decoder, codec, nullptr) < 0) { cleanup(); return "{\"error\":\"boundary decoder open failed\"}"; }
  last_dts.assign(input->nb_streams, AV_NOPTS_VALUE); const auto decode_limit = expected_frames > 512 ? std::uint64_t{256} : expected_frames;
  while (packet && av_read_frame(input, packet) >= 0) { if (packet->stream_index == video_stream) { ++packets; if (packets == 1) first_is_key = (packet->flags & AV_PKT_FLAG_KEY) != 0; if (packet->pts != AV_NOPTS_VALUE && packet->pts < 0) ++timing_violations; const auto previous_dts = last_dts[static_cast<std::size_t>(video_stream)]; if (packet->dts != AV_NOPTS_VALUE) { if (packet->dts < 0 && seen_nonnegative_dts) ++timing_violations; if (packet->dts >= 0) seen_nonnegative_dts = true; if (previous_dts != AV_NOPTS_VALUE && packet->dts < previous_dts && input->streams[video_stream]->codecpar->codec_id != AV_CODEC_ID_MPEG2VIDEO) ++timing_violations; last_dts[static_cast<std::size_t>(video_stream)] = packet->dts; } if (decoded_frames < decode_limit) { if (avcodec_send_packet(decoder, packet) < 0) { ++timing_violations; } while (avcodec_receive_frame(decoder, frame) >= 0) { ++decoded_frames; av_frame_unref(frame); } } } av_packet_unref(packet); }
  if (decoded_frames < decode_limit) { avcodec_send_packet(decoder, nullptr); while (avcodec_receive_frame(decoder, frame) >= 0) { ++decoded_frames; av_frame_unref(frame); } } const bool decode_valid = decoded_frames >= decode_limit && (expected_frames > 512 || decoded_frames == expected_frames); const bool passed = packets > 0 && decode_valid && first_is_key && codec_match && color_match && timing_violations == 0; std::ostringstream report; report << "{\"schema\":\"boundary-validation-report-v1\",\"status\":\"" << (passed ? "PASSED" : "FAILED VALIDATION") << "\",\"expected_frames\":" << expected_frames << ",\"packets\":" << packets << ",\"decoded_frames\":" << decoded_frames << ",\"decode_scope\":\"" << (expected_frames > 512 ? "boundary-sample" : "complete") << "\",\"first_packet_keyframe\":" << (first_is_key ? "true" : "false") << ",\"codec_match\":" << (codec_match ? "true" : "false") << ",\"source_profile\":" << source_codec->profile << ",\"output_profile\":" << output_codec->profile << ",\"color_match\":" << (color_match ? "true" : "false") << ",\"source_format\":" << source_codec->format << ",\"output_format\":" << output_codec->format << ",\"source_color_range\":" << source_codec->color_range << ",\"output_color_range\":" << output_codec->color_range << ",\"source_color_primaries\":" << source_codec->color_primaries << ",\"output_color_primaries\":" << output_codec->color_primaries << ",\"source_color_trc\":" << source_codec->color_trc << ",\"output_color_trc\":" << output_codec->color_trc << ",\"source_colorspace\":" << source_codec->color_space << ",\"output_colorspace\":" << output_codec->color_space << ",\"source_chroma_location\":" << source_codec->chroma_location << ",\"output_chroma_location\":" << output_codec->chroma_location << ",\"source_sar\":\"" << source_codec->sample_aspect_ratio.num << '/' << source_codec->sample_aspect_ratio.den << "\",\"output_sar\":\"" << output_codec->sample_aspect_ratio.num << '/' << output_codec->sample_aspect_ratio.den << "\",\"timing_violations\":" << timing_violations << "}"; cleanup(); return report.str();
#endif
}

std::string join_mkv_video_segments(const std::string& copied, const std::string& replacement, const std::string& output,
                                    std::uint64_t copied_source_first_frame, std::uint64_t replacement_source_first_frame,
                                    bool prefer_first_codec_parameters) {
#ifndef SMARTCUT_HAS_FFMPEG
  (void)copied; (void)replacement; (void)output; (void)copied_source_first_frame; (void)replacement_source_first_frame; (void)prefer_first_codec_parameters; return "{\"error\":\"FFmpeg support is not enabled; configure with SMARTCUT_MEDIA_ROOT\"}";
#else
  if (std::filesystem::weakly_canonical(copied) == std::filesystem::weakly_canonical(output) || std::filesystem::weakly_canonical(replacement) == std::filesystem::weakly_canonical(output)) return "{\"error\":\"segment and output paths must differ\"}";
  AVFormatContext* first = nullptr; AVFormatContext* second = nullptr; AVFormatContext* destination = nullptr; AVPacket* packet = av_packet_alloc(); int result = 0; const char* failure_phase = "none"; std::uint64_t first_packets = 0; std::uint64_t replacement_packets = 0; std::uint64_t injected_parameter_bytes = 0; std::int64_t first_end = 0; std::int64_t first_base = AV_NOPTS_VALUE; std::int64_t second_pts_base = AV_NOPTS_VALUE; std::int64_t second_dts_base = AV_NOPTS_VALUE; std::int64_t second_timestamp_shift = AV_NOPTS_VALUE; std::int64_t second_decode_shift = AV_NOPTS_VALUE; std::int64_t last_output_dts = AV_NOPTS_VALUE; bool completed = false; auto cleanup = [&] { av_packet_free(&packet); avformat_close_input(&first); avformat_close_input(&second); if (destination && destination->pb) avio_closep(&destination->pb); avformat_free_context(destination); if (!completed) { std::error_code ignored; std::filesystem::remove(output, ignored); } };
  if (avformat_open_input(&first, copied.c_str(), nullptr, nullptr) < 0 || avformat_find_stream_info(first, nullptr) < 0 || avformat_open_input(&second, replacement.c_str(), nullptr, nullptr) < 0 || avformat_find_stream_info(second, nullptr) < 0) { cleanup(); return "{\"error\":\"segment open failed\"}"; }
  const int first_stream = find_video_stream(first); const int second_stream = find_video_stream(second); if (first_stream < 0 || second_stream < 0) { cleanup(); return "{\"error\":\"segment video stream not found\"}"; }
  if (avformat_alloc_output_context2(&destination, nullptr, "matroska", output.c_str()) < 0 || !destination) { cleanup(); return "{\"error\":\"join output context failed\"}"; }
  const auto* parameter_source = prefer_first_codec_parameters ? first->streams[first_stream] : second->streams[second_stream];
  auto* output_stream = avformat_new_stream(destination, nullptr); if (!output_stream || avcodec_parameters_copy(output_stream->codecpar, parameter_source->codecpar) < 0) { cleanup(); return "{\"error\":\"join stream setup failed\"}"; } output_stream->time_base = second->streams[second_stream]->time_base;
  if ((!(destination->oformat->flags & AVFMT_NOFILE) && avio_open(&destination->pb, output.c_str(), AVIO_FLAG_WRITE) < 0) || avformat_write_header(destination, nullptr) < 0) { cleanup(); return "{\"error\":\"join header failed\"}"; }
  std::int64_t second_composition_lead = 0;
  std::int64_t second_min_pts = AV_NOPTS_VALUE;
  std::int64_t second_min_dts = AV_NOPTS_VALUE;
  AVPacket* timing_probe = av_packet_alloc();
  while (timing_probe && av_read_frame(second, timing_probe) >= 0) {
    if (timing_probe->stream_index == second_stream) {
      const auto pts = timing_probe->pts == AV_NOPTS_VALUE ? AV_NOPTS_VALUE :
          av_rescale_q(timing_probe->pts, second->streams[second_stream]->time_base, output_stream->time_base);
      const auto dts = timing_probe->dts == AV_NOPTS_VALUE ? AV_NOPTS_VALUE :
          av_rescale_q(timing_probe->dts, second->streams[second_stream]->time_base, output_stream->time_base);
      if (pts != AV_NOPTS_VALUE) second_min_pts = second_min_pts == AV_NOPTS_VALUE ? pts : std::min(second_min_pts, pts);
      if (dts != AV_NOPTS_VALUE) second_min_dts = second_min_dts == AV_NOPTS_VALUE ? dts : std::min(second_min_dts, dts);
      if (pts != AV_NOPTS_VALUE && dts != AV_NOPTS_VALUE)
        second_composition_lead = std::max(second_composition_lead, pts - dts);
    }
    av_packet_unref(timing_probe);
  }
  av_packet_free(&timing_probe);
  if (av_seek_frame(second, second_stream, 0, AVSEEK_FLAG_BACKWARD) < 0) { cleanup(); return "{\"error\":\"second segment rewind failed\"}"; }
  avformat_flush(second);
  const auto normalize_timestamps = [&](AVPacket* item) {
    const auto step = std::max<std::int64_t>(item->duration, 1);
    if (item->dts == AV_NOPTS_VALUE) item->dts = last_output_dts == AV_NOPTS_VALUE ? 0 : last_output_dts + step;
    if (last_output_dts != AV_NOPTS_VALUE && item->dts <= last_output_dts) {
      const auto replacement_dts = last_output_dts + step;
      if (item->pts != AV_NOPTS_VALUE) item->pts += replacement_dts - item->dts;
      item->dts = replacement_dts;
    }
    if (item->pts == AV_NOPTS_VALUE) item->pts = item->dts;
    last_output_dts = item->dts;
  };
  const auto write_join_packet = [&](AVPacket* item) {
    item->dts = AV_NOPTS_VALUE;
    return av_write_frame(destination, item);
  };
  const auto first_parameter_prefix = prefer_first_codec_parameters ? std::vector<std::uint8_t>{} : codec_parameter_set_prefix(first->streams[first_stream]->codecpar);
  while (packet && av_read_frame(first, packet) >= 0) { if (packet->stream_index == first_stream) { if (first_packets == 0 && !first_parameter_prefix.empty()) { const auto old_size = packet->size; if (av_grow_packet(packet, static_cast<int>(first_parameter_prefix.size())) < 0) { result = AVERROR(ENOMEM); failure_phase = "first-prefix"; } else { std::memmove(packet->data + first_parameter_prefix.size(), packet->data, static_cast<std::size_t>(old_size)); std::memcpy(packet->data, first_parameter_prefix.data(), first_parameter_prefix.size()); injected_parameter_bytes += first_parameter_prefix.size(); } } av_packet_rescale_ts(packet, first->streams[first_stream]->time_base, output_stream->time_base); const bool missing_dts = packet->dts == AV_NOPTS_VALUE; if (first_base == AV_NOPTS_VALUE) { first_base = packet->pts != AV_NOPTS_VALUE && packet->dts != AV_NOPTS_VALUE ? std::min(packet->pts, packet->dts) : (packet->pts != AV_NOPTS_VALUE ? packet->pts : packet->dts); } if (packet->pts != AV_NOPTS_VALUE) packet->pts -= first_base; if (packet->dts != AV_NOPTS_VALUE) packet->dts -= first_base; if (!missing_dts) normalize_timestamps(packet); else if (packet->pts == AV_NOPTS_VALUE) packet->pts = 0; if (packet->pts != AV_NOPTS_VALUE) first_end = std::max(first_end, packet->pts + std::max<std::int64_t>(packet->duration, 1)); packet->stream_index = output_stream->index; packet->pos = -1; if (result == 0) { const int write = write_join_packet(packet); if (write < 0) { result = write; failure_phase = "first-write"; } else ++first_packets; } } av_packet_unref(packet); if (result < 0) break; }
  // Re-announce the second segment's parameter sets at every codec-parameter
  // transition. This is required even when the container header was copied
  // from the second segment: the first segment may have reused and replaced
  // the same SPS/PPS identifiers in the decoder before the transition.
  const auto second_parameter_prefix = codec_parameter_set_prefix(second->streams[second_stream]->codecpar);
  while (result == 0 && packet && av_read_frame(second, packet) >= 0) { if (packet->stream_index == second_stream) { if (replacement_packets == 0 && !second_parameter_prefix.empty()) { const auto old_size = packet->size; if (av_grow_packet(packet, static_cast<int>(second_parameter_prefix.size())) < 0) { result = AVERROR(ENOMEM); failure_phase = "second-prefix"; } else { std::memmove(packet->data + second_parameter_prefix.size(), packet->data, static_cast<std::size_t>(old_size)); std::memcpy(packet->data, second_parameter_prefix.data(), second_parameter_prefix.size()); injected_parameter_bytes += second_parameter_prefix.size(); } } av_packet_rescale_ts(packet, second->streams[second_stream]->time_base, output_stream->time_base); if (second_pts_base == AV_NOPTS_VALUE) second_pts_base = packet->pts != AV_NOPTS_VALUE ? packet->pts : packet->dts; if (second_dts_base == AV_NOPTS_VALUE) second_dts_base = packet->dts != AV_NOPTS_VALUE ? packet->dts : packet->pts; if (second_timestamp_shift == AV_NOPTS_VALUE) { const auto step = std::max<std::int64_t>(packet->duration, 1); const auto display_start = second_min_pts != AV_NOPTS_VALUE ? second_min_pts : (second_min_dts != AV_NOPTS_VALUE ? second_min_dts : second_pts_base); const auto decode_start = packet->dts != AV_NOPTS_VALUE ? packet->dts : (second_min_dts != AV_NOPTS_VALUE ? second_min_dts - step : display_start - second_composition_lead); const auto target_dts = last_output_dts == AV_NOPTS_VALUE ? 0 : last_output_dts + step; second_timestamp_shift = first_end - display_start; second_decode_shift = target_dts - decode_start; } if (packet->pts != AV_NOPTS_VALUE) packet->pts += second_timestamp_shift; if (packet->dts != AV_NOPTS_VALUE) packet->dts += second_decode_shift; else packet->dts = last_output_dts == AV_NOPTS_VALUE ? 0 : last_output_dts + std::max<std::int64_t>(packet->duration, 1); normalize_timestamps(packet); packet->stream_index = output_stream->index; packet->pos = -1; if (result == 0) { const int write = write_join_packet(packet); if (write < 0) { result = write; failure_phase = "second-write"; } else ++replacement_packets; } } av_packet_unref(packet); if (result < 0) break; }
  if (result == 0) { const int trailer = av_write_trailer(destination); if (trailer < 0) { result = trailer; failure_phase = "trailer"; } }
  if (result == 0) completed = true;
  cleanup();
  if (result < 0) { char error_text[AV_ERROR_MAX_STRING_SIZE]{}; av_strerror(result, error_text, sizeof(error_text)); std::ostringstream report; report << "{\"error\":\"segment join failed\",\"phase\":\"" << failure_phase << "\",\"ffmpeg_error\":\"" << error_text << "\",\"first_packets\":" << first_packets << ",\"second_packets\":" << replacement_packets << ",\"first_end\":" << first_end << ",\"second_pts_base\":" << second_pts_base << ",\"second_dts_base\":" << second_dts_base << '}'; return report.str(); }
  std::ostringstream report; report << "{\"schema\":\"join-report-v1\",\"copied_packets\":" << first_packets << ",\"replacement_packets\":" << replacement_packets << ",\"output_packets\":" << (first_packets + replacement_packets) << ",\"copied_source_first_frame\":" << copied_source_first_frame << ",\"copied_source_end_frame\":" << (copied_source_first_frame + first_packets) << ",\"replacement_source_first_frame\":" << replacement_source_first_frame << ",\"replacement_source_end_frame\":" << (replacement_source_first_frame + replacement_packets) << ",\"output_copied_first_frame\":0,\"output_copied_end_frame\":" << first_packets << ",\"output_replacement_first_frame\":" << first_packets << ",\"output_replacement_end_frame\":" << (first_packets + replacement_packets) << ",\"codec_parameters\":\"" << (prefer_first_codec_parameters ? "first" : "second") << "\",\"injected_parameter_bytes\":" << injected_parameter_bytes << ",\"second_composition_lead\":" << second_composition_lead << ",\"validation\":\"pending-output-audit\"}"; return report.str();
#endif
}

std::string validate_mkv_join(const std::string& copied, const std::string& replacement, const std::string& output, std::uint64_t expected_frames) {
#ifndef SMARTCUT_HAS_FFMPEG
  (void)copied; (void)replacement; (void)output; (void)expected_frames; return "{\"error\":\"FFmpeg support is not enabled; configure with SMARTCUT_MEDIA_ROOT\"}";
#else
  AVFormatContext* first = nullptr; AVFormatContext* second = nullptr; AVFormatContext* joined = nullptr; AVCodecContext* decoder = nullptr; AVPacket* packet = av_packet_alloc(); AVPacket* expected_packet = av_packet_alloc(); AVFrame* frame = av_frame_alloc(); auto cleanup = [&] { av_frame_free(&frame); av_packet_free(&packet); av_packet_free(&expected_packet); avcodec_free_context(&decoder); avformat_close_input(&first); avformat_close_input(&second); avformat_close_input(&joined); };
  if (avformat_open_input(&first, copied.c_str(), nullptr, nullptr) < 0 || avformat_find_stream_info(first, nullptr) < 0 || avformat_open_input(&second, replacement.c_str(), nullptr, nullptr) < 0 || avformat_find_stream_info(second, nullptr) < 0 || avformat_open_input(&joined, output.c_str(), nullptr, nullptr) < 0 || avformat_find_stream_info(joined, nullptr) < 0) { cleanup(); return "{\"error\":\"join validation input open failed\"}"; }
  const int first_stream = find_video_stream(first); const int second_stream = find_video_stream(second); const int joined_stream = find_video_stream(joined); if (first_stream < 0 || second_stream < 0 || joined_stream < 0) { cleanup(); return "{\"error\":\"join validation video stream not found\"}"; }
  const auto first_parameter_prefix = codec_parameter_set_prefix(first->streams[first_stream]->codecpar);
  const auto second_parameter_prefix = codec_parameter_set_prefix(second->streams[second_stream]->codecpar);
  const std::vector<std::uint8_t> no_parameter_prefix;
  const auto next_video_packet = [](AVFormatContext* context, int stream, AVPacket* item) {
    av_packet_unref(item);
    while (av_read_frame(context, item) >= 0) {
      if (item->stream_index == stream) return true;
      av_packet_unref(item);
    }
    return false;
  };
  std::uint64_t negative_pts = 0; std::uint64_t negative_dts = 0; std::uint64_t non_monotonic_dts = 0; std::uint64_t decoder_submit_errors = 0; std::uint64_t first_non_monotonic_packet = 0; std::int64_t first_non_monotonic_previous_dts = AV_NOPTS_VALUE; std::int64_t first_non_monotonic_dts = AV_NOPTS_VALUE; std::int64_t last_dts = AV_NOPTS_VALUE; std::uint64_t output_packets = 0; bool seen_nonnegative_dts = false;
  const auto audit_joined_packet = [&](const AVPacket* item) {
    if (item->pts != AV_NOPTS_VALUE && item->pts < 0) ++negative_pts;
    if (item->dts != AV_NOPTS_VALUE && item->dts < 0 && seen_nonnegative_dts) ++negative_dts;
    if (item->dts != AV_NOPTS_VALUE && last_dts != AV_NOPTS_VALUE && item->dts < last_dts) {
      if (non_monotonic_dts == 0) { first_non_monotonic_packet = output_packets; first_non_monotonic_previous_dts = last_dts; first_non_monotonic_dts = item->dts; }
      ++non_monotonic_dts;
    }
    if (item->dts != AV_NOPTS_VALUE) { if (item->dts >= 0) seen_nonnegative_dts = true; last_dts = item->dts; }
    ++output_packets;
  };
  std::uint64_t copied_packets = 0; std::uint64_t replacement_packets = 0; std::uint64_t copied_mismatches = 0; std::uint64_t replacement_mismatches = 0;
  const bool complete_payload_audit = expected_frames <= 512;
  if (complete_payload_audit) {
    while (next_video_packet(first, first_stream, expected_packet)) {
      if (!next_video_packet(joined, joined_stream, packet)) { ++copied_mismatches; break; }
      const auto& prefix = copied_packets == 0 ? first_parameter_prefix : no_parameter_prefix;
      if (!packet_exact_or_hevc_parameter_prefixed(expected_packet, packet, prefix)) ++copied_mismatches;
      audit_joined_packet(packet); ++copied_packets;
    }
    while (next_video_packet(second, second_stream, expected_packet)) {
      if (!next_video_packet(joined, joined_stream, packet)) { ++replacement_mismatches; break; }
      const auto& prefix = replacement_packets == 0 ? second_parameter_prefix : no_parameter_prefix;
      if (!packet_exact_or_hevc_parameter_prefixed(expected_packet, packet, prefix)) ++replacement_mismatches;
      audit_joined_packet(packet); ++replacement_packets;
    }
    if (next_video_packet(joined, joined_stream, packet)) { ++replacement_mismatches; do { audit_joined_packet(packet); } while (next_video_packet(joined, joined_stream, packet)); }
  } else {
    std::error_code size_error;
    const auto first_size = std::filesystem::file_size(copied, size_error); size_error.clear();
    const auto second_size = std::filesystem::file_size(replacement, size_error);
    if (first_size <= second_size) {
      while (next_video_packet(first, first_stream, expected_packet)) ++copied_packets;
      replacement_packets = expected_frames > copied_packets ? expected_frames - copied_packets : 0;
    } else {
      while (next_video_packet(second, second_stream, expected_packet)) ++replacement_packets;
      copied_packets = expected_frames > replacement_packets ? expected_frames - replacement_packets : 0;
    }
    while (next_video_packet(joined, joined_stream, packet)) audit_joined_packet(packet);
  }
  avformat_close_input(&joined); if (avformat_open_input(&joined, output.c_str(), nullptr, nullptr) < 0 || avformat_find_stream_info(joined, nullptr) < 0) { cleanup(); return "{\"error\":\"join validation output reopen failed\"}"; } const int reopened_stream = find_video_stream(joined); const AVCodec* codec = reopened_stream < 0 ? nullptr : ffmpeg::preferred_video_decoder(joined->streams[reopened_stream]->codecpar->codec_id); decoder = avcodec_alloc_context3(codec); std::uint64_t decoded_frames = 0; if (decoder) decoder->thread_count = 1; if (!codec || !decoder || avcodec_parameters_to_context(decoder, joined->streams[reopened_stream]->codecpar) < 0 || avcodec_open2(decoder, codec, nullptr) < 0) { cleanup(); return "{\"error\":\"join validation decoder open failed\"}"; }
  AVRational joined_rate{}; std::int64_t joined_first_pts = AV_NOPTS_VALUE; const bool cfr = constant_frame_timing(joined->streams[reopened_stream], joined_rate, joined_first_pts); const auto window_start = copied_packets > 64 ? copied_packets - 64 : 0; const auto window_end = std::min<std::uint64_t>(expected_frames, copied_packets + 65); if (expected_frames > 512 && cfr && window_start > 0) { const auto target = joined_first_pts + av_rescale_q(static_cast<std::int64_t>(window_start), AVRational{joined_rate.den, joined_rate.num}, joined->streams[reopened_stream]->time_base); if (av_seek_frame(joined, reopened_stream, target, AVSEEK_FLAG_BACKWARD) >= 0) { avformat_flush(joined); avcodec_flush_buffers(decoder); } }
  bool decode_window_done = false; const auto decode_limit = expected_frames > 512 ? std::uint64_t{512} : expected_frames;
  while (packet && !decode_window_done && av_read_frame(joined, packet) >= 0) { if (packet->stream_index == reopened_stream) { if (avcodec_send_packet(decoder, packet) < 0) ++decoder_submit_errors; while (avcodec_receive_frame(decoder, frame) >= 0) { ++decoded_frames; if (expected_frames > 512 && cfr) { const auto source_pts = frame->best_effort_timestamp != AV_NOPTS_VALUE ? frame->best_effort_timestamp : frame->pts; if (const auto mapped = frame_for_pts(source_pts, joined->streams[reopened_stream], joined_rate, joined_first_pts); mapped && *mapped + 1 >= window_end) decode_window_done = true; } if (decoded_frames >= decode_limit) decode_window_done = true; av_frame_unref(frame); if (decode_window_done) break; } } av_packet_unref(packet); }
  if (!decode_window_done) { avcodec_send_packet(decoder, nullptr); while (avcodec_receive_frame(decoder, frame) >= 0) { ++decoded_frames; av_frame_unref(frame); } }
  // Matroska stores MPEG-2 presentation order and libavformat reconstructs
  // decode timestamps on demux. For B-picture GOPs that reconstructed DTS can
  // regress even though packet order, payload, and complete decode are valid.
  // Keep it diagnostic, but do not reject an otherwise exact MPEG-2 join.
  const bool reconstructed_mpeg2_dts =
      joined->streams[joined_stream]->codecpar->codec_id == AV_CODEC_ID_MPEG2VIDEO;
  const auto timing_violations = negative_pts + negative_dts +
                                 (reconstructed_mpeg2_dts ? 0 : non_monotonic_dts);
  const bool decode_valid = decoded_frames > 0 && (expected_frames > 512 || decoded_frames == expected_frames);
  // Interlaced field-coded streams can legitimately carry more than one video
  // packet per decoded frame. Frame-accurate decode and exact segment payload
  // audits are the authoritative checks; packet count is diagnostic only.
  const bool passed = output_packets > 0 && decode_valid && copied_mismatches == 0 && replacement_mismatches == 0 && timing_violations == 0 && decoder_submit_errors == 0; cleanup(); std::ostringstream report; report << "{\"schema\":\"join-validation-report-v1\",\"status\":\"" << (passed ? "PASSED" : "FAILED VALIDATION") << "\",\"expected_frames\":" << expected_frames << ",\"output_packets\":" << output_packets << ",\"decoded_frames\":" << decoded_frames << ",\"decode_scope\":\"" << (expected_frames > 512 ? "join-window" : "complete") << "\",\"payload_audit\":\"" << (complete_payload_audit ? "complete" : "streaming-construction-and-packet-count") << "\",\"copied_payload_mismatches\":" << copied_mismatches << ",\"replacement_payload_mismatches\":" << replacement_mismatches << ",\"timing_violations\":" << timing_violations << ",\"negative_pts\":" << negative_pts << ",\"negative_dts\":" << negative_dts << ",\"non_monotonic_dts\":" << non_monotonic_dts << ",\"first_non_monotonic_packet\":" << first_non_monotonic_packet << ",\"first_non_monotonic_previous_dts\":" << first_non_monotonic_previous_dts << ",\"first_non_monotonic_dts\":" << first_non_monotonic_dts << ",\"decoder_submit_errors\":" << decoder_submit_errors << "}"; return report.str();
#endif
}
}
