rustduck-sys 1.1.0

Raw Rust FFI bindings to the C ABI used by TSDuck's Python API
Documentation
#include "rustduck-sys/native/bridge/analyzer.h"

#include "rustduck-sys/native/bridge/test_hooks.h"
#include "rustduck-sys/src/bridge.rs.h"

#include <cmath>
#include <cstdint>
#include <cstring>
#include <limits>
#include <memory>
#include <stdexcept>
#include <type_traits>

#include <tsTSAnalyzer.h>
#include <tsTSPacketMetadata.h>

namespace {

#if defined(TS_BITRATE_FIXED)
static_assert(
    std::is_same_v<ts::BitRate,
                   ts::FixedPoint<std::int64_t, TS_BITRATE_DECIMALS>>);
#elif defined(TS_BITRATE_FLOAT)
static_assert(
    std::is_same_v<ts::BitRate,
                   ts::FloatingPoint<double, TS_BITRATE_DISPLAY_DECIMALS>>);
#elif defined(TS_BITRATE_FRACTION)
static_assert(std::is_same_v<ts::BitRate, ts::Fraction<std::uint64_t>>);
#elif defined(TS_BITRATE_INTEGER)
static_assert(std::is_same_v<ts::BitRate, ts::Integer<std::uint64_t>>);
#else
#error "unsupported TSDuck BitRate representation"
#endif

#if defined(TS_BITRATE_FRACTION) || defined(TS_BITRATE_INTEGER)
ts::BitRate make_unsigned_bitrate(double value) {
  const long double rounded = std::round(static_cast<long double>(value));
  if (rounded >=
      static_cast<long double>(std::numeric_limits<std::uint64_t>::max())) {
    return ts::BitRate(std::numeric_limits<std::uint64_t>::max());
  }
  return ts::BitRate(static_cast<std::uint64_t>(rounded));
}
#endif

// The conversion point enforces one input domain for every caller and native
// representation, including representations that narrow to integers.
ts::BitRate make_bitrate(double value) {
  if (!std::isfinite(value) || value < 0.0) {
    throw std::invalid_argument(
        "bitrate hint must be finite and non-negative");
  }
#if defined(TS_BITRATE_FIXED)
  const long double scaled =
      std::round(static_cast<long double>(value) *
                 static_cast<long double>(ts::BitRate::FACTOR));
  if (scaled >=
      static_cast<long double>(std::numeric_limits<std::int64_t>::max())) {
    return ts::BitRate(std::numeric_limits<std::int64_t>::max(), true);
  }
  if (scaled <=
      static_cast<long double>(std::numeric_limits<std::int64_t>::min())) {
    return ts::BitRate(std::numeric_limits<std::int64_t>::min(), true);
  }
  return ts::BitRate(static_cast<std::int64_t>(scaled), true);
#elif defined(TS_BITRATE_FLOAT)
  return ts::BitRate(value);
#elif defined(TS_BITRATE_FRACTION) || defined(TS_BITRATE_INTEGER)
  return make_unsigned_bitrate(value);
#endif
}

ts::BitRateConfidence confidence_from_value(std::uint8_t value) {
  switch (value) {
  case 0:
    return ts::BitRateConfidence::LOW;
  case 1:
    return ts::BitRateConfidence::PCR_CONTINUOUS;
  case 2:
    return ts::BitRateConfidence::PCR_AVERAGE;
  case 3:
    return ts::BitRateConfidence::CLOCK;
  case 4:
    return ts::BitRateConfidence::HARDWARE;
  case 5:
    return ts::BitRateConfidence::OVERRIDE;
  default:
    throw std::invalid_argument("invalid bitrate confidence value");
  }
}

} // namespace

RustDuckTSAnalyzer::RustDuckTSAnalyzer(const RustDuckDuckContext &context)
    : RustDuckAnalyzerContextLease(context.retain()),
      ts::TSAnalyzer(context.native()), pmt_collector_(context.native()) {}

void RustDuckTSAnalyzer::feed(const ts::TSPacket &packet,
                              const ts::TSPacketMetadata &metadata) {
  feedPacket(packet, metadata);
  pmt_collector_.feed_packet(packet);
}

void RustDuckTSAnalyzer::set_bitrate_hint(double bitrate,
                                          std::uint8_t confidence) {
  setBitrateHint(make_bitrate(bitrate), confidence_from_value(confidence));
}

void RustDuckTSAnalyzer::reset_state() {
  reset();
  pmt_collector_.reset();
}

void RustDuckTSAnalyzer::build_summary(RustDuckAnalyzerReport &report) {
  report.summary.packet_count = _ts_pkt_cnt;
  report.summary.ts_bitrate = _ts_bitrate.toDouble();
  report.summary.ts_pcr_bitrate_188 = _ts_pcr_bitrate_188.toDouble();
  report.summary.invalid_sync_count = _invalid_sync;
  report.summary.transport_error_count = _transport_errors;
  report.summary.pcr_pid_count = _pcr_pid_cnt;
}

void RustDuckTSAnalyzer::build_services(RustDuckAnalyzerReport &report) {
  report.services.reserve(_services.size());
  for (const auto &[_, source] : _services) {
    RustDuckAnalyzerService service;
    service.service_id = source->service_id;
    service.name = source->getName().toUTF8();
    service.provider = source->getProvider().toUTF8();
    service.pid_count = source->pid_cnt;
    service.pmt_pid = source->pmt_pid;
    service.pcr_pid = source->pcr_pid;
    service.bitrate = source->bitrate.toDouble();
    service.packet_count = source->ts_pkt_cnt;
    service.scrambled_pid_count = source->scrambled_pid_cnt;
    build_ca_descriptors(service);
    report.services.push_back(std::move(service));
  }
}

void RustDuckTSAnalyzer::build_ca_descriptors(
    RustDuckAnalyzerService &service) {
  const auto descriptors =
      pmt_collector_.ca_descriptors().find(service.service_id);
  if (descriptors == pmt_collector_.ca_descriptors().end()) {
    return;
  }
  service.ca_descriptors.reserve(descriptors->second.size());
  for (const auto &source : descriptors->second) {
    RustDuckAnalyzerCaDescriptor descriptor;
    descriptor.cas_id = source.cas_id;
    descriptor.ca_pid = source.ca_pid;
    descriptor.program_level = source.program_level;
    descriptor.has_elementary_pid = source.has_elementary_pid;
    descriptor.elementary_pid = source.elementary_pid;
    service.ca_descriptors.push_back(std::move(descriptor));
  }
}

void RustDuckTSAnalyzer::build_pids(RustDuckAnalyzerReport &report) {
  report.pids.reserve(_pids.size());
  for (const auto &[_, source] : _pids) {
    RustDuckAnalyzerPid pid;
    pid.pid = source->pid;
    pid.services.reserve(source->services.size());
    for (const auto service : source->services) {
      pid.services.push_back(service);
    }
    pid.carries_video = source->carry_video;
    pid.carries_audio = source->carry_audio;
    pid.scrambled = source->scrambled;
    pid.description = source->description.toUTF8();
    pid.packet_count = source->ts_pkt_cnt;
    pid.scrambled_packet_count = source->ts_sc_cnt;
    pid.invalid_pes_count = source->inv_pes;
    pid.invalid_pes_start_count = source->inv_pes_start;
    pid.bitrate = source->bitrate.toDouble();
    pid.ts_pcr_bitrate = source->ts_pcr_bitrate.toDouble();
    pid.current_continuity = source->cur_continuity;
    pid.unexpected_discontinuity_count = source->unexp_discont;
    pid.duplicated_packet_count = source->duplicated;
    pid.invalid_scrambling_control_count = source->inv_ts_sc_cnt;
    pid.cas_id = source->cas_id;
    pid.cas_operators.reserve(source->cas_operators.size());
    for (const auto operator_id : source->cas_operators) {
      pid.cas_operators.push_back(operator_id);
    }
    pid.current_scrambling_control = source->cur_ts_sc;
    report.pids.push_back(std::move(pid));
  }
}

RustDuckAnalyzerReport RustDuckTSAnalyzer::snapshot() {
  recomputeStatistics();
  RustDuckAnalyzerReport report;
  build_summary(report);
  build_services(report);
  build_pids(report);
  return report;
}

std::unique_ptr<RustDuckTSAnalyzer>
rustduck_analyzer_new(const RustDuckDuckContext &context) {
  rustduck_test_maybe_fail(RustDuckFailurePoint::AnalyzerConstruct);
  return std::make_unique<RustDuckTSAnalyzer>(context);
}

void rustduck_analyzer_feed(RustDuckTSAnalyzer &analyzer,
                            rust::Slice<const std::uint8_t> packets) {
  rustduck_test_maybe_fail(RustDuckFailurePoint::AnalyzerFeed);
  if (packets.size() % ts::PKT_SIZE != 0) {
    throw std::invalid_argument("packets must be aligned to 188 bytes");
  }
  ts::TSPacketMetadata metadata;
  for (size_t offset = 0; offset < packets.size(); offset += ts::PKT_SIZE) {
    ts::TSPacket packet;
    std::memcpy(packet.b, packets.data() + offset, ts::PKT_SIZE);
    analyzer.feed(packet, metadata);
  }
}

RustDuckAnalyzerReport
rustduck_analyzer_snapshot(RustDuckTSAnalyzer &analyzer) {
  rustduck_test_maybe_fail(RustDuckFailurePoint::AnalyzerSnapshot);
  return analyzer.snapshot();
}

void rustduck_analyzer_set_bitrate_hint(RustDuckTSAnalyzer &analyzer,
                                        double bitrate,
                                        std::uint8_t confidence) {
  rustduck_test_maybe_fail(RustDuckFailurePoint::AnalyzerSetBitrateHint);
  analyzer.set_bitrate_hint(bitrate, confidence);
}

void rustduck_analyzer_reset(RustDuckTSAnalyzer &analyzer) {
  rustduck_test_maybe_fail(RustDuckFailurePoint::AnalyzerReset);
  analyzer.reset_state();
}