#include <cassert>
#include <chrono>
#include <cstdint>
#include <cstring>
#include <string_view>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <limits>
#include <thread>
#include <vector>

#ifdef _WIN32
#include <process.h>
#endif

#include "core/entitlement.hpp"
#include "core/source_identity.hpp"
#include "core/control_ipc.hpp"
#include "core/bounded_queue.hpp"
#include "core/preview_frame.hpp"
#include "core/preview_shared_memory.hpp"
#include "core/thumbnail_cache.hpp"
#include "core/frame_navigation.hpp"
#include "core/preview_clock.hpp"
#include "core/project_model.hpp"
#include "core/project_editor.hpp"
#include "core/project_journal.hpp"
#include "core/json.hpp"
#include "core/videoredo_project.hpp"
#include "core/videoredo_batch.hpp"
#include "core/videoredo_joiner.hpp"
#include "core/render_plan.hpp"
#include "core/gop_planner.hpp"
#include "core/repair_windows.hpp"
#include "core/render_report.hpp"
#include "core/preview_sync.hpp"
#include "media/preview_conversion.hpp"
#include "media/access_unit_index.hpp"
#include "media/audio_playback.hpp"
#include "media/index_cache.hpp"
#include "media/nal_inventory.hpp"
#include "media/rpu_injector.hpp"
#include "media/sei_injector.hpp"
#include "media/stream_probe.hpp"
#include "media/edit_export.hpp"
#include "media/pcm_normalize.hpp"
#include "media/trial_watermark.hpp"
#include "media/video_transform.hpp"
#include "media/video_stream_selection.hpp"

#ifdef SMARTCUT_HAS_FFMPEG
extern "C" {
#include <libavutil/frame.h>
#include <libavutil/pixfmt.h>
}
#endif

#ifdef SMARTCUT_USE_CATCH2
#include <catch2/catch_test_macros.hpp>
#undef assert
#define assert(expression) REQUIRE((expression))
TEST_CASE("SmartCut64 core and media smoke coverage") {
#else
int main() {
#endif
  using smartcut::media::VideoHardwareEncoder;
  using smartcut::media::VideoOutputCodec;
  using smartcut::media::VideoStreamRole;
  using smartcut::media::AudioDevicePositionUnit;
  assert(smartcut::media::audio_device_position_us(48000, AudioDevicePositionUnit::samples, 48000, 4) == 1000000);
  assert(smartcut::media::audio_device_position_us(192000, AudioDevicePositionUnit::bytes, 48000, 4) == 1000000);
  assert(smartcut::media::audio_device_position_us(1000, AudioDevicePositionUnit::milliseconds, 48000, 4) == 1000000);
  assert(!smartcut::media::audio_device_position_us(1, AudioDevicePositionUnit::samples, 0, 4));
  assert(!smartcut::media::audio_device_position_us(1, AudioDevicePositionUnit::bytes, 48000, 0));
  assert(!smartcut::media::audio_device_position_us(std::numeric_limits<std::uint64_t>::max(), AudioDevicePositionUnit::milliseconds, 48000, 4));
  assert(smartcut::media::video_output_codec_from_name("ffv1") == VideoOutputCodec::ffv1);
  assert(smartcut::media::video_output_codec_from_name("prores") == VideoOutputCodec::prores);
  assert(smartcut::media::video_output_codec_from_name("prores_ks") == VideoOutputCodec::prores);
  assert(smartcut::media::video_hardware_encoder_from_name("vulkan") ==
         VideoHardwareEncoder::vulkan);
  const std::vector<VideoStreamRole> cover_before_program{
      VideoStreamRole::attached_picture, VideoStreamRole::program_video};
  const auto selected_program =
      smartcut::media::first_program_video_stream(cover_before_program);
  assert(selected_program && *selected_program == 1);
  const std::vector<VideoStreamRole> cover_only{VideoStreamRole::attached_picture};
  assert(!smartcut::media::first_program_video_stream(cover_only));
  using smartcut::core::EntitlementPublicKey;
  using smartcut::core::EntitlementState;
  using smartcut::core::verify_entitlement;
  assert(verify_entitlement("", EntitlementPublicKey{}, 1500,
                            "00000000000000000000000000000000").state == EntitlementState::missing);
  assert(verify_entitlement("not-a-licence", EntitlementPublicKey{}, 1500,
                            "00000000000000000000000000000000").state == EntitlementState::malformed);
  assert(verify_entitlement(std::string(16 * 1024 + 1, 'x'), EntitlementPublicKey{}, 1500,
                            "00000000000000000000000000000000").state == EntitlementState::malformed);
  assert(verify_entitlement("SC64-1.ZXh0cmE9MQ.AA", EntitlementPublicKey{}, 1500,
                            "00000000000000000000000000000000").state == EntitlementState::malformed);
  const std::string entitlement_token =
      "SC64-1.cHJvZHVjdD1TbWFydEN1dDY0CmVkaXRpb249cGFpZApsaWNlbnNlX2lkPXRlc3QtbGljZW5zZS0wMDEKY3VzdG9tZ"
      "XI9U21hcnRDdXQ2NCBUZXN0Cmluc3RhbGxhdGlvbl9pZD0wMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAppc3N1Z"
      "WRfdW5peD0xMDAwCm5vdF9iZWZvcmVfdW5peD0xMDAwCmV4cGlyZXNfdW5peD0yMDAwCmNsZWFuX2V4cG9ydD0x.U1UfYCcS"
      "Kk1Lay0E8q4Xjh6TIVzNoSGUaw38r6fJHlof-kt2Ttsa84RyeCZoTLeEo6aZWTE_rCkxsY-AcIpNN0IGC7UPF_DFRd9WITgM"
      "7Y5xWucCVxQMEejHW8yOgjvEvHErfPuFASDV9eVvgflf74oeGbuSBTgX5f2oNtJ23qti9JcbYz8u15ptB-sIeBm2CYrtVwmt"
      "n2u8I9fyWbBvoqx-itWXOYBGBy9_633-uNJdCsjWjj0_-bkqNe5Q0rxs8lTLHLeLUj_IN6efzDFfcHKl2aFfzOTWFempz8Uq"
      "8jUM7luiq6Jm3kab29XxJ1Sh375d_Xmc6Zd1Nl2t0bItCQ";
  assert(verify_entitlement(entitlement_token, EntitlementPublicKey{}, 1500,
                            "00000000000000000000000000000000").state ==
         EntitlementState::no_verification_key);
#ifdef _WIN32
  const auto decode_hex = [](std::string_view text) {
    const auto nibble = [](char value) -> int {
      if (value >= '0' && value <= '9') return value - '0';
      if (value >= 'a' && value <= 'f') return value - 'a' + 10;
      if (value >= 'A' && value <= 'F') return value - 'A' + 10;
      return -1;
    };
    std::vector<std::uint8_t> bytes;
    for (std::size_t index = 0; index + 1 < text.size(); index += 2)
      bytes.push_back(static_cast<std::uint8_t>((nibble(text[index]) << 4) | nibble(text[index + 1])));
    return bytes;
  };
  const EntitlementPublicKey test_key{
      decode_hex("f176b42b21b534b27f64549ba8c173c3535b4ad86bea22b3fd31fc6f98d4a4036399e015db0701454422a9297a8a5db4"
                 "9027c4e221adf2f5195063a5096dd0fce2ee4d3fda96ba887a3811c8185671c2363bd1009ba8789ccf6a3ca5f15c4604"
                 "16163c68857d69081a84cf5434c23675a2c2e45e6e6562c65bb00e8cce256f95e18979f3dfc75655f9b064f365c2a9f0"
                 "622ea4d7d9e000155bb36a71df09d6bbb20de82b2b4a7a405e2846bf9424c5fd6cf6b34ee7c0e2e743ff12f93b7e355a"
                 "00e1e6e47bf1b07c5fb1838c7ed00d605c683f286af382fa699962f717204cb057d7caf2772236b4cee0f319fd2ca1ce"
                 "7d9996e5852a53a3e849c8c621e325ad"),
      decode_hex("010001")};
  const auto paid_entitlement = verify_entitlement(entitlement_token, test_key, 1500,
                                                    "00000000000000000000000000000000");
  assert(paid_entitlement.paid() && paid_entitlement.customer == "SmartCut64 Test" &&
         paid_entitlement.license_id == "test-license-001");
  auto tampered_entitlement = entitlement_token;
  const auto signature_start = tampered_entitlement.rfind('.') + 1;
  tampered_entitlement[signature_start + 8] = tampered_entitlement[signature_start + 8] == 'A' ? 'B' : 'A';
  assert(verify_entitlement(tampered_entitlement, test_key, 1500,
                            "00000000000000000000000000000000").state == EntitlementState::invalid_signature);
  auto short_signature_entitlement = entitlement_token;
  short_signature_entitlement.resize(short_signature_entitlement.size() - 2);
  assert(verify_entitlement(short_signature_entitlement, test_key, 1500,
                            "00000000000000000000000000000000").state == EntitlementState::invalid_signature);
  assert(verify_entitlement(entitlement_token, test_key, 1500,
                            "11111111111111111111111111111111").state == EntitlementState::wrong_installation);
  assert(verify_entitlement(entitlement_token, test_key, 500,
                            "00000000000000000000000000000000").state == EntitlementState::not_yet_valid);
  assert(verify_entitlement(entitlement_token, test_key, 2001,
                            "00000000000000000000000000000000").state == EntitlementState::expired);
#endif
  const std::vector<std::uint8_t> sample{0,0,0,1,0x40,1,2,0,0,1,0x4e,3,4,0,0,1,0x26,5,0,0,1,0x7c,1,9};
  const auto inventory = smartcut::media::inventory_annex_b(smartcut::media::Codec::hevc, sample);
  assert(inventory.units.size() == 4);
  assert(inventory.units[0].parameter_set && inventory.units[0].type == 32);
  assert(inventory.units[1].sei && inventory.units[1].type == 39);
  assert(inventory.units[2].random_access && inventory.units[2].type == 19);
  assert(inventory.units[3].dolby_vision_rpu && inventory.units[3].type == 62);
  const auto sei = smartcut::media::make_hevc_prefix_sei_t35(std::vector<std::uint8_t>{0,0,1});
  assert(sei.size() >= 12 && sei[0] == 0 && sei[4] == (39u << 1u));
  const auto injected = smartcut::media::prepend_hevc_rpu({}, std::vector<std::uint8_t>{0xaa,0x55});
  assert(smartcut::media::inventory_annex_b(smartcut::media::Codec::hevc, injected).units.front().dolby_vision_rpu);
  const std::vector<std::uint8_t> indexed{0,0,0,1,0x26,1,0x80,0,0,0,1,0x02,1,0x80};
  const auto access_units = smartcut::media::index_hevc_annex_b(indexed);
  assert(access_units.access_units.size() == 2);
  assert(access_units.access_units.front().random_access);
  std::vector<std::uint8_t> random_access_fixture;
  for (const unsigned type : {16U, 19U, 20U, 21U, 8U, 9U}) {
    const std::uint8_t unit[] = {0, 0, 0, 1, static_cast<std::uint8_t>(type << 1U), 1, 0x80};
    random_access_fixture.insert(random_access_fixture.end(), std::begin(unit), std::end(unit));
  }
  const auto classified = smartcut::media::index_hevc_annex_b(random_access_fixture);
  assert(classified.access_units.size() == 6);
  assert(classified.access_units[0].random_access_nal_type == 16 && classified.access_units[0].closed_random_access);
  assert(classified.access_units[1].random_access_nal_type == 19 && classified.access_units[1].closed_random_access);
  assert(classified.access_units[2].random_access_nal_type == 20 && classified.access_units[2].closed_random_access);
  assert(classified.access_units[3].random_access_nal_type == 21 && !classified.access_units[3].closed_random_access);
  assert(!classified.access_units[4].random_access && classified.access_units[4].vcl_nal_type == 8);
  assert(!classified.access_units[5].random_access && classified.access_units[5].vcl_nal_type == 9);

  const auto fixture = std::filesystem::temp_directory_path() / "smartcut-source-identity.fixture";
  { std::ofstream output(fixture, std::ios::binary); output << "smartcut-m3-fixture"; }
  const auto identity = smartcut::core::SourceIdentity::from_file(fixture);
  assert(identity.byte_length == 19);
  assert(identity.first_block_hash == identity.last_block_hash);
  assert(identity.source_uuid.rfind("source-", 0) == 0);
  const std::string json_roundtrip_value{"quote=\" slash=\\ newline=\n tab=\t"};
  const auto quoted_json = std::string{"{\"value\":"} + smartcut::core::json_quote(json_roundtrip_value) + "}";
  assert(smartcut::core::json_field(quoted_json, "value") == json_roundtrip_value);
  const std::string embedded_key_json =
      R"({"source_uuid":"text containing \"frame_count\":999","frame_count":4})";
  assert(smartcut::core::json_field(embedded_key_json, "frame_count") == std::optional<std::string>{"4"});
  assert(!smartcut::core::json_field(R"({"value":"first","value":"second"})", "value"));
  assert(!smartcut::core::json_field(R"({"value":"first",})", "value"));
  assert(!smartcut::core::json_field(std::string{"{\"value\":\"bad\nline\"}"}, "value"));
  std::string invalid_utf8_json{"{\"value\":\""};
  invalid_utf8_json.push_back(static_cast<char>(0xC3));
  invalid_utf8_json += "(\"}";
  assert(!smartcut::core::json_field(invalid_utf8_json, "value"));
  assert(!smartcut::core::parse_unsigned<std::uint64_t>("-1"));
  assert(!smartcut::core::parse_unsigned<std::uint8_t>("256"));
  assert(smartcut::core::parse_unsigned<std::uint64_t>("18446744073709551615") == std::numeric_limits<std::uint64_t>::max());
#ifdef _WIN32
  const auto pipe_name = std::string("smartcut-unit-") + std::to_string(_getpid()) + "-" +
                         std::to_string(std::chrono::steady_clock::now().time_since_epoch().count());
  std::jthread pipe_server([&] { assert(smartcut::core::serve_control_pipe(pipe_name, [](std::string_view request) { return request == "{\"schema\":\"control-request-v1\",\"id\":7,\"command\":\"ping\"}" ? "{\"schema\":\"control-response-v1\",\"id\":7,\"ok\":true}" : "{\"schema\":\"control-response-v1\",\"id\":7,\"ok\":false}"; }, 1) == 0); });
  const auto pipe_response = smartcut::core::request_control_pipe(pipe_name, "{\"schema\":\"control-request-v1\",\"id\":7,\"command\":\"ping\"}", 5000); pipe_server.join(); assert(pipe_response && pipe_response->find("\"ok\":true") != std::string::npos);
  const auto idle_pipe_name = pipe_name + "-idle";
  const auto idle_start = std::chrono::steady_clock::now();
  assert(smartcut::core::serve_control_pipe(idle_pipe_name, [](std::string_view) { return std::string{}; }, 1, 75) == 5);
  assert(std::chrono::steady_clock::now() - idle_start < std::chrono::seconds(2));
#endif
  const auto probe = smartcut::media::probe_container(fixture);
  assert(probe.find("source_identity") != std::string::npos || probe.find("error") != std::string::npos);
  const auto index_source = std::filesystem::temp_directory_path() / "smartcut-index-cache.hevc";
  const auto index_cache = std::filesystem::temp_directory_path() / "smartcut-index-cache.json";
  { std::ofstream output(index_source, std::ios::binary | std::ios::trunc); output.write(reinterpret_cast<const char*>(indexed.data()), static_cast<std::streamsize>(indexed.size())); }
  const auto cache_document = smartcut::media::make_hevc_index_cache(index_source);
  assert(cache_document.find("index-cache-v3") != std::string::npos);
  assert(smartcut::media::validate_hevc_index_cache(index_source, cache_document).valid());
  auto corrupt_cache = cache_document; corrupt_cache[corrupt_cache.find("payload_hash") - 2] = 'X';
  assert(smartcut::media::validate_hevc_index_cache(index_source, corrupt_cache).status == smartcut::media::IndexCacheStatus::corrupt);
  assert(smartcut::media::write_hevc_index_cache_atomic(index_source, index_cache));
  { std::ofstream output(index_cache, std::ios::binary | std::ios::trunc); output << "{\"schema\":\"index-cache-v3\""; }
  const auto recovered_cache = smartcut::media::recover_hevc_index_cache(index_source, index_cache);
  assert(recovered_cache.valid() && recovered_cache.detail.find("rebuilt") != std::string::npos);
  { std::ofstream output(index_source, std::ios::binary | std::ios::app); output.put('\0'); }
  assert(smartcut::media::validate_hevc_index_cache(index_source, cache_document).status == smartcut::media::IndexCacheStatus::stale_source);
  std::filesystem::remove(index_cache); std::filesystem::remove(index_source);
  smartcut::core::BoundedQueue<int> preview_queue(2);
  assert(preview_queue.push(1)); assert(preview_queue.push(2)); assert(!preview_queue.push(3));
  assert(preview_queue.pop().value() == 1); assert(preview_queue.pop().value() == 2); assert(!preview_queue.pop().has_value());
  smartcut::core::BoundedQueue<int> cancellable_queue(1);
  const auto cancellation_started = std::chrono::steady_clock::now();
  std::jthread blocked_consumer([&](std::stop_token stop) { assert(!cancellable_queue.wait_pop(stop).has_value()); });
  blocked_consumer.request_stop(); blocked_consumer.join();
  assert(std::chrono::steady_clock::now() - cancellation_started < std::chrono::seconds(2));
  smartcut::core::BoundedQueue<int> closable_queue(1); assert(closable_queue.wait_push(7)); closable_queue.close();
  assert(closable_queue.wait_pop().value() == 7); assert(!closable_queue.wait_pop().has_value()); assert(closable_queue.closed());
  smartcut::core::PreviewFrameTransport transport(1);
  auto preview = std::make_shared<smartcut::core::PreviewFrame>(); preview->sequence = 7; preview->frame_index = 3; preview->width = 64; preview->height = 64; preview->stride = 128; preview->pixel_format = 62; preview->pixels.resize(128);
  assert(transport.publish(preview)); assert(!transport.publish(preview));
  const auto acquired = transport.acquire(); assert(acquired && acquired->sequence == 7 && transport.outstanding() == 1);
  assert(acquired->display_color_mode == "source" && !acquired->tone_mapped);
  assert(transport.acknowledge(7)); assert(!transport.acknowledge(7)); assert(transport.outstanding() == 0);
#ifdef _WIN32
  const auto shared_name = std::string("SmartCutPreview-unit-") + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()); preview->display_color_mode = "tone-mapped-sdr"; preview->tone_mapped = true; const auto shared_publisher = smartcut::core::SharedPreviewPublisher::publish(shared_name, *preview); assert(shared_publisher && shared_publisher->valid() && shared_publisher->sequence() == 7 && !shared_publisher->acknowledged()); const auto shared_frame = smartcut::core::acquire_shared_preview(shared_name); assert(shared_frame && shared_frame->sequence == 7 && shared_frame->frame_index == 3 && shared_frame->width == 64 && shared_frame->height == 64 && shared_frame->stride == 128 && shared_frame->pixel_format == 62 && shared_frame->pixels == preview->pixels && shared_frame->tone_mapped && shared_frame->display_color_mode == "tone-mapped-sdr"); assert(!smartcut::core::acknowledge_shared_preview(shared_name, 8)); assert(smartcut::core::acknowledge_shared_preview(shared_name, 7) && shared_publisher->acknowledged());
#endif
  std::jthread preview_waiter([&](std::stop_token stop) { assert(!transport.wait_acquire(stop)); });
  preview_waiter.request_stop(); preview_waiter.join(); transport.close(); assert(transport.closed());
  smartcut::core::ThumbnailCache thumbnails(1);
  assert(!thumbnails.put("source-a", "", 3, preview));
  assert(thumbnails.put("source-a", "index-v2-a", 3, preview));
  assert(thumbnails.get("source-a", "index-v2-a", 3) == preview);
  assert(!thumbnails.get("source-a", "index-v2-b", 3));
  assert(thumbnails.put("source-a", "index-v2-a", 4, acquired));
  assert(!thumbnails.get("source-a", "index-v2-a", 3));
  auto bgra = std::make_shared<smartcut::core::PreviewFrame>(); bgra->pixel_format = 28; bgra->width = 1; bgra->height = 1; bgra->stride = 4; bgra->pixels = {255, 128, 64, 255};
  const auto sdr = smartcut::media::tone_map_bgra_sdr(bgra); assert(sdr && sdr->tone_mapped && sdr->display_color_mode == "tone-mapped-sdr" && sdr->pixels[0] < bgra->pixels[0]);
  smartcut::core::FrameNavigation navigation(10, {0, 4, 8});
  assert(navigation.current() == 0); assert(navigation.step(2) == 2); assert(navigation.next_keyframe() && navigation.current() == 4);
  assert(navigation.previous_keyframe() && navigation.current() == 0); assert(navigation.set_frame(9)); assert(!navigation.next_keyframe()); assert(navigation.step(2) == 9); assert(navigation.step(-20) == 0);
  smartcut::core::FrameNavigation timed_navigation(5, {0, 3}, {0, 400, 900, 1200, 2200}, 1, 1000);
  assert(timed_navigation.step_seconds(1) && timed_navigation.current() == 3);
  assert(timed_navigation.step_seconds(-1) && timed_navigation.current() == 1);
  assert(timed_navigation.current_time_us() == 400000);
  assert(timed_navigation.set_time_us(1200000) && timed_navigation.current() == 3);
  smartcut::core::PreviewClock clock({1, 1000}, {1, 25}); clock.set_audio_pts(1000); clock.set_video_pts(26);
  assert(clock.audio_master_video_pts() == 25); assert(clock.video_drift_ticks() == 1);
  smartcut::core::PreviewSynchronizer sync({1, 1000}, {1, 25}, 1);
  assert(sync.update(1000, 25) == smartcut::core::SyncAction::present);
  assert(sync.update(1000, 27) == smartcut::core::SyncAction::hold_video);
  assert(sync.update(1000, 23) == smartcut::core::SyncAction::advance_video);
  smartcut::core::Project project; project.add_source({"source-a", "fixture.mkv"}); project.add_segment({"source-a", 0, 10, 20}); project.set_chapter_markers({3, 17});
  assert(project.valid()); assert(project.to_json().find("project-v1") != std::string::npos); assert(project.to_json().find("\"chapter_markers\":[3,17]") != std::string::npos);
  smartcut::core::Project stream_project; stream_project.add_source({"source-streams", "fixture.mkv", 1, 1, 1000, 48000, 2, {0, 2, 3}}); stream_project.add_segment({"source-streams", 0, 0, 10}); assert(stream_project.to_json().find("\"selected_streams\":[0,2,3]") != std::string::npos);
  smartcut::core::Project invalid; invalid.add_segment({"missing", 0, 0, 1}); assert(!invalid.valid());
  smartcut::core::ProjectEditor editor(project); editor.add_segment({"source-a", 0, 20, 30}); assert(editor.project().segments().size() == 2); assert(editor.undo()); assert(editor.project().segments().size() == 1); assert(editor.redo()); assert(editor.project().segments().size() == 2);
  const auto project_path = std::filesystem::temp_directory_path() / "smartcut-project-v1.json"; assert(editor.save_atomic(project_path)); assert(std::filesystem::exists(project_path)); std::filesystem::remove(project_path);
  const auto vrd_path = std::filesystem::temp_directory_path() / "smartcut-videoredo-project.VPrj";
  smartcut::core::VideoReDoProject vrd_project; vrd_project.source_path = "G:\\Media & Tests\\source.mkv"; vrd_project.description = "A <clean-room> fixture"; vrd_project.duration_us = 5'000'000; vrd_project.sync_adjustment_ms = -125; vrd_project.audio_volume_adjust = 1.25; vrd_project.cut_mode = true; vrd_project.video_pid = 513; vrd_project.audio_pid = 514; vrd_project.selections = {{400'000, 900'000}, {2'000'000, 2'500'000}}; vrd_project.scene_markers_us = {250'000, 1'100'000}; vrd_project.chapter_markers_us = {0, 3'000'000};
  std::string vrd_error; assert(smartcut::core::write_videoredo_project(vrd_path, vrd_project, &vrd_error)); const auto vrd_roundtrip = smartcut::core::read_videoredo_project(vrd_path, &vrd_error); assert(vrd_roundtrip && vrd_roundtrip->source_path == vrd_project.source_path && vrd_roundtrip->description == vrd_project.description && vrd_roundtrip->duration_us == vrd_project.duration_us && vrd_roundtrip->sync_adjustment_ms == -125 && vrd_roundtrip->selections.size() == 2 && vrd_roundtrip->scene_markers_us == vrd_project.scene_markers_us && vrd_roundtrip->chapter_markers_us == vrd_project.chapter_markers_us); std::filesystem::remove(vrd_path);
  const auto batch_path = std::filesystem::temp_directory_path() / "smartcut-videoredo-batch.BPrj"; smartcut::core::VideoReDoBatchProject batch_project; batch_project.output_file = "G:\\Media & Tests\\output.mkv"; batch_project.project = vrd_project; batch_project.quick_stream_fix = true; batch_project.dimension_width = 1920; batch_project.dimension_height = 1080; batch_project.profile.name = "Matroska MKV"; batch_project.profile.width = 1920; batch_project.profile.height = 1080; batch_project.profile.audio_encoder = "AAC"; batch_project.profile.audio_bitrate_kbps = 192; assert(smartcut::core::write_videoredo_batch_project(batch_path, batch_project, &vrd_error)); const auto batch_roundtrip = smartcut::core::read_videoredo_batch_project(batch_path, &vrd_error); assert(batch_roundtrip && batch_roundtrip->output_file == batch_project.output_file && batch_roundtrip->project.source_path == vrd_project.source_path && batch_roundtrip->project.selections.size() == 2 && batch_roundtrip->quick_stream_fix && batch_roundtrip->dimension_width == 1920 && batch_roundtrip->profile.name == "Matroska MKV" && batch_roundtrip->profile.audio_encoder == "AAC" && batch_roundtrip->profile.audio_bitrate_kbps == 192); std::filesystem::remove(batch_path);
  const auto authentic_vrd = smartcut::core::parse_videoredo_project("<VideoReDoProject Version=\"5\"><Filename>J:\\fixture.mkv</Filename><Duration>50000000</Duration><OpenStreamParams><AudioStreamPID_0>514</AudioStreamPID_0></OpenStreamParams><CutList><cut><CutTimeStart>10000000</CutTimeStart><CutTimeEnd>25000000</CutTimeEnd></cut></CutList><SceneList><SceneMarker Sequence=\"1\" Timecode=\"00:00:02;00\">20000000</SceneMarker></SceneList><ChapterList><ChapterMarker Sequence=\"1\">30000000</ChapterMarker></ChapterList></VideoReDoProject>", &vrd_error); const std::vector<smartcut::core::VideoReDoTimeRange> expected_authentic_ranges{{1'000'000, 2'500'000}}; const std::vector<std::uint64_t> expected_authentic_scenes{2'000'000}; const std::vector<std::uint64_t> expected_authentic_chapters{3'000'000}; assert(authentic_vrd && authentic_vrd->duration_us == 5'000'000 && authentic_vrd->audio_pid == 514 && authentic_vrd->selections == expected_authentic_ranges && authentic_vrd->scene_markers_us == expected_authentic_scenes && authentic_vrd->chapter_markers_us == expected_authentic_chapters);
  const auto joiner_path = std::filesystem::temp_directory_path() / "smartcut-videoredo-joiner.VJnr"; smartcut::core::VideoReDoJoinerProject joiner_project; joiner_project.items.push_back({vrd_project, 1, vrd_project.duration_us, vrd_project.duration_us, 12345}); auto second_vrd = vrd_project; second_vrd.source_path = "G:\\Media & Tests\\second.mkv"; second_vrd.description = "Second item"; joiner_project.items.push_back({second_vrd, 1, second_vrd.duration_us, second_vrd.duration_us, 67890}); assert(smartcut::core::write_videoredo_joiner_project(joiner_path, joiner_project, &vrd_error)); const auto joiner_roundtrip = smartcut::core::read_videoredo_joiner_project(joiner_path, &vrd_error); assert(joiner_roundtrip && joiner_roundtrip->items.size() == 2 && joiner_roundtrip->items[0].project.source_path == vrd_project.source_path && joiner_roundtrip->items[0].project.selections.size() == 2 && joiner_roundtrip->items[0].output_bytes == 12345 && joiner_roundtrip->items[1].project.description == "Second item" && joiner_roundtrip->items[1].cut_duration_us == second_vrd.duration_us); std::filesystem::remove(joiner_path);
  const auto journal_path = std::filesystem::temp_directory_path() / "smartcut-project-v1.journal"; std::filesystem::remove(journal_path); assert(smartcut::core::ProjectJournal::append_add_segment(journal_path, {"source-a", 0, 30, 40})); assert(smartcut::core::ProjectJournal::append_export_evidence(journal_path, {"source-a", "output-a", 10, 20, "PASSED"})); assert(smartcut::core::ProjectJournal::append_audio_validation(journal_path, "PASSED")); assert(smartcut::core::ProjectJournal::append_edit_snapshot(journal_path, {"source-a", 100, {{10, 20}, {40, 50}}, {0, 2}, {12, 45}})); { std::ofstream partial(journal_path, std::ios::app); partial << "{\"op\":\"edit_snapshot\",\"source_uuid\":"; } const auto snapshot = smartcut::core::ProjectJournal::latest_edit_snapshot(journal_path); assert(snapshot && snapshot->frame_count == 100 && snapshot->cuts.size() == 2 && snapshot->selected_streams == std::vector<std::size_t>({0, 2}) && snapshot->chapter_markers == std::vector<std::uint64_t>({12, 45})); smartcut::core::Project recovered = project; assert(smartcut::core::ProjectJournal::recover(journal_path, recovered)); assert(recovered.segments().size() == 2 && recovered.exports().size() == 1 && recovered.audio_validation_status() == "PASSED"); std::filesystem::remove(journal_path);
  const auto hostile_journal_path = std::filesystem::temp_directory_path() / "smartcut-hostile-project-v1.journal"; std::filesystem::remove(hostile_journal_path); const std::string hostile_source{"source-\"quoted\"\nline"}; assert(smartcut::core::ProjectJournal::append_edit_snapshot(hostile_journal_path, {hostile_source, 10, {{2, 4}}, {0}, {5}})); const auto hostile_snapshot = smartcut::core::ProjectJournal::latest_edit_snapshot(hostile_journal_path); assert(hostile_snapshot && hostile_snapshot->source_uuid == hostile_source); assert(!smartcut::core::ProjectJournal::append_edit_snapshot(hostile_journal_path, {"invalid", 10, {{9, 11}}, {}, {}})); { std::ofstream malicious(hostile_journal_path, std::ios::trunc); malicious << "{\"op\":\"add_segment\",\"source_uuid\":\"source-a\",\"video_stream\":0,\"first_display_frame\":-1,\"end_display_frame_exclusive\":2}\n"; } smartcut::core::Project hostile_recovery = project; assert(!smartcut::core::ProjectJournal::recover(hostile_journal_path, hostile_recovery)); std::filesystem::remove(hostile_journal_path);
  const auto plan = smartcut::core::RenderPlan::from_project(project); assert(plan.operations().size() == 2); assert(plan.operations().front().kind == "CopyVideoPackets" && plan.operations()[1].kind == "CopyAudioPackets"); assert(plan.source_fingerprints().size() == 1); assert(plan.to_json().find("dependency_versions") != std::string::npos); assert(plan.explain_text().find("CopyVideoPackets video frames 10-20") != std::string::npos && plan.explain_text().find("boundary safety classification pending") != std::string::npos);
  const std::vector<smartcut::media::HevcAccessUnit> gops{{0, 10, 2, true, 0}, {10, 20, 2, false, 0}, {20, 30, 2, true, 0}};
  const auto safe_plan = smartcut::core::plan_hevc_segment({"source-a", 0, 0, 2}, gops); assert(safe_plan.operations().front().kind == "CopyVideoPackets");
  const auto repair_plan = smartcut::core::plan_hevc_segment({"source-a", 0, 1, 2}, gops); assert(repair_plan.operations().front().kind == "EncodeVideoBoundary");
  for (std::uint64_t first = 0; first < gops.size(); ++first) {
    for (std::uint64_t end = first + 1; end <= gops.size(); ++end) {
      const auto exhaustive = smartcut::core::plan_hevc_segment({"source-a", 0, first, end}, gops);
      assert(!exhaustive.operations().empty());
      for (const auto& operation : exhaustive.operations()) {
        if (operation.stream_type != "video" || operation.kind != "CopyVideoPackets") continue;
        assert(operation.first_frame < gops.size() && gops[operation.first_frame].random_access);
        assert(operation.end_frame == gops.size() || gops[operation.end_frame].random_access);
      }
    }
  }
  auto cra_gops = gops; cra_gops[0].random_access_nal_type = 21; cra_gops[0].closed_random_access = false;
  const auto cra_plan = smartcut::core::plan_hevc_segment({"source-a", 0, 0, 2}, cra_gops);
  assert(cra_plan.operations().front().kind == "EncodeVideoBoundary");
  smartcut::core::Project multi; multi.add_source({"source-a", "a.mkv", 1, 1, 1000, 48000, 2}); multi.add_source({"source-b", "b.mkv"}); multi.add_segment({"source-a", 0, 0, 2}); multi.add_segment({"source-b", 0, 1, 2});
  const auto multi_plan = smartcut::core::plan_project_segments(multi, {{"source-a", gops}, {"source-b", gops}}); assert(multi_plan.operations().size() == 4 && multi_plan.operations()[2].kind == "EncodeVideoBoundary" && multi_plan.operations()[3].kind == "CopyAudioPackets"); assert(multi_plan.operations()[1].audio_stream == 1 && multi_plan.operations()[1].audio_time_base_den == 1000 && multi_plan.operations()[1].audio_policy == "copy-complete-source-audio-packets"); assert(multi_plan.operations()[3].audio_policy == "pending-audio-range-selection");
  const auto render_report = smartcut::core::RenderReport::from_plan(multi_plan).to_json(); assert(render_report.find("render-report-v1") != std::string::npos && render_report.find("pending-executor") != std::string::npos && render_report.find("copy_ranges") != std::string::npos && render_report.find("packet-copy-selected") != std::string::npos && render_report.find("audio_operations") != std::string::npos && render_report.find("\"audio_ready\":false") != std::string::npos);
  project.add_export_evidence({"source-a", "output-a", 10, 20, "PASSED"}); assert(project.exports().size() == 1 && project.to_json().find("output-a") != std::string::npos);
  const auto merged_windows = smartcut::core::merge_repair_windows({{10, 20}, {18, 30}, {30, 40}, {50, 50}, {60, 70}}); assert(merged_windows.size() == 2 && merged_windows[0].first == 10 && merged_windows[0].end == 40 && merged_windows[1].first == 60);
  const auto normalized_cuts = smartcut::media::normalize_removed_ranges(100, {{20, 30}, {10, 25}, {90, 120}, {40, 40}});
  assert((normalized_cuts == std::vector<smartcut::media::EditRange>{{10, 30}, {90, 100}}));
  const auto kept_edits = smartcut::media::kept_ranges_for_edits(100, normalized_cuts);
  assert((kept_edits == std::vector<smartcut::media::EditRange>{{0, 10}, {30, 90}}));
  assert(smartcut::media::kept_ranges_for_edits(10, {{0, 10}}).empty());
  smartcut::core::PreviewFrame still_capture;
  still_capture.width = 320;
  still_capture.height = 180;
  still_capture.stride = still_capture.width * 4;
  still_capture.pixels.assign(static_cast<std::size_t>(still_capture.stride * still_capture.height), 96);
  for (std::size_t offset = 3; offset < still_capture.pixels.size(); offset += 4)
    still_capture.pixels[offset] = 255;
  const auto original_capture = still_capture.pixels;
  assert(smartcut::media::apply_trial_watermark(&still_capture));
  assert(still_capture.pixels != original_capture);
  assert(!smartcut::media::apply_trial_watermark(static_cast<smartcut::core::PreviewFrame*>(nullptr)));
#ifdef SMARTCUT_HAS_FFMPEG
  int metadata_number = 0;
  assert(smartcut::media::parse_pcm_metadata_integer("24", &metadata_number));
  assert(metadata_number == 24);
  assert(!smartcut::media::parse_pcm_metadata_integer("24junk", &metadata_number));
  assert(!smartcut::media::parse_pcm_metadata_integer("", &metadata_number));
  assert(!smartcut::media::apply_trial_watermark(static_cast<AVFrame*>(nullptr)));
  AVFrame* watermark_frame = av_frame_alloc();
  assert(watermark_frame);
  watermark_frame->format = AV_PIX_FMT_YUV420P;
  watermark_frame->width = 320;
  watermark_frame->height = 180;
  assert(av_frame_get_buffer(watermark_frame, 32) == 0);
  for (int row = 0; row < watermark_frame->height; ++row)
    std::memset(watermark_frame->data[0] + row * watermark_frame->linesize[0], 96,
                static_cast<std::size_t>(watermark_frame->width));
  for (int plane = 1; plane <= 2; ++plane)
    for (int row = 0; row < watermark_frame->height / 2; ++row)
      std::memset(watermark_frame->data[plane] + row * watermark_frame->linesize[plane], 128,
                  static_cast<std::size_t>(watermark_frame->width / 2));
  assert(smartcut::media::apply_trial_watermark(watermark_frame));
  std::size_t changed_luma = 0;
  std::size_t bright_text_luma = 0;
  std::size_t dark_banner_luma = 0;
  for (int row = 0; row < watermark_frame->height; ++row) {
    const auto* pixels = watermark_frame->data[0] + row * watermark_frame->linesize[0];
    for (int column = 0; column < watermark_frame->width; ++column) {
      changed_luma += pixels[column] != 96;
      bright_text_luma += pixels[column] > 200;
      dark_banner_luma += pixels[column] < 50;
    }
  }
  assert(changed_luma > 1000 && bright_text_luma > 100 && dark_banner_luma > 500);
  av_frame_free(&watermark_frame);

  AVCodecParameters dvd_lpcm{};
  dvd_lpcm.codec_type = AVMEDIA_TYPE_AUDIO;
  dvd_lpcm.codec_id = AV_CODEC_ID_PCM_DVD;
  dvd_lpcm.bits_per_coded_sample = 16;
  dvd_lpcm.bits_per_raw_sample = 16;
  AVCodecParameters working_lpcm = dvd_lpcm;
  assert(smartcut::media::normalize_pcm_parameters_for_matroska(&working_lpcm));
  assert(working_lpcm.codec_id == AV_CODEC_ID_PCM_S16BE);
  assert(smartcut::media::matroska_codec_equivalent(&dvd_lpcm, &working_lpcm));
  AVPacket* dvd_packet = av_packet_alloc();
  assert(dvd_packet && av_new_packet(dvd_packet, 7) == 0);
  const std::uint8_t dvd_payload[] = {0x0c, 0x01, 0x80, 0x00, 0x01, 0xff, 0xfe};
  std::memcpy(dvd_packet->data, dvd_payload, sizeof(dvd_payload));
  const auto normalized_payload = smartcut::media::matroska_normalized_payload(dvd_packet, &dvd_lpcm);
  assert((normalized_payload == std::vector<std::uint8_t>{0x00, 0x01, 0xff, 0xfe}));
  assert(smartcut::media::normalize_pcm_packet_for_matroska(dvd_packet, &dvd_lpcm));
  assert(dvd_packet->size == 4 && dvd_packet->data[0] == 0x00 && dvd_packet->data[3] == 0xfe);
  av_packet_free(&dvd_packet);
  AVCodecParameters unsupported_dvd_lpcm = dvd_lpcm;
  unsupported_dvd_lpcm.bits_per_coded_sample = 24;
  unsupported_dvd_lpcm.bits_per_raw_sample = 24;
  assert(!smartcut::media::normalize_pcm_parameters_for_matroska(&unsupported_dvd_lpcm));

  AVCodecParameters bluray_lpcm{};
  bluray_lpcm.codec_type = AVMEDIA_TYPE_AUDIO;
  bluray_lpcm.codec_id = AV_CODEC_ID_PCM_BLURAY;
  bluray_lpcm.bits_per_coded_sample = 24;
  bluray_lpcm.bits_per_raw_sample = 24;
  bluray_lpcm.sample_rate = 48000;
  const AVChannelLayout five_one = AV_CHANNEL_LAYOUT_5POINT1;
  assert(av_channel_layout_copy(&bluray_lpcm.ch_layout, &five_one) == 0);
  AVCodecParameters working_bluray{};
  assert(avcodec_parameters_copy(&working_bluray, &bluray_lpcm) == 0);
  assert(smartcut::media::normalize_pcm_parameters_for_matroska(&working_bluray));
  assert(working_bluray.codec_id == AV_CODEC_ID_PCM_S24BE);
  assert(smartcut::media::matroska_codec_equivalent(&bluray_lpcm, &working_bluray));
  AVPacket* bluray_packet = av_packet_alloc();
  assert(bluray_packet && av_new_packet(bluray_packet, 22) == 0);
  const std::uint8_t bluray_payload[] = {
      0x00, 0x12, 0x91, 0xc0,
      0x00, 0x00, 0x01, 0x00, 0x00, 0x02, 0x00, 0x00, 0x03,
      0x00, 0x00, 0x04, 0x00, 0x00, 0x05, 0x00, 0x00, 0x06};
  std::memcpy(bluray_packet->data, bluray_payload, sizeof(bluray_payload));
  const std::vector<std::uint8_t> canonical_bluray = {
      0x00, 0x00, 0x01, 0x00, 0x00, 0x02, 0x00, 0x00, 0x03,
      0x00, 0x00, 0x06, 0x00, 0x00, 0x04, 0x00, 0x00, 0x05};
  assert(smartcut::media::matroska_normalized_payload(bluray_packet, &bluray_lpcm) == canonical_bluray);
  assert(smartcut::media::normalize_pcm_packet_for_matroska(bluray_packet, &bluray_lpcm));
  assert(std::vector<std::uint8_t>(bluray_packet->data, bluray_packet->data + bluray_packet->size) == canonical_bluray);
  assert(smartcut::media::restore_pcm_bluray_packet(bluray_packet, &working_bluray));
  assert(bluray_packet->size == static_cast<int>(sizeof(bluray_payload)) &&
         std::memcmp(bluray_packet->data, bluray_payload, sizeof(bluray_payload)) == 0);
  av_packet_free(&bluray_packet);
  av_channel_layout_uninit(&bluray_lpcm.ch_layout);
  av_channel_layout_uninit(&working_bluray.ch_layout);

  // Every channel arrangement accepted by FFmpeg's Blu-ray LPCM codec must
  // survive the packet-domain bridge at both supported sample depths. Odd
  // channel counts include the zero padding slot required on Blu-ray media.
  for (const int layout_code : {1, 3, 4, 5, 6, 7, 8, 9, 10, 11}) {
    for (const int depth : {16, 24}) {
      AVCodecParameters native{};
      native.codec_type = AVMEDIA_TYPE_AUDIO;
      native.codec_id = AV_CODEC_ID_PCM_BLURAY;
      native.bits_per_coded_sample = depth;
      native.bits_per_raw_sample = depth;
      native.sample_rate = 48000;
      assert(smartcut::media::set_pcm_bluray_channel_layout(&native, layout_code));
      const auto mapping = smartcut::media::pcm_bluray_coded_to_canonical(layout_code);
      const auto bytes = static_cast<std::size_t>(depth / 8);
      std::vector<std::uint8_t> native_bytes(4 + mapping.size() * bytes, 0);
      native_bytes[0] = static_cast<std::uint8_t>((native_bytes.size() - 4) >> 8);
      native_bytes[1] = static_cast<std::uint8_t>((native_bytes.size() - 4) & 0xff);
      native_bytes[2] = static_cast<std::uint8_t>((layout_code << 4) | 1);
      native_bytes[3] = static_cast<std::uint8_t>((depth == 16 ? 1 : 3) << 6);
      for (std::size_t coded = 0; coded < mapping.size(); ++coded) {
        if (mapping[coded] < 0) continue;
        for (std::size_t byte = 0; byte < bytes; ++byte)
          native_bytes[4 + coded * bytes + byte] =
              static_cast<std::uint8_t>(1 + mapping[coded] * bytes + byte);
      }
      AVPacket* roundtrip = av_packet_alloc();
      assert(roundtrip && av_new_packet(roundtrip, static_cast<int>(native_bytes.size())) == 0);
      std::memcpy(roundtrip->data, native_bytes.data(), native_bytes.size());
      AVCodecParameters normalized{};
      assert(avcodec_parameters_copy(&normalized, &native) == 0);
      assert(smartcut::media::normalize_pcm_parameters_for_matroska(&normalized));
      assert(smartcut::media::normalize_pcm_packet_for_matroska(roundtrip, &native));
      assert(roundtrip->size == native.ch_layout.nb_channels * static_cast<int>(bytes));
      assert(smartcut::media::restore_pcm_bluray_packet(roundtrip, &normalized, layout_code));
      assert(std::vector<std::uint8_t>(roundtrip->data, roundtrip->data + roundtrip->size) == native_bytes);
      av_packet_free(&roundtrip);
      av_channel_layout_uninit(&native.ch_layout);
      av_channel_layout_uninit(&normalized.ch_layout);
    }
  }
#endif
  std::filesystem::remove(fixture);
  std::cout << "smartcut-unit-tests: M3 source identity passed\n";
#ifndef SMARTCUT_USE_CATCH2
  return 0;
#endif
}
