Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
1539 lines (1384 loc) · 70.8 KB
/
Copy pathmain.cpp
File metadata and controls
1539 lines (1384 loc) · 70.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ============================================================================
// crête — Zero-dependency Dynamic Range Meter
//
// Measures TT Dynamic Range (Pleasurize Music Foundation algorithm),
// EBU R128 integrated loudness, and crest factor for audio files.
//
// Native formats: WAV / RF64 / BW64 / Wave64, AIFF/AIFF-C, FLAC, DSF, DFF (DSD)
// SACD images: .iso, both areas, DST included (accepted by content, not name)
// Disc audio: TrueHD/MLP, AC-3, E-AC-3, DTS/DTS-HD MA (FFmpeg tier)
// Cue sheets: parsed automatically when present alongside a monolithic
// audio file; each TRACK becomes its own analysed entry.
// Output compatible with dr.loudness-war.info submission format.
//
// Usage: crete [options] <path...>
//
// Build: make (or: g++ -std=c++17 -O2 -o crete main.cpp)
// ============================================================================
#include "analysis.hpp"
#include "audio.hpp"
#include "cue.hpp"
#include "groups.hpp"
#ifdef CRETE_HAS_JSON
#include <nlohmann/json.hpp>
#endif
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <iomanip>
#include <iostream>
#include <map>
#include <mutex>
#include <sstream>
#include <string>
#include <system_error>
#include <thread>
#include <tuple>
#include <vector>
#ifdef CRETE_HAS_FFMPEG
extern "C" {
#include <libavutil/avutil.h>
}
#endif
// ── Version info ───────────────────────────────────────────────────────────
#ifndef CRETE_VERSION
#define CRETE_VERSION "0.16.1"
#endif
static constexpr const char* PROGRAM_NAME = "crête";
static constexpr const char* PROGRAM_BIN = "crete";
static constexpr const char* PROGRAM_VERSION = CRETE_VERSION;
// DSD decode options in effect for this run (chain / final-stage filter /
// output rate). Set once from --dsd-* flags in main(); read by print_json() so
// a JSON result always records how its DSD numbers were produced.
static dsd::Options g_dsd_opt;
// Container audio-stream index to decode, or -1 for "let FFmpeg choose".
// Only multi-stream containers (.mkv/.mp4 Blu-ray rips) can honour it.
static int g_stream = -1;
// drc_scale for AC-3 / E-AC-3 decodes. 0 = the encoded audio: crete's rule
// since 0.15 and what every reference row was measured with. Anything else
// measures a playback rendition, which is what --dolby-drc exists to show.
static double g_dolby_drc = 0.0;
// --dolby-drc <off|on|SCALE>. off = 0, on = 1 (FFmpeg's and most players'
// default: the full compression the metadata asks for), SCALE in [0, 6] --
// FFmpeg's own range for drc_scale, where > 1 over-applies it.
static bool parse_dolby_drc(const std::string& v, double& out) {
if (v == "off") { out = 0.0; return true; }
if (v == "on") { out = 1.0; return true; }
char* end = nullptr;
const double d = std::strtod(v.c_str(), &end);
if (v.empty() || !end || *end || !(d >= 0.0 && d <= 6.0)) return false;
out = d;
return true;
}
// "on" / "0.5" for a message; only called when DRC was applied (> 0).
static std::string dolby_drc_label(double scale) {
if (scale == 1.0) return "on (scale 1)";
char b[32];
std::snprintf(b, sizeof(b), "scale %g", scale);
return b;
}
static dr::RmsMean g_rms_mean = dr::RmsMean::Quadratic;
// Whether the LFE counts toward the TT DR score. Exclude is crete's rule and
// the default; Include matches foobar2000's DR Meter. Affects TT DR only --
// BS.1770 loudness and Min. PSR are untouched. See dr::LfeScoring.
static dr::LfeScoring g_lfe = dr::LfeScoring::Exclude;
// Which 3 s blocks enter the DR pools. Reference is the PMF reference
// implementation and the default since 0.14.0 -- it keeps the trailing partial
// block and drops the block gate, both of which biased crete's DR low. Legacy
// is the pre-0.14.0 accounting, kept so any reference row recorded under it
// stays reproducible. See dr::BlockSet.
static dr::BlockSet g_dr_blocks = dr::BlockSet::Reference;
// Tracks under 10 s: Exclude (default) reports no DR for them and leaves them
// out of the album DR, as MAAT does; Include reproduces <= 0.19.5. See
// dr::ShortTracks.
static dr::ShortTracks g_short = dr::ShortTracks::Exclude;
// Whether a declared speaker mask may describe the layout (see chan::use_mask).
// use is the default since 0.21.0; ignore takes labels, weights and the LFE
// from the channel count alone, which reproduces <= 0.20.0.
static bool g_channel_mask = true;
static const char* channel_mask_name(bool use) { return use ? "use" : "ignore"; }
// Which SACD audio area to measure. Auto prefers the 2-channel area:
// it is the layer crete's DR references are built on, the one comparable
// with every other release of the album, and on most discs the
// uncompressed one. --sacd-area multichannel is one flag away.
static sacd::AreaSel g_sacd_area = sacd::AreaSel::Auto;
static constexpr const char* PROGRAM_DESC = "TT Dynamic Range Meter (zero-dependency)";
namespace fs = std::filesystem;
#ifdef CRETE_HAS_JSON
using json = nlohmann::json;
#endif
// ── Output format modes ────────────────────────────────────────────────────
enum class OutputFormat {
Standard, // dr.loudness-war.info compatible
Foobar, // foobar2000 DR Meter style
Extended, // MAAT DROffline–style pipe-delimited table
Detail, // per-track per-channel block view
Json, // machine-readable JSON (requires CRETE_HAS_JSON)
};
// ── Formatting helpers ─────────────────────────────────────────────────────
std::string format_duration(double secs) {
int m = static_cast<int>(secs) / 60;
int s = static_cast<int>(secs) % 60;
char buf[16];
std::snprintf(buf, sizeof(buf), "%d:%02d", m, s);
return buf;
}
std::string format_peak(double peak_dbfs, bool is_clipping, OutputFormat fmt) {
if (fmt == OutputFormat::Foobar) {
if (is_clipping) return " 0.00 dB";
char buf[16];
std::snprintf(buf, sizeof(buf), "%7.2f dB", peak_dbfs);
return buf;
} else {
if (is_clipping) return "over ";
char buf[16];
std::snprintf(buf, sizeof(buf), "%.2f dB", peak_dbfs);
return buf;
}
}
std::string format_sr(uint32_t sr) {
double k = sr / 1000.0;
if (k == std::floor(k))
return std::to_string(static_cast<int>(k)) + "k";
char buf[16];
std::snprintf(buf, sizeof(buf), "%.1fk", k);
return buf;
}
std::string format_signed(double db) {
char buf[16];
if (db >= 0.0)
std::snprintf(buf, sizeof(buf), "+%.2f", db);
else
std::snprintf(buf, sizeof(buf), "%.2f", db);
return buf;
}
std::string format_db(double db) {
char buf[16];
std::snprintf(buf, sizeof(buf), "%.2f", db);
return buf;
}
std::string strip_ext(const std::string& filename) {
auto dot = filename.rfind('.');
if (dot != std::string::npos) return filename.substr(0, dot);
return filename;
}
std::string get_ext(const std::string& filename) {
auto dot = filename.rfind('.');
if (dot != std::string::npos) return filename.substr(dot);
return "";
}
// ════════════════════════════════════════════════════════════════════════════
// Analysis grouping
//
// An AnalysisGroup represents one decode operation. Two cases:
// 1. sheet.tracks.empty() — a single-track file, analysed as-is
// 2. sheet.tracks non-empty — a monolithic file paired with a cue sheet;
// the decoded PCM is sliced per TRACK and each slice analysed separately
//
// collect_groups() scans a directory for cue files first, parses them, and
// claims the audio files they reference. Audio files not claimed by any cue
// fall through to single-track groups. A folder with no cue files behaves
// exactly as it did before cue support was added.
// ════════════════════════════════════════════════════════════════════════════
// Group collection, SACD area resolution and the per-group analysis all live
// in groups.hpp so the GUI runs the identical code path -- see that header.
// The CLI adds only its own reporting: warnings to stderr, a progress line.
// ── MQA warning block (all human-facing formats) ───────────────────────────
//
// A listener measuring DR is entitled to know the source is MQA-encoded lossy
// audio rather than lossless. This block fires ONLY on a verified datasync
// packet — a 40-bit magic plus a well-formed field structure, which is never a
// coincidence. The LSB-entropy heuristic is deliberately NOT surfaced here: it
// cannot separate MQA from analog tape hiss or a prior lossy generation, and a
// false "this is MQA" on legitimate lossless would betray the whole tool. Hits
// are grouped by their authoritative fields so an album collapses to one line.
std::string format_khz(int hz) {
std::ostringstream os;
os << std::fixed << std::setprecision(1) << (hz / 1000.0) << " kHz";
return os.str();
}
void print_mqa_summary(const std::vector<dr::TrackResult>& tracks) {
// key: (orig_rate, studio, auth_level, bit_position) → track count
std::map<std::tuple<int,int,int,int>, int> hits;
for (const auto& t : tracks) {
if (t.mqa.datasync_found)
hits[std::make_tuple(t.mqa.orig_rate, t.mqa.studio ? 1 : 0,
t.mqa.auth_level, t.mqa.bit_position)]++;
}
if (hits.empty()) return;
const std::string top(94, '=');
const std::string mid(94, '-');
std::cout << "\n" << top << "\n";
std::cout << " ⚠ MQA LOSSY ENCODING DETECTED — source is not lossless\n";
std::cout << mid << "\n";
for (const auto& [k, count] : hits) {
const int orig = std::get<0>(k);
const bool studio = std::get<1>(k) != 0;
const int auth = std::get<2>(k);
const int bp = std::get<3>(k);
std::cout << " " << count << " track(s) · "
<< (studio ? "MQA Studio" : "MQA")
<< " · authored " << (orig ? format_khz(orig) : "unknown rate")
<< " · carrier bit " << bp
<< " · auth level " << auth << "\n";
}
std::cout << mid << "\n";
std::cout << " DR is measured on the delivered PCM stream; content encoded above the base\n";
std::cout << " band is not reconstructed (no open MQA decoder exists).\n";
std::cout << top << "\n";
}
// ── Standard output (dr.loudness-war.info compatible) ──────────────────────
void print_standard(const std::vector<dr::TrackResult>& tracks,
const std::string& folder_path) {
const std::string sep(94, '-');
const std::string sep2(94, '=');
std::cout << sep << "\n";
std::cout << " Analyzed Folder: " << folder_path << "\n";
std::cout << sep << "\n";
std::cout << "DR Peak RMS Filename\n";
std::cout << sep << "\n\n";
for (const auto& t : tracks) {
char dr_str[8];
std::snprintf(dr_str, sizeof(dr_str), "%-5s", dr::track_dr_text(t).c_str());
std::string peak_str;
if (t.is_clipping) {
peak_str = "over ";
} else {
char buf[16];
std::snprintf(buf, sizeof(buf), "%.2f dB ", t.peak_dbfs);
peak_str = buf;
}
char rms_str[16];
std::snprintf(rms_str, sizeof(rms_str), "%.2f dB", t.rms_dbfs);
std::printf("%-10s %-10s %-10s %s\n",
dr_str, peak_str.c_str(), rms_str, t.filename.c_str());
}
std::cout << sep << "\n\n";
std::cout << " Number of Files: " << tracks.size() << "\n";
std::cout << " Official DR Value: " << dr::album_dr_text(tracks) << "\n";
std::cout << "\n" << sep2 << "\n";
}
// ── Foobar2000 style output ────────────────────────────────────────────────
void print_foobar(const std::vector<dr::TrackResult>& tracks,
const std::string& folder_name) {
const std::string sep(80, '-');
const std::string sep2(80, '=');
auto now = std::chrono::system_clock::now();
auto t = std::chrono::system_clock::to_time_t(now);
char date_buf[32];
std::strftime(date_buf, sizeof(date_buf), "%Y-%m-%d %H:%M:%S", std::localtime(&t));
std::cout << PROGRAM_NAME << " " << PROGRAM_VERSION
<< " / TT DR Offline Meter\n";
std::cout << "log date: " << date_buf << "\n\n";
std::cout << sep << "\n";
std::cout << "Analyzed: " << folder_name << "\n";
std::cout << sep << "\n\n";
std::cout << "DR Peak RMS Duration Track\n";
std::cout << sep << "\n";
for (const auto& t : tracks) {
char dr_str[8];
std::snprintf(dr_str, sizeof(dr_str), "%-5s", dr::track_dr_text(t).c_str());
char peak_str[16];
if (t.is_clipping)
std::snprintf(peak_str, sizeof(peak_str), " 0.00 dB");
else
std::snprintf(peak_str, sizeof(peak_str), "%6.2f dB", t.peak_dbfs);
char rms_str[16];
std::snprintf(rms_str, sizeof(rms_str), "%7.2f dB", t.rms_dbfs);
std::string dur = format_duration(t.duration_secs);
auto name = strip_ext(t.filename);
std::printf("%-10s %s %s %8s %s\n",
dr_str, peak_str, rms_str, dur.c_str(), name.c_str());
}
std::cout << sep << "\n\n";
std::cout << "Number of tracks: " << tracks.size() << "\n";
std::cout << "Official DR value: " << dr::album_dr_text(tracks) << "\n\n";
if (!tracks.empty()) {
const auto& first = tracks[0];
std::cout << "Samplerate: " << first.sample_rate << " Hz\n";
std::cout << "Channels: " << first.channels << "\n";
std::cout << "Bits per sample: " << first.bit_depth << "\n";
std::cout << "Codec: " << first.codec << "\n";
}
std::cout << sep2 << "\n";
}
// ── Extended output (MAAT DROffline–style pipe-delimited table) ────────────
void print_extended(const std::vector<dr::TrackResult>& tracks,
const std::string& folder_path) {
if (tracks.empty()) return;
struct Row {
std::string name, ext, sr, wl;
std::string tpl, sppm_l, sppm_r, sppm_j;
std::string rms_l, rms_r;
std::string mom_l, mom_r, st_l, st_r;
std::string lufs_i, dr_pmf, bits_used;
std::string plr, lra;
std::string mom_j, st_j;
std::string dr_l, tpl_l, tpl_r, dr_r, min_psr;
};
std::vector<Row> rows;
rows.reserve(tracks.size());
size_t fname_w = 9;
size_t sr_w = 2;
for (const auto& t : tracks) {
Row r;
r.name = strip_ext(t.filename);
r.ext = get_ext(t.filename);
r.sr = format_sr(t.sample_rate);
r.wl = std::to_string(t.bit_depth);
size_t nch = t.ch_metrics.size();
r.tpl = format_signed(t.max_true_peak_dbtp);
double sp_l = (nch > 0) ? t.ch_metrics[0].sample_peak_dbfs : t.peak_dbfs;
double sp_r = (nch > 1) ? t.ch_metrics[1].sample_peak_dbfs : sp_l;
r.sppm_l = format_db(sp_l);
r.sppm_r = format_db(sp_r);
r.sppm_j = format_db(std::max(sp_l, sp_r));
r.rms_l = format_db((nch > 0) ? t.ch_metrics[0].rms_dbfs : t.rms_dbfs);
r.rms_r = format_db((nch > 1) ? t.ch_metrics[1].rms_dbfs
: ((nch > 0) ? t.ch_metrics[0].rms_dbfs : t.rms_dbfs));
r.mom_l = format_db((nch > 0) ? t.ch_metrics[0].max_momentary_lufs : t.max_momentary_lufs);
r.mom_r = format_db((nch > 1) ? t.ch_metrics[1].max_momentary_lufs
: ((nch > 0) ? t.ch_metrics[0].max_momentary_lufs : t.max_momentary_lufs));
r.st_l = format_db((nch > 0) ? t.ch_metrics[0].max_short_term_lufs : t.max_short_term_lufs);
r.st_r = format_db((nch > 1) ? t.ch_metrics[1].max_short_term_lufs
: ((nch > 0) ? t.ch_metrics[0].max_short_term_lufs : t.max_short_term_lufs));
r.lufs_i = format_db(t.integrated_lufs);
r.dr_pmf = t.dr_defined ? std::to_string(t.dr_score) : std::string("--");
r.bits_used = std::to_string(t.bit_depth);
r.plr = format_db(t.plr_db);
r.lra = format_db(t.lra_lu);
r.mom_j = format_db(t.max_momentary_lufs);
r.st_j = format_db(t.max_short_term_lufs);
r.dr_l = !t.dr_defined ? std::string("--")
: format_db((nch > 0) ? t.ch_metrics[0].dr_raw : t.dr_score_raw);
r.dr_r = !t.dr_defined ? std::string("--")
: format_db((nch > 1) ? t.ch_metrics[1].dr_raw
: ((nch > 0) ? t.ch_metrics[0].dr_raw : t.dr_score_raw));
r.tpl_l = format_signed((nch > 0) ? t.ch_metrics[0].true_peak_dbtp : t.max_true_peak_dbtp);
r.tpl_r = format_signed((nch > 1) ? t.ch_metrics[1].true_peak_dbtp
: ((nch > 0) ? t.ch_metrics[0].true_peak_dbtp : t.max_true_peak_dbtp));
r.min_psr = format_db(t.psr_db);
fname_w = std::max(fname_w, r.name.length());
sr_w = std::max(sr_w, r.sr.length());
rows.push_back(std::move(r));
}
int aFN = static_cast<int>(fname_w);
int aFmt = 6;
int aSR = static_cast<int>(sr_w);
int aWL = 11;
int aTPL = 8;
int aSPL = 14;
int aSPR = 15;
int aSPJ = 17;
int aRL = 8;
int aRR = 9;
int aML = 11;
int aMR = 12;
int aSL = 11;
int aSRt = 12;
int aLU = 6;
int aDR = 8;
int aBU = 9;
int aPL = 5;
int aLA = 5;
int aMJ = 6;
int aSJ = 6;
int aDL = 7;
int aTL = 13;
int aTR = 14;
int aDRR = 8;
int aPS = 8;
auto print_row = [&](
const char* fn, const char* fmt, const char* sr, const char* wl,
const char* tpl,
const char* spl, const char* spr, const char* spj,
const char* rl, const char* rr,
const char* ml, const char* mr, const char* sl, const char* srt,
const char* lu, const char* dr, const char* bu,
const char* pl, const char* la,
const char* mj, const char* sj,
const char* dl, const char* tl, const char* tr,
const char* drr, const char* ps)
{
std::printf("%*s | %*s | %*s | %*s | %*s | %*s | %*s | %*s | "
"%*s | %*s | %*s | %*s | %*s | %*s | %*s | %*s | "
"%*s | %*s | %*s | %*s | %*s | %*s | %*s | %*s | "
"%*s | %*s | \n",
aFN, fn, aFmt, fmt, aSR, sr, aWL, wl,
aTPL, tpl,
aSPL, spl, aSPR, spr, aSPJ, spj,
aRL, rl, aRR, rr,
aML, ml, aMR, mr, aSL, sl, aSRt, srt,
aLU, lu, aDR, dr, aBU, bu,
aPL, pl, aLA, la,
aMJ, mj, aSJ, sj,
aDL, dl, aTL, tl, aTR, tr,
aDRR, drr, aPS, ps);
};
std::cout << "Folder Path: " << folder_path << "\n\n";
print_row("File Name", "Format", "SR", "Word Length",
"Max. TPL",
"Max. SPPM LEFT", "Max. SPPM RIGHT", "Max. SPPM (JOINT)",
"RMS LEFT", "RMS RIGHT",
"Max. M LEFT", "Max. M RIGHT", "Max. S LEFT", "Max. S RIGHT",
"LUFSi", "DR (PMF)", "Bits Used",
"PLR", "LRA",
"Max. M", "Max. S",
"DR LEFT", "Max. TPL LEFT", "Max. TPL RIGHT",
"DR RIGHT", "Min. PSR");
std::cout << "\n";
for (const auto& r : rows) {
print_row(r.name.c_str(), r.ext.c_str(), r.sr.c_str(), r.wl.c_str(),
r.tpl.c_str(),
r.sppm_l.c_str(), r.sppm_r.c_str(), r.sppm_j.c_str(),
r.rms_l.c_str(), r.rms_r.c_str(),
r.mom_l.c_str(), r.mom_r.c_str(), r.st_l.c_str(), r.st_r.c_str(),
r.lufs_i.c_str(), r.dr_pmf.c_str(), r.bits_used.c_str(),
r.plr.c_str(), r.lra.c_str(),
r.mom_j.c_str(), r.st_j.c_str(),
r.dr_l.c_str(), r.tpl_l.c_str(), r.tpl_r.c_str(),
r.dr_r.c_str(), r.min_psr.c_str());
}
std::printf("\nNumber of EP/Album Files: %zu\n", tracks.size());
{
auto a = dr::album_dr(tracks);
std::printf("Official EP/Album DR: %s\n", a ? std::to_string(*a).c_str() : "--");
}
}
// ── Detail output (per-track per-channel block view) ───────────────────────
void print_detail(const std::vector<dr::TrackResult>& tracks,
const std::string& folder_name) {
const std::string sep(80, '=');
auto now = std::chrono::system_clock::now();
auto t_now = std::chrono::system_clock::to_time_t(now);
char date_buf[32];
std::strftime(date_buf, sizeof(date_buf), "%Y-%m-%d %H:%M:%S", std::localtime(&t_now));
std::cout << PROGRAM_NAME << " " << PROGRAM_VERSION
<< " — Detailed Track Analysis\n";
std::cout << "log date: " << date_buf << "\n\n";
std::cout << sep << "\n";
std::cout << "Analyzed: " << folder_name << "\n";
std::cout << sep << "\n";
for (size_t idx = 0; idx < tracks.size(); ++idx) {
const auto& t = tracks[idx];
size_t nch = t.ch_metrics.size();
auto name = strip_ext(t.filename);
std::cout << "\n" << sep << "\n";
std::printf("Track %zu/%zu: %s\n", idx + 1, tracks.size(), name.c_str());
std::cout << sep << "\n\n";
std::printf(" Format: %s %u-bit / %u Hz\n",
t.codec.c_str(), t.bit_depth, t.sample_rate);
if (!t.codec_profile.empty())
std::printf(" Profile: %s\n", t.codec_profile.c_str());
if (t.dolby_drc > 0.0)
std::printf(" Dolby DRC: %s -- a playback rendition, not the encoded audio\n",
dolby_drc_label(t.dolby_drc).c_str());
if (t.ps.present) {
// What carried it, and which of its streams this is, by the ID
// the disc gives it -- stable across fragments, unlike the index.
std::printf(" Carrier: %s\n", mpegps::carriage_line(t.ps).c_str());
const std::string m = mpegps::measured_line(t.ps);
if (!m.empty()) std::printf(" Measured stream: %s\n", m.c_str());
}
{
// An immersive carrier is measured as its channel bed -- FFmpeg has
// no Atmos or DTS:X renderer -- so the layout says which it is.
const std::string q = audio::layout_qualifier(t.codec_profile);
std::string line = chan::layout_detail(t.channels, t.channel_mask);
if (!q.empty()) line += " [bed -- " + q + "]";
std::printf(" Layout: %s\n", line.c_str());
}
std::printf(" Duration: %s\n\n",
format_duration(t.duration_secs).c_str());
// Speaker names come from the shared layout table so the CLI, the JSON
// and the GUI cannot drift apart. See channels.hpp.
const unsigned unch = static_cast<unsigned>(nch);
const uint32_t mask = t.channel_mask;
auto ch_label = [&](size_t c) -> std::string {
return chan::label_long(unch, c, mask);
};
std::printf(" %-22s", "");
for (size_t c = 0; c < nch; ++c)
std::printf("%-12s", ch_label(c).c_str());
std::printf("%-12s\n", "Joint");
std::cout << " " << std::string(22 + 12 * (nch + 1), '-') << "\n";
// Standards tags mirror MAAT DROffline's convention: the governing
// standard follows the joint value; per-channel M/S are (non-ITU)
// informative variants (BS.1770 defines them for the summed program
// only). Legend printed once in the summary footer.
std::printf(" %-22s", "Max True Peak");
for (size_t c = 0; c < nch; ++c)
std::printf("%-12.2f", t.ch_metrics[c].true_peak_dbtp);
std::printf("%.2f dB (ITU)\n", t.max_true_peak_dbtp);
std::printf(" %-22s", "Max Sample Peak");
for (size_t c = 0; c < nch; ++c)
std::printf("%-12.2f", t.ch_metrics[c].sample_peak_dbfs);
if (t.is_clipping) std::printf("over\n");
else std::printf("%.2f dBFS\n", t.peak_dbfs);
std::printf(" %-22s", "RMS");
for (size_t c = 0; c < nch; ++c)
std::printf("%-12.2f", t.ch_metrics[c].rms_dbfs);
std::printf("%.2f dB\n", t.rms_dbfs);
std::printf(" %-22s", "Max Momentary");
for (size_t c = 0; c < nch; ++c)
std::printf("%-12.2f", t.ch_metrics[c].max_momentary_lufs);
std::printf("%.2f LUFS (ITU)\n", t.max_momentary_lufs);
std::printf(" %-22s", "Max Short-Term");
for (size_t c = 0; c < nch; ++c)
std::printf("%-12.2f", t.ch_metrics[c].max_short_term_lufs);
std::printf("%.2f LUFS (ITU)\n", t.max_short_term_lufs);
std::printf(" %-22s", "Integrated");
for (size_t c = 0; c < nch; ++c) std::printf("%-12s", "—");
std::printf("%.2f LUFS (ITU)\n", t.integrated_lufs);
std::printf(" %-22s", "DR (PMF)");
if (!t.dr_defined) {
for (size_t c = 0; c < nch; ++c) std::printf("%-12s", "—");
std::printf("no DR: under %.0f s (%s)\n", dr::MIN_DR_SECONDS,
"MAAT omits such tracks; not in the album DR");
} else
for (size_t c = 0; c < nch; ++c) {
// Brackets mark a channel that is measured but not scored (LFE).
if (t.ch_metrics[c].scored) {
std::printf("%-12.2f", t.ch_metrics[c].dr_raw);
} else {
char br[16];
std::snprintf(br, sizeof(br), "[%.2f]", t.ch_metrics[c].dr_raw);
std::printf("%-12s", br);
}
}
if (t.dr_defined) std::printf("DR%d (PMF)\n", t.dr_score);
std::printf(" %-22s", "Min PSR");
for (size_t c = 0; c < nch; ++c) std::printf("%-12s", "—");
std::printf("%.2f dB (AES)\n", t.psr_db);
std::printf(" %-22s", "PLR");
for (size_t c = 0; c < nch; ++c) std::printf("%-12s", "—");
std::printf("%.2f dB (AES)\n", t.plr_db);
std::printf(" %-22s", "LRA");
for (size_t c = 0; c < nch; ++c) std::printf("%-12s", "—");
std::printf("%.2f LU (EBU)\n", t.lra_lu);
// Multichannel needs its aggregation rule stated next to the number:
// TT DR defines no procedure beyond stereo, so the reader is entitled
// to know which channels produced the headline and which did not.
if (nch > 2 && t.dr_defined) {
const bool lfe_in = (g_lfe == dr::LfeScoring::Include);
std::printf("\n DR (PMF) = mean of the %u scored channel%s%s.\n",
chan::scored_count(unch, lfe_in, mask),
chan::scored_count(unch, lfe_in, mask) == 1 ? "" : "s",
!chan::has_lfe(unch, mask) ? ""
: lfe_in ? " — LFE INCLUDED (--dr-lfe include)"
: " — LFE measured, not scored");
std::printf(" Front L/R DR: %.2f (the figure comparable "
"with a stereo master)\n", t.dr_front_raw);
if (t.worst_channel >= 0)
std::printf(" Lowest scored: %.2f (%s)\n",
t.ch_metrics[t.worst_channel].dr_raw,
chan::label_long(unch, t.worst_channel, mask).c_str());
}
}
std::cout << "\n" << sep << "\nSummary\n" << sep << "\n\n";
std::cout << "Number of tracks: " << tracks.size() << "\n";
std::cout << "Official DR value: " << dr::album_dr_text(tracks) << "\n";
{
size_t undefined = 0;
for (const auto& t : tracks) undefined += t.dr_defined ? 0 : 1;
if (undefined)
std::printf(" (%zu track%s under %.0f s: no DR, not in the album mean)\n",
undefined, undefined == 1 ? "" : "s", dr::MIN_DR_SECONDS);
}
if (!tracks.empty()) {
double sum_lufs = 0.0;
for (const auto& t : tracks) sum_lufs += t.integrated_lufs;
std::printf("Avg. loudness: %.1f LUFS\n", sum_lufs / tracks.size());
const auto& first = tracks[0];
std::cout << "\nSamplerate: " << first.sample_rate << " Hz\n";
std::cout << "Channels: " << first.channels
<< " (" << chan::layout_detail(first.channels, first.channel_mask) << ")\n";
std::cout << "Bits per sample: " << first.bit_depth << "\n";
std::cout << "Codec: " << first.codec << "\n";
if (!first.codec_profile.empty())
std::cout << "Profile: " << first.codec_profile
<< (audio::profile_is_immersive(first.codec_profile)
? " [measured as the channel bed]" : "")
<< "\n";
if (first.dolby_drc > 0.0)
std::cout << "Dolby DRC: " << dolby_drc_label(first.dolby_drc)
<< " [a playback rendition, not the encoded audio]\n";
if (first.audio_stream_count > 1)
std::cout << "Audio stream: " << first.stream_index
<< (first.ps.measured >= 0 ? " [" + mpegps::hex_id(first.ps.measured) + "]" : "")
<< " of " << first.audio_stream_count
<< " in container\n";
if (first.ps.present)
std::cout << "Carrier: " << mpegps::carriage_line(first.ps) << "\n";
if (first.channels > 2)
std::cout << "Loudness summing: "
<< chan::loudness_mode(first.channels, first.channel_mask) << "\n";
auto v = dr::album_verdict(tracks);
std::cout << "Verdict: " << dr::verdict_string(v) << "\n";
}
std::cout << sep << "\n";
std::cout <<
"Standards\n"
" (ITU) ITU-R BS.1770-4 — K-weighted loudness (LUFS) and 4x-oversampled\n"
" true peak. Gating per EBU R 128.\n"
" (EBU) EBU Tech 3342 — Loudness Range (LRA), 3 s short-term distribution,\n"
" 10th-95th percentile with -20 LU relative gate.\n"
" (AES) AES loudness conventions — PLR (true peak minus integrated LUFS),\n"
" Min PSR (window sample peak minus 3 s short-term loudness, minimum\n"
" over the track).\n"
" (PMF) TT Dynamic Range, Pleasurize Music Foundation — peak-to-loudest-RMS\n"
" metric matching dr.loudness-war.info.\n"
" Per-channel Momentary/Short-Term columns are informative (non-ITU):\n"
" BS.1770 defines these values for the summed program only.\n"
<< sep << "\n";
if (!tracks.empty() && tracks[0].channels > 2) {
std::cout <<
"Multichannel\n"
" TT DR / dr.loudness-war.info define no procedure beyond stereo, so\n"
" crete states its rule rather than implying one: DR (PMF) is the mean\n"
" of the scored channels, whose two-channel case IS the stereo rule.\n"
" The front L/R DR (comparable with a stereo master) and the lowest\n"
" scored channel are reported alongside it, never in place of it.\n"
" The LFE is measured in full and scored in nothing: a band-limited\n"
" effects channel has a nearly flat crest factor, so folding it in\n"
" would measure bass management rather than the music.\n"
" Loudness follows BS.1770-4 channel weighting: front channels unity,\n"
" surrounds +1.5 dB, LFE excluded.\n"
<< sep << "\n";
}
}
// ════════════════════════════════════════════════════════════════════════════
// JSON output
// ════════════════════════════════════════════════════════════════════════════
#ifdef CRETE_HAS_JSON
void print_json(const std::vector<dr::TrackResult>& tracks,
const std::string& folder_path,
const std::vector<std::string>& notes) {
json j;
j["version"] = std::string(PROGRAM_NAME) + " " + PROGRAM_VERSION;
j["folder_path"] = folder_path;
// null when no track is long enough for a DR (see dr::MIN_DR_SECONDS).
if (auto a = dr::album_dr(tracks)) j["album_dr"] = *a;
else j["album_dr"] = nullptr;
j["num_tracks"] = tracks.size();
// Integrity and selection notes for this run: failed decodes, CRC
// mismatches, truncation, the multi-stream choice. ALWAYS present, so a
// consumer can test it without first testing for the key -- an empty
// array is the positive statement "nothing was wrong", which is exactly
// what a silently damaged file used to be indistinguishable from.
//
// num_tracks counts what was MEASURED. A file that failed to decode
// contributes a note here and no track, so the two together are what
// tell a consumer that something is missing.
j["warnings"] = notes;
// Self-documenting standards map: which spec governs each reported field.
// Mirrors MAAT DROffline's per-metric tags. Per-channel momentary/short-term
// are non-ITU informative variants (BS.1770 defines them for the summed
// program only).
j["standards"] = {
{"dr_score", "TT Dynamic Range (PMF)"},
{"dr_raw", "TT Dynamic Range (PMF)"},
{"peak_dbfs", "sample peak (dBFS)"},
{"rms_dbfs", "RMS (dBFS)"},
{"max_true_peak_dbtp", "ITU-R BS.1770-4"},
{"integrated_lufs", "ITU-R BS.1770-4 / EBU R 128"},
{"max_momentary_lufs", "ITU-R BS.1770-4 (EBU 3341)"},
{"max_short_term_lufs", "ITU-R BS.1770-4 (EBU 3341)"},
{"lra_lu", "EBU Tech 3342"},
{"plr_db", "AES (TP - integrated LUFS)"},
{"psr_db", "AES (min window SPPM - short-term LUFS)"},
{"crest_factor_db", "sample peak - RMS, per-channel mean"},
{"channel_metrics.max_momentary_lufs", "non-ITU (per-channel, informative)"},
{"channel_metrics.max_short_term_lufs", "non-ITU (per-channel, informative)"},
{"dr_front_raw", "TT DR of the front L/R pair (crete, multichannel)"},
{"worst_channel", "lowest-DR scored channel index (crete, multichannel)"},
{"channel_layout", "WAVE/ITU channel order (crete)"},
{"loudness_summing", "ITU-R BS.1770-4 channel weighting"},
};
if (!tracks.empty()) {
const auto& first = tracks[0];
j["sample_rate"] = first.sample_rate;
j["channels"] = first.channels;
j["channel_layout"] = chan::layout_short(first.channels, first.channel_mask);
// Only when the mask is what described the layout, so a file the
// channel count already describes keeps its pre-0.21.0 JSON.
if (const uint32_t m = chan::effective_mask(first.channels, first.channel_mask))
j["channel_mask"] = chan::mask_string(m);
if (const char* n = chan::auro_layout(first.channels, first.channel_mask))
j["layout_name"] = n;
j["scored_channels"] = chan::scored_count(first.channels, g_lfe == dr::LfeScoring::Include,
first.channel_mask);
j["loudness_summing"] = chan::loudness_mode(first.channels, first.channel_mask);
j["bit_depth"] = first.bit_depth;
j["codec"] = first.codec;
if (!first.codec_profile.empty()) {
j["codec_profile"] = first.codec_profile;
j["immersive_bed"] = audio::profile_is_immersive(first.codec_profile);
}
// Present wherever the codec carries Dolby DRC, 0 included, so a
// result says how its numbers were produced -- as dsd_* does for DSD.
if (first.dolby_drc >= 0.0)
j["dolby_drc"] = first.dolby_drc;
j["dr_rms_mean"] = dr::rms_mean_name(g_rms_mean);
j["dr_blocks"] = dr::block_set_name(g_dr_blocks);
j["dr_lfe"] = dr::lfe_scoring_name(g_lfe);
j["dr_short"] = dr::short_tracks_name(g_short);
j["channel_mask_mode"] = channel_mask_name(g_channel_mask);
if (first.audio_stream_count > 1) {
j["audio_stream_count"] = first.audio_stream_count;
j["stream_index"] = first.stream_index;
}
if (first.codec == "DSD") {
j["dsd_mode"] = dsd::mode_name(g_dsd_opt.mode);
j["dsd_filter"] = dsd::filter_name(g_dsd_opt.filter);
j["dsd_out_rate"] = g_dsd_opt.out_rate;
// "default" | "full" | the corner in Hz, as passed; *_applied says
// whether the post-filter actually ran at this output rate.
if (dsd::is_full_bandwidth(g_dsd_opt.bandwidth) ||
g_dsd_opt.bandwidth == DSDDPCM_BW_DEFAULT)
j["dsd_bandwidth"] = dsd::bandwidth_name(g_dsd_opt.bandwidth);
else
j["dsd_bandwidth"] = g_dsd_opt.bandwidth;
j["dsd_bandwidth_applied"] = dsd::bandwidth_applies(g_dsd_opt);
}
}
json jtracks = json::array();
for (const auto& t : tracks) {
json jt;
jt["filename"] = t.filename;
jt["codec"] = t.codec;
if (!t.codec_profile.empty()) {
jt["codec_profile"] = t.codec_profile;
jt["immersive_bed"] = audio::profile_is_immersive(t.codec_profile);
}
if (t.dolby_drc >= 0.0)
jt["dolby_drc"] = t.dolby_drc;
jt["sample_rate"] = t.sample_rate;
jt["bit_depth"] = t.bit_depth;
jt["channels"] = t.channels;
jt["duration_secs"] = t.duration_secs;
if (t.audio_stream_count > 1) {
jt["audio_stream_count"] = t.audio_stream_count;
jt["stream_index"] = t.stream_index;
}
// Program streams (.vob / .aob) only: the carrier, and every audio
// stream by the ID the disc gives it. Descriptive -- see mpegps.hpp.
if (t.ps.present) {
json jp;
jp["carrier"] = t.ps.carrier;
jp["fragments"] = t.ps.fragments;
jp["mpeg"] = t.ps.mpeg;
jp["video"] = t.ps.video.empty() ? json(nullptr) : json(t.ps.video);
json ja = json::array();
for (const auto& a : t.ps.audio)
ja.push_back({{"id", mpegps::hex_id(a.first)}, {"codec", a.second}});
jp["audio_streams"] = ja;
jp["measured_stream_id"] = t.ps.measured >= 0 ? json(mpegps::hex_id(t.ps.measured))
: json(nullptr);
jp["scanned_bytes"] = t.ps.scanned;
jp["scan_complete"] = t.ps.complete;
jt["program_stream"] = jp;
}
// A track under dr::MIN_DR_SECONDS has no DR: null, not 0, and
// dr_defined says so explicitly for consumers that test a flag.
jt["dr_defined"] = t.dr_defined;
if (t.dr_defined) {
jt["dr_score"] = t.dr_score;
jt["dr_raw"] = t.dr_score_raw;
} else {
jt["dr_score"] = nullptr;
jt["dr_raw"] = nullptr;
}
jt["peak_dbfs"] = t.peak_dbfs;
jt["rms_dbfs"] = t.rms_dbfs;
jt["max_true_peak_dbtp"] = t.max_true_peak_dbtp;
jt["is_clipping"] = t.is_clipping;
jt["integrated_lufs"] = t.integrated_lufs;
jt["max_momentary_lufs"] = t.max_momentary_lufs;
jt["max_short_term_lufs"] = t.max_short_term_lufs;
jt["lra_lu"] = t.lra_lu;
jt["plr_db"] = t.plr_db;
jt["psr_db"] = t.psr_db;
jt["crest_factor_db"] = t.crest_factor_db;
jt["verdict"] = dr::verdict_string(t.verdict);
// MQA forensic verdict. Emitted for every track so downstream tools can
// flag lossy-encoded "hi-res" without re-analysing the PCM.
{
json jm;
jm["detected"] = t.mqa.datasync_found;
jm["confidence"] = t.mqa.confidence;
if (t.mqa.datasync_found) {
jm["studio"] = t.mqa.studio;
jm["original_rate"] = t.mqa.orig_rate;
jm["stream_rate"] = t.mqa.src_rate;
jm["auth_level"] = t.mqa.auth_level;
jm["render_filter"] = t.mqa.render_filter;
jm["render_bitdepth"] = t.mqa.render_bitdepth;
jm["carrier_bit"] = t.mqa.bit_position;
} else {
jm["lsb_entropy"] = t.mqa.lsb_entropy;
}
jt["mqa"] = jm;
}
jt["channel_layout"] = chan::layout_short(t.channels, t.channel_mask);
if (const uint32_t m = chan::effective_mask(t.channels, t.channel_mask))
jt["channel_mask"] = chan::mask_string(m);
if (const char* n = chan::auro_layout(t.channels, t.channel_mask))
jt["layout_name"] = n;
jt["scored_channels"] = chan::scored_count(t.channels, g_lfe == dr::LfeScoring::Include,
t.channel_mask);
// Multichannel companions to dr_score_raw. On mono/stereo dr_front_raw
// equals dr_score_raw and worst_channel is just the lower-DR channel,
// so consumers can read them unconditionally.
if (t.dr_defined) jt["dr_front_raw"] = t.dr_front_raw;
else jt["dr_front_raw"] = nullptr;
jt["worst_channel"] = t.worst_channel;
json jch = json::array();
size_t nch = t.ch_metrics.size();
for (size_t c = 0; c < nch; ++c) {
const auto& cm = t.ch_metrics[c];
json jc;
// label_long keeps the historical "Mono"/"Left"/"Right" spellings
// for 1- and 2-channel files, so the existing JSON schema is
// unchanged for every consumer that predates multichannel.
jc["label"] = chan::label_long(static_cast<unsigned>(nch), c, t.channel_mask);
jc["short_label"] = chan::label(static_cast<unsigned>(nch), c, t.channel_mask);
jc["is_lfe"] = cm.is_lfe;
jc["scored"] = cm.scored;
jc["sample_peak_dbfs"] = cm.sample_peak_dbfs;
jc["true_peak_dbtp"] = cm.true_peak_dbtp;
jc["rms_dbfs"] = cm.rms_dbfs;
if (t.dr_defined) {
jc["dr_score"] = cm.dr_score;
jc["dr_raw"] = cm.dr_raw;
} else {
jc["dr_score"] = nullptr;
jc["dr_raw"] = nullptr;
}
jc["max_momentary_lufs"] = cm.max_momentary_lufs;
jc["max_short_term_lufs"] = cm.max_short_term_lufs;
jch.push_back(std::move(jc));
}
jt["channel_metrics"] = std::move(jch);
jtracks.push_back(std::move(jt));
}
j["tracks"] = std::move(jtracks);
std::cout << j.dump(2) << "\n";
}
#endif // CRETE_HAS_JSON
// ── Usage ──────────────────────────────────────────────────────────────────
void print_usage(const char* argv0) {
std::cerr << PROGRAM_NAME << " — Zero-dependency Dynamic Range Meter\n\n"
<< "Usage: " << argv0 << " [options] <file_or_folder...>\n\n"
<< "Options:\n"
<< " -f, --format <std|foobar|ext|detail"
#ifdef CRETE_HAS_JSON
<< "|json"
#endif