Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -807,6 +807,7 @@ add_executable(mirakc-arib
src/main.cc
src/packet_sink.hh
src/packet_source.hh
src/packet_stats_collector.hh
src/pcr_synchronizer.hh
src/pes_printer.hh
src/program_filter.hh
Expand Down Expand Up @@ -880,6 +881,7 @@ if(MIRAKC_ARIB_TEST)
test/eitpf_collector_test.cc
test/logo_collector_test.cc
test/packet_source_test.cc
test/packet_stats_collector_test.cc
test/pcr_synchronizer_test.cc
test/program_filter_test.cc
test/ring_file_sink_test.cc
Expand Down
67 changes: 59 additions & 8 deletions src/main.cc
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ Tools to process ARIB TS streams.
[--pre-streaming] [<file>]
mirakc-arib filter-program-metadata [--sid=<sid>] [<file>]
mirakc-arib record-service --sid=<sid> --file=<file>
--chunk-size=<bytes> --num-chunks=<num> [--start-pos=<pos>] [<file>]
--chunk-size=<bytes> --num-chunks=<num> [--start-pos=<pos>] [--packet-stats] [<file>]
mirakc-arib track-airtime --sid=<sid> --eid=<eid> [<file>]
mirakc-arib seek-start --sid=<sid>
[--max-duration=<ms>] [--max-packets=<num>] [<file>]
Expand Down Expand Up @@ -651,7 +651,7 @@ Record a service stream into a ring buffer file

Usage:
mirakc-arib record-service --sid=<sid> --file=<file>
--chunk-size=<bytes> --num-chunks=<num> [--start-pos=<pos>] [<file>]
--chunk-size=<bytes> --num-chunks=<num> [--start-pos=<pos>] [--packet-stats] [<file>]

Options:
-h --help
Expand All @@ -674,6 +674,9 @@ Record a service stream into a ring buffer file
A file position to start recoring.
The value must be a multiple of the chunk size.

--packet-stats
Collect statistics on TS packets and send `packet-stats` messages.

Arguments:
<file>
Path to a TS file.
Expand All @@ -690,12 +693,12 @@ JSON Messages:
"type": "start"
}}

end
The `end` message is sent when `record-service` ends. The message structure
is like below:
stop
The `stop` message is sent when `record-service` ends. The message
structure is like below:

{{
"type": "end",
"type": "stop",
"data": {{
"reset": false,
}}
Expand Down Expand Up @@ -761,6 +764,51 @@ JSON Messages:
The `event-end` message is sent when ended recoring a program. The message
structure is the same as the `event-start` message.

packet-stats
The `packet-stats` message is sent when `--packet-stats` is specified.
The message is sent immediately before each `chunk`, `event-end`, and `stop`
message, except for the first `chunk` message which is sent when recording
starts. Each message reports statistics for the packets recorded since the
previous `packet-stats` message, or since recording started in the case of
the first message. The counters are reset each time the message is sent.
The message structure is like below:

{{
"type": "packet-stats",
"data": {{
"errorPackets": 0,
"scrambledPackets": 0,
"droppedPackets": {{
"video": 0,
"audio": 0,
"subtitle": 0,
"pmt": 0
}}
}}
}}

where:
errorPackets
The number of TS packets with TEI (transport_error_indicator) set to 1.
Only packets retained by service filtering are counted.

scrambledPackets
The number of TS packets with TSC (transport_scrambling_control) set to
a nonzero value. Only packets retained by service filtering are
counted. Null packets and packets with TEI set are excluded because
their TSC value is not meaningful.

droppedPackets
The estimated number of missing TS packets, calculated from continuity
counter discontinuities and broken down by category. Only packets
belonging to the selected service are counted.

video PES packets carrying video.
audio PES packets carrying audio.
subtitle PES packets carrying subtitles, including ARIB subtitles and
superimposed text.
pmt Packets carrying the selected service's PMT.

Environment Variables:
MIRAKC_ARIB_KEEP_UNICODE_SYMBOLS
Set `1` if you like to keep Unicode symbols like enclosed ideographic
Expand Down Expand Up @@ -1243,6 +1291,7 @@ void LoadOption(const Args& args, ServiceRecorderOption* opt) {
static const std::string kChunkSize = "--chunk-size";
static const std::string kNumChunks = "--num-chunks";
static const std::string kStartPos = "--start-pos";
static const std::string kPacketStats = "--packet-stats";

opt->sid = static_cast<uint16_t>(args.at(kSid).asLong());
opt->file = args.at(kFile).asString();
Expand Down Expand Up @@ -1280,9 +1329,11 @@ void LoadOption(const Args& args, ServiceRecorderOption* opt) {
std::abort();
}
}
opt->packet_stats = args.at(kPacketStats).asBool();
MIRAKC_ARIB_INFO(
"ServiceRecorderOptions: sid={:04X} file={} chunk-size={} num-chunks={} start-pos={}",
opt->sid, opt->file, opt->chunk_size, opt->num_chunks, opt->start_pos);
"ServiceRecorderOptions: sid={:04X} file={} chunk-size={} num-chunks={} start-pos={} "
"packet-stats={}",
opt->sid, opt->file, opt->chunk_size, opt->num_chunks, opt->start_pos, opt->packet_stats);
}

void LoadOption(const Args& args, AirtimeTrackerOption* opt) {
Expand Down
219 changes: 219 additions & 0 deletions src/packet_stats_collector.hh
Original file line number Diff line number Diff line change
@@ -0,0 +1,219 @@
// SPDX-License-Identifier: GPL-2.0-or-later

// mirakc-arib
// Copyright (C) 2019 masnagam
//
// This program is free software; you can redistribute it and/or modify it under the terms of the
// GNU General Public License as published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
// without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
// the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with this program; if
// not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
// 02110-1301, USA.

#pragma once

#include <algorithm>
#include <array>
#include <cstdint>
#include <optional>
#include <vector>

#include <tsduck/tsduck.h>

#include "base.hh"
#include "tsduck_helper.hh"

namespace {

enum class PacketCategory : uint8_t {
kVideo,
kAudio,
kSubtitle,
kPmt,
kNumCategories,
};

constexpr size_t kNumPacketCategories = static_cast<size_t>(PacketCategory::kNumCategories);

constexpr std::array<const char*, kNumPacketCategories> kPacketCategoryNames = {
"video",
"audio",
"subtitle",
"pmt",
};

class PacketStatsCollector final {
public:
PacketStatsCollector() = default;

// Changes the PMT PID tracked for packet statistics after a PAT update.
void SetPmtPid(ts::PID pid) {
if (pmt_pid_ == pid) {
return;
}

const auto old_pid = pmt_pid_;
pmt_pid_ = pid;

if (old_pid.has_value()) {
RemoveCategory(*old_pid);
}

SetCategory(pid, PacketCategory::kPmt);
}

// Classifies each PID carried by `pmt` into a PacketCategory.
void UpdatePidCategories(const ts::PMT& pmt) {
RebuildPidCategories(pmt);
}

void CollectPacketStats(const ts::TSPacket& packet) {
// Packets with TEI set may have invalid PID or CC values.
// Count them as errors and return early.
if (packet.getTEI()) {
++error_packets_;
return;
}

auto pid = packet.getPID();
if (pid == ts::PID_NULL) {
return;
}

if (packet.getScrambling() != 0) {
++scrambled_packets_;
}

auto& stat = stats_[pid];
if (!stat.category.has_value()) {
return;
}

auto cc = packet.getCC();

// Although MPEG-2 TS permits a packet to be transmitted twice, we intentionally do not retain
// the previous packet to detect duplicates.
//
// We are not aware of any reports of duplicate packets in Japanese digital broadcasts, and
// we see little value in handling them. If a duplicate payload packet is ever transmitted,
// its repeated CC is counted as 15 dropped packets.
if (stat.last_cc != ts::INVALID_CC && !packet.getDiscontinuityIndicator()) {
// The continuity counter increments only when the packet has a payload.
// Keep the expected CC unchanged for packets without payload.
uint8_t expected_cc =
packet.hasPayload() ? ((stat.last_cc + 1) & ts::CC_MASK) : stat.last_cc;

uint8_t missed = (cc - expected_cc) & ts::CC_MASK;
if (missed != 0) {
dropped_packets_[static_cast<size_t>(*stat.category)] += missed;
}
}

stat.last_cc = cc;
}

void ResetPacketStats() {
error_packets_ = 0;
scrambled_packets_ = 0;
dropped_packets_.fill(0);
}

uint64_t GetErrorPackets() const {
return error_packets_;
}

uint64_t GetScrambledPackets() const {
return scrambled_packets_;
}

uint64_t GetDroppedPackets(PacketCategory category) const {
MIRAKC_ARIB_ASSERT(static_cast<size_t>(category) < kNumPacketCategories);
return dropped_packets_[static_cast<size_t>(category)];
}

private:
struct PacketStat {
uint8_t last_cc = ts::INVALID_CC;
std::optional<PacketCategory> category;
};

static void ClearCategory(PacketStat& stat) {
stat.category.reset();
stat.last_cc = ts::INVALID_CC;
}

void SetCategory(ts::PID pid, PacketCategory category) {
auto& stat = stats_[pid];
if (!stat.category.has_value()) {
categorized_pids_.push_back(pid);
}
stat.category = category;
}

void RemoveCategory(ts::PID pid) {
ClearCategory(stats_[pid]);
const auto it = std::find(categorized_pids_.begin(), categorized_pids_.end(), pid);
if (it != categorized_pids_.end()) {
categorized_pids_.erase(it);
}
}

// Rebuilds packet-statistics PID categories from the tracked PMT PID and PMT.
void RebuildPidCategories(const ts::PMT& pmt) {
std::vector<ts::PID> previous_pids;
previous_pids.swap(categorized_pids_);

// Clear the previous category assignments before rebuilding them from the current PMT.
// Do not clear the last_cc of existing stats here, as it may still be used by the current PMT.
for (auto pid : previous_pids) {
stats_[pid].category.reset();
}

if (pmt_pid_.has_value()) {
SetCategory(*pmt_pid_, PacketCategory::kPmt);
}

RebuildStreamPidCategories(pmt);

// Clear both the category and saved CC for PIDs that are no longer tracked.
for (auto pid : previous_pids) {
if (!stats_[pid].category.has_value()) {
ClearCategory(stats_[pid]);
}
}
}

// Assigns categories to the PIDs referenced by `pmt`.
void RebuildStreamPidCategories(const ts::PMT& pmt) {
for (const auto& [pid, stream] : pmt.streams) {
// Do not classify the PMT PID as other categories.
if (pmt_pid_.has_value() && pid == *pmt_pid_) {
continue;
}

if (stream.isVideo()) {
SetCategory(pid, PacketCategory::kVideo);
} else if (stream.isAudio()) {
SetCategory(pid, PacketCategory::kAudio);
} else if (stream.isSubtitles() || IsAribSubtitle(stream) ||
IsAribSuperimposedText(stream)) {
SetCategory(pid, PacketCategory::kSubtitle);
}
Comment on lines +203 to +206

@vroad vroad Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@masnagam
自分で見ていて気づきましたが、
isSubtitlesはARIBのMPEG2-TSでは絶対にtrueにはならないかと思うので、削除しようと思います。
tsduck-aribのisSubtitles()は、ARIBでは使用しないDVBのDescriptorの内容を見ています。mirakc-aribの既存コードにも使用箇所はありますが、同じ理由でtrueにはならないのではと思いました。

あとカテゴリ名がsubtitleなのにsuperimposed textも含めてしまっていますが、
名称に偽りのある状態なので
これは対象外としても良いかと思いました。

なら別途superimposed textのカテゴリを作るか?と言う論点も出てくると思いますが
一旦カウントしない方針にしようかと思っています。
めったにsuperimposed textは実TSに入らないとは言え視聴に影響あるとは思いますが、
(めったに実TSに入らないので)確認が難しいためです。

https://github.com/mirakc/tsduck-arib/blob/c400025b7d31e26c0c15471e81adf2ad50632281/src/libtsduck/dtv/tables/tsPMT.cpp#L228-L233

}
}

MIRAKC_ARIB_NON_COPYABLE(PacketStatsCollector);
std::array<PacketStat, ts::PID_MAX> stats_;
std::vector<ts::PID> categorized_pids_;
std::optional<ts::PID> pmt_pid_;
uint64_t error_packets_ = 0;
uint64_t scrambled_packets_ = 0;
std::array<uint64_t, kNumPacketCategories> dropped_packets_{};
};

} // namespace
Loading