moq-mux 0.9.7

Media muxers and demuxers for MoQ
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
//! Fragmented MP4 (fMP4 / CMAF).
//!
//! A widely supported file format that's also a viable wire format.
//! Each moq frame carries one moof+mdat fragment, optionally with
//! several samples packed inside. [`Wire`] is the wire-level
//! container; [`Import`] parses external fMP4 streams and [`Export`]
//! produces them.

mod export;
pub mod fragment;
mod fragmenter;
mod import;
mod muxer;

pub use export::*;
pub use fragmenter::*;
pub use import::*;
pub use muxer::*;

#[cfg(test)]
mod export_test;
#[cfg(test)]
mod import_test;

use std::{task::Poll, time::Duration};

use bytes::Bytes;
use hang::catalog::{AudioCodec, AudioConfig, VideoCodec, VideoConfig};
use mp4_atom::Atom;

use moq_net::Timestamp;

use crate::container::{Container, Frame};

#[derive(Debug, Clone, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
	#[error("mp4: {0}")]
	Mp4(std::sync::Arc<mp4_atom::Error>),

	#[error("moq: {0}")]
	Moq(#[from] moq_net::Error),

	#[error("flac: {0}")]
	Flac(#[from] crate::codec::flac::Error),

	#[error("opus: {0}")]
	Opus(#[from] crate::codec::opus::Error),

	#[error("missing keyframe: a group must open on a keyframe")]
	MissingKeyframe(#[from] crate::container::MissingKeyframe),

	#[error("timestamp overflow")]
	TimestampOverflow(#[from] moq_net::TimeOverflow),

	#[error("no traf in moof")]
	NoTraf,

	#[error("no tfdt in traf")]
	NoTfdt,

	#[error("PTS overflow")]
	PtsOverflow,

	#[error("missing moof")]
	NoMoof,

	#[error("missing mdat")]
	NoMdat,

	#[error("missing moov")]
	NoMoov,

	#[error("no tracks in moov")]
	NoTracks,

	#[error("multiple tracks in moov, use Trak instead")]
	MultipleTracks,

	#[error("can't synthesize CMAF init for {0}")]
	UnsupportedSynthesis(String),

	#[error("subtitle tracks are not supported")]
	UnsupportedSubtitle,

	#[error("unknown track handler: {0:?}")]
	UnknownTrackHandler([u8; 4]),

	#[error("missing codec")]
	MissingCodec,

	#[error("multiple codecs")]
	MultipleCodecs,

	#[error("unknown codec: {0:?}")]
	UnknownCodec(mp4_atom::FourCC),

	#[error("unsupported codec: {0:?}")]
	UnsupportedCodec(Box<mp4_atom::Codec>),

	#[error("unsupported codec: MPEG2")]
	UnsupportedMpeg2,

	/// An AAC sample entry needs DecoderSpecificInfo to identify its codec profile.
	#[error("AAC sample entry missing DecoderSpecificInfo")]
	MissingDecoderSpecific,

	#[error("duplicate moof")]
	DuplicateMoof,

	#[error("missing trun")]
	MissingTrun,

	#[error("missing tfdt")]
	MissingTfdt,

	#[error("video codec {0} needs a description (codec config record) to synthesize a CMAF init")]
	MissingVideoDescription(String),

	#[error("video track {0} missing in catalog")]
	MissingVideoTrack(String),

	/// A synthesized video track has no usable encoded dimensions.
	#[error("missing video dimensions for codec: {0}")]
	MissingVideoDimensions(String),

	#[error("audio track {0} missing in catalog")]
	MissingAudioTrack(String),

	#[error("invalid data offset")]
	InvalidDataOffset,

	#[error("unknown track {0}")]
	UnknownTrack(u32),

	#[error("no keyframe at start of group")]
	NoKeyframe,

	#[error("track sample range {start}..{end} is out of bounds of mdat (len {len})")]
	SampleRangeOutOfBounds { start: usize, end: usize, len: usize },

	#[error("no catalog snapshot")]
	NoCatalogSnapshot,

	#[error("encode_fragment called with no frames")]
	NoFrames,

	#[error("audio codec {0} needs a description (AudioSpecificConfig) to synthesize a CMAF init")]
	MissingAudioDescription(String),

	#[error("multi-sample fragment has a non-final sample with no duration; DTS is unrecoverable")]
	MissingSampleDuration,

	/// `mdhd.timescale` is a 32-bit field, so a larger scale would reach the init segment
	/// truncated while the fragments kept the full value, putting them on different timelines.
	#[error("timescale {0} does not fit the 32-bit mdhd field")]
	TimescaleTooLarge(u64),

	/// A `Cmaf` rendition's init passes through from the catalog at its own scale, so
	/// [`Muxer::with_timescale`] can't move it without desynchronising it from the fragments.
	#[error("a CMAF rendition's timescale comes from its init segment and can't be overridden")]
	TimescaleOverride,

	/// A sample duration is a 32-bit `trun` field. A larger value would wrap in the media
	/// while the fragment metadata kept the full duration, putting them on different timelines.
	#[error("sample duration {0} does not fit the 32-bit trun field")]
	SampleDurationTooLarge(u64),

	/// A positive sample duration must occupy at least one tick in the output timescale.
	#[error("sample duration is shorter than one tick at timescale {0}")]
	SampleDurationTooSmall(u64),

	/// Repeatedly flooring fractional sample ticks would make the decode timeline drift.
	#[error("sample duration is not exactly representable at timescale {0}")]
	SampleDurationInexact(u64),

	/// Presentation timestamps do not reveal decode duration for reordered video.
	#[error("duration-less video needs stated durations or presentation-ordered inference")]
	MissingVideoDuration,
}

impl From<mp4_atom::Error> for Error {
	fn from(err: mp4_atom::Error) -> Self {
		Error::Mp4(std::sync::Arc::new(err))
	}
}

pub type Result<T> = std::result::Result<T, Error>;

/// CMAF container: encodes/decodes a single track's moof+mdat fragments.
///
/// Build from a CMAF init segment with [`Wire::from_init`], or wrap a
/// pre-extracted [`mp4_atom::Trak`] directly with [`Wire::new`].
///
/// The [`mp4_atom::Trak`] is heap-allocated so that embedding `Wire`
/// in other enums (e.g. [`catalog::hang::Container`](crate::catalog::hang::Container))
/// doesn't bloat unrelated variants.
pub struct Wire {
	trak: Box<mp4_atom::Trak>,
}

impl Wire {
	/// Wrap an already-parsed track.
	pub fn new(trak: mp4_atom::Trak) -> Self {
		Self { trak: Box::new(trak) }
	}

	/// Parse a CMAF init segment (ftyp+moov), extracting the single track.
	pub fn from_init(init_data: &[u8]) -> Result<Self> {
		use mp4_atom::DecodeMaybe;

		let mut cursor = std::io::Cursor::new(init_data);
		while let Some(atom) = mp4_atom::Any::decode_maybe(&mut cursor)? {
			if let mp4_atom::Any::Moov(mut moov) = atom {
				return match moov.trak.len() {
					1 => Ok(Self::new(moov.trak.remove(0))),
					0 => Err(Error::NoTracks),
					_ => Err(Error::MultipleTracks),
				};
			}
		}
		Err(Error::NoMoov)
	}

	pub fn trak(&self) -> &mp4_atom::Trak {
		&self.trak
	}
}

impl Container for Wire {
	type Error = Error;

	fn write(&self, group: &mut moq_net::group::Producer, frames: &[Frame]) -> std::result::Result<(), Self::Error> {
		let timescale = moq_net::Timescale::new(self.trak.mdia.mdhd.timescale as u64)?;
		let track_id = self.trak.tkhd.track_id;
		encode(group, frames, timescale, track_id)
	}

	fn poll_read(
		&self,
		group: &mut moq_net::group::Consumer,
		waiter: &kio::Waiter,
	) -> Poll<std::result::Result<Option<Vec<Frame>>, Self::Error>> {
		use std::task::ready;

		let Some(frame) = ready!(group.poll_read_frame(waiter)?) else {
			return Poll::Ready(Ok(None));
		};

		let timescale = moq_net::Timescale::new(self.trak.mdia.mdhd.timescale as u64)?;
		Poll::Ready(Ok(Some(decode(frame.payload, timescale)?)))
	}
}

pub(crate) fn decode(data: Bytes, timescale: moq_net::Timescale) -> Result<Vec<Frame>> {
	use mp4_atom::DecodeMaybe;

	let mut cursor = std::io::Cursor::new(&data);
	let mut moof = None;
	let mut mdat_data = None;

	while let Some(atom) = mp4_atom::Any::decode_maybe(&mut cursor)? {
		match atom {
			mp4_atom::Any::Moof(m) => moof = Some(m),
			mp4_atom::Any::Mdat(m) => mdat_data = Some(m.data),
			_ => {}
		}
	}

	let moof = moof.ok_or(Error::NoMoof)?;
	let mdat_data = mdat_data.ok_or(Error::NoMdat)?;
	let traf = moof.traf.first().ok_or(Error::NoTraf)?;
	let tfdt = traf.tfdt.as_ref().ok_or(Error::NoTfdt)?;
	let base_dts = tfdt.base_media_decode_time;

	let default_size = traf.tfhd.default_sample_size;
	let default_duration = traf.tfhd.default_sample_duration;

	// DTS is reconstructed by accumulating each sample's duration. A non-final sample
	// with no resolvable duration would leave every following sample stuck at the same
	// DTS, silently collapsing their timestamps, so reject that fragment instead.
	let total_samples: usize = traf.trun.iter().map(|t| t.entries.len()).sum();

	let mut frames = Vec::new();
	let mut offset = 0usize;
	let mut dts = base_dts;
	let mut sample_index = 0usize;

	for trun in &traf.trun {
		for entry in &trun.entries {
			let size = entry.size.or(default_size).unwrap_or(0) as usize;
			let end = offset + size;

			if end > mdat_data.len() {
				return Err(Error::SampleRangeOutOfBounds {
					start: offset,
					end,
					len: mdat_data.len(),
				});
			}

			let cts = entry.cts.unwrap_or_default() as i64;
			let pts = dts.checked_add_signed(cts).ok_or(Error::PtsOverflow)?;
			// Preserve the fmp4 track's native scale through the pipeline.
			let timestamp = Timestamp::new(pts, timescale)?;
			let payload = Bytes::copy_from_slice(&mdat_data[offset..end]);
			let flags = entry.flags.unwrap_or(0);
			// depends_on_no_other (bits 24-25 == 0x2) means keyframe
			let keyframe = (flags >> 24) & 0x3 == 0x2;

			// Carry the sample-duration through at the track's scale when present, so
			// the jitter buffer can use it and an exporter can write it back.
			let sample_duration = entry.duration.or(default_duration).filter(|d| *d != 0);

			// The last sample needs no duration (nothing follows it to time), but any
			// earlier sample without one makes the rest of the fragment's DTS ambiguous.
			let is_last = sample_index + 1 == total_samples;
			if sample_duration.is_none() && !is_last {
				return Err(Error::MissingSampleDuration);
			}

			let duration = sample_duration
				.map(|d| Timestamp::new(d as u64, timescale))
				.transpose()?;

			frames.push(Frame {
				timestamp,
				payload,
				keyframe,
				duration,
			});

			offset = end;
			dts += sample_duration.unwrap_or(0) as u64;
			sample_index += 1;
		}
	}

	Ok(frames)
}

pub(crate) fn encode(
	group: &mut moq_net::group::Producer,
	frames: &[Frame],
	timescale: moq_net::Timescale,
	track_id: u32,
) -> Result<()> {
	if frames.is_empty() {
		return Ok(());
	}

	let sequence_number = group.frame_count() as u32;
	let info = FragmentInfo {
		track_id,
		timescale,
		sequence_number,
	};
	let bytes = encode_fragment(info, frames)?;
	// The fragment may carry several samples; the net frame's timestamp is the
	// fragment's earliest presentation time so a relay can order it.
	let mut writer = group.create_frame(moq_net::frame::Info {
		size: bytes.len() as u64,
		timestamp: frames[0].timestamp,
	})?;
	writer.write(bytes)?;
	writer.finish()?;

	Ok(())
}

/// Which track a fragment belongs to, and where it sits in that track.
///
/// Bundled rather than passed positionally because `track_id` and `sequence_number` are both
/// `u32`, so a swapped pair would still compile.
#[derive(Debug, Clone, Copy)]
pub(crate) struct FragmentInfo {
	/// The `tfhd` track id, which must match the one the init segment declares.
	pub track_id: u32,
	/// The track's media timescale, which every timestamp is re-expressed at.
	pub timescale: moq_net::Timescale,
	/// The `mfhd` sequence number, informative only.
	pub sequence_number: u32,
}

/// Encode a single-traf moof+mdat fragment anchored at its own first frame.
///
/// The fragment stands alone: its `tfdt` is `frames[0]`'s presentation time, so it decodes
/// without reference to whatever came before it. To cut a stream into one fragment per
/// frame, on a single continuous decode timeline, use [`Fragmenter`].
///
/// Returns an empty `Bytes` when `frames` is empty.
pub(crate) fn encode_fragment(info: FragmentInfo, frames: &[Frame]) -> Result<Bytes> {
	let Some(first) = frames.first() else {
		return Ok(Bytes::new());
	};
	encode_at(info, base_ticks(first, info.timescale)?, frames)
}

/// A frame's presentation time as a tick count at the track's timescale.
///
/// When the importer preserved the source scale (the common passthrough case) this is a no-op;
/// otherwise it's a single rescale rather than the legacy `micros * scale / 1_000_000`
/// round-trip.
fn base_ticks(frame: &Frame, timescale: moq_net::Timescale) -> Result<u64> {
	timestamp_ticks(frame.timestamp, timescale)
}

/// Round an absolute timestamp to its nearest tick at the output scale.
fn timestamp_ticks(timestamp: Timestamp, timescale: moq_net::Timescale) -> Result<u64> {
	let source_scale = u128::from(timestamp.scale().as_u64());
	let scaled = u128::from(timestamp.value()) * u128::from(timescale.as_u64());
	let ticks = (scaled + source_scale / 2) / source_scale;
	u64::try_from(ticks).map_err(|_| Error::PtsOverflow)
}

/// Encode a single-traf moof+mdat fragment whose decode timeline starts at `base_dts` ticks.
///
/// Performs the two-pass encoding required by ISO/IEC 14496-12: encode once
/// to learn the moof size, then again with `trun.data_offset` pointing past
/// the moof and mdat header.
///
/// `base_dts` is already at the track's timescale, so it is the same unit the `trun` sample
/// durations are written in. That's what lets [`Fragmenter`] carry a timeline across
/// calls without a rounding step between them.
///
/// Frames arrive in decode order carrying presentation timestamps. DTS is authored by
/// accumulating sample durations from `base_dts`, and each sample stores `PTS - DTS` as its
/// signed composition offset, so a reordered frame keeps its presentation time even when the
/// fragment holds a single sample.
///
/// Returns an empty `Bytes` when `frames` is empty.
fn encode_at(info: FragmentInfo, base_dts: u64, frames: &[Frame]) -> Result<Bytes> {
	let FragmentInfo {
		track_id,
		timescale,
		sequence_number,
	} = info;

	use mp4_atom::Encode;

	if frames.is_empty() {
		return Ok(Bytes::new());
	}

	let mut dts = base_dts;

	let entries: Vec<_> = frames
		.iter()
		.map(|f| {
			let flags = if f.keyframe { 0x0200_0000 } else { 0x0001_0000 };
			// Write the sample-duration back at the track's scale when we know it, so
			// fMP4 -> fMP4 round-trips it. Frames without one stay byte-identical.
			let duration = f.duration.map(|d| trun_duration(d, timescale)).transpose()?;
			let pts = i128::from(timestamp_ticks(f.timestamp, timescale)?);
			let cts = pts - i128::from(dts);
			let cts = i32::try_from(cts).map_err(|_| Error::PtsOverflow)?;

			// Frame timestamps are PTS while sample order is decode order. Author DTS
			// by accumulating durations and store PTS-DTS as the signed CTS.
			if let Some(duration) = duration {
				dts = dts.checked_add(u64::from(duration)).ok_or(Error::PtsOverflow)?;
			}

			Ok(mp4_atom::TrunEntry {
				duration,
				size: Some(f.payload.len() as u32),
				flags: Some(flags),
				cts: (cts != 0).then_some(cts),
			})
		})
		.collect::<Result<_>>()?;

	let mdat_data: Vec<u8> = frames.iter().flat_map(|f| f.payload.iter().copied()).collect();

	let build_moof = |data_offset| mp4_atom::Moof {
		mfhd: mp4_atom::Mfhd { sequence_number },
		traf: vec![mp4_atom::Traf {
			tfhd: mp4_atom::Tfhd {
				track_id,
				..Default::default()
			},
			tfdt: Some(mp4_atom::Tfdt {
				base_media_decode_time: base_dts,
			}),
			trun: vec![mp4_atom::Trun {
				data_offset: Some(data_offset),
				entries: entries.clone(),
			}],
			..Default::default()
		}],
	};

	// First pass to learn the moof size.
	let mut buf = Vec::new();
	build_moof(0).encode(&mut buf)?;
	let moof_size = buf.len();

	// Second pass with data_offset = moof_size + 8 (mdat header).
	buf.clear();
	build_moof((moof_size + 8) as i32).encode(&mut buf)?;

	let mdat = mp4_atom::Mdat { data: mdat_data };
	mdat.encode(&mut buf)?;

	Ok(Bytes::from(buf))
}

/// Convert a duration to the exact value stored in a 32-bit `trun` sample-duration field.
fn trun_duration(duration: Timestamp, timescale: moq_net::Timescale) -> Result<u32> {
	let source_timescale = duration.scale().as_u64();
	let output_timescale = timescale.as_u64();
	let scaled = u128::from(duration.value()) * u128::from(output_timescale);
	let ticks = scaled / u128::from(source_timescale);
	if !duration.is_zero() && ticks == 0 {
		return Err(Error::SampleDurationTooSmall(timescale.as_u64()));
	}
	if scaled % u128::from(source_timescale) != 0 {
		return Err(Error::SampleDurationInexact(output_timescale));
	}
	u32::try_from(ticks).map_err(|_| Error::SampleDurationTooLarge(u64::try_from(ticks).unwrap_or(u64::MAX)))
}

/// Synthesize a CMAF `Trak` for a video rendition that has no init segment.
///
/// Used by the fMP4 exporter when its source is a `Container::Legacy` track
/// (Avc3/Hev1/etc. importers that publish raw codec bitstreams). H.264/H.265
/// need their out-of-band configuration record (`description`), e.g. because the
/// Avc1 / Hvc1 transform has finished building it from inline parameter sets.
/// VP8 carries no out-of-band config, so `description` is `None` for it.
pub(crate) fn synthesize_video_trak(
	track_id: u32,
	timescale: u64,
	config: &VideoConfig,
	description: Option<&[u8]>,
) -> Result<mp4_atom::Trak> {
	if !matches!(
		config.codec,
		VideoCodec::H264(_) | VideoCodec::H265(_) | VideoCodec::AV1(_) | VideoCodec::VP8 | VideoCodec::VP9(_)
	) {
		return Err(Error::UnsupportedSynthesis(format!("video codec {:?}", config.codec)));
	}

	let width = u16::try_from(
		config
			.coded_width
			.ok_or_else(|| Error::MissingVideoDimensions(config.codec.to_string()))?,
	)
	.map_err(|_| Error::MissingVideoDimensions(config.codec.to_string()))?;
	let height = u16::try_from(
		config
			.coded_height
			.ok_or_else(|| Error::MissingVideoDimensions(config.codec.to_string()))?,
	)
	.map_err(|_| Error::MissingVideoDimensions(config.codec.to_string()))?;
	if width == 0 || height == 0 {
		return Err(Error::MissingVideoDimensions(config.codec.to_string()));
	}
	let visual = mp4_atom::Visual {
		data_reference_index: 1,
		width,
		height,
		..Default::default()
	};

	// Codecs that carry an out-of-band config record require `description`.
	let require_description = || description.ok_or_else(|| Error::MissingVideoDescription(config.codec.to_string()));

	let sample_entry = match &config.codec {
		VideoCodec::H264(_) => {
			let mut cursor = std::io::Cursor::new(require_description()?);
			let avcc = mp4_atom::Avcc::decode_body(&mut cursor).map_err(Error::from)?;
			mp4_atom::Codec::from(mp4_atom::Avc1 {
				visual,
				avcc,
				..Default::default()
			})
		}
		VideoCodec::H265(h265) => {
			let mut cursor = std::io::Cursor::new(require_description()?);
			let hvcc = mp4_atom::Hvcc::decode_body(&mut cursor).map_err(Error::from)?;
			// `in_band` (catalog) ↔ hev1 sample entry; otherwise hvc1.
			if h265.in_band {
				mp4_atom::Codec::from(mp4_atom::Hev1 {
					visual,
					hvcc,
					..Default::default()
				})
			} else {
				mp4_atom::Codec::from(mp4_atom::Hvc1 {
					visual,
					hvcc,
					..Default::default()
				})
			}
		}
		VideoCodec::AV1(av1) => mp4_atom::Codec::from(mp4_atom::Av01 {
			visual,
			av1c: crate::codec::av1::av1c_from_av1(av1),
			..Default::default()
		}),
		VideoCodec::VP8 => mp4_atom::Codec::from(mp4_atom::Vp08 {
			visual,
			vpcc: crate::codec::vp8::vpcc(),
			..Default::default()
		}),
		VideoCodec::VP9(vp9) => mp4_atom::Codec::from(mp4_atom::Vp09 {
			visual,
			vpcc: crate::codec::vp9::vpcc(vp9),
			..Default::default()
		}),
		other => unreachable!("unsupported codecs rejected before geometry synthesis: {other:?}"),
	};

	Ok(build_video_trak(
		track_id,
		mdhd_timescale(timescale)?,
		sample_entry,
		width,
		height,
	))
}

/// Synthesize a CMAF `Trak` for an audio rendition that has no init segment.
pub(crate) fn synthesize_audio_trak(track_id: u32, timescale: u64, config: &AudioConfig) -> Result<mp4_atom::Trak> {
	use mp4_atom::Decode;

	let audio = mp4_atom::Audio {
		data_reference_index: 1,
		channel_count: config.channel_count as u16,
		sample_size: 16,
		sample_rate: mp4_atom::FixedPoint::from(config.sample_rate as u16),
	};

	let sample_entry = match &config.codec {
		AudioCodec::Opus => {
			let pre_skip = match &config.description {
				Some(description) => {
					let mut description = description.as_ref();
					crate::codec::opus::Config::parse(&mut description)?.pre_skip
				}
				None => 0,
			};
			mp4_atom::Codec::from(mp4_atom::Opus {
				audio,
				dops: mp4_atom::Dops {
					output_channel_count: config.channel_count as u8,
					pre_skip,
					input_sample_rate: config.sample_rate,
					output_gain: 0,
				},
				btrt: None,
			})
		}
		AudioCodec::AAC(_) => {
			// The catalog `description` is the AudioSpecificConfig (set by the TS
			// importer via aac::Config::encode, or carried over from a CMAF source).
			// mp4_atom models the esds DecoderSpecific as the parsed
			// AudioSpecificConfig, so decode the blob back into that shape.
			let description = config
				.description
				.as_ref()
				.ok_or_else(|| Error::MissingAudioDescription(config.codec.to_string()))?;
			let mut cursor = std::io::Cursor::new(description.as_ref());
			let dec_specific = mp4_atom::esds::DecoderSpecific::decode(&mut cursor)?;

			// Safari and AVFoundation reject an AAC track whose DecoderConfigDescriptor is all
			// zeros: they endOfStream("decode") on the *init* append, which leaves the
			// ManagedMediaSource ended and every later audio and video append failing. The
			// catalog bitrate is optional and real publishers omit it, so fall back to the
			// AAC-LC values ffmpeg and the iTunes encoders write. A zero or wider-than-u32
			// bitrate takes the fallback as well, since writing it back would rebuild the
			// all-zero descriptor this exists to avoid.
			let bitrate = config.bitrate.and_then(|b| u32::try_from(b).ok()).filter(|b| *b > 0);
			let (max_bitrate, avg_bitrate) = match bitrate {
				Some(bitrate) => (bitrate, bitrate),
				None => (256_000, 128_000),
			};
			mp4_atom::Codec::from(mp4_atom::Mp4a {
				audio,
				esds: mp4_atom::Esds {
					es_desc: mp4_atom::esds::EsDescriptor {
						// ISO/IEC 14496-14 §5.6: ES_ID is 0 in an MP4 file (the track id carries identity).
						es_id: 0,
						dec_config: mp4_atom::esds::DecoderConfig {
							object_type_indication: 0x40, // MPEG-4 AAC
							stream_type: 0x05,            // audio
							up_stream: 0,
							// 24 KiB, the decoder buffer those same encoders declare.
							buffer_size_db: mp4_atom::u24::from([0x00, 0x60, 0x00]),
							max_bitrate,
							avg_bitrate,
							dec_specific: Some(dec_specific),
						},
						sl_config: Default::default(),
					},
				},
				btrt: None,
				taic: None,
			})
		}
		AudioCodec::Flac => {
			// The catalog `description` is the FLAC header (`fLaC` marker + STREAMINFO).
			// Parse it back into the STREAMINFO fields the `dfLa` box stores.
			let description = config
				.description
				.as_ref()
				.ok_or_else(|| Error::MissingAudioDescription(config.codec.to_string()))?;
			let info = crate::codec::flac::Config::parse(&mut description.as_ref())?;

			let stream_info = mp4_atom::FlacMetadataBlock::StreamInfo {
				minimum_block_size: info.min_block_size,
				maximum_block_size: info.max_block_size,
				// Frame sizes are 24-bit; clamp defensively so the conversion can't fail.
				minimum_frame_size: info.min_frame_size.min(0xFF_FFFF).try_into().expect("fits in u24"),
				maximum_frame_size: info.max_frame_size.min(0xFF_FFFF).try_into().expect("fits in u24"),
				sample_rate: info.sample_rate,
				num_channels_minus_one: info.channel_count.saturating_sub(1) as u8,
				bits_per_sample_minus_one: info.bits_per_sample.saturating_sub(1) as u8,
				number_of_interchannel_samples: info.total_samples,
				md5_checksum: info.md5.to_vec(),
			};

			mp4_atom::Codec::from(mp4_atom::Flac {
				audio,
				dfla: mp4_atom::Dfla {
					blocks: vec![stream_info],
				},
			})
		}
		other => return Err(Error::UnsupportedSynthesis(format!("audio codec {:?}", other))),
	};

	Ok(build_audio_trak(track_id, mdhd_timescale(timescale)?, sample_entry))
}

/// All-ones: the ISO/IEC 14496-12 spelling of "duration not known up front", which is always
/// the case for the live fragmented streams synthesized here. Zero reads as an empty file to a
/// strict parser, and VLC refuses to play one.
const UNKNOWN_DURATION: u64 = u64::MAX;

fn build_video_trak(
	track_id: u32,
	timescale: u32,
	sample_entry: mp4_atom::Codec,
	width: u16,
	height: u16,
) -> mp4_atom::Trak {
	mp4_atom::Trak {
		tkhd: mp4_atom::Tkhd {
			track_id,
			enabled: true,
			// track_in_movie. A player is entitled to skip a track the presentation doesn't
			// claim, and the flags field is 0x000001 rather than 0x000003 without it.
			in_movie: true,
			duration: UNKNOWN_DURATION,
			width: mp4_atom::FixedPoint::from(width),
			height: mp4_atom::FixedPoint::from(height),
			..Default::default()
		},
		mdia: build_mdia(timescale, b"vide", true, sample_entry),
		..Default::default()
	}
}

fn build_audio_trak(track_id: u32, timescale: u32, sample_entry: mp4_atom::Codec) -> mp4_atom::Trak {
	mp4_atom::Trak {
		tkhd: mp4_atom::Tkhd {
			track_id,
			enabled: true,
			in_movie: true,
			duration: UNKNOWN_DURATION,
			// Full volume (8.8 fixed point). The default is 0, which is a muted track, and
			// only an audio track carries a meaningful value.
			volume: mp4_atom::FixedPoint::from(1),
			..Default::default()
		},
		mdia: build_mdia(timescale, b"soun", false, sample_entry),
		..Default::default()
	}
}

/// Assemble a fragmented init segment (ftyp + moov) around already-built traks.
///
/// `ftyp` is the one a passed-through CMAF init carried, if any; otherwise a plain `isom` one
/// is synthesized. The `mvhd` is ours either way, so it declares the unknown duration and the
/// movie timescale of the assembled init rather than of whatever source a trak came from.
/// [`extract_init`] normalizes a passed-through trak to match.
pub(crate) fn encode_init(
	ftyp: Option<mp4_atom::Ftyp>,
	traks: Vec<mp4_atom::Trak>,
	trexs: Vec<mp4_atom::Trex>,
) -> Result<Bytes> {
	use mp4_atom::Encode;

	let ftyp = ftyp.unwrap_or(mp4_atom::Ftyp {
		major_brand: b"isom".into(),
		minor_version: 0x200,
		compatible_brands: vec![b"isom".into(), b"iso6".into(), b"mp41".into()],
	});
	let timescale = traks.first().map(|t| t.mdia.mdhd.timescale).unwrap_or(1000);
	let next_track_id = traks.iter().map(|t| t.tkhd.track_id).max().unwrap_or(0) + 1;

	let moov = mp4_atom::Moov {
		mvhd: mp4_atom::Mvhd {
			timescale,
			duration: UNKNOWN_DURATION,
			// Normal playback rate and full volume (16.16 and 8.8 fixed point). Both default
			// to 0, which declares a stopped, muted presentation.
			rate: mp4_atom::FixedPoint::from(1),
			volume: mp4_atom::FixedPoint::from(1),
			// The next id a track could take, so it must be past every one already present.
			next_track_id,
			..Default::default()
		},
		trak: traks,
		mvex: (!trexs.is_empty()).then(|| mp4_atom::Mvex {
			trex: trexs,
			..Default::default()
		}),
		..Default::default()
	};

	let mut buf = Vec::new();
	ftyp.encode(&mut buf)?;
	moov.encode(&mut buf)?;
	Ok(Bytes::from(buf))
}

/// Narrow a media timescale to the 32-bit `mdhd` field, rejecting what would truncate.
///
/// `moq_net::Timescale` permits the whole QUIC varint range, so a caller-supplied scale can be
/// wider than the field. Truncating would put the init segment and the fragments on different
/// timelines, silently, so refuse instead.
fn mdhd_timescale(timescale: u64) -> Result<u32> {
	u32::try_from(timescale).map_err(|_| Error::TimescaleTooLarge(timescale))
}

fn build_mdia(timescale: u32, handler: &[u8; 4], is_video: bool, sample_entry: mp4_atom::Codec) -> mp4_atom::Mdia {
	mp4_atom::Mdia {
		mdhd: mp4_atom::Mdhd {
			timescale,
			..Default::default()
		},
		hdlr: mp4_atom::Hdlr {
			handler: mp4_atom::FourCC::new(handler),
			name: String::new(),
		},
		minf: mp4_atom::Minf {
			vmhd: is_video.then(mp4_atom::Vmhd::default),
			smhd: (!is_video).then(mp4_atom::Smhd::default),
			dinf: mp4_atom::Dinf {
				dref: mp4_atom::Dref {
					urls: vec![mp4_atom::Url::default()],
				},
			},
			stbl: mp4_atom::Stbl {
				stsd: mp4_atom::Stsd {
					codecs: vec![sample_entry],
				},
				..Default::default()
			},
			..Default::default()
		},
	}
}

/// Default video timescale when the catalog doesn't supply one.
///
/// Used by the fMP4 exporter when synthesizing an init segment for a Legacy or LOC source.
/// Prefer `framerate * 1000`, then the common NTSC denominator, an exact scale for the
/// nanosecond-rounded cadence, and finally the highest safe approximate scale.
///
/// A framerate that scales to less than one tick takes the fallback too: zero and negative land
/// on 0 through `as u64`, which is not a timescale anything accepts, and a non-finite one is
/// filtered out before the cast, since infinity would saturate to `u64::MAX`, past the varint
/// range a `Timescale` holds.
pub(crate) fn default_video_timescale(config: &VideoConfig) -> u64 {
	usable_video_framerate(config)
		.and_then(select_video_timescale)
		.unwrap_or(90_000)
}

/// A finite catalog framerate with a synthesized scale and duration that fit their MP4 fields.
pub(crate) fn usable_video_framerate(config: &VideoConfig) -> Option<f64> {
	config
		.framerate
		.filter(|fps| fps.is_finite() && *fps > 0.0 && (*fps * 1000.0) as u64 > 0)
		.filter(|fps| select_video_timescale(*fps).is_some())
}

/// Choose a scale that represents the rounded cadence without overflowing `trun` duration.
fn select_video_timescale(framerate: f64) -> Option<u64> {
	let preferred = (framerate * 1000.0) as u64;

	let frame = Duration::from_secs_f64(1.0 / framerate);
	for timescale in [preferred, (framerate * 1001.0).round() as u64] {
		if duration_fits_trun(frame, timescale) {
			return Some(timescale);
		}
	}

	const NANOS_PER_SECOND: u128 = 1_000_000_000;
	let exact = NANOS_PER_SECOND / gcd(frame.as_nanos(), NANOS_PER_SECOND);
	let exact = u64::try_from(exact).ok()?;
	if duration_fits_trun(frame, exact) {
		return Some(exact);
	}
	if let Some(timescale) = rational_timescale(frame) {
		return Some(timescale);
	}

	let max_scale = u128::from(u32::MAX)
		.checked_mul(NANOS_PER_SECOND)?
		.checked_div(frame.as_nanos())?
		.min(u128::from(u32::MAX));
	let max_scale = u64::try_from(max_scale).ok()?;
	duration_fits_trun(frame, max_scale).then_some(max_scale)
}

/// Find a small rational scale whose rounded cadence stays within one nanosecond.
fn rational_timescale(duration: Duration) -> Option<u64> {
	const NANOS_PER_SECOND: u128 = 1_000_000_000;
	let mut numerator = duration.as_nanos();
	let mut denominator = NANOS_PER_SECOND;
	let (mut previous_ticks, mut ticks) = (0_u128, 1_u128);
	let (mut previous_scale, mut scale) = (1_u128, 0_u128);

	while denominator != 0 {
		let coefficient = numerator / denominator;
		let next_ticks = coefficient.checked_mul(ticks)?.checked_add(previous_ticks)?;
		let next_scale = coefficient.checked_mul(scale)?.checked_add(previous_scale)?;
		if next_ticks > u128::from(u32::MAX) || next_scale > u128::from(u32::MAX) {
			break;
		}

		let candidate = u64::try_from(next_scale).ok()?;
		if duration_fits_trun(duration, candidate) {
			return Some(candidate);
		}

		(previous_ticks, ticks) = (ticks, next_ticks);
		(previous_scale, scale) = (scale, next_scale);
		(numerator, denominator) = (denominator, numerator % denominator);
	}

	None
}

/// Whether the scale represents the rounded cadence and keeps its sample duration 32-bit.
fn duration_fits_trun(duration: Duration, timescale: u64) -> bool {
	timescale > 0 && rounded_duration_ticks(duration, timescale).is_some_and(|ticks| u32::try_from(ticks).is_ok())
}

/// Convert a rounded duration to ticks when it is within one nanosecond of an exact tick.
fn rounded_duration_ticks(duration: Duration, timescale: u64) -> Option<u64> {
	const NANOS_PER_SECOND: u128 = 1_000_000_000;
	let scaled = duration.as_nanos().checked_mul(u128::from(timescale))?;
	let rounded = scaled.checked_add(NANOS_PER_SECOND / 2)? / NANOS_PER_SECOND;
	let exact = rounded.checked_mul(NANOS_PER_SECOND)?;
	if scaled.abs_diff(exact) > u128::from(timescale) {
		return None;
	}
	u64::try_from(rounded).ok()
}

/// Greatest common divisor for reducing exact timestamp ratios.
fn gcd(mut a: u128, mut b: u128) -> u128 {
	while b != 0 {
		(a, b) = (b, a % b);
	}
	a
}

/// The decode timeline a fragment actually carries: its `tfdt` and each sample's composition
/// offset. This is what a player reads, as opposed to the PTS [`decode`] reconstructs from it.
#[cfg(test)]
pub(crate) fn timeline(fragment: &Bytes) -> (u64, Vec<i32>) {
	let traf = first_traf(fragment);
	let cts = traf.trun[0].entries.iter().map(|e| e.cts.unwrap_or_default()).collect();
	(traf.tfdt.as_ref().unwrap().base_media_decode_time, cts)
}

/// How long each sample in a fragment claims to last, as written into its `trun`.
#[cfg(test)]
pub(crate) fn sample_durations(fragment: &Bytes) -> Vec<Option<u32>> {
	first_traf(fragment).trun[0]
		.entries
		.iter()
		.map(|e| e.duration)
		.collect()
}

#[cfg(test)]
fn first_traf(fragment: &Bytes) -> mp4_atom::Traf {
	use mp4_atom::DecodeMaybe;

	let mut cursor = std::io::Cursor::new(fragment.as_ref());
	while let Some(atom) = mp4_atom::Any::decode_maybe(&mut cursor).unwrap() {
		if let mp4_atom::Any::Moof(moof) = atom {
			return moof.traf.into_iter().next().expect("a traf");
		}
	}
	panic!("no moof");
}

#[cfg(test)]
mod tests {
	use super::*;

	fn ts(micros: u64) -> Timestamp {
		Timestamp::from_micros(micros).unwrap()
	}

	fn info(track_id: u32, timescale: moq_net::Timescale, sequence_number: u32) -> FragmentInfo {
		FragmentInfo {
			track_id,
			timescale,
			sequence_number,
		}
	}

	// An AAC-LC / 44.1 kHz / stereo AudioSpecificConfig, the catalog `description` shape.
	fn aac_config(bitrate: Option<u64>) -> AudioConfig {
		let mut config = AudioConfig::new(AudioCodec::AAC(hang::catalog::AAC { profile: 2 }), 44_100, 2);
		config.description = Some(Bytes::from_static(&[0x12, 0x10]));
		config.bitrate = bitrate;
		config
	}

	/// The moov an encoded init segment carries, so a test asserts on what a player parses
	/// rather than on the struct that went in.
	fn moov(init: &Bytes) -> mp4_atom::Moov {
		use mp4_atom::DecodeMaybe;

		let mut cursor = std::io::Cursor::new(init.as_ref());
		while let Some(atom) = mp4_atom::Any::decode_maybe(&mut cursor).unwrap() {
			if let mp4_atom::Any::Moov(moov) = atom {
				return moov;
			}
		}
		panic!("no moov");
	}

	fn dec_config(trak: &mp4_atom::Trak) -> mp4_atom::esds::DecoderConfig {
		match &trak.mdia.minf.stbl.stsd.codecs[0] {
			mp4_atom::Codec::Mp4a(mp4a) => mp4a.esds.es_desc.dec_config.clone(),
			other => panic!("expected mp4a, got {other:?}"),
		}
	}

	// Safari and AVFoundation reject an all-zero DecoderConfigDescriptor on the *init* append,
	// which ends the ManagedMediaSource and fails every append after it. The catalog bitrate is
	// optional and real publishers omit it, so a synthesized esds must not lean on it.
	#[test]
	fn synthesized_aac_init_has_non_zero_bitrates() {
		let inferred = dec_config(&synthesize_audio_trak(1, 44_100, &aac_config(None)).unwrap());
		assert_ne!(u32::from(inferred.buffer_size_db), 0);
		assert_ne!(inferred.max_bitrate, 0);
		assert_ne!(inferred.avg_bitrate, 0);

		let stated = dec_config(&synthesize_audio_trak(1, 44_100, &aac_config(Some(96_000))).unwrap());
		assert_eq!(stated.max_bitrate, 96_000, "the catalog's bitrate wins");
		assert_eq!(stated.avg_bitrate, 96_000);

		// A stated bitrate the field can't carry rebuilds the same all-zero descriptor, so it
		// takes the fallback rather than the catalog.
		for unusable in [Some(0), Some(u64::from(u32::MAX) + 1)] {
			let config = dec_config(&synthesize_audio_trak(1, 44_100, &aac_config(unusable)).unwrap());
			assert_eq!(config.max_bitrate, inferred.max_bitrate, "{unusable:?}");
			assert_eq!(config.avg_bitrate, inferred.avg_bitrate, "{unusable:?}");
		}
	}

	// `framerate * 1000` is 0 for a zero, negative or non-finite catalog framerate, and 0 is not
	// a timescale: Timescale::new rejects it, so Muxer::video would fail to build at all.
	#[test]
	fn default_video_timescale_ignores_an_unusable_framerate() {
		let mut config = VideoConfig::new(hang::catalog::VideoCodec::VP8);
		for unusable in [0.0, -30.0, f64::NAN, f64::INFINITY, 0.0005] {
			config.framerate = Some(unusable);
			assert_eq!(default_video_timescale(&config), 90_000, "{unusable}");
		}

		config.framerate = Some(30.0);
		assert_eq!(default_video_timescale(&config), 30_000);

		config.framerate = Some(30_000.0 / 1001.0);
		assert_eq!(default_video_timescale(&config), 30_000);
	}

	#[test]
	fn default_video_timescale_keeps_low_cadence_within_trun() {
		let mut config = VideoConfig::new(hang::catalog::VideoCodec::VP8);
		for framerate in [0.2001, 0.0011] {
			config.framerate = Some(framerate);
			let timescale = default_video_timescale(&config);
			let duration = Duration::from_secs_f64(1.0 / framerate);
			let ticks = rounded_duration_ticks(duration, timescale).unwrap();

			assert!(timescale <= u64::from(u32::MAX));
			assert!(ticks <= u64::from(u32::MAX));
		}

		assert_eq!(default_video_timescale(&config), 11);
	}

	// A live fragmented stream's duration isn't known up front. Zero reads as an empty file to a
	// strict parser: VLC refuses to play one.
	#[test]
	fn synthesized_init_declares_unknown_duration() {
		let trak = synthesize_audio_trak(1, 44_100, &aac_config(None)).unwrap();
		assert_eq!(trak.tkhd.duration, u64::MAX);

		let init = encode_init(None, vec![trak], Vec::new()).unwrap();
		let moov = moov(&init);
		assert_eq!(moov.mvhd.duration, u64::MAX);
		assert_eq!(moov.trak[0].tkhd.duration, u64::MAX);
	}

	// The header defaults are all the "off" value: a track the presentation doesn't claim, a
	// stopped playback rate, a muted volume, and a next id that collides with the track already
	// there. A strict player is entitled to act on any of them.
	#[test]
	fn synthesized_init_headers_describe_a_playable_presentation() {
		let audio = synthesize_audio_trak(1, 44_100, &aac_config(None)).unwrap();
		let init = encode_init(None, vec![audio], Vec::new()).unwrap();
		let moov = moov(&init);

		assert_eq!(moov.mvhd.rate.integer(), 1, "normal playback rate");
		assert_eq!(moov.mvhd.volume.integer(), 1, "full volume");
		assert_eq!(moov.mvhd.next_track_id, 2, "past the only track id");

		let tkhd = &moov.trak[0].tkhd;
		assert!(tkhd.enabled && tkhd.in_movie, "flags 0x000003");
		assert_eq!(tkhd.volume.integer(), 1, "an audio track carries the volume");
	}

	// A video track's volume stays 0: the field only means something for audio.
	#[test]
	fn synthesized_video_init_sets_the_track_flags() {
		let mut config = VideoConfig::new(hang::catalog::VideoCodec::VP8);
		config.coded_width = Some(320);
		config.coded_height = Some(240);
		config.framerate = Some(30.0);
		let video = synthesize_video_trak(1, 30_000, &config, None).unwrap();
		let init = encode_init(None, vec![video], Vec::new()).unwrap();
		let moov = moov(&init);

		let tkhd = &moov.trak[0].tkhd;
		assert!(tkhd.enabled && tkhd.in_movie, "flags 0x000003");
		assert_eq!(tkhd.volume.integer(), 0);
	}

	#[test]
	fn synthesized_video_init_rejects_missing_dimensions() {
		let config = VideoConfig::new(hang::catalog::VideoCodec::VP8);
		let error = synthesize_video_trak(1, 30_000, &config, None).unwrap_err();
		assert!(matches!(error, Error::MissingVideoDimensions(_)));
	}

	#[test]
	fn decode_reads_trun_sample_duration() {
		use mp4_atom::Encode;

		// Microsecond timescale so each tick maps 1:1 to the Timestamp's µs.
		// decode() walks the mdat by sample size and ignores data_offset, so a
		// hand-built moof+mdat with explicit per-sample durations is enough.
		let timescale = moq_net::Timescale::MICRO;
		let moof = mp4_atom::Moof {
			mfhd: mp4_atom::Mfhd { sequence_number: 0 },
			traf: vec![mp4_atom::Traf {
				tfhd: mp4_atom::Tfhd {
					track_id: 1,
					..Default::default()
				},
				tfdt: Some(mp4_atom::Tfdt {
					base_media_decode_time: 0,
				}),
				trun: vec![mp4_atom::Trun {
					data_offset: Some(0),
					entries: vec![
						mp4_atom::TrunEntry {
							size: Some(2),
							duration: Some(33_333),
							..Default::default()
						},
						mp4_atom::TrunEntry {
							size: Some(2),
							duration: Some(33_333),
							..Default::default()
						},
					],
				}],
				..Default::default()
			}],
		};

		let mut buf = Vec::new();
		moof.encode(&mut buf).unwrap();
		mp4_atom::Mdat {
			data: vec![0xDE, 0xAD, 0xBE, 0xEF],
		}
		.encode(&mut buf)
		.unwrap();

		let frames = decode(Bytes::from(buf), timescale).unwrap();
		assert_eq!(frames.len(), 2);
		assert_eq!(frames[0].timestamp, ts(0));
		assert_eq!(frames[0].duration, Some(ts(33_333)));
		assert_eq!(frames[1].timestamp, ts(33_333));
		assert_eq!(frames[1].duration, Some(ts(33_333)));
	}

	#[test]
	fn duration_round_trips_through_encode() {
		// A frame with a known duration must survive encode -> decode.
		let timescale = moq_net::Timescale::MICRO;
		let input = vec![Frame {
			timestamp: ts(0),
			payload: Bytes::from_static(&[0xDE, 0xAD]),
			keyframe: true,
			duration: Some(ts(33_333)),
		}];

		let fragment = encode_fragment(info(1, timescale, 0), &input).unwrap();
		let frames = decode(fragment, timescale).unwrap();

		assert_eq!(frames.len(), 1);
		assert_eq!(frames[0].duration, Some(ts(33_333)));
	}

	// A trun sample duration is 32 bits. Narrowing silently would make the media claim a
	// shorter duration than the metadata returned to the fragmenting consumer.
	#[test]
	fn encode_fragment_rejects_a_duration_too_large_for_trun() {
		let timescale = moq_net::Timescale::new(u64::from(u32::MAX)).unwrap();
		let over = u64::from(u32::MAX) + 1;
		let frame = Frame {
			timestamp: Timestamp::from_scale(0, timescale.as_u64()).unwrap(),
			payload: Bytes::from_static(&[0xDE, 0xAD]),
			keyframe: true,
			duration: Some(Timestamp::from_scale(over, timescale.as_u64()).unwrap()),
		};

		let err = encode_fragment(info(1, timescale, 0), std::slice::from_ref(&frame)).unwrap_err();
		assert!(matches!(err, Error::SampleDurationTooLarge(ticks) if ticks == over));

		let largest = Frame {
			duration: Some(Timestamp::from_scale(u64::from(u32::MAX), timescale.as_u64()).unwrap()),
			..frame
		};
		let fragment = encode_fragment(info(1, timescale, 0), &[largest]).unwrap();
		assert_eq!(sample_durations(&fragment), vec![Some(u32::MAX)]);
	}

	// A positive duration that becomes zero ticks would leave tfdt stationary while the
	// fragment metadata still advances, so a coarse override has to fail explicitly.
	#[test]
	fn encode_fragment_rejects_a_duration_shorter_than_one_tick() {
		let timescale = moq_net::Timescale::SECOND;
		let frame = Frame {
			timestamp: Timestamp::from_secs(0).unwrap(),
			payload: Bytes::from_static(&[0xDE, 0xAD]),
			keyframe: true,
			duration: Some(Timestamp::from_millis(33).unwrap()),
		};

		let err = encode_fragment(info(1, timescale, 0), std::slice::from_ref(&frame)).unwrap_err();
		assert!(matches!(err, Error::SampleDurationTooSmall(1)));

		let one_tick = Frame {
			duration: Some(Timestamp::from_secs(1).unwrap()),
			..frame
		};
		let fragment = encode_fragment(info(1, timescale, 0), &[one_tick]).unwrap();
		assert_eq!(sample_durations(&fragment), vec![Some(1)]);
	}

	// Flooring every 1/24-second sample at a 1 kHz output scale would lose 16 ticks per
	// second. The caller must choose a scale that represents the duration exactly.
	#[test]
	fn encode_fragment_rejects_an_inexact_sample_duration() {
		let input_scale = moq_net::Timescale::new(24).unwrap();
		let output_scale = moq_net::Timescale::MILLI;
		let frame = Frame {
			timestamp: Timestamp::new(0, input_scale).unwrap(),
			payload: Bytes::from_static(&[0xDE, 0xAD]),
			keyframe: true,
			duration: Some(Timestamp::new(1, input_scale).unwrap()),
		};

		let err = encode_fragment(info(1, output_scale, 0), std::slice::from_ref(&frame)).unwrap_err();
		assert!(matches!(err, Error::SampleDurationInexact(1_000)));

		let exact_scale = moq_net::Timescale::new(24_000).unwrap();
		let fragment = encode_fragment(info(1, exact_scale, 0), &[frame]).unwrap();
		assert_eq!(sample_durations(&fragment), vec![Some(1_000)]);
	}

	// tfdt is 64 bits. A timestamp rescaled past that range must fail rather than wrap the
	// fragment back onto an unrelated point in the presentation.
	#[test]
	fn encode_fragment_rejects_a_pts_too_large_for_tfdt() {
		let timescale = moq_net::Timescale::new(u64::from(u32::MAX)).unwrap();
		let frame = Frame {
			timestamp: Timestamp::from_secs(1 << 40).unwrap(),
			payload: Bytes::from_static(&[0xDE, 0xAD]),
			keyframe: true,
			duration: None,
		};

		let err = encode_fragment(info(1, timescale, 0), &[frame]).unwrap_err();
		assert!(matches!(err, Error::PtsOverflow));
	}

	#[test]
	fn reordered_pts_round_trips_with_cts() {
		let timescale = moq_net::Timescale::new(1_000_000).unwrap();
		let input = vec![
			Frame {
				timestamp: ts(0),
				payload: Bytes::from_static(&[0x00]),
				keyframe: true,
				duration: Some(ts(33_000)),
			},
			Frame {
				timestamp: ts(99_000),
				payload: Bytes::from_static(&[0x01]),
				keyframe: false,
				duration: Some(ts(33_000)),
			},
			Frame {
				timestamp: ts(33_000),
				payload: Bytes::from_static(&[0x02]),
				keyframe: false,
				duration: Some(ts(33_000)),
			},
		];

		let fragment = encode_fragment(info(1, timescale, 0), &input).unwrap();
		let frames = decode(fragment, timescale).unwrap();

		assert_eq!(frames.len(), input.len());
		for (actual, expected) in frames.iter().zip(&input) {
			assert_eq!(actual.timestamp, expected.timestamp);
			assert_eq!(actual.duration, expected.duration);
			assert_eq!(actual.payload, expected.payload);
		}
	}

	#[test]
	fn decode_without_duration_reports_none() {
		// encode_fragment writes no sample-duration for a duration-less frame,
		// so decode must report None (and output stays byte-identical to before).
		let timescale = moq_net::Timescale::new(90_000).unwrap();
		let frames = vec![Frame {
			timestamp: ts(0),
			payload: Bytes::from_static(&[0xDE, 0xAD]),
			keyframe: true,
			duration: None,
		}];

		let fragment = encode_fragment(info(1, timescale, 0), &frames).unwrap();
		let frames = decode(fragment, timescale).unwrap();

		assert_eq!(frames.len(), 1);
		assert_eq!(frames[0].duration, None);
	}

	#[test]
	fn decode_zero_duration_reports_none() {
		use mp4_atom::Encode;

		let timescale = moq_net::Timescale::new(24_000).unwrap();
		let moof = mp4_atom::Moof {
			mfhd: mp4_atom::Mfhd { sequence_number: 0 },
			traf: vec![mp4_atom::Traf {
				tfhd: mp4_atom::Tfhd {
					track_id: 1,
					default_sample_duration: Some(0),
					default_sample_size: Some(2),
					..Default::default()
				},
				tfdt: Some(mp4_atom::Tfdt {
					base_media_decode_time: 2_000,
				}),
				trun: vec![mp4_atom::Trun {
					data_offset: Some(0),
					entries: vec![mp4_atom::TrunEntry {
						size: None,
						duration: None,
						..Default::default()
					}],
				}],
				..Default::default()
			}],
		};

		let mut buf = Vec::new();
		moof.encode(&mut buf).unwrap();
		mp4_atom::Mdat { data: vec![0xDE, 0xAD] }.encode(&mut buf).unwrap();

		let frames = decode(Bytes::from(buf), timescale).unwrap();
		assert_eq!(frames.len(), 1);
		assert_eq!(frames[0].timestamp.as_micros(), 83_333);
		assert_eq!(frames[0].duration, None);
	}
}