#ifndef NOMINMAX
#define NOMINMAX 1
#endif

#include <iostream>
#include <string>
#include <string_view>
#include <stdexcept>
#include <fstream>
#include <algorithm>
#include <vector>
#include <optional>
#include <filesystem>
#include "core/entitlement.hpp"
#include "core/windows_utf8_argv.hpp"
#include "core/control_ipc.hpp"
#include "core/preview_shared_memory.hpp"
#include <cctype>
#include <charconv>
#include <cmath>
#include <cstdlib>
#include <sstream>
#include <chrono>
#include <limits>
#include <thread>

#ifdef _WIN32
#include <windows.h>
#include <bcrypt.h>
#endif

#include "media/audio_timing.hpp"
#include "media/audio_playback.hpp"
#include "media/audio_transform.hpp"
#include "media/ad_detective.hpp"
#include "media/media_joiner.hpp"
#include "media/title_media.hpp"
#include "media/video_transform.hpp"
#include "media/hardware_self_test.hpp"
#include "media/edit_export.hpp"
#include "media/frame_decode.hpp"
#include "media/video_frame_index.hpp"
#include "media/stream_probe.hpp"
#include "media/mkv_copy.hpp"
#include "media/container_mux.hpp"
#include "media/dimension_filter.hpp"
#include "media/preview_conversion.hpp"
#include "media/trial_watermark.hpp"
#include "worker/playback_session.hpp"
#include "core/source_identity.hpp"
#include "core/build_info.hpp"
#include "core/project_journal.hpp"
#include "core/project_editor.hpp"
#include "core/videoredo_project.hpp"
#include "core/videoredo_batch.hpp"
#include "core/render_plan.hpp"

namespace {
unsigned long process_id() {
#ifdef _WIN32
  return GetCurrentProcessId();
#else
  return 0;
#endif
}
void set_worker_priority(std::string_view priority) {
#ifdef _WIN32
  DWORD value = NORMAL_PRIORITY_CLASS;
  if (priority == "idle") value = IDLE_PRIORITY_CLASS;
  else if (priority == "below-normal") value = BELOW_NORMAL_PRIORITY_CLASS;
  else if (priority == "above-normal") value = ABOVE_NORMAL_PRIORITY_CLASS;
  SetPriorityClass(GetCurrentProcess(), value);
#else
  (void)priority;
#endif
}
std::uint64_t checked_stoull(std::string_view text, bool allow_trailing = false) {
  while (!text.empty() && std::isspace(static_cast<unsigned char>(text.front()))) text.remove_prefix(1);
  if (text.empty() || text.front() == '-' || text.front() == '+')
    throw std::invalid_argument("unsigned integer expected");
  std::uint64_t value{};
  const auto parsed = std::from_chars(text.data(), text.data() + text.size(), value);
  if (parsed.ec == std::errc::result_out_of_range)
    throw std::out_of_range("unsigned integer is out of range");
  if (parsed.ec != std::errc{} || parsed.ptr == text.data())
    throw std::invalid_argument("unsigned integer expected");
  if (!allow_trailing) {
    auto trailing = std::string_view(parsed.ptr, static_cast<std::size_t>(text.data() + text.size() - parsed.ptr));
    while (!trailing.empty() && std::isspace(static_cast<unsigned char>(trailing.front()))) trailing.remove_prefix(1);
    if (!trailing.empty()) throw std::invalid_argument("unexpected characters after unsigned integer");
  }
  return value;
}
std::int64_t checked_stoll(std::string_view text, bool allow_trailing = false) {
  while (!text.empty() && std::isspace(static_cast<unsigned char>(text.front()))) text.remove_prefix(1);
  if (text.empty() || text.front() == '+') throw std::invalid_argument("signed integer expected");
  std::int64_t value{};
  const auto parsed = std::from_chars(text.data(), text.data() + text.size(), value);
  if (parsed.ec == std::errc::result_out_of_range)
    throw std::out_of_range("signed integer is out of range");
  if (parsed.ec != std::errc{} || parsed.ptr == text.data())
    throw std::invalid_argument("signed integer expected");
  if (!allow_trailing) {
    auto trailing = std::string_view(parsed.ptr, static_cast<std::size_t>(text.data() + text.size() - parsed.ptr));
    while (!trailing.empty() && std::isspace(static_cast<unsigned char>(trailing.front()))) trailing.remove_prefix(1);
    if (!trailing.empty()) throw std::invalid_argument("unexpected characters after signed integer");
  }
  return value;
}
int checked_int(std::string_view text) {
  const auto value = checked_stoll(text);
  if (value < std::numeric_limits<int>::min() || value > std::numeric_limits<int>::max())
    throw std::out_of_range("integer is out of range");
  return static_cast<int>(value);
}
double checked_double(std::string_view text) {
  while (!text.empty() && std::isspace(static_cast<unsigned char>(text.front()))) text.remove_prefix(1);
  if (text.empty() || text.front() == '+') throw std::invalid_argument("number expected");
  double value{};
  const auto parsed = std::from_chars(text.data(), text.data() + text.size(), value,
                                      std::chars_format::general);
  if (parsed.ec == std::errc::result_out_of_range)
    throw std::out_of_range("number is out of range");
  if (parsed.ec != std::errc{} || parsed.ptr == text.data() || !std::isfinite(value))
    throw std::invalid_argument("finite number expected");
  auto trailing = std::string_view(parsed.ptr, static_cast<std::size_t>(text.data() + text.size() - parsed.ptr));
  while (!trailing.empty() && std::isspace(static_cast<unsigned char>(trailing.front()))) trailing.remove_prefix(1);
  if (!trailing.empty()) throw std::invalid_argument("unexpected characters after number");
  return value;
}
std::int64_t json_int(const std::string& text, const std::string& key, std::int64_t fallback = 0) {
  const auto marker = "\"" + key + "\":"; const auto start = text.find(marker); if (start == std::string::npos) return fallback;
  const auto value_start = start + marker.size(); try { return checked_stoll(text.substr(value_start), true); } catch (...) { return fallback; }
}
std::string json_string(const std::string& text, const std::string& key) {
  const auto marker = "\"" + key + "\":\""; const auto start = text.find(marker); if (start == std::string::npos) return {};
  const auto value_start = start + marker.size(); std::string value; value.reserve(256); bool escaped = false;
  for (std::size_t cursor = value_start; cursor < text.size(); ++cursor) {
    const char character = text[cursor];
    if (escaped) { switch (character) { case '"': value.push_back('"'); break; case '\\': value.push_back('\\'); break; case '/': value.push_back('/'); break; case 'b': value.push_back('\b'); break; case 'f': value.push_back('\f'); break; case 'n': value.push_back('\n'); break; case 'r': value.push_back('\r'); break; case 't': value.push_back('\t'); break; default: return {}; } escaped = false; continue; }
    if (character == '\\') { escaped = true; continue; }
    if (character == '"') return value;
    value.push_back(character);
  }
  return {};
}
bool report_status_is(const std::string& report, std::string_view expected) {
  return json_string(report, "status") == expected;
}
std::string navigation_report(const std::string& index) {
  if (index.find("\"error\"") != std::string::npos) return index;
  const auto key_marker = index.find("\"keyframes\":["); const auto key_start = key_marker == std::string::npos ? std::string::npos : key_marker + 13; const auto key_end = key_start == std::string::npos ? std::string::npos : index.find(']', key_start);
  const auto frames_start = index.find("\"frames\":[", key_end); if (key_start == std::string::npos || key_end == std::string::npos || frames_start == std::string::npos) return "{\"schema\":\"worker-navigation-v1\",\"error\":\"invalid frame index\"}";
  std::ostringstream pts; bool first = true; std::size_t cursor = frames_start;
  while ((cursor = index.find("\"pts\":", cursor)) != std::string::npos) {
    const auto value_start = cursor + 6; std::int64_t value = 0; const auto* begin = index.data() + value_start; const auto* end = index.data() + index.size(); const auto parsed = std::from_chars(begin, end, value);
    if (parsed.ec == std::errc{}) { if (!first) pts << ','; first = false; pts << value; cursor = static_cast<std::size_t>(parsed.ptr - index.data()); } else { cursor = value_start; }
  }
  std::ostringstream output; output << "{\"schema\":\"worker-navigation-v1\",\"source_uuid\":\"" << json_string(index, "source_uuid")
    << "\",\"time_base_num\":" << json_int(index, "time_base_num", 1) << ",\"time_base_den\":" << json_int(index, "time_base_den", 1)
    << ",\"frame_count\":" << json_int(index, "frame_count") << ",\"keyframes\":[" << index.substr(key_start, key_end - key_start)
    << "],\"frame_pts\":[" << pts.str() << "]}"; return output.str();
}
std::vector<std::string> json_values(const std::string& text, std::size_t begin, std::size_t end, const std::string& key) { std::vector<std::string> values; const std::string marker = "\"" + key + "\":\""; std::size_t cursor = begin; while (cursor < end) { const auto start = text.find(marker, cursor); if (start == std::string::npos || start >= end) break; const auto value_start = start + marker.size(); const auto value_end = text.find('"', value_start); if (value_end == std::string::npos || value_end > end) break; values.push_back(text.substr(value_start, value_end - value_start)); cursor = value_end + 1; } return values; }
std::vector<std::uint64_t> json_uints(const std::string& text, std::size_t begin, std::size_t end, const std::string& key) { std::vector<std::uint64_t> values; const std::string marker = "\"" + key + "\":"; std::size_t cursor = begin; while (cursor < end) { const auto start = text.find(marker, cursor); if (start == std::string::npos || start >= end) break; const auto value_start = start + marker.size(); try { values.push_back(checked_stoull(text.substr(value_start), true)); } catch (...) {} cursor = value_start; } return values; }
std::vector<std::uint64_t> json_uint_array(const std::string& text, const std::string& key, std::size_t begin, std::size_t end) { std::vector<std::uint64_t> values; const auto marker = text.find("\"" + key + "\":[", begin); if (marker == std::string::npos || marker >= end) return values; const auto close = text.find(']', marker); if (close == std::string::npos || close > end) return values; std::stringstream input(text.substr(text.find('[', marker) + 1, close - text.find('[', marker) - 1)); std::string token; try { while (std::getline(input, token, ',')) if (!token.empty()) values.push_back(checked_stoull(token)); } catch (...) { values.clear(); } return values; }
bool json_bool(const std::string& text, const std::string& key, bool fallback = false) { const auto marker = text.find("\"" + key + "\":"); if (marker == std::string::npos) return fallback; const auto start = marker + key.size() + 3; return text.compare(start, 4, "true") == 0 ? true : text.compare(start, 5, "false") == 0 ? false : fallback; }
bool parse_transport_stream_option(std::string_view key, const char* value,
                                   smartcut::media::MpegTsMuxOptions& options) {
  if (key == "--ts-transport-stream-id") options.transport_stream_id = checked_int(value);
  else if (key == "--ts-original-network-id") options.original_network_id = checked_int(value);
  else if (key == "--ts-service-id") options.service_id = checked_int(value);
  else if (key == "--ts-pmt-start-pid") options.pmt_start_pid = checked_int(value);
  else if (key == "--ts-start-pid") options.elementary_start_pid = checked_int(value);
  else if (key == "--ts-mux-rate") options.mux_rate = checked_int(value);
  else if (key == "--ts-pcr-period-ms") options.pcr_period_ms = checked_int(value);
  else if (key == "--ts-pat-period") options.pat_period_seconds = checked_double(value);
  else if (key == "--ts-sdt-period") options.sdt_period_seconds = checked_double(value);
  else if (key == "--ts-m2ts-mode") options.m2ts_mode = std::string_view(value) == "1" || std::string_view(value) == "true";
  else if (key == "--ts-resend-headers") options.resend_headers = std::string_view(value) == "1" || std::string_view(value) == "true";
  else if (key == "--ts-system-b") options.system_b = std::string_view(value) == "1" || std::string_view(value) == "true";
  else if (key == "--ts-emit-nit") options.emit_nit = std::string_view(value) == "1" || std::string_view(value) == "true";
  else if (key == "--ts-service-name") options.service_name = value;
  else if (key == "--ts-service-provider") options.service_provider = value;
  else if (key == "--trial-watermark") {
    const std::string_view requested(value);
    if (requested != "true" && requested != "false") return false;
  }
  else return false;
  return true;
}
std::vector<std::int64_t> json_int_array(const std::string& text, const std::string& key) { std::vector<std::int64_t> values; const auto marker = text.find("\"" + key + "\":["); if (marker == std::string::npos) return values; const auto begin = text.find('[', marker); const auto end = text.find(']', begin); if (begin == std::string::npos || end == std::string::npos) return values; std::stringstream input(text.substr(begin + 1, end - begin - 1)); std::string token; try { while (std::getline(input, token, ',')) if (!token.empty()) values.push_back(checked_stoll(token)); } catch (...) { values.clear(); } return values; }
std::size_t frame_at_microseconds(const std::vector<std::int64_t>& pts, std::int64_t time_base_num, std::int64_t time_base_den, std::uint64_t microseconds) { if (pts.empty() || time_base_num <= 0 || time_base_den <= 0) return 0; const long double ticks = static_cast<long double>(microseconds) * static_cast<long double>(time_base_den) / (1'000'000.0L * static_cast<long double>(time_base_num)); const auto target = pts.front() + static_cast<std::int64_t>(std::llround(ticks)); const auto found = std::lower_bound(pts.begin(), pts.end(), target); return static_cast<std::size_t>(std::distance(pts.begin(), found)); }
std::uint64_t frame_microseconds(const std::vector<std::int64_t>& pts, std::int64_t time_base_num, std::int64_t time_base_den, std::size_t frame) { if (pts.empty() || time_base_num <= 0 || time_base_den <= 0) return 0; if (frame >= pts.size()) { const auto delta = pts.size() > 1 ? std::max<std::int64_t>(1, pts.back() - pts[pts.size() - 2]) : 1; const auto target = pts.back() + delta * static_cast<std::int64_t>(frame - pts.size() + 1); return static_cast<std::uint64_t>(std::max<long double>(0.0L, static_cast<long double>(target - pts.front()) * 1'000'000.0L * static_cast<long double>(time_base_num) / static_cast<long double>(time_base_den))); } return static_cast<std::uint64_t>(std::max<long double>(0.0L, static_cast<long double>(pts[frame] - pts.front()) * 1'000'000.0L * static_cast<long double>(time_base_num) / static_cast<long double>(time_base_den))); }
bool parse_ad_region(std::string_view text, smartcut::media::AdScanRegion& region) {
  std::stringstream values{std::string(text)};
  std::string token;
  std::vector<double> parsed;
  try { while (std::getline(values, token, ',')) parsed.push_back(checked_double(token)); } catch (...) { return false; }
  if (parsed.size() != 4) return false;
  region = {parsed[0], parsed[1], parsed[2], parsed[3]};
  return parsed[0] >= 0.0 && parsed[1] >= 0.0 && parsed[2] >= 0.0 && parsed[3] >= 0.0 &&
         parsed[0] + parsed[2] < 0.95 && parsed[1] + parsed[3] < 0.95;
}
bool audio_metadata_matches(const std::string& document, std::size_t sources_start, std::size_t segments_start, const std::string& source_path) {
  const auto audio = source_path.empty() ? std::optional<smartcut::media::AudioTrackInfo>{} : smartcut::media::primary_audio_track(source_path);
  if (!audio) return true;
  const auto source_end = segments_start == std::string::npos ? document.size() : segments_start;
  const auto streams = json_uints(document, sources_start, source_end, "audio_stream");
  const auto nums = json_uints(document, sources_start, source_end, "audio_time_base_num");
  const auto dens = json_uints(document, sources_start, source_end, "audio_time_base_den");
  const auto rates = json_uints(document, sources_start, source_end, "audio_sample_rate");
  const auto channels = json_uints(document, sources_start, source_end, "audio_channels");
  return streams.size() == 1 && nums.size() == 1 && dens.size() == 1 && rates.size() == 1 && channels.size() == 1 &&
         streams[0] == audio->stream_index && nums[0] == static_cast<std::uint64_t>(audio->time_base_num) &&
         dens[0] == static_cast<std::uint64_t>(audio->time_base_den) && rates[0] == static_cast<std::uint64_t>(audio->sample_rate) &&
         channels[0] == static_cast<std::uint64_t>(audio->channels);
}
std::string sha256_file(const std::filesystem::path& path) {
#ifdef _WIN32
  BCRYPT_ALG_HANDLE algorithm = nullptr; BCRYPT_HASH_HANDLE hash = nullptr; DWORD object_size = 0; DWORD digest_size = 0; DWORD received = 0;
  if (BCryptOpenAlgorithmProvider(&algorithm, BCRYPT_SHA256_ALGORITHM, nullptr, 0) < 0 ||
      BCryptGetProperty(algorithm, BCRYPT_OBJECT_LENGTH, reinterpret_cast<PUCHAR>(&object_size), sizeof(object_size), &received, 0) < 0 ||
      BCryptGetProperty(algorithm, BCRYPT_HASH_LENGTH, reinterpret_cast<PUCHAR>(&digest_size), sizeof(digest_size), &received, 0) < 0) {
    if (algorithm) BCryptCloseAlgorithmProvider(algorithm, 0);
    return {};
  }
  std::vector<UCHAR> object(object_size); std::vector<UCHAR> digest(digest_size);
  if (BCryptCreateHash(algorithm, &hash, object.data(), static_cast<ULONG>(object.size()), nullptr, 0, 0) < 0) { BCryptCloseAlgorithmProvider(algorithm, 0); return {}; }
  std::ifstream input(path, std::ios::binary); std::vector<char> buffer(1024 * 1024); bool passed = static_cast<bool>(input);
  while (passed && input) { input.read(buffer.data(), static_cast<std::streamsize>(buffer.size())); const auto bytes = input.gcount(); if (bytes > 0 && BCryptHashData(hash, reinterpret_cast<PUCHAR>(buffer.data()), static_cast<ULONG>(bytes), 0) < 0) passed = false; }
  if (passed && BCryptFinishHash(hash, digest.data(), static_cast<ULONG>(digest.size()), 0) < 0) passed = false;
  BCryptDestroyHash(hash); BCryptCloseAlgorithmProvider(algorithm, 0); if (!passed) return {};
  constexpr char hex[] = "0123456789abcdef"; std::string output; output.reserve(digest.size() * 2); for (const auto byte : digest) { output.push_back(hex[byte >> 4]); output.push_back(hex[byte & 0x0f]); } return output;
#else
  (void)path; return {};
#endif
}
std::string output_hash_field(bool passed, const std::filesystem::path& path) { const auto digest = passed ? sha256_file(path) : std::string{}; return digest.empty() ? ",\"output_sha256\":null" : ",\"output_sha256\":\"" + digest + "\""; }
std::string export_completion_fields(bool passed, const std::filesystem::path& path) {
  std::ostringstream output; output << output_hash_field(passed, path) << ",\"dependency_versions\":{\"smartcut\":\"" << smartcut::build_info::application_version
    << "\",\"ffmpeg\":\"" << smartcut::build_info::ffmpeg_version << " @ " << smartcut::build_info::ffmpeg_revision
    << "\",\"x264\":\"" << smartcut::build_info::x264_revision << "\",\"x265\":\"" << smartcut::build_info::x265_version
    << "\",\"libaom\":\"" << smartcut::build_info::libaom_version << "\",\"libvpx\":\"" << smartcut::build_info::libvpx_version
    << "\",\"libdovi\":\"" << smartcut::build_info::libdovi_version << "\"}"; return output.str();
}
struct FileRangeCopyResult {
  bool passed{};
  std::uint64_t copied{};
  std::string error;
};
FileRangeCopyResult copy_file_range(const std::filesystem::path& input_path, const std::filesystem::path& output_path,
                                    std::uint64_t start, std::uint64_t requested) {
  FileRangeCopyResult result;
  std::error_code error;
  const auto input = std::filesystem::absolute(input_path, error).lexically_normal();
  if (error) { result.error = "invalid input path"; return result; }
  const auto output = std::filesystem::absolute(output_path, error).lexically_normal();
  if (error) { result.error = "invalid output path"; return result; }
  bool same_file = false;
#ifdef _WIN32
  same_file = CompareStringOrdinal(input.c_str(), -1, output.c_str(), -1, TRUE) == CSTR_EQUAL;
#else
  same_file = input == output;
#endif
  if (!same_file && std::filesystem::exists(output, error) && !error) same_file = std::filesystem::equivalent(input, output, error);
  if (same_file) { result.error = "source and output must differ"; return result; }
  const auto size = std::filesystem::file_size(input, error);
  if (error) { result.error = "source file is unavailable"; return result; }
  if (requested == 0 || start >= size) { result.error = "requested byte range is empty or outside the source"; return result; }
  const auto bytes = std::min<std::uint64_t>(requested, size - start);
  auto partial = output;
#ifdef _WIN32
  partial += ".smartcut-partial-" + std::to_string(GetCurrentProcessId());
#else
  partial += ".smartcut-partial";
#endif
  std::filesystem::remove(partial, error); error.clear();
  std::ifstream source(input, std::ios::binary); std::ofstream destination(partial, std::ios::binary | std::ios::trunc);
  if (!source || !destination) { std::filesystem::remove(partial, error); result.error = "could not open source or temporary output"; return result; }
  source.seekg(static_cast<std::streamoff>(start));
  std::vector<char> buffer(1024 * 1024); std::uint64_t remaining = bytes;
  while (remaining > 0 && source && destination) {
    const auto chunk = static_cast<std::streamsize>(std::min<std::uint64_t>(remaining, buffer.size()));
    source.read(buffer.data(), chunk); const auto received = source.gcount();
    if (received <= 0) break;
    destination.write(buffer.data(), received); remaining -= static_cast<std::uint64_t>(received);
  }
  destination.flush(); const bool complete = remaining == 0 && static_cast<bool>(destination); source.close(); destination.close();
  if (!complete) { std::filesystem::remove(partial, error); result.error = "source read or output write failed"; return result; }
#ifdef _WIN32
  if (!MoveFileExW(partial.c_str(), output.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
    std::filesystem::remove(partial, error); result.error = "could not replace destination"; return result;
  }
#else
  std::filesystem::rename(partial, output, error);
  if (error) { std::filesystem::remove(partial, error); result.error = "could not replace destination"; return result; }
#endif
  result.passed = true; result.copied = bytes; return result;
}
const smartcut::core::EntitlementResult& delivery_entitlement() {
  static const auto result = [] {
#ifdef SMARTCUT_INTERNAL_TEST_WORKER
    smartcut::core::EntitlementResult entitlement;
    entitlement.state = smartcut::core::EntitlementState::paid;
    entitlement.detail = "Internal non-packaged test worker";
    return entitlement;
#else
    const auto now = std::chrono::duration_cast<std::chrono::seconds>(
        std::chrono::system_clock::now().time_since_epoch()).count();
    return smartcut::core::verify_installed_entitlement(now);
#endif
  }();
  return result;
}
bool evaluation_video_delivery() { return !delivery_entitlement().paid(); }
bool source_contains_video(const std::string& input) {
  const auto types = smartcut::media::probe_stream_media_types(input);
  if (!types) return true;
  return std::find(types->begin(), types->end(), 0) != types->end();
}
bool selected_delivery_contains_video(const std::string& input,
                                      const std::vector<std::size_t>& selected_streams) {
  const auto types = smartcut::media::probe_stream_media_types(input);
  if (!types) return true;
  if (selected_streams.empty())
    return std::find(types->begin(), types->end(), 0) != types->end();
  for (const auto stream : selected_streams) {
    // Unknown or unreadable selections fail closed: they must never be treated
    // as a proven audio-only delivery and bypass evaluation enforcement.
    if (stream >= types->size() || (*types)[stream] == 0) return true;
  }
  return false;
}
int reject_evaluation_clean_delivery(std::string_view operation) {
  std::cout << "{\"schema\":\"worker-entitlement-v1\",\"status\":\"BLOCKED\","
            << "\"edition\":\"evaluation\",\"operation\":\"" << operation
            << "\",\"entitlement_state\":\""
            << smartcut::core::entitlement_state_name(delivery_entitlement().state)
            << "\",\"reason\":\"A paid licence is required for this clean-copy video operation; use Save Video in the GUI to create a permanently watermarked evaluation export\"}\n";
  return 6;
}
}

int main(int argc, char** argv) {
  auto utf8_arguments = smartcut::core::windows_utf8_argv();
  if (!utf8_arguments.pointers.empty()) { argc = static_cast<int>(utf8_arguments.pointers.size()); argv = utf8_arguments.pointers.data(); }
  std::setlocale(LC_ALL, ".UTF-8");
  try {
  if (argc == 2 && std::string_view(argv[1]) == "--video-encoder-capabilities") {
    std::cout << smartcut::media::video_encoder_capabilities_report() << '\n';
    return 0;
  }
  if (argc == 10 && std::string_view(argv[1]) == "--hardware-self-test" &&
      std::string_view(argv[2]) == "--input" &&
      std::string_view(argv[4]) == "--start-frame" &&
      std::string_view(argv[6]) == "--start-pts" &&
      std::string_view(argv[8]) == "--frames") {
    std::size_t start_frame = 0;
    std::int64_t start_pts = 0;
    std::size_t frames = 0;
    try {
      start_frame = static_cast<std::size_t>(checked_stoull(argv[5]));
      start_pts = checked_stoll(argv[7]);
      frames = static_cast<std::size_t>(checked_stoull(argv[9]));
    } catch (...) {
      return 2;
    }
#ifdef _WIN32
    _putenv_s("SMARTCUT_DISABLE_HARDWARE_DECODE", "");
#else
    unsetenv("SMARTCUT_DISABLE_HARDWARE_DECODE");
#endif
    const auto report = smartcut::media::run_hardware_self_test(
        argv[3], start_frame, start_pts, frames);
    std::cout << report << '\n';
    return report_status_is(report, "PASSED") ? 0 : 5;
  }
  if (argc == 10 && std::string_view(argv[1]) == "--preview-stream-benchmark" &&
      std::string_view(argv[2]) == "--input" &&
      std::string_view(argv[4]) == "--start-frame" &&
      std::string_view(argv[6]) == "--start-pts" &&
      std::string_view(argv[8]) == "--frames") {
    const auto start_frame = static_cast<std::size_t>(checked_stoull(argv[5]));
    const auto start_pts = checked_stoll(argv[7]);
    const auto requested = static_cast<std::size_t>(checked_stoull(argv[9]));
    std::size_t converted = 0;
    bool conversion_failed = false;
    const auto started = std::chrono::steady_clock::now();
    const auto report = smartcut::media::decode_preview_stream(
        argv[3], start_frame, start_pts,
        [&](std::shared_ptr<smartcut::core::PreviewFrame> source, std::uint64_t) {
          if (!smartcut::media::convert_preview_to_bgra(std::move(source))) {
            conversion_failed = true;
            return false;
          }
          ++converted;
          return converted < requested;
        });
    const auto elapsed = std::chrono::duration<double>(
        std::chrono::steady_clock::now() - started).count();
    const auto fps = elapsed > 0.0 ? static_cast<double>(converted) / elapsed : 0.0;
    const bool passed = requested > 0 && converted == requested &&
                        report.completed && !conversion_failed;
    std::cout << "{\"schema\":\"preview-stream-benchmark-v1\",\"status\":\""
              << (passed ? "PASSED" : "FAILED") << "\",\"frames\":" << converted
              << ",\"seconds\":" << elapsed << ",\"fps\":" << fps
              << ",\"decode_backend\":\""
              << report.backend << "\"}\n";
    return passed ? 0 : 5;
  }
  if (argc == 12 && std::string_view(argv[1]) == "--play-video-shared" &&
      std::string_view(argv[2]) == "--input" &&
      std::string_view(argv[4]) == "--start-frame" &&
      std::string_view(argv[6]) == "--start-pts" &&
      std::string_view(argv[8]) == "--mapping-prefix" &&
      std::string_view(argv[10]) == "--cancel-file") {
    const auto start_frame = static_cast<std::size_t>(checked_stoull(argv[5]));
    const auto start_pts = checked_stoll(argv[7]);
    const std::string mapping_prefix = argv[9];
    const std::filesystem::path cancel_file = argv[11];
    std::optional<std::uint64_t> first_source_us;
    const auto wall_start = std::chrono::steady_clock::now();
    const auto cancelled = [&] { return std::filesystem::exists(cancel_file); };
    const auto report = smartcut::media::decode_preview_stream(
        argv[3], start_frame, start_pts,
        [&](std::shared_ptr<smartcut::core::PreviewFrame> source,
            std::uint64_t source_us) {
          if (!source || cancelled()) return false;
          auto frame = smartcut::media::convert_preview_to_bgra(source);
          if (!frame) return false;
          if (!first_source_us) first_source_us = source_us;
          const auto elapsed_us = source_us >= *first_source_us
              ? source_us - *first_source_us : std::uint64_t{0};
          const auto due = wall_start + std::chrono::microseconds(elapsed_us);
          while (!cancelled() && std::chrono::steady_clock::now() < due)
            std::this_thread::sleep_for(std::chrono::milliseconds(1));
          if (cancelled()) return false;
          frame->sequence = (static_cast<std::uint64_t>(process_id()) << 32U) ^
                            static_cast<std::uint64_t>(frame->frame_index + 1);
          const auto mapping = mapping_prefix + "-" + std::to_string(frame->frame_index);
          auto publisher = smartcut::core::SharedPreviewPublisher::publish(mapping, *frame);
          if (!publisher) return false;
          std::cout << "{\"schema\":\"worker-video-playback-v1\",\"event\":\"ready\",\"mapping\":\""
                    << mapping << "\",\"sequence\":" << frame->sequence
                    << ",\"frame_index\":" << frame->frame_index
                    << ",\"source_us\":" << source_us
                    << ",\"decode_backend\":\"" << source->decode_backend << "\"}\n"
                    << std::flush;
          for (int wait = 0; wait < 1000 && !cancelled() && !publisher->acknowledged(); ++wait)
            std::this_thread::sleep_for(std::chrono::milliseconds(1));
          return !cancelled() && publisher->acknowledged();
        });
    const bool was_cancelled = cancelled();
    const bool passed = report.completed && report.decoded_frames > 0;
    std::cout << "{\"schema\":\"worker-video-playback-v1\",\"event\":\"completed\",\"status\":\""
              << (was_cancelled ? "CANCELLED" : (passed ? "PASSED" : "FAILED"))
              << "\",\"frames\":" << report.decoded_frames
              << ",\"decode_backend\":\""
              << report.backend << "\"}\n";
    return was_cancelled || passed ? 0 : 5;
  }
  if (argc >= 10 && argc % 2 == 0 && std::string_view(argv[1]) == "--video-transform" &&
      std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--output" &&
      std::string_view(argv[6]) == "--first-frame" && std::string_view(argv[8]) == "--end-frame") {
    smartcut::media::VideoTransformOptions video;
    try {
      for (int option = 10; option + 1 < argc; option += 2) {
        const std::string_view key(argv[option]);
        if (key == "--video-codec") { const std::string value(argv[option + 1]); if (value != "source" && value != "mpeg2" && value != "h264" && value != "hevc" && value != "av1" && value != "vp9" && value != "ffv1" && value != "prores") return 2; video.codec = smartcut::media::video_output_codec_from_name(value); }
        else if (key == "--video-hardware") { const std::string value(argv[option + 1]); if (value != "auto" && value != "software" && value != "qsv" && value != "nvenc" && value != "amf" && value != "vulkan") return 2; video.hardware = smartcut::media::video_hardware_encoder_from_name(value); }
        else if (key == "--video-width") video.width = checked_int(argv[option + 1]);
        else if (key == "--video-height") video.height = checked_int(argv[option + 1]);
        else if (key == "--video-bit-depth") video.bit_depth = checked_int(argv[option + 1]);
        else if (key == "--video-bitrate-kbps") video.bitrate_kbps = checked_int(argv[option + 1]);
        else if (key == "--video-max-bitrate-kbps") video.max_bitrate_kbps = checked_int(argv[option + 1]);
        else if (key == "--video-aspect") video.aspect_ratio = argv[option + 1];
        else if (key == "--video-deinterlace") video.deinterlace = argv[option + 1];
        else if (key == "--video-frame-rate") video.frame_rate = argv[option + 1];
        else return 2;
      }
    } catch (...) { return 2; }
    video.trial_watermark = evaluation_video_delivery();
    if (video.width < 0 || video.height < 0 || (video.bit_depth != 0 && video.bit_depth != 8 && video.bit_depth != 10) || video.bitrate_kbps < 0 || video.max_bitrate_kbps < 0) return 2;
    const auto transform = smartcut::media::transcode_mkv_video_range(
        argv[3], argv[5], checked_stoull(argv[7]), checked_stoull(argv[9]), video);
    const auto validation = transform.find("\"status\":\"PASSED\"") != std::string::npos
                                ? smartcut::media::validate_transcoded_video(argv[5], video)
                                : std::string{"{\"schema\":\"video-transform-validation-v1\",\"status\":\"FAILED\"}"};
    const bool passed = transform.find("\"status\":\"PASSED\"") != std::string::npos &&
                        validation.find("\"status\":\"PASSED\"") != std::string::npos;
    std::cout << "{\"schema\":\"worker-video-transform-v1\",\"status\":\""
              << (passed ? "PASSED" : "FAILED") << "\",\"transform\":" << transform
              << ",\"validation\":" << validation << "}\n";
    return passed ? 0 : 5;
  }
  if ((argc == 4 || argc == 6) && std::string_view(argv[1]) == "--control-server" && std::string_view(argv[2]) == "--pipe") {
    std::size_t request_limit = 0; if (argc == 6) { if (std::string_view(argv[4]) != "--requests") return 2; request_limit = static_cast<std::size_t>(checked_stoull(argv[5])); }
    return smartcut::core::serve_control_pipe(argv[3], [](std::string_view request) {
      const auto id = json_int(std::string(request), "id", 0);
      if (request.find("\"schema\":\"control-request-v1\"") == std::string_view::npos) return std::string{"{\"schema\":\"control-response-v1\",\"id\":"} + std::to_string(id) + ",\"ok\":false,\"error\":\"unsupported request schema\"}";
      if (request.find("\"command\":\"ping\"") != std::string_view::npos) return std::string{"{\"schema\":\"control-response-v1\",\"id\":"} + std::to_string(id) + ",\"ok\":true,\"protocol_version\":1,\"worker_version\":\"" + std::string(smartcut::build_info::application_version) + "\",\"pid\":" + std::to_string(process_id()) + "}";
      if (request.find("\"command\":\"navigation-info\"") != std::string_view::npos) { const auto input = json_string(std::string(request), "input"); if (input.empty()) return std::string{"{\"schema\":\"control-response-v1\",\"id\":"} + std::to_string(id) + ",\"ok\":false,\"error\":\"input is missing\"}"; auto report = smartcut::media::build_fast_video_navigation(input); if (report.find("\"error\"") != std::string::npos) report = navigation_report(smartcut::media::load_or_build_video_frame_index(input)); const bool passed = report.find("\"error\"") == std::string::npos; return std::string{"{\"schema\":\"control-response-v1\",\"id\":"} + std::to_string(id) + ",\"ok\":" + (passed ? "true" : "false") + ",\"payload\":" + report + "}"; }
      if (request.find("\"command\":\"shutdown\"") != std::string_view::npos) return std::string{"{\"schema\":\"control-response-v1\",\"id\":"} + std::to_string(id) + ",\"ok\":true,\"shutdown\":true}";
      return std::string{"{\"schema\":\"control-response-v1\",\"id\":"} + std::to_string(id) + ",\"ok\":false,\"error\":\"unknown command\"}";
    }, request_limit);
  }
  if (argc == 8 && std::string_view(argv[1]) == "--plan" && std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--first-frame" && std::string_view(argv[6]) == "--end-frame") {
    try {
      const auto identity = smartcut::core::SourceIdentity::from_file(argv[3]);
      smartcut::core::Project project;
      smartcut::core::ProjectSource source{identity.source_uuid, identity.canonical_path};
      if (const auto audio = smartcut::media::primary_audio_track(argv[3])) {
        source.audio_stream = audio->stream_index;
        source.audio_time_base_num = audio->time_base_num;
        source.audio_time_base_den = audio->time_base_den;
        source.audio_sample_rate = audio->sample_rate;
        source.audio_channels = audio->channels;
      }
      project.add_source(source);
      project.add_segment({identity.source_uuid, 0, static_cast<std::uint64_t>(checked_stoull(argv[5])), static_cast<std::uint64_t>(checked_stoull(argv[7]))});
      std::cout << smartcut::core::RenderPlan::from_project(project).to_json() << '\n';
      return 0;
    } catch (const std::exception& error) {
      std::cout << "{\"schema\":\"worker-plan-error-v1\",\"error\":\"" << error.what() << "\"}\n";
      return 5;
    }
  }
  if (argc == 4 && std::string_view(argv[1]) == "--probe" && std::string_view(argv[2]) == "--input") {
    const auto report = smartcut::media::probe_container(argv[3]);
    std::cout << report << '\n';
    return report.find("\"error\"") == std::string::npos ? 0 : 5;
  }
  if ((argc == 8 || argc == 10) && std::string_view(argv[1]) == "--preview-shared" && std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--frame" && std::string_view(argv[6]) == "--mapping" && (argc == 8 || std::string_view(argv[8]) == "--pts")) {
    const auto frame_index = static_cast<std::size_t>(checked_stoull(argv[5])); const auto decoded = argc == 10 ? smartcut::media::decode_preview_frame(argv[3], frame_index, checked_stoll(argv[9])) : smartcut::media::decode_preview_frame(argv[3], frame_index); const auto frame = smartcut::media::convert_preview_to_bgra(decoded); if (!frame) { std::cout << "{\"schema\":\"worker-preview-shared-v1\",\"event\":\"failed\",\"status\":\"FAILED\"}\n"; return 5; } frame->sequence = (static_cast<std::uint64_t>(process_id()) << 32U) ^ static_cast<std::uint64_t>(frame_index + 1); auto publisher = smartcut::core::SharedPreviewPublisher::publish(argv[7], *frame); if (!publisher) { std::cout << "{\"schema\":\"worker-preview-shared-v1\",\"event\":\"failed\",\"status\":\"FAILED\"}\n"; return 5; } std::cout << "{\"schema\":\"worker-preview-shared-v1\",\"event\":\"ready\",\"mapping\":\"" << argv[7] << "\",\"sequence\":" << frame->sequence << ",\"frame_index\":" << frame->frame_index << ",\"width\":" << frame->width << ",\"height\":" << frame->height << ",\"stride\":" << frame->stride << ",\"pixel_format\":" << frame->pixel_format << "}\n" << std::flush; for (int wait = 0; wait < 1000 && !publisher->acknowledged(); ++wait) std::this_thread::sleep_for(std::chrono::milliseconds(5)); const bool acknowledged = publisher->acknowledged(); std::cout << "{\"schema\":\"worker-preview-shared-v1\",\"event\":\"completed\",\"status\":\"" << (acknowledged ? "PASSED" : "FAILED") << "\",\"acknowledged\":" << (acknowledged ? "true" : "false") << "}\n"; return acknowledged ? 0 : 5;
  }
  if (argc >= 6 && argc <= 12 && argc % 2 == 0 && std::string_view(argv[1]) == "--play-audio" && std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--start-us") {
    std::filesystem::path cancel_file;
    std::filesystem::path volume_file;
    std::optional<std::uint64_t> end_us;
    for (int option = 6; option + 1 < argc; option += 2) {
      if (std::string_view(argv[option]) == "--cancel-file") cancel_file = argv[option + 1];
      else if (std::string_view(argv[option]) == "--volume-file") volume_file = argv[option + 1];
      else if (std::string_view(argv[option]) == "--end-us") end_us = checked_stoull(argv[option + 1]);
      else { std::cerr << "Unknown audio playback option: " << argv[option] << '\n'; return 2; }
    }
    const auto volume_gain = [&] {
      if (volume_file.empty()) return 1.0;
      std::ifstream input(volume_file);
      double percent = 100.0;
      if (!(input >> percent)) return 1.0;
      return std::clamp(percent / 100.0, 0.0, 1.0);
    };
    const auto report = smartcut::media::play_audio_device(argv[3], checked_stoull(argv[5]), end_us, {}, [](std::uint64_t played_us) {
      std::cout << "{\"schema\":\"worker-audio-progress-v1\",\"played_us\":" << played_us << "}\n" << std::flush;
    }, [&] { return !cancel_file.empty() && std::filesystem::exists(cancel_file); }, volume_gain);
    std::cout << report << '\n'; return report.find("\"status\":\"PASSED\"") != std::string::npos || report.find("\"status\":\"CANCELLED\"") != std::string::npos ? 0 : 5;
  }
  if (argc == 10 && std::string_view(argv[1]) == "--audio-waveform" &&
      std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--start-us" &&
      std::string_view(argv[6]) == "--end-us" && std::string_view(argv[8]) == "--buckets") {
    const auto report = smartcut::media::audio_waveform_report(
        argv[3], checked_stoull(argv[5]), checked_stoull(argv[7]),
        static_cast<std::size_t>(checked_stoull(argv[9])));
    std::cout << report << '\n';
    return report.find("\"status\":\"PASSED\"") != std::string::npos ? 0 : 5;
  }
  if (argc >= 12 && argc % 2 == 0 && std::string_view(argv[1]) == "--ad-detect" &&
      std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--start-frame" &&
      std::string_view(argv[6]) == "--scene-threshold") {
    smartcut::media::AdDetectiveParameters parameters;
    std::string priority{"normal"};
    try {
      parameters.scene_threshold = checked_double(argv[7]);
      for (int option = 8; option + 1 < argc; option += 2) {
        const std::string_view name(argv[option]); const std::string_view value(argv[option + 1]);
        if (name == "--black-level" || name == "--average-black") parameters.average_black_level = checked_double(value);
        else if (name == "--peak-black") parameters.peak_black_level = checked_double(value);
        else if (name == "--contrast") parameters.contrast_threshold = checked_double(value);
        else if (name == "--minimum-frames") parameters.minimum_frame_spacing = static_cast<std::size_t>(checked_stoull(std::string(value)));
        else if (name == "--region") { if (!parse_ad_region(value, parameters.region)) return 2; }
        else if (name == "--ip-only") parameters.i_and_p_frames_only = value == "1" || value == "true";
        else if (name == "--black-detection") parameters.detect_black_transitions = value == "1" || value == "true";
        else if (name == "--priority") priority = value;
        else return 2;
      }
    } catch (...) { return 2; }
    set_worker_priority(priority);
    const auto report = smartcut::media::detect_ad_transitions(argv[3], static_cast<std::size_t>(checked_stoull(argv[5])), parameters,
        [](const smartcut::media::AdFrameStatistics& statistics) {
          std::cout << "{\"schema\":\"worker-ad-progress-v2\",\"frame\":" << statistics.frame
                    << ",\"average\":" << statistics.average << ",\"peak\":" << statistics.peak
                    << ",\"contrast\":" << statistics.contrast << ",\"scene_score\":" << statistics.scene_score
                    << ",\"black\":" << (statistics.black ? "true" : "false")
                    << ",\"picture_type\":\"" << statistics.picture_type << "\"}\n" << std::flush;
        });
    std::cout << report << '\n';
    return report_status_is(report, "PASSED") ? 0 : 5;
  }
  if (argc >= 12 && argc % 2 == 0 && std::string_view(argv[1]) == "--ad-detect-project" &&
      std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--project" &&
      std::string_view(argv[6]) == "--scene-threshold") {
    smartcut::media::AdDetectiveParameters parameters;
    double minimum_seconds = 1.0;
    std::string priority{"normal"};
    try {
      parameters.scene_threshold = checked_double(argv[7]);
      for (int option = 8; option + 1 < argc; option += 2) {
        const std::string_view name(argv[option]); const std::string_view value(argv[option + 1]);
        if (name == "--black-level" || name == "--average-black") parameters.average_black_level = checked_double(value);
        else if (name == "--peak-black") parameters.peak_black_level = checked_double(value);
        else if (name == "--contrast") parameters.contrast_threshold = checked_double(value);
        else if (name == "--minimum-seconds") minimum_seconds = std::max(0.0, checked_double(value));
        else if (name == "--region") { if (!parse_ad_region(value, parameters.region)) return 2; }
        else if (name == "--ip-only") parameters.i_and_p_frames_only = value == "1" || value == "true";
        else if (name == "--black-detection") parameters.detect_black_transitions = value == "1" || value == "true";
        else if (name == "--priority") priority = value;
        else return 2;
      }
    } catch (...) { return 2; }
    set_worker_priority(priority);
    const auto probe = smartcut::media::probe_container(argv[3]);
    const auto video_start = probe.find("\"type\":0");
    const auto video_end = video_start == std::string::npos ? std::string::npos : probe.find('}', video_start);
    const auto video_probe = video_start == std::string::npos ? std::string{} : probe.substr(video_start, video_end - video_start);
    auto frame_rate_num = json_int(video_probe, "avg_frame_rate_num");
    auto frame_rate_den = json_int(video_probe, "avg_frame_rate_den");
    if (frame_rate_num <= 0 || frame_rate_den <= 0) { frame_rate_num = json_int(video_probe, "frame_rate_num", 25); frame_rate_den = json_int(video_probe, "frame_rate_den", 1); }
    if (frame_rate_num <= 0 || frame_rate_den <= 0) { frame_rate_num = 25; frame_rate_den = 1; }
    const auto minimum_frames = static_cast<std::size_t>(std::max(1.0, std::ceil(minimum_seconds * static_cast<double>(frame_rate_num) / static_cast<double>(frame_rate_den))));
    parameters.minimum_frame_spacing = minimum_frames;
    const auto report = smartcut::media::detect_ad_transitions(argv[3], 0, parameters,
        [](const smartcut::media::AdFrameStatistics& statistics) { std::cout << "{\"schema\":\"worker-ad-progress-v2\",\"frame\":" << statistics.frame << "}\n" << std::flush; });
    if (!report_status_is(report, "PASSED")) { std::cout << report << '\n'; return 5; }
    const auto index = smartcut::media::load_or_build_video_frame_index(argv[3]);
    const auto frame_count = static_cast<std::uint64_t>(json_int(index, "frame_count"));
    if (frame_count == 0) { std::cout << "{\"schema\":\"worker-ad-project-v1\",\"status\":\"FAILED\",\"error\":\"empty frame index\"}\n"; return 5; }
    const auto identity = smartcut::core::SourceIdentity::from_file(argv[3]); smartcut::core::Project project; project.set_journal_path(std::string(argv[5]) + ".journal"); smartcut::core::ProjectSource source{identity.source_uuid, identity.canonical_path};
    if (const auto audio = smartcut::media::primary_audio_track(argv[3])) { source.audio_stream = audio->stream_index; source.audio_time_base_num = audio->time_base_num; source.audio_time_base_den = audio->time_base_den; source.audio_sample_rate = audio->sample_rate; source.audio_channels = audio->channels; }
    std::size_t video_stream = 0; for (std::size_t stream = 0; stream < 256; ++stream) if (probe.find("\"index\":" + std::to_string(stream) + ",\"type\":0") != std::string::npos) { video_stream = stream; break; }
    project.add_source(std::move(source)); project.add_segment({identity.source_uuid, video_stream, 0, frame_count}); project.set_chapter_markers(json_uints(report, 0, report.size(), "frame"));
    const bool saved = smartcut::core::ProjectEditor(project).save_atomic(argv[5]);
    std::cout << "{\"schema\":\"worker-ad-project-v1\",\"status\":\"" << (saved ? "PASSED" : "FAILED") << "\",\"chapter_markers\":" << project.chapter_markers().size() << ",\"minimum_seconds\":" << minimum_seconds << ",\"minimum_frames\":" << minimum_frames << ",\"frame_rate_num\":" << frame_rate_num << ",\"frame_rate_den\":" << frame_rate_den << "}\n";
    return saved ? 0 : 5;
  }
  if (argc == 12 && std::string_view(argv[1]) == "--ad-calibrate" &&
      std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--first-frame" &&
      std::string_view(argv[6]) == "--end-frame" && std::string_view(argv[8]) == "--region" &&
      std::string_view(argv[10]) == "--ip-only") {
    smartcut::media::AdScanRegion region;
    if (!parse_ad_region(argv[9], region)) return 2;
    const auto report = smartcut::media::calibrate_ad_thresholds(
        argv[3], static_cast<std::size_t>(checked_stoull(argv[5])), static_cast<std::size_t>(checked_stoull(argv[7])),
        region, std::string_view(argv[11]) == "1" || std::string_view(argv[11]) == "true");
    std::cout << report << '\n';
    return report_status_is(report, "PASSED") ? 0 : 5;
  }
  if (argc == 6 && std::string_view(argv[1]) == "--qsf-dimensions" &&
      std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--sample-seconds") {
    const auto report = smartcut::media::scan_video_dimensions(argv[3], checked_double(argv[5]));
    std::cout << report << '\n'; return report_status_is(report, "PASSED") ? 0 : 5;
  }
  if (argc == 10 && std::string_view(argv[1]) == "--qsf-filter" &&
      std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--output" &&
      std::string_view(argv[6]) == "--width" && std::string_view(argv[8]) == "--height") {
    if (evaluation_video_delivery()) return reject_evaluation_clean_delivery("qsf-filter");
    const auto report = smartcut::media::filter_video_dimensions(argv[3], argv[5], checked_int(argv[7]), checked_int(argv[9]));
    std::cout << report << '\n'; return report_status_is(report, "PASSED") ? 0 : 5;
  }
  if (argc >= 8 && argc % 2 == 0 && std::string_view(argv[1]) == "--export-project" &&
      std::string_view(argv[2]) == "--project" && std::string_view(argv[4]) == "--output" &&
      std::string_view(argv[6]) == "--mode") {
    std::ifstream project_file(argv[3]); const std::string document((std::istreambuf_iterator<char>(project_file)), {});
    const auto source = json_string(document, "canonical_path"); const auto segments = document.find("\"segments\":["); const auto exports = document.find("\"exports\":", segments);
    const auto first = json_uints(document, segments, exports == std::string::npos ? document.size() : exports, "first_display_frame");
    const auto ends = json_uints(document, segments, exports == std::string::npos ? document.size() : exports, "end_display_frame_exclusive");
    if (source.empty() || first.empty() || first.size() != ends.size()) { std::cout << "{\"schema\":\"project-export-v1\",\"status\":\"FAILED\",\"error\":\"invalid or multi-source project\"}\n"; return 5; }
    const auto index = smartcut::media::load_or_build_video_frame_index(source); const auto frame_count = static_cast<std::size_t>(json_int(index, "frame_count"));
    std::vector<smartcut::media::EditRange> kept; for (std::size_t i = 0; i < first.size(); ++i) kept.emplace_back(static_cast<std::size_t>(first[i]), static_cast<std::size_t>(ends[i]));
    std::sort(kept.begin(), kept.end()); std::vector<smartcut::media::EditRange> removed; std::size_t cursor = 0; for (const auto& range : kept) { if (cursor < range.first) removed.emplace_back(cursor, range.first); cursor = std::max(cursor, range.second); } if (cursor < frame_count) removed.emplace_back(cursor, frame_count);
    std::vector<std::size_t> streams; const auto sources = document.find("\"sources\":["); for (const auto value : json_uint_array(document, "selected_streams", sources, segments)) streams.push_back(static_cast<std::size_t>(value));
    auto mode = smartcut::media::EditExportMode::smart_render; const std::string_view mode_text(argv[7]); if (mode_text == "keyframe") mode = smartcut::media::EditExportMode::keyframe_copy; else if (mode_text == "full") mode = smartcut::media::EditExportMode::full_transcode; else if (mode_text != "smart") return 2;
    smartcut::media::AudioTransformOptions audio;
    smartcut::media::VideoTransformOptions video;
    smartcut::media::MpegTsMuxOptions transport_stream;
    for (int option = 8; option + 1 < argc; option += 2) {
      if (std::string_view(argv[option]) != "--trial-watermark") continue;
      const std::string_view requested(argv[option + 1]);
      if (requested != "true" && requested != "false") return 2;
      video.trial_watermark = requested == "true";
    }
    try {
      for (int option = 8; option + 1 < argc; option += 2) {
        const std::string_view key(argv[option]);
        if (key == "--audio-codec") {
          const std::string value(argv[option + 1]);
          if (value != "copy" && value != "source" && value != "aac" && value != "ac3" &&
              value != "mp2" && value != "opus" && value != "pcm" && value != "pcm_s16le") return 2;
          audio.codec = smartcut::media::audio_output_codec_from_name(value);
        } else if (key == "--audio-gain-db") audio.gain_db = checked_double(argv[option + 1]);
        else if (key == "--audio-bitrate") audio.bitrate = checked_int(argv[option + 1]);
        else if (key == "--audio-sample-rate") audio.sample_rate = checked_int(argv[option + 1]);
        else if (key == "--audio-channels") audio.channels = checked_int(argv[option + 1]);
        else if (key == "--video-codec") {
          const std::string value(argv[option + 1]);
          if (value != "source" && value != "mpeg2" && value != "h264" && value != "hevc" &&
              value != "av1" && value != "vp9" && value != "ffv1" && value != "prores") return 2;
          video.codec = smartcut::media::video_output_codec_from_name(value);
        } else if (key == "--video-hardware") {
          const std::string value(argv[option + 1]);
          if (value != "auto" && value != "software" && value != "qsv" && value != "nvenc" &&
              value != "amf" && value != "vulkan") return 2;
          video.hardware = smartcut::media::video_hardware_encoder_from_name(value);
        } else if (key == "--video-width") video.width = checked_int(argv[option + 1]);
        else if (key == "--video-height") video.height = checked_int(argv[option + 1]);
        else if (key == "--video-bit-depth") video.bit_depth = checked_int(argv[option + 1]);
        else if (key == "--video-bitrate-kbps") video.bitrate_kbps = checked_int(argv[option + 1]);
        else if (key == "--video-max-bitrate-kbps") video.max_bitrate_kbps = checked_int(argv[option + 1]);
        else if (key == "--video-aspect") video.aspect_ratio = argv[option + 1];
        else if (key == "--video-deinterlace") video.deinterlace = argv[option + 1];
        else if (key == "--video-frame-rate") video.frame_rate = argv[option + 1];
        else if (!parse_transport_stream_option(key, argv[option + 1], transport_stream)) return 2;
      }
    } catch (...) { return 2; }
    if (evaluation_video_delivery() && source_contains_video(source))
      video.trial_watermark = true;
    if (video.width < 0 || video.height < 0 || (video.bit_depth != 0 && video.bit_depth != 8 && video.bit_depth != 10) || video.bitrate_kbps < 0 || video.max_bitrate_kbps < 0) return 2;
    if (transport_stream.pmt_start_pid < 0x20 || transport_stream.pmt_start_pid > 0x1ffe || transport_stream.elementary_start_pid < 0x20 || transport_stream.elementary_start_pid > 0x1ffe || transport_stream.mux_rate < 0) return 2;
    const auto report = smartcut::media::export_mkv_edits(source, argv[5], frame_count, removed, streams, mode, json_int(document, "audio_offset_ms"), audio, video, transport_stream);
    const bool passed = report_status_is(report, "PASSED"); std::cout << "{\"schema\":\"project-export-v1\",\"status\":\"" << (passed ? "PASSED" : "FAILED") << "\",\"source\":\"" << source << "\",\"report\":" << report << export_completion_fields(passed, argv[5]) << "}\n"; return passed ? 0 : 5;
  }
  if (argc == 6 && std::string_view(argv[1]) == "--join-media" &&
      std::string_view(argv[2]) == "--list" && std::string_view(argv[4]) == "--output") {
    if (evaluation_video_delivery()) return reject_evaluation_clean_delivery("join-media");
    std::ifstream list(argv[3]);
    std::vector<std::filesystem::path> inputs;
    std::string path;
    while (std::getline(list, path)) if (!path.empty()) inputs.emplace_back(path);
    const auto report = smartcut::media::join_media_files(inputs, argv[5]);
    std::cout << report << '\n';
    return report.find("\"status\":\"PASSED\"") != std::string::npos ? 0 : 5;
  }
  if (argc == 20 && std::string_view(argv[1]) == "--create-title" &&
      std::string_view(argv[2]) == "--reference" && std::string_view(argv[4]) == "--bgra" &&
      std::string_view(argv[6]) == "--width" && std::string_view(argv[8]) == "--height" &&
      std::string_view(argv[10]) == "--output" && std::string_view(argv[12]) == "--duration" &&
      std::string_view(argv[14]) == "--fade-in" && std::string_view(argv[16]) == "--fade-out" &&
      std::string_view(argv[18]) == "--description") {
    if (evaluation_video_delivery()) return reject_evaluation_clean_delivery("create-title");
    const auto report = smartcut::media::create_title_media(argv[3], argv[5], checked_int(argv[7]), checked_int(argv[9]),
                                                             argv[11], checked_double(argv[13]), checked_double(argv[15]),
                                                             checked_double(argv[17]), argv[19]);
    std::cout << report << '\n';
    return report.find("\"status\":\"PASSED\"") != std::string::npos ? 0 : 5;
  }
  if (argc == 4 && std::string_view(argv[1]) == "--audio-info" && std::string_view(argv[2]) == "--input") {
    const auto audio = smartcut::media::primary_audio_track(argv[3]); if (!audio) { std::cout << "{\"schema\":\"worker-audio-info-v1\",\"status\":\"FAILED\"}\n"; return 5; }
    std::cout << "{\"schema\":\"worker-audio-info-v1\",\"status\":\"PASSED\",\"stream\":" << audio->stream_index << ",\"time_base_num\":" << audio->time_base_num << ",\"time_base_den\":" << audio->time_base_den << ",\"sample_rate\":" << audio->sample_rate << ",\"channels\":" << audio->channels << "}\n"; return 0;
  }
  if (argc == 8 && std::string_view(argv[1]) == "--create-videoredo-batch" &&
      std::string_view(argv[2]) == "--project" && std::string_view(argv[4]) == "--batch" &&
      std::string_view(argv[6]) == "--output") {
    std::string error; const auto project = smartcut::core::read_videoredo_project(argv[3], &error); if (!project) { std::cout << "{\"schema\":\"worker-videoredo-batch-create-v1\",\"status\":\"FAILED\",\"error\":\"" << error << "\"}\n"; return 5; }
    smartcut::core::VideoReDoBatchProject batch; batch.project = *project; auto media_output = std::filesystem::path(argv[7]); media_output.make_preferred(); batch.output_file = media_output.string(); const auto extension = media_output.extension().string(); if (extension == ".mp4" || extension == ".mov") { batch.profile.id = 3; batch.profile.name = extension == ".mov" ? "QuickTime MOV" : "MPEG-4 MP4"; batch.profile.file_type = extension == ".mov" ? "MOV" : "MP4"; } else if (extension == ".ts" || extension == ".m2ts") { batch.profile.id = 4; batch.profile.name = extension == ".m2ts" ? "M2TS" : "MPEG Transport Stream"; batch.profile.file_type = extension == ".m2ts" ? "M2TS" : "TS"; }
    const bool saved = smartcut::core::write_videoredo_batch_project(argv[5], batch, &error); std::cout << "{\"schema\":\"worker-videoredo-batch-create-v1\",\"status\":\"" << (saved ? "PASSED" : "FAILED") << "\"}\n"; return saved ? 0 : 5;
  }
  if (argc >= 4 && argc % 2 == 0 && std::string_view(argv[1]) == "--run-videoredo-batch" &&
      std::string_view(argv[2]) == "--project") {
    std::string error; const auto batch = smartcut::core::read_videoredo_batch_project(argv[3], &error);
    if (!batch || !std::filesystem::is_regular_file(batch->project.source_path)) { std::cout << "{\"schema\":\"worker-videoredo-batch-v1\",\"status\":\"FAILED\",\"error\":\"" << (error.empty() ? "source file is unavailable" : error) << "\"}\n"; return 5; }
    std::string output = batch->output_file;
    bool trial_watermark = false;
    for (int option = 4; option + 1 < argc; option += 2) {
      const std::string_view key(argv[option]);
      if (key == "--output") output = argv[option + 1];
      else if (key == "--trial-watermark") { const std::string_view value(argv[option + 1]); if (value != "true" && value != "false") return 2; trial_watermark = value == "true"; }
      else return 2;
    }
    if (output.empty()) return 2;
    if (evaluation_video_delivery()) trial_watermark = true;
    const bool quick_stream_substituted = batch->quick_stream_fix && trial_watermark;
    if (batch->quick_stream_fix && !trial_watermark) { const auto report = batch->dimension_width > 0 && batch->dimension_height > 0 ? smartcut::media::filter_video_dimensions(batch->project.source_path, output, batch->dimension_width, batch->dimension_height) : smartcut::media::export_media(batch->project.source_path, output); const bool passed = report_status_is(report, "PASSED"); std::cout << "{\"schema\":\"worker-videoredo-batch-v1\",\"status\":\"" << (passed ? "PASSED" : "FAILED") << "\",\"quick_stream_fix\":true,\"report\":" << report << export_completion_fields(passed, output) << "}\n"; return passed ? 0 : 5; }
    const auto index = smartcut::media::load_or_build_video_frame_index(batch->project.source_path); const auto navigation = navigation_report(index); const auto frame_pts = json_int_array(navigation, "frame_pts"); const auto frame_count = static_cast<std::size_t>(json_int(index, "frame_count")); const auto time_base_num = json_int(index, "time_base_num", 1); const auto time_base_den = json_int(index, "time_base_den", 1); if (frame_pts.size() != frame_count || frame_count == 0) return 5;
    std::vector<smartcut::media::EditRange> selected; for (const auto& range : batch->project.selections) { const auto first = std::min(frame_at_microseconds(frame_pts, time_base_num, time_base_den, range.start_us), frame_count); const auto end = std::min(frame_at_microseconds(frame_pts, time_base_num, time_base_den, range.end_us), frame_count); if (first < end) selected.emplace_back(first, end); } std::sort(selected.begin(), selected.end()); std::vector<smartcut::media::EditRange> merged; for (const auto& range : selected) { if (!merged.empty() && range.first <= merged.back().second) merged.back().second = std::max(merged.back().second, range.second); else merged.push_back(range); }
    std::vector<smartcut::media::EditRange> removed; if (batch->project.cut_mode) removed = merged; else { std::size_t cursor{}; for (const auto& range : merged) { if (cursor < range.first) removed.emplace_back(cursor, range.first); cursor = std::max(cursor, range.second); } if (cursor < frame_count) removed.emplace_back(cursor, frame_count); }
    const auto lowercase = [](std::string value) { std::transform(value.begin(), value.end(), value.begin(), [](unsigned char character) { return static_cast<char>(std::tolower(character)); }); value.erase(std::remove_if(value.begin(), value.end(), [](unsigned char character) { return !std::isalnum(character); }), value.end()); return value; };
    const auto video_name = lowercase(batch->profile.video_encoder); smartcut::media::VideoTransformOptions video; if (video_name == "mpeg2" || video_name == "mpeg2video") video.codec = smartcut::media::VideoOutputCodec::mpeg2; else if (video_name == "h264" || video_name == "avc") video.codec = smartcut::media::VideoOutputCodec::h264; else if (video_name == "hevc" || video_name == "h265") video.codec = smartcut::media::VideoOutputCodec::hevc; else if (video_name == "av1") video.codec = smartcut::media::VideoOutputCodec::av1; else if (video_name == "vp9") video.codec = smartcut::media::VideoOutputCodec::vp9; else if (video_name == "ffv1") video.codec = smartcut::media::VideoOutputCodec::ffv1; else if (video_name == "prores" || video_name == "proresks" || video_name == "prores_ks") video.codec = smartcut::media::VideoOutputCodec::prores; if (video.codec != smartcut::media::VideoOutputCodec::source) { video.width = batch->profile.width; video.height = batch->profile.height; video.bitrate_kbps = batch->profile.bitrate_kbps; video.max_bitrate_kbps = batch->profile.max_bitrate_kbps; video.deinterlace = batch->profile.deinterlace; video.frame_rate = batch->profile.frame_rate; }
    video.trial_watermark = trial_watermark;
    const auto audio_name = lowercase(batch->profile.audio_encoder); smartcut::media::AudioTransformOptions audio; if (audio_name == "aac") audio.codec = smartcut::media::AudioOutputCodec::aac; else if (audio_name == "ac3" || audio_name == "dolbydigital") audio.codec = smartcut::media::AudioOutputCodec::ac3; else if (audio_name == "mp2" || audio_name == "mpegaudio") audio.codec = smartcut::media::AudioOutputCodec::mp2; else if (audio_name == "pcm" || audio_name == "lpcm" || audio_name == "pcm_s16le") audio.codec = smartcut::media::AudioOutputCodec::pcm_s16le; else if (audio_name == "opus") audio.codec = smartcut::media::AudioOutputCodec::opus; if (audio.codec != smartcut::media::AudioOutputCodec::copy) { audio.bitrate = batch->profile.audio_bitrate_kbps > 0 ? batch->profile.audio_bitrate_kbps * 1000 : 192000; try { if (batch->profile.audio_sample_rate != "No Change") audio.sample_rate = checked_int(batch->profile.audio_sample_rate); } catch (...) {} const auto channels = lowercase(batch->profile.audio_channels); if (channels == "mono") audio.channels = 1; else if (channels == "stereo") audio.channels = 2; else if (channels == "51" || channels == "surround") audio.channels = 6; }
    auto mode = smartcut::media::EditExportMode::smart_render; const auto output_mode = lowercase(batch->profile.output_mode); if (output_mode == "recode" || output_mode == "forcerecode" || video.codec != smartcut::media::VideoOutputCodec::source) mode = smartcut::media::EditExportMode::full_transcode; else if (output_mode == "copy" || output_mode == "same") mode = smartcut::media::EditExportMode::keyframe_copy;
    const auto report = smartcut::media::export_mkv_edits(batch->project.source_path, output, frame_count, removed, {}, mode, batch->project.sync_adjustment_ms, audio, video); const bool passed = report_status_is(report, "PASSED"); std::cout << "{\"schema\":\"worker-videoredo-batch-v1\",\"status\":\"" << (passed ? "PASSED" : "FAILED") << "\",\"requested_quick_stream_fix\":" << (batch->quick_stream_fix ? "true" : "false") << ",\"quick_stream_fix\":false,\"substitution_reason\":\"" << (quick_stream_substituted ? "evaluation_watermark_requires_reencode" : "") << "\",\"removed_ranges\":" << removed.size() << ",\"report\":" << report << export_completion_fields(passed, output) << "}\n"; return passed ? 0 : 5;
  }
  if (argc == 6 && std::string_view(argv[1]) == "--import-videoredo-project" && std::string_view(argv[2]) == "--project" && std::string_view(argv[4]) == "--output") {
    std::string error;
    const auto imported = smartcut::core::read_videoredo_project(argv[3], &error);
    if (!imported || !std::filesystem::is_regular_file(imported->source_path)) { std::cout << "{\"schema\":\"worker-videoredo-import-v1\",\"status\":\"FAILED\",\"error\":\"" << (error.empty() ? "source file is unavailable" : error) << "\"}\n"; return 5; }
    const auto index = smartcut::media::load_or_build_video_frame_index(imported->source_path); const auto pts = json_int_array(index, "frames").empty() ? json_int_array(navigation_report(index), "frame_pts") : json_int_array(index, "frames");
    const auto frame_pts = pts.empty() ? json_int_array(navigation_report(index), "frame_pts") : pts;
    const auto frame_count = static_cast<std::size_t>(json_int(index, "frame_count")); const auto time_base_num = json_int(index, "time_base_num", 1); const auto time_base_den = json_int(index, "time_base_den", 1);
    if (frame_count == 0 || frame_pts.size() != frame_count) { std::cout << "{\"schema\":\"worker-videoredo-import-v1\",\"status\":\"FAILED\",\"error\":\"source frame index is unavailable\"}\n"; return 5; }
    std::vector<smartcut::media::EditRange> selected;
    for (const auto& range : imported->selections) { const auto first = std::min(frame_at_microseconds(frame_pts, time_base_num, time_base_den, range.start_us), frame_count); const auto end = std::min(frame_at_microseconds(frame_pts, time_base_num, time_base_den, range.end_us), frame_count); if (first < end) selected.emplace_back(first, end); }
    std::sort(selected.begin(), selected.end()); std::vector<smartcut::media::EditRange> merged; for (const auto& range : selected) { if (!merged.empty() && range.first <= merged.back().second) merged.back().second = std::max(merged.back().second, range.second); else merged.push_back(range); }
    std::vector<smartcut::media::EditRange> kept;
    if (merged.empty()) kept.emplace_back(0, frame_count); else if (imported->cut_mode) kept = smartcut::media::kept_ranges_for_edits(frame_count, merged); else kept = merged;
    if (kept.empty()) { std::cout << "{\"schema\":\"worker-videoredo-import-v1\",\"status\":\"FAILED\",\"error\":\"project removes every frame\"}\n"; return 5; }
    std::vector<std::uint64_t> chapters; auto marker_times = imported->chapter_markers_us; marker_times.insert(marker_times.end(), imported->scene_markers_us.begin(), imported->scene_markers_us.end()); std::sort(marker_times.begin(), marker_times.end()); marker_times.erase(std::unique(marker_times.begin(), marker_times.end()), marker_times.end()); for (const auto marker : marker_times) { const auto frame = frame_at_microseconds(frame_pts, time_base_num, time_base_den, marker); if (frame < frame_count) chapters.push_back(frame); }
    const auto probe = smartcut::media::probe_container(imported->source_path); const auto streams = json_uints(probe, 0, probe.size(), "index"); std::size_t video_stream = 0; for (const auto stream : streams) if (probe.find("\"index\":" + std::to_string(stream) + ",\"type\":0") != std::string::npos) { video_stream = static_cast<std::size_t>(stream); break; }
    const auto identity = smartcut::core::SourceIdentity::from_file(imported->source_path); smartcut::core::Project project; project.set_journal_path(std::string(argv[5]) + ".journal"); smartcut::core::ProjectSource source{identity.source_uuid, identity.canonical_path}; source.selected_streams.assign(streams.begin(), streams.end()); if (const auto audio = smartcut::media::primary_audio_track(imported->source_path)) { source.audio_stream = audio->stream_index; source.audio_time_base_num = audio->time_base_num; source.audio_time_base_den = audio->time_base_den; source.audio_sample_rate = audio->sample_rate; source.audio_channels = audio->channels; }
    project.add_source(std::move(source)); for (const auto& range : kept) project.add_segment({identity.source_uuid, video_stream, range.first, range.second}); project.set_chapter_markers(std::move(chapters)); project.set_scene_mode(!imported->cut_mode); project.set_audio_offset_ms(imported->sync_adjustment_ms);
    const bool saved = smartcut::core::ProjectEditor(project).save_atomic(argv[5]); std::cout << "{\"schema\":\"worker-videoredo-import-v1\",\"status\":\"" << (saved ? "PASSED" : "FAILED") << "\",\"kept_segments\":" << kept.size() << ",\"chapter_markers\":" << project.chapter_markers().size() << "}\n"; return saved ? 0 : 5;
  }
  if (argc == 6 && std::string_view(argv[1]) == "--export-videoredo-project" && std::string_view(argv[2]) == "--project" && std::string_view(argv[4]) == "--output") {
    std::ifstream input(argv[3], std::ios::binary); const std::string document((std::istreambuf_iterator<char>(input)), {}); const auto source_path = json_string(document, "canonical_path"); if (source_path.empty() || !std::filesystem::is_regular_file(source_path)) { std::cout << "{\"schema\":\"worker-videoredo-export-v1\",\"status\":\"FAILED\",\"error\":\"source file is unavailable\"}\n"; return 5; }
    const auto index = smartcut::media::load_or_build_video_frame_index(source_path); const auto navigation = navigation_report(index); const auto frame_pts = json_int_array(navigation, "frame_pts"); const auto frame_count = static_cast<std::size_t>(json_int(index, "frame_count")); const auto time_base_num = json_int(index, "time_base_num", 1); const auto time_base_den = json_int(index, "time_base_den", 1); if (frame_pts.size() != frame_count || frame_count == 0) return 5;
    const auto segments_start = document.find("\"segments\":"); const auto exports_start = document.find("\"exports\":", segments_start); const auto firsts = json_uints(document, segments_start, exports_start, "first_display_frame"); const auto ends = json_uints(document, segments_start, exports_start, "end_display_frame_exclusive"); std::vector<smartcut::media::EditRange> kept; for (std::size_t item = 0; item < std::min(firsts.size(), ends.size()); ++item) if (firsts[item] < ends[item] && ends[item] <= frame_count) kept.emplace_back(static_cast<std::size_t>(firsts[item]), static_cast<std::size_t>(ends[item])); if (kept.empty()) return 5;
    const bool scene_mode = json_bool(document, "scene_mode"); std::vector<smartcut::media::EditRange> selections = scene_mode ? kept : std::vector<smartcut::media::EditRange>{}; if (!scene_mode) { std::size_t cursor = 0; for (const auto& range : kept) { if (cursor < range.first) selections.emplace_back(cursor, range.first); cursor = std::max(cursor, range.second); } if (cursor < frame_count) selections.emplace_back(cursor, frame_count); }
    smartcut::core::VideoReDoProject exported; exported.source_path = source_path; exported.description = "Exported by SmartCut64"; exported.duration_us = frame_microseconds(frame_pts, time_base_num, time_base_den, frame_count); exported.sync_adjustment_ms = json_int(document, "audio_offset_ms"); exported.cut_mode = !scene_mode; for (const auto& range : selections) exported.selections.push_back({frame_microseconds(frame_pts, time_base_num, time_base_den, range.first), frame_microseconds(frame_pts, time_base_num, time_base_den, range.second)}); const auto chapters = json_uint_array(document, "chapter_markers", 0, document.size()); for (const auto frame : chapters) if (frame < frame_count) exported.chapter_markers_us.push_back(frame_microseconds(frame_pts, time_base_num, time_base_den, static_cast<std::size_t>(frame)));
    std::string error; const bool saved = smartcut::core::write_videoredo_project(argv[5], exported, &error); std::cout << "{\"schema\":\"worker-videoredo-export-v1\",\"status\":\"" << (saved ? "PASSED" : "FAILED") << "\",\"selections\":" << exported.selections.size() << ",\"chapter_markers\":" << exported.chapter_markers_us.size() << "}\n"; return saved ? 0 : 5;
  }
  if (argc == 4 && std::string_view(argv[1]) == "--project-summary" && std::string_view(argv[2]) == "--project") {
    std::ifstream input(argv[3]); const std::string document((std::istreambuf_iterator<char>(input)), {}); const auto string_value = [&document](const std::string& key) { const auto marker = "\"" + key + "\":\""; const auto start = document.find(marker); if (start == std::string::npos) return std::string{}; const auto begin = start + marker.size(); const auto end = document.find('"', begin); return end == std::string::npos ? std::string{} : document.substr(begin, end - begin); }; const auto number_value = [&document](const std::string& key) { const auto marker = "\"" + key + "\":"; const auto start = document.find(marker); if (start == std::string::npos) return std::string{}; const auto begin = start + marker.size(); const auto end = document.find_first_of(",}", begin); return document.substr(begin, end == std::string::npos ? std::string::npos : end - begin); };
    const auto status = string_value("audio_validation_status"); const auto stream = number_value("audio_stream"); const auto sample_rate = number_value("audio_sample_rate"); const auto channels = number_value("audio_channels"); const bool ok = input.good() || input.eof(); std::cout << "{\"schema\":\"worker-project-summary-v1\",\"status\":\"" << (ok ? "PASSED" : "FAILED") << "\",\"audio_validation_status\":\"" << status << "\",\"audio_stream\":" << (stream.empty() ? "null" : stream) << ",\"audio_sample_rate\":" << (sample_rate.empty() ? "null" : sample_rate) << ",\"audio_channels\":" << (channels.empty() ? "null" : channels) << "}\n"; return ok ? 0 : 5;
  }
  if (argc == 4 && std::string_view(argv[1]) == "--validate-project-audio" && std::string_view(argv[2]) == "--project") {
    std::ifstream input(argv[3]);
    const std::string document((std::istreambuf_iterator<char>(input)), {});
    const auto path_marker = document.find("\"canonical_path\":\"");
    const auto path_start = path_marker == std::string::npos ? std::string::npos : path_marker + 18;
    const auto path_end = path_start == std::string::npos ? std::string::npos : document.find('\"', path_start);
    const std::string source_path = path_start == std::string::npos || path_end == std::string::npos ? std::string{} : document.substr(path_start, path_end - path_start);
    const bool metadata = audio_metadata_matches(document, document.find("\"sources\":"), document.find("\"segments\":"), source_path);
    std::cout << "{\"schema\":\"worker-project-audio-validation-v1\",\"status\":\"" << (metadata ? "PASSED" : "FAILED") << "\",\"audio_metadata\":" << (metadata ? "true" : "false") << "}\n";
    return metadata ? 0 : 5;
  }
  if (argc == 4 && std::string_view(argv[1]) == "--validate-project" && std::string_view(argv[2]) == "--project") {
    std::ifstream input(argv[3]);
    const std::string document((std::istreambuf_iterator<char>(input)), {});
    const auto path_marker = document.find("\"canonical_path\":\"");
    const auto path_start = path_marker == std::string::npos ? std::string::npos : path_marker + 18;
    const auto path_end = path_start == std::string::npos ? std::string::npos : document.find('\"', path_start);
    const std::string source_path = path_start == std::string::npos || path_end == std::string::npos ? std::string{} : document.substr(path_start, path_end - path_start);
    if (!audio_metadata_matches(document, document.find("\"sources\":"), document.find("\"segments\":"), source_path)) {
      std::cout << "{\"schema\":\"worker-project-validation-v1\",\"status\":\"FAILED\",\"audio_metadata\":false}\n";
      return 5;
    }
  }
  if (argc == 4 && std::string_view(argv[1]) == "--validate-project" && std::string_view(argv[2]) == "--project") {
    std::ifstream input(argv[3]); std::string document((std::istreambuf_iterator<char>(input)), {}); const bool valid = input.good() || input.eof(); const bool schema = document.find("\"schema\":\"project-v1\"") != std::string::npos; const auto sources_start = document.find("\"sources\":"); const auto segments_start = document.find("\"segments\":"); const auto exports_start = document.find("\"exports\":", segments_start); const bool sources = sources_start != std::string::npos; const bool segments = segments_start != std::string::npos; const bool source_fields = document.find("\"source_uuid\":") != std::string::npos && document.find("\"canonical_path\":") != std::string::npos; const bool segment_fields = document.find("\"video_stream\":") != std::string::npos && document.find("\"first_display_frame\":") != std::string::npos && document.find("\"end_display_frame_exclusive\":") != std::string::npos; const auto declared_sources = json_values(document, sources_start, segments_start, "source_uuid"); const auto segment_sources = json_values(document, segments_start, exports_start == std::string::npos ? document.size() : exports_start, "source_uuid"); bool cross_reference = !declared_sources.empty(); for (const auto& segment_source : segment_sources) if (std::find(declared_sources.begin(), declared_sources.end(), segment_source) == declared_sources.end()) cross_reference = false; const auto first_frames = json_uints(document, segments_start, exports_start == std::string::npos ? document.size() : exports_start, "first_display_frame"); const auto end_frames = json_uints(document, segments_start, exports_start == std::string::npos ? document.size() : exports_start, "end_display_frame_exclusive"); bool range_ordering = first_frames.size() == end_frames.size() && !first_frames.empty(); for (std::size_t i = 0; i < std::min(first_frames.size(), end_frames.size()); ++i) if (end_frames[i] <= first_frames[i]) range_ordering = false; const auto path_marker = document.find("\"canonical_path\":\""); const auto path_start = path_marker == std::string::npos ? std::string::npos : path_marker + 18; const auto path_end = path_start == std::string::npos ? std::string::npos : document.find('"', path_start); const std::string source_path = path_start == std::string::npos || path_end == std::string::npos ? std::string{} : document.substr(path_start, path_end - path_start); const auto probe = source_path.empty() ? std::string{} : smartcut::media::probe_container(source_path); std::size_t stream_count = 0; for (std::size_t cursor = 0; (cursor = probe.find("\"index\":", cursor)) != std::string::npos; cursor += 8) ++stream_count; const auto video_streams = json_uints(document, segments_start, exports_start == std::string::npos ? document.size() : exports_start, "video_stream"); bool stream_bounds = stream_count > 0 && !video_streams.empty(); bool video_stream_types = stream_bounds; for (const auto stream : video_streams) { if (stream >= stream_count) stream_bounds = false; const auto marker = "\"index\":" + std::to_string(stream) + ",\"type\":0"; if (probe.find(marker) == std::string::npos) video_stream_types = false; } std::cout << "{\"schema\":\"worker-project-validation-v1\",\"status\":\"" << (valid && schema && sources && segments && source_fields && segment_fields && cross_reference && range_ordering && stream_bounds && video_stream_types ? "PASSED" : "FAILED") << "\",\"schema_present\":" << (schema ? "true" : "false") << ",\"sources_present\":" << (sources ? "true" : "false") << ",\"segments_present\":" << (segments ? "true" : "false") << ",\"source_fields_present\":" << (source_fields ? "true" : "false") << ",\"segment_fields_present\":" << (segment_fields ? "true" : "false") << ",\"source_cross_reference\":" << (cross_reference ? "true" : "false") << ",\"range_ordering\":" << (range_ordering ? "true" : "false") << ",\"stream_bounds\":" << (stream_bounds ? "true" : "false") << ",\"video_stream_types\":" << (video_stream_types ? "true" : "false") << "}\n"; return valid && schema && sources && segments && source_fields && segment_fields && cross_reference && range_ordering && stream_bounds && video_stream_types ? 0 : 5;
  }
  if (argc == 12 && std::string_view(argv[1]) == "--save-project" && std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--project" && std::string_view(argv[6]) == "--first-frame" && std::string_view(argv[8]) == "--end-frame" && std::string_view(argv[10]) == "--journal") {
    const auto identity = smartcut::core::SourceIdentity::from_file(argv[3]); smartcut::core::Project project; project.set_journal_path(argv[11]); smartcut::core::ProjectSource source{identity.source_uuid, identity.canonical_path}; if (const auto audio = smartcut::media::primary_audio_track(argv[3])) { source.audio_stream = audio->stream_index; source.audio_time_base_num = audio->time_base_num; source.audio_time_base_den = audio->time_base_den; source.audio_sample_rate = audio->sample_rate; source.audio_channels = audio->channels; } project.add_source(source); project.add_segment({identity.source_uuid, 0, static_cast<std::uint64_t>(checked_stoull(argv[7])), static_cast<std::uint64_t>(checked_stoull(argv[9]))}); const bool saved = smartcut::core::ProjectEditor(project).save_atomic(argv[5]); std::cout << "{\"schema\":\"worker-project-save-v1\",\"status\":\"" << (saved ? "PASSED" : "FAILED") << "\"}\n"; return saved ? 0 : 5;
  }
  if ((argc == 12 || argc == 14 || argc == 16 || argc == 18 || argc == 20) && std::string_view(argv[1]) == "--save-edit-project" &&
      std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--project" &&
      std::string_view(argv[6]) == "--frame-count" && std::string_view(argv[8]) == "--cuts" &&
      std::string_view(argv[10]) == "--journal") {
    std::size_t frame_count = 0;
    std::vector<smartcut::media::EditRange> cuts;
    std::vector<std::size_t> streams;
    std::vector<std::uint64_t> chapters;
    bool scene_mode = false;
    std::int64_t audio_offset_ms = 0;
    try {
      frame_count = static_cast<std::size_t>(checked_stoull(argv[7]));
      std::stringstream ranges(argv[9]); std::string token;
      while (std::getline(ranges, token, ',')) { if (token.empty()) continue; const auto separator = token.find(':'); if (separator == std::string::npos) return 2; cuts.emplace_back(static_cast<std::size_t>(checked_stoull(token.substr(0, separator))), static_cast<std::size_t>(checked_stoull(token.substr(separator + 1)))); }
      for (int option = 12; option + 1 < argc; option += 2) { std::stringstream values(argv[option + 1]); if (std::string_view(argv[option]) == "--streams") { while (std::getline(values, token, ',')) if (!token.empty()) streams.push_back(static_cast<std::size_t>(checked_stoull(token))); } else if (std::string_view(argv[option]) == "--chapters") { while (std::getline(values, token, ',')) if (!token.empty()) chapters.push_back(checked_stoull(token)); } else if (std::string_view(argv[option]) == "--scene-mode") scene_mode = std::string_view(argv[option + 1]) == "1"; else if (std::string_view(argv[option]) == "--audio-offset-ms") audio_offset_ms = checked_stoll(argv[option + 1]); else return 2; }
    } catch (...) { return 2; }
    const auto kept = smartcut::media::kept_ranges_for_edits(frame_count, cuts);
    if (frame_count == 0 || kept.empty()) { std::cout << "{\"schema\":\"worker-edit-project-save-v1\",\"status\":\"FAILED\",\"reason\":\"project has no kept frames\"}\n"; return 5; }
    const auto identity = smartcut::core::SourceIdentity::from_file(argv[3]); smartcut::core::Project project; project.set_journal_path(argv[11]); smartcut::core::ProjectSource source{identity.source_uuid, identity.canonical_path}; source.selected_streams = streams;
    if (const auto audio = smartcut::media::primary_audio_track(argv[3])) { source.audio_stream = audio->stream_index; source.audio_time_base_num = audio->time_base_num; source.audio_time_base_den = audio->time_base_den; source.audio_sample_rate = audio->sample_rate; source.audio_channels = audio->channels; }
    const auto probe = smartcut::media::probe_container(argv[3]); std::size_t video_stream = 0; for (const auto stream : streams) if (probe.find("\"index\":" + std::to_string(stream) + ",\"type\":0") != std::string::npos) { video_stream = stream; break; }
    project.add_source(std::move(source)); for (const auto& range : kept) project.add_segment({identity.source_uuid, video_stream, range.first, range.second}); project.set_chapter_markers(std::move(chapters)); project.set_scene_mode(scene_mode); project.set_audio_offset_ms(audio_offset_ms);
    const bool saved = smartcut::core::ProjectEditor(project).save_atomic(argv[5]); std::cout << "{\"schema\":\"worker-edit-project-save-v1\",\"status\":\"" << (saved ? "PASSED" : "FAILED") << "\",\"kept_segments\":" << kept.size() << ",\"selected_streams\":" << streams.size() << ",\"chapter_markers\":" << project.chapter_markers().size() << "}\n"; return saved ? 0 : 5;
  }
  if ((argc == 14 || argc == 16 || argc == 18) && std::string_view(argv[1]) == "--record-edit-snapshot" && std::string_view(argv[2]) == "--journal" && std::string_view(argv[4]) == "--source-uuid" && std::string_view(argv[6]) == "--frame-count" && std::string_view(argv[8]) == "--cuts" && std::string_view(argv[10]) == "--streams" && std::string_view(argv[12]) == "--chapters" && (argc == 14 || std::string_view(argv[14]) == "--scene-mode") && (argc != 18 || std::string_view(argv[16]) == "--audio-offset-ms")) {
    smartcut::core::EditSnapshot snapshot; snapshot.source_uuid = argv[5];
    try { snapshot.frame_count = checked_stoull(argv[7]); std::stringstream ranges(argv[9]); std::string token; while (std::getline(ranges, token, ',')) { if (token.empty()) continue; const auto separator = token.find(':'); if (separator == std::string::npos) return 2; snapshot.cuts.emplace_back(checked_stoull(token.substr(0, separator)), checked_stoull(token.substr(separator + 1))); } std::stringstream streams(argv[11]); while (std::getline(streams, token, ',')) if (!token.empty()) snapshot.selected_streams.push_back(static_cast<std::size_t>(checked_stoull(token))); std::stringstream chapters(argv[13]); while (std::getline(chapters, token, ',')) if (!token.empty()) snapshot.chapter_markers.push_back(checked_stoull(token)); if (argc >= 16) snapshot.scene_mode = std::string_view(argv[15]) == "1"; if (argc == 18) snapshot.audio_offset_ms = checked_stoll(argv[17]); } catch (...) { return 2; }
    const bool saved = smartcut::core::ProjectJournal::append_edit_snapshot(argv[3], snapshot); std::cout << "{\"schema\":\"worker-edit-snapshot-v1\",\"status\":\"" << (saved ? "PASSED" : "FAILED") << "\"}\n"; return saved ? 0 : 5;
  }
  if (argc == 4 && std::string_view(argv[1]) == "--latest-edit-snapshot" && std::string_view(argv[2]) == "--journal") {
    const auto snapshot = smartcut::core::ProjectJournal::latest_edit_snapshot(argv[3]); if (!snapshot) { std::cout << "{\"schema\":\"worker-edit-snapshot-v1\",\"status\":\"NONE\"}\n"; return 0; }
    std::cout << "{\"schema\":\"worker-edit-snapshot-v1\",\"status\":\"PASSED\",\"source_uuid\":\"" << snapshot->source_uuid << "\",\"frame_count\":" << snapshot->frame_count << ",\"cuts\":["; for (std::size_t index = 0; index < snapshot->cuts.size(); ++index) { if (index) std::cout << ','; std::cout << "{\"first\":" << snapshot->cuts[index].first << ",\"end\":" << snapshot->cuts[index].second << '}'; } std::cout << "],\"selected_streams\":["; for (std::size_t index = 0; index < snapshot->selected_streams.size(); ++index) { if (index) std::cout << ','; std::cout << snapshot->selected_streams[index]; } std::cout << "],\"chapter_markers\":["; for (std::size_t index = 0; index < snapshot->chapter_markers.size(); ++index) { if (index) std::cout << ','; std::cout << snapshot->chapter_markers[index]; } std::cout << "],\"scene_mode\":" << (snapshot->scene_mode ? "true" : "false") << ",\"audio_offset_ms\":" << snapshot->audio_offset_ms << "}\n"; return 0;
  }
  if (argc == 4 && std::string_view(argv[1]) == "--export-history" && std::string_view(argv[2]) == "--journal") {
    std::ifstream input(argv[3]); std::string line; std::cout << "{\"schema\":\"worker-export-history-v1\",\"entries\":["; bool first = true; while (std::getline(input, line)) { if (line.find("\"op\":\"export_evidence\"") == std::string::npos && line.find("\"op\":\"audio_validation\"") == std::string::npos) continue; if (!first) std::cout << ','; first = false; std::cout << line; } std::cout << "]}\n"; return input.good() || input.eof() ? 0 : 5;
  }
  if (argc == 6 && std::string_view(argv[1]) == "--record-audio-validation" && std::string_view(argv[2]) == "--journal" && std::string_view(argv[4]) == "--status") {
    const bool recorded = smartcut::core::ProjectJournal::append_audio_validation(argv[3], argv[5]);
    std::cout << "{\"schema\":\"worker-audio-validation-evidence-v1\",\"status\":\"" << (recorded ? "PASSED" : "FAILED") << "\"}\n";
    return recorded ? 0 : 5;
  }
  if (argc == 6 && std::string_view(argv[1]) == "--update-project-audio-validation" && std::string_view(argv[2]) == "--project" && std::string_view(argv[4]) == "--status") {
    std::ifstream input(argv[3]); std::string document((std::istreambuf_iterator<char>(input)), {}); const auto marker = std::string("\"audio_validation_status\":\""); const auto start = document.find(marker); const auto replacement = marker + std::string(argv[5]) + "\""; bool updated = false;
    while (!document.empty() && std::isspace(static_cast<unsigned char>(document.back()))) { document.pop_back(); }
    if (start != std::string::npos) { const auto value_end = document.find('"', start + marker.size()); if (value_end != std::string::npos) { document.replace(start, value_end + 1 - start, replacement); updated = true; } } else if (!document.empty() && document.back() == '}') { document.pop_back(); document += ",\"audio_validation_status\":\"" + std::string(argv[5]) + "\"}"; updated = true; }
    if (updated) { std::ofstream output(argv[3], std::ios::binary | std::ios::trunc); output << document << '\n'; updated = static_cast<bool>(output); }
    std::cout << "{\"schema\":\"worker-project-audio-status-v1\",\"status\":\"" << (updated ? "PASSED" : "FAILED") << "\"}\n"; return updated ? 0 : 5;
  }
  if (argc == 12 && std::string_view(argv[1]) == "--record-export" && std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--output" && std::string_view(argv[6]) == "--first-frame" && std::string_view(argv[8]) == "--end-frame" && std::string_view(argv[10]) == "--journal") {
    const auto source = smartcut::core::SourceIdentity::from_file(argv[3]); const auto output = smartcut::core::SourceIdentity::from_file(argv[5]); const smartcut::core::ExportEvidence evidence{source.source_uuid, output.source_uuid, static_cast<std::uint64_t>(checked_stoull(argv[7])), static_cast<std::uint64_t>(checked_stoull(argv[9])), "PASSED"}; const bool recorded = smartcut::core::ProjectJournal::append_export_evidence(argv[11], evidence); std::cout << "{\"schema\":\"worker-export-evidence-v1\",\"status\":\"" << (recorded ? "PASSED" : "FAILED") << "\",\"source_uuid\":\"" << evidence.source_uuid << "\",\"output_uuid\":\"" << evidence.output_uuid << "\"}\n"; return recorded ? 0 : 5;
  }
  if (argc == 10 && std::string_view(argv[1]) == "--export-range" && std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--output" && std::string_view(argv[6]) == "--first-frame" && std::string_view(argv[8]) == "--end-frame") {
    if (evaluation_video_delivery()) return reject_evaluation_clean_delivery("export-range");
    const auto report = smartcut::media::export_mkv_range(argv[3], argv[5], static_cast<std::size_t>(checked_stoull(argv[7])), static_cast<std::size_t>(checked_stoull(argv[9]))); const bool passed = report.find("\"status\":\"PASSED\"") != std::string::npos; std::cout << "{\"schema\":\"worker-export-range-v1\",\"event\":\"completed\",\"report\":" << report << export_completion_fields(passed, argv[5]) << "}\n"; return passed ? 0 : 5;
  }
  if (argc == 12 && std::string_view(argv[1]) == "--transport-step") {
    std::size_t frame = 0, frame_count = 0, in_frame = 0, out_frame = 0; bool hold = false;
    for (int i = 2; i + 1 < argc; i += 2) { const auto option = std::string_view(argv[i]); const auto value = checked_stoull(argv[i + 1]); if (option == "--frame") frame = value; else if (option == "--frame-count") frame_count = value; else if (option == "--in") in_frame = value; else if (option == "--out") out_frame = value; else if (option == "--hold") hold = value != 0; else return 2; }
    const bool range_valid = out_frame >= in_frame && out_frame < frame_count && frame < frame_count; const auto next_frame = !range_valid || hold ? frame : std::min(frame + 1, frame_count == 0 ? 0ULL : frame_count - 1); const bool completed = !range_valid || next_frame >= out_frame || (frame_count > 0 && next_frame + 1 >= frame_count); std::cout << "{\"schema\":\"worker-transport-step-v1\",\"frame\":" << frame << ",\"next_frame\":" << next_frame << ",\"range_valid\":" << (range_valid ? "true" : "false") << ",\"hold\":" << (hold ? "true" : "false") << ",\"completed\":" << (completed ? "true" : "false") << "}\n"; return range_valid ? 0 : 5;
  }
  if ((argc == 6 || argc == 8) && std::string_view(argv[1]) == "--preview-sync" && std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--frame" && (argc == 6 || std::string_view(argv[6]) == "--pts")) {
    const auto input = std::string(argv[3]); const auto frame = static_cast<std::size_t>(checked_stoull(argv[5])); const auto audio = smartcut::media::probe_audio_timing(input, 1); const auto video = argc == 8 ? std::string{} : smartcut::media::decode_frame(input, frame); const auto probe = smartcut::media::probe_container(input); const auto audio_pts = json_int(audio, "pts", 0); const auto video_pts = argc == 8 ? checked_stoll(argv[7]) : json_int(video, "pts", 0); const auto audio_num = json_int(audio, "time_base_num", 1); const auto audio_den = json_int(audio, "time_base_den", 1); const auto video_num = json_int(probe, "time_base_num", 1); const auto video_den = json_int(probe, "time_base_den", 1000); smartcut::worker::PlaybackSession session({audio_num, audio_den}, {video_num, video_den}, 1); const auto action = session.sync_step(audio_pts, video_pts); const char* name = action == smartcut::core::SyncAction::present ? "present" : action == smartcut::core::SyncAction::hold_video ? "hold_video" : "advance_video"; std::cout << "{\"schema\":\"worker-preview-sync-v1\",\"frame_index\":" << frame << ",\"audio_pts\":" << audio_pts << ",\"video_pts\":" << video_pts << ",\"drift_ticks\":" << session.drift_ticks() << ",\"action\":\"" << name << "\"}\n"; return 0;
  }
  if (argc == 8 && std::string_view(argv[1]) == "--preview-image" && std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--frame" && std::string_view(argv[6]) == "--output") {
    const auto frame = smartcut::media::convert_preview_to_bgra(smartcut::media::decode_preview_frame(argv[3], static_cast<std::size_t>(checked_stoull(argv[5]))));
    if (!frame) { std::cout << "{\"schema\":\"worker-preview-image-v1\",\"status\":\"FAILED\"}\n"; return 5; }
    const bool watermarked = evaluation_video_delivery();
    if (watermarked && !smartcut::media::apply_trial_watermark(frame.get())) { std::cout << "{\"schema\":\"worker-preview-image-v1\",\"status\":\"FAILED\",\"reason\":\"evaluation watermark failed\"}\n"; return 5; }
    std::ofstream output(argv[7], std::ios::binary); if (!output) return 2;
    output << "P6\n" << frame->width << ' ' << frame->height << "\n255\n";
    for (int y = 0; y < frame->height; ++y) for (int x = 0; x < frame->width; ++x) { const auto offset = static_cast<std::size_t>(y * frame->stride + x * 4); output.put(static_cast<char>(frame->pixels[offset + 2])).put(static_cast<char>(frame->pixels[offset + 1])).put(static_cast<char>(frame->pixels[offset])); }
    output.close(); std::cout << "{\"schema\":\"worker-preview-image-v1\",\"status\":\"PASSED\",\"frame_index\":" << frame->frame_index << ",\"width\":" << frame->width << ",\"height\":" << frame->height << ",\"decode_backend\":\"" << frame->decode_backend << "\",\"trial_watermark\":" << (watermarked ? "true" : "false") << "}\n"; return 0;
  }
  if (argc == 10 && std::string_view(argv[1]) == "--preview-image-pts" && std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--frame" && std::string_view(argv[6]) == "--pts" && std::string_view(argv[8]) == "--output") {
    const auto frame_index = static_cast<std::size_t>(checked_stoull(argv[5])); const auto pts = checked_stoll(argv[7]);
    const auto frame = smartcut::media::convert_preview_to_bgra(smartcut::media::decode_preview_frame(argv[3], frame_index, pts));
    if (!frame) { std::cout << "{\"schema\":\"worker-preview-image-v1\",\"status\":\"FAILED\"}\n"; return 5; }
    const bool watermarked = evaluation_video_delivery();
    if (watermarked && !smartcut::media::apply_trial_watermark(frame.get())) { std::cout << "{\"schema\":\"worker-preview-image-v1\",\"status\":\"FAILED\",\"reason\":\"evaluation watermark failed\"}\n"; return 5; }
    std::ofstream output(argv[9], std::ios::binary); if (!output) return 2; output << "P6\n" << frame->width << ' ' << frame->height << "\n255\n";
    for (int y = 0; y < frame->height; ++y) for (int x = 0; x < frame->width; ++x) { const auto offset = static_cast<std::size_t>(y * frame->stride + x * 4); output.put(static_cast<char>(frame->pixels[offset + 2])).put(static_cast<char>(frame->pixels[offset + 1])).put(static_cast<char>(frame->pixels[offset])); }
    output.close(); std::cout << "{\"schema\":\"worker-preview-image-v1\",\"status\":\"PASSED\",\"frame_index\":" << frame->frame_index << ",\"width\":" << frame->width << ",\"height\":" << frame->height << ",\"decode_backend\":\"" << frame->decode_backend << "\",\"trial_watermark\":" << (watermarked ? "true" : "false") << "}\n"; return 0;
  }
  if (argc == 8 && std::string_view(argv[1]) == "--thumbnail-strip-pts" && std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--frames" && std::string_view(argv[6]) == "--output-dir") {
    const std::filesystem::path output_dir = argv[7]; std::error_code directory_error; std::filesystem::create_directories(output_dir, directory_error); if (directory_error) return 2;
    const std::string specification = argv[5]; const auto requested = specification.empty() ? std::size_t{0} : static_cast<std::size_t>(std::count(specification.begin(), specification.end(), ',')) + 1; if (requested == 0 || requested > 64) return 2; std::size_t cursor = 0; std::vector<std::pair<std::size_t, std::int64_t>> frame_requests; frame_requests.reserve(requested);
    while (cursor <= specification.size()) {
      const auto separator = specification.find(',', cursor); const auto token = specification.substr(cursor, separator == std::string::npos ? std::string::npos : separator - cursor); const auto colon = token.find(':'); if (colon == std::string::npos || frame_requests.size() >= requested) return 2;
      frame_requests.emplace_back(static_cast<std::size_t>(checked_stoull(token.substr(0, colon))), checked_stoll(token.substr(colon + 1))); if (separator == std::string::npos) break; cursor = separator + 1;
    }
    constexpr int thumbnail_width = 320;
    const auto decoded = smartcut::media::decode_preview_frames(argv[3], frame_requests, thumbnail_width); if (decoded.size() != requested) return 5; std::size_t slot = 0;
    for (const auto& source_frame : decoded) { if (!source_frame || source_frame->width <= 0 || source_frame->height <= 0) return 5; const auto thumbnail_height = std::max(1, static_cast<int>(static_cast<std::int64_t>(source_frame->height) * thumbnail_width / source_frame->width)); const auto frame = smartcut::media::convert_preview_to_bgra(source_frame, thumbnail_width, thumbnail_height); if (!frame) return 5; std::ofstream output(output_dir / (std::to_string(slot) + ".ppm"), std::ios::binary); if (!output) return 2; output << "P6\n" << frame->width << ' ' << frame->height << "\n255\n"; for (int y = 0; y < frame->height; ++y) for (int x = 0; x < frame->width; ++x) { const auto offset = static_cast<std::size_t>(y * frame->stride + x * 4); output.put(static_cast<char>(frame->pixels[offset + 2])).put(static_cast<char>(frame->pixels[offset + 1])).put(static_cast<char>(frame->pixels[offset])); } output.close(); ++slot; }
    const auto backend = !decoded.empty() && decoded.front() ? decoded.front()->decode_backend : "unavailable";
    std::cout << "{\"schema\":\"worker-thumbnail-strip-v1\",\"status\":\"" << (slot == requested ? "PASSED" : "FAILED") << "\",\"count\":" << slot << ",\"requested\":" << requested << ",\"decode_backend\":\"" << backend << "\"}\n"; return slot == requested ? 0 : 5;
  }
  if (argc == 6 && std::string_view(argv[1]) == "--preview" && std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--frame") {
    std::cout << smartcut::media::decode_frame(argv[3], static_cast<std::size_t>(checked_stoull(argv[5]))) << '\n'; return 0;
  }
  if (argc == 4 && std::string_view(argv[1]) == "--source-info" && std::string_view(argv[2]) == "--input") {
    const auto report = smartcut::media::load_or_build_video_frame_index(argv[3]);
    std::cout << report << '\n'; return report.find("\"error\"") == std::string::npos ? 0 : 5;
  }
  if (argc == 4 && std::string_view(argv[1]) == "--navigation-info" && std::string_view(argv[2]) == "--input") {
    auto report = smartcut::media::build_fast_video_navigation(argv[3]);
    if (report.find("\"error\"") != std::string::npos) report = navigation_report(smartcut::media::load_or_build_video_frame_index(argv[3]));
    std::cout << report << '\n'; return report.find("\"error\"") == std::string::npos ? 0 : 5;
  }
  if (argc == 4 && std::string_view(argv[1]) == "--source-identity" && std::string_view(argv[2]) == "--input") {
    const auto identity = smartcut::core::SourceIdentity::from_file(argv[3]); std::cout << "{\"schema\":\"worker-source-identity-v1\",\"status\":\"PASSED\",\"source_uuid\":\"" << identity.source_uuid << "\",\"canonical_path\":\"" << identity.canonical_path << "\"}\n"; return 0;
  }
  if (argc == 10 && std::string_view(argv[1]) == "--trimmed-file-copy" &&
      std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--output" &&
      std::string_view(argv[6]) == "--start-byte" && std::string_view(argv[8]) == "--byte-count") {
    if (evaluation_video_delivery()) return reject_evaluation_clean_delivery("trimmed-file-copy");
    try {
      const auto start = checked_stoull(argv[7]); const auto count = checked_stoull(argv[9]);
      const auto result = copy_file_range(argv[3], argv[5], start, count);
      std::cout << "{\"schema\":\"worker-trimmed-file-copy-v1\",\"status\":\"" << (result.passed ? "PASSED" : "FAILED")
                << "\",\"start_byte\":" << start << ",\"requested_bytes\":" << count << ",\"copied_bytes\":" << result.copied;
      if (result.passed) std::cout << output_hash_field(true, argv[5]);
      else std::cout << ",\"error\":\"" << result.error << "\"";
      std::cout << "}\n"; return result.passed ? 0 : 5;
    } catch (...) { std::cout << "{\"schema\":\"worker-trimmed-file-copy-v1\",\"status\":\"FAILED\",\"error\":\"invalid byte range\"}\n"; return 2; }
  }
  if (argc == 6 && std::string_view(argv[1]) == "--multiplex" &&
      std::string_view(argv[2]) == "--inputs" && std::string_view(argv[4]) == "--output") {
    if (evaluation_video_delivery()) return reject_evaluation_clean_delivery("multiplex");
    std::vector<std::string> inputs;
    std::stringstream values(argv[3]);
    std::string value;
    while (std::getline(values, value, '|')) if (!value.empty()) inputs.push_back(value);
    if (inputs.size() < 2) return 2;
    std::cout << "{\"schema\":\"worker-elementary-multiplex-v1\",\"event\":\"started\"}\n" << std::flush;
    const auto report = smartcut::media::multiplex_elementary_streams(inputs, argv[5]);
    const bool passed = report_status_is(report, "PASSED");
    std::cout << "{\"schema\":\"worker-elementary-multiplex-v1\",\"event\":\"completed\",\"status\":\""
              << (passed ? "PASSED" : "FAILED VALIDATION") << "\",\"report\":" << report
              << export_completion_fields(passed, argv[5]) << "}\n";
    return passed ? 0 : 5;
  }
  if (argc == 6 && std::string_view(argv[1]) == "--demultiplex" &&
      std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--output") {
    if (evaluation_video_delivery()) return reject_evaluation_clean_delivery("demultiplex");
    std::cout << "{\"schema\":\"worker-elementary-demultiplex-v1\",\"event\":\"started\"}\n" << std::flush;
    const auto report = smartcut::media::demultiplex_elementary_streams(argv[3], argv[5]);
    const bool passed = report_status_is(report, "PASSED");
    std::cout << "{\"schema\":\"worker-elementary-demultiplex-v1\",\"event\":\"completed\",\"status\":\""
              << (passed ? "PASSED" : "FAILED VALIDATION") << "\",\"report\":" << report
              << export_completion_fields(passed, argv[5]) << "}\n";
    return passed ? 0 : 5;
  }
  if (argc >= 9 && (argc - 6) % 3 == 0 &&
      std::string_view(argv[1]) == "--edit-metadata" &&
      std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--output") {
    if (evaluation_video_delivery()) return reject_evaluation_clean_delivery("edit-metadata");
    smartcut::media::ContainerMetadata metadata;
    for (int option = 6; option + 2 < argc; option += 3) {
      if (std::string_view(argv[option]) != "--metadata" || std::string_view(argv[option + 1]).empty())
        return 2;
      metadata.emplace_back(argv[option + 1], argv[option + 2]);
    }
    if (metadata.empty()) return 2;
    std::cout << "{\"schema\":\"worker-metadata-edit-v1\",\"event\":\"started\"}\n" << std::flush;
    const auto report = smartcut::media::remux_media_container(argv[3], argv[5], {}, metadata);
    const bool passed = report_status_is(report, "PASSED");
    std::cout << "{\"schema\":\"worker-metadata-edit-v1\",\"event\":\"completed\",\"status\":\""
              << (passed ? "PASSED" : "FAILED VALIDATION") << "\",\"report\":" << report
              << export_completion_fields(passed, argv[5]) << "}\n";
    return passed ? 0 : 5;
  }
  if (argc == 6 && std::string_view(argv[1]) == "--export" && std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--output") {
    if (evaluation_video_delivery()) return reject_evaluation_clean_delivery("export");
    const std::string input = argv[3]; const std::string output = argv[5];
    std::cout << "{\"schema\":\"worker-export-v1\",\"event\":\"started\",\"phase\":\"prepare\"}\n" << std::flush;
    const auto report = smartcut::media::export_media(input, output);
    const bool passed = report_status_is(report, "PASSED");
    std::cout << "{\"schema\":\"worker-export-v1\",\"event\":\"completed\",\"phase\":\"validated\",\"status\":\"" << (passed ? "PASSED" : "FAILED VALIDATION") << "\",\"report\":" << report << export_completion_fields(passed, output) << "}\n" << std::flush;
    return passed ? 0 : 5;
  }
  if (argc == 8 && std::string_view(argv[1]) == "--export-selected" && std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--output" && std::string_view(argv[6]) == "--streams") {
    std::vector<std::size_t> streams; std::stringstream values(argv[7]); std::string value; try { while (std::getline(values, value, ',')) if (!value.empty()) streams.push_back(static_cast<std::size_t>(checked_stoull(value))); } catch (...) { return 2; }
    if (evaluation_video_delivery() && selected_delivery_contains_video(argv[3], streams))
      return reject_evaluation_clean_delivery("export-selected");
    std::cout << "{\"schema\":\"worker-selected-stream-export-v1\",\"event\":\"started\"}\n" << std::flush;
    const auto report = smartcut::media::export_media_selected_streams(argv[3], argv[5], streams); const bool passed = report_status_is(report, "PASSED");
    std::cout << "{\"schema\":\"worker-selected-stream-export-v1\",\"event\":\"completed\",\"status\":\"" << (passed ? "PASSED" : "FAILED VALIDATION") << "\",\"report\":" << report << export_completion_fields(passed, argv[5]) << "}\n"; return passed ? 0 : 5;
  }
  if (argc == 12 && std::string_view(argv[1]) == "--export-range-selected" && std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--output" && std::string_view(argv[6]) == "--first-frame" && std::string_view(argv[8]) == "--end-frame" && std::string_view(argv[10]) == "--streams") {
    std::vector<std::size_t> streams; std::stringstream values(argv[11]); std::string value; try { while (std::getline(values, value, ',')) if (!value.empty()) streams.push_back(static_cast<std::size_t>(checked_stoull(value))); } catch (...) { return 2; }
    if (evaluation_video_delivery() && source_contains_video(argv[3]))
      return reject_evaluation_clean_delivery("export-range-selected");
    auto intermediate = std::filesystem::path(argv[5]); intermediate += ".smartcut-selected-stage.mkv"; std::error_code ignored; std::filesystem::remove(intermediate, ignored);
    const auto range = smartcut::media::export_mkv_range(argv[3], intermediate.string(), static_cast<std::size_t>(checked_stoull(argv[7])), static_cast<std::size_t>(checked_stoull(argv[9])));
    const auto selected = report_status_is(range, "PASSED") ? smartcut::media::export_media_selected_streams(intermediate.string(), argv[5], streams) : std::string{"{\"schema\":\"selected-stream-export-v1\",\"status\":\"FAILED\",\"reason\":\"range stage failed\"}"}; std::filesystem::remove(intermediate, ignored);
    const bool passed = report_status_is(selected, "PASSED"); if (!passed) std::filesystem::remove(argv[5], ignored);
    std::cout << "{\"schema\":\"worker-range-selected-export-v1\",\"event\":\"completed\",\"status\":\"" << (passed ? "PASSED" : "FAILED VALIDATION") << "\",\"range_report\":" << range << ",\"selection_report\":" << selected << export_completion_fields(passed, argv[5]) << "}\n"; return passed ? 0 : 5;
  }
  if (argc >= 10 && argc % 2 == 0 && std::string_view(argv[1]) == "--export-edits" &&
      std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--output" &&
      std::string_view(argv[6]) == "--frame-count" && std::string_view(argv[8]) == "--cuts") {
    std::vector<smartcut::media::EditRange> cuts;
    std::vector<std::size_t> streams;
    auto mode = smartcut::media::EditExportMode::smart_render;
    std::int64_t audio_offset_ms = 0;
    smartcut::media::AudioTransformOptions audio;
    smartcut::media::VideoTransformOptions video;
    smartcut::media::MpegTsMuxOptions transport_stream;
    try {
      std::stringstream ranges(argv[9]); std::string token;
      while (std::getline(ranges, token, ',')) {
        if (token.empty()) continue;
        const auto separator = token.find(':'); if (separator == std::string::npos) return 2;
        cuts.emplace_back(static_cast<std::size_t>(checked_stoull(token.substr(0, separator))),
                          static_cast<std::size_t>(checked_stoull(token.substr(separator + 1))));
      }
      for (int option = 10; option + 1 < argc; option += 2) {
        if (std::string_view(argv[option]) == "--streams") { std::stringstream values(argv[option + 1]); while (std::getline(values, token, ',')) if (!token.empty()) streams.push_back(static_cast<std::size_t>(checked_stoull(token))); }
        else if (std::string_view(argv[option]) == "--mode") { const std::string_view value(argv[option + 1]); if (value == "keyframe") mode = smartcut::media::EditExportMode::keyframe_copy; else if (value == "full") mode = smartcut::media::EditExportMode::full_transcode; else if (value != "smart") return 2; }
        else if (std::string_view(argv[option]) == "--audio-offset-ms") audio_offset_ms = checked_stoll(argv[option + 1]);
        else if (std::string_view(argv[option]) == "--audio-codec") { const std::string value(argv[option + 1]); if (value != "copy" && value != "source" && value != "aac" && value != "ac3" && value != "mp2" && value != "opus" && value != "pcm" && value != "pcm_s16le") return 2; audio.codec = smartcut::media::audio_output_codec_from_name(value); }
        else if (std::string_view(argv[option]) == "--audio-gain-db") audio.gain_db = checked_double(argv[option + 1]);
        else if (std::string_view(argv[option]) == "--audio-bitrate") audio.bitrate = checked_int(argv[option + 1]);
        else if (std::string_view(argv[option]) == "--audio-sample-rate") audio.sample_rate = checked_int(argv[option + 1]);
        else if (std::string_view(argv[option]) == "--audio-channels") audio.channels = checked_int(argv[option + 1]);
        else if (std::string_view(argv[option]) == "--video-codec") { const std::string value(argv[option + 1]); if (value != "source" && value != "mpeg2" && value != "h264" && value != "hevc" && value != "av1" && value != "vp9" && value != "ffv1" && value != "prores") return 2; video.codec = smartcut::media::video_output_codec_from_name(value); }
        else if (std::string_view(argv[option]) == "--video-hardware") { const std::string value(argv[option + 1]); if (value != "auto" && value != "software" && value != "qsv" && value != "nvenc" && value != "amf" && value != "vulkan") return 2; video.hardware = smartcut::media::video_hardware_encoder_from_name(value); }
        else if (std::string_view(argv[option]) == "--video-width") video.width = checked_int(argv[option + 1]);
        else if (std::string_view(argv[option]) == "--video-height") video.height = checked_int(argv[option + 1]);
        else if (std::string_view(argv[option]) == "--video-bit-depth") video.bit_depth = checked_int(argv[option + 1]);
        else if (std::string_view(argv[option]) == "--video-bitrate-kbps") video.bitrate_kbps = checked_int(argv[option + 1]);
        else if (std::string_view(argv[option]) == "--video-max-bitrate-kbps") video.max_bitrate_kbps = checked_int(argv[option + 1]);
        else if (std::string_view(argv[option]) == "--trial-watermark") { const std::string_view value(argv[option + 1]); if (value != "true" && value != "false") return 2; video.trial_watermark = value == "true"; }
        else if (std::string_view(argv[option]) == "--video-aspect") video.aspect_ratio = argv[option + 1];
        else if (std::string_view(argv[option]) == "--video-deinterlace") video.deinterlace = argv[option + 1];
        else if (std::string_view(argv[option]) == "--video-frame-rate") video.frame_rate = argv[option + 1];
        else if (parse_transport_stream_option(argv[option], argv[option + 1], transport_stream)) {}
        else return 2;
      }
    } catch (...) { return 2; }
    if (evaluation_video_delivery() && source_contains_video(argv[3]))
      video.trial_watermark = true;
    if (video.width < 0 || video.height < 0 || (video.bit_depth != 0 && video.bit_depth != 8 && video.bit_depth != 10) || video.bitrate_kbps < 0 || video.max_bitrate_kbps < 0 || transport_stream.pmt_start_pid < 0x20 || transport_stream.pmt_start_pid > 0x1ffe || transport_stream.elementary_start_pid < 0x20 || transport_stream.elementary_start_pid > 0x1ffe || transport_stream.mux_rate < 0) return 2;
    std::size_t frame_count = 0;
    try { frame_count = static_cast<std::size_t>(checked_stoull(argv[7])); } catch (...) { return 2; }
    if (frame_count == 0) {
      const auto index = smartcut::media::load_or_build_video_frame_index(argv[3]);
      const auto indexed_frames = json_int(index, "frame_count");
      if (indexed_frames <= 0) return 5;
      frame_count = static_cast<std::size_t>(indexed_frames);
    }
    std::cout << "{\"schema\":\"worker-edit-export-v1\",\"event\":\"started\"}\n" << std::flush;
    const auto report = smartcut::media::export_mkv_edits(argv[3], argv[5], frame_count, cuts, streams, mode, audio_offset_ms, audio, video, transport_stream);
    const bool passed = report_status_is(report, "PASSED");
    std::cout << "{\"schema\":\"worker-edit-export-v1\",\"event\":\"completed\",\"status\":\"" << (passed ? "PASSED" : "FAILED VALIDATION") << "\",\"report\":" << report << export_completion_fields(passed, argv[5]) << "}\n";
    return passed ? 0 : 5;
  }
  if (argc >= 8 && argc % 2 == 0 && std::string_view(argv[1]) == "--audio-transform" &&
      std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--output") {
    if (evaluation_video_delivery()) return reject_evaluation_clean_delivery("audio-transform-container");
    smartcut::media::AudioTransformOptions audio;
    try {
      for (int option = 6; option + 1 < argc; option += 2) {
        const std::string_view key(argv[option]);
        if (key == "--codec") { const std::string value(argv[option + 1]); if (value != "source" && value != "aac" && value != "ac3" && value != "mp2" && value != "opus" && value != "pcm" && value != "pcm_s16le") return 2; audio.codec = smartcut::media::audio_output_codec_from_name(value); }
        else if (key == "--gain-db") audio.gain_db = checked_double(argv[option + 1]);
        else if (key == "--bitrate") audio.bitrate = checked_int(argv[option + 1]);
        else if (key == "--sample-rate") audio.sample_rate = checked_int(argv[option + 1]);
        else if (key == "--channels") audio.channels = checked_int(argv[option + 1]);
        else return 2;
      }
    } catch (...) { return 2; }
    const auto report = smartcut::media::transform_primary_audio_mkv(argv[3], argv[5], audio);
    std::cout << report << '\n'; return report_status_is(report, "PASSED") ? 0 : 5;
  }
  if (argc == 6 && std::string_view(argv[1]) == "--sync-input" && std::string_view(argv[2]) == "--input" && std::string_view(argv[4]) == "--frame") {
    const auto input = std::string(argv[3]); const auto frame_index = static_cast<std::size_t>(checked_stoull(argv[5]));
    const auto audio = smartcut::media::probe_audio_timing(input, 1);
    if (audio.find("\"packets\":[{") == std::string::npos) { std::cerr << "sync input requires an audio packet\n"; return 4; }
    const auto video = smartcut::media::decode_frame(input, frame_index);
    const auto probe = smartcut::media::probe_container(input);
    const auto video_pts = json_int(video, "pts", -1); const auto audio_pts = json_int(audio, "pts", 0);
    const auto audio_num = json_int(audio, "time_base_num", 1); const auto audio_den = json_int(audio, "time_base_den", 1);
    const auto video_num = json_int(probe, "time_base_num", 1); const auto video_den = json_int(probe, "time_base_den", 1000);
    smartcut::worker::PlaybackSession session({audio_num, audio_den}, {video_num, video_den}, 1);
    const auto action = session.sync_step(audio_pts, video_pts);
    const char* name = action == smartcut::core::SyncAction::present ? "present" : action == smartcut::core::SyncAction::hold_video ? "hold_video" : "advance_video";
    std::cout << "{\"schema\":\"worker-media-sync-v1\",\"frame_index\":" << frame_index << ",\"audio_pts\":" << audio_pts << ",\"video_pts\":" << video_pts << ",\"video_time_base_num\":" << video_num << ",\"video_time_base_den\":" << video_den << ",\"drift_ticks\":" << session.drift_ticks() << ",\"action\":\"" << name << "\"}\n";
    return 0;
  }
  if (argc == 16 && std::string_view(argv[1]) == "--sync-step") {
    std::int64_t audio_pts = 0, video_pts = 0, tolerance = 0, audio_num = 1, audio_den = 1, video_num = 1, video_den = 1;
    for (int i = 2; i + 1 < argc; i += 2) {
      const std::string_view option = argv[i]; const auto value = checked_stoll(argv[i + 1]);
      if (option == "--audio-pts") audio_pts = value; else if (option == "--video-pts") video_pts = value; else if (option == "--tolerance") tolerance = value;
      else if (option == "--audio-num") audio_num = value; else if (option == "--audio-den") audio_den = value; else if (option == "--video-num") video_num = value; else if (option == "--video-den") video_den = value;
      else { std::cerr << "unknown sync option\n"; return 2; }
    }
    smartcut::worker::PlaybackSession session({audio_num, audio_den}, {video_num, video_den}, tolerance);
    const auto action = session.sync_step(audio_pts, video_pts);
    const char* name = action == smartcut::core::SyncAction::present ? "present" : action == smartcut::core::SyncAction::hold_video ? "hold_video" : "advance_video";
    std::cout << "{\"schema\":\"worker-playback-sync-v1\",\"drift_ticks\":" << session.drift_ticks() << ",\"action\":\"" << name << "\"}\n";
    return 0;
  }
  std::cout << "SmartCut64 worker bootstrap (M4)\n";
  return 0;
  } catch (const std::exception& error) {
    std::cerr << "smartcut-worker: invalid request: " << error.what() << '\n';
    return 2;
  } catch (...) {
    std::cerr << "smartcut-worker: invalid request\n";
    return 2;
  }
}
#include <clocale>
