transmux 0.25.0

Any-to-any media container muxing hub: demux TS, fMP4/CMAF, MPEG-PS, WebM, FLV, or RTMP into one neutral IR and mux to CMAF/fMP4, progressive MP4, TS, DASH, low-latency DASH, HLS, low-latency HLS, Smooth Streaming, or RTMP. CENC/CBCS encrypt+decrypt, SSAI splice, RTP/RTCP, and an fMP4/CMAF conformance validator; parses codec config headers only, samples stay opaque. no_std + alloc, except the XML manifest paths (DASH/Smooth/PlayReady), which need the std feature.
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
//! Microsoft Smooth Streaming (ISM/PIFF) output — [MS-SSTR].
//!
//! The Smooth-Streaming sibling of [`crate::dash::DashPackager`] and
//! [`crate::media::HlsPackager`]: [`SmoothPackager`] renders a [`Media`] as a
//! Smooth **client Manifest** (XML) plus a set of Smooth **fragment** responses,
//! each a fragmented-MP4 `moof`+`mdat` carrying the Smooth-specific `tfxd`
//! `uuid` box.
//!
//! # Structure ([MS-SSTR]; see `transmux/docs/smooth/ms-sstr.md`)
//!
//! - **Client Manifest** (§2.2.2): `SmoothStreamingMedia`(`MajorVersion=2`,
//!   `MinorVersion=0`, `Duration`, `TimeScale=10000000`) → one `StreamIndex`
//!   per media kind (`Type="video"`/`"audio"`, `Chunks`, `QualityLevels`,
//!   `Url`) → a `QualityLevel` (§2.2.2.5: `Index`, `Bitrate`, `FourCC`,
//!   `CodecPrivateData`, geometry / audio params) → one `c` element per
//!   fragment (§2.2.2.6: `d` = duration, `t` = absolute time on the first,
//!   `n` = ordinal).
//! - **Fragment response** (§2.2.4): `moof`(`mfhd` `traf`(`tfhd` `trun`
//!   **`tfxd`**)) `mdat`. The `tfxd` box (§2.2.4.4) is a `uuid` box with
//!   extended-type [`TFXD_UUID`] carrying `FragmentAbsoluteTime` +
//!   `FragmentDuration` (both in the manifest [`SMOOTH_TIMESCALE`]).
//! - **`tfrf`** look-ahead (§2.2.4.5) is live-only; omitted for VOD output.
//!
//! The standard `mfhd`/`tfhd`/`trun`/`mdat` boxes are the same fMP4 framing
//! (ISO/IEC 14496-12:2015 §8.8) the crate already builds; this module reuses
//! [`crate::segmenter::Segmenter`] for keyframe-aligned segmentation and injects
//! the `tfxd` `uuid` box into each fragment's `traf`.
//!
//! FourCC / `CodecPrivateData` (§2.2.2.5):
//! - Video `FourCC="H264"`: `CodecPrivateData` = the hex of SPS+PPS as
//!   start-code-prefixed NAL units (`00000001 <sps> 00000001 <pps>`).
//! - Audio `FourCC="AACL"`: `CodecPrivateData` = the hex of the
//!   AudioSpecificConfig; `AudioTag="255"` (raw AAC).
//!
//! Like the DASH / HLS packagers, the manifest is emitted with a tiny
//! [`quick_xml::Writer`] (`std` feature; every attribute value and text node is
//! escaped by quick-xml). Integer arithmetic only.

use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;

use broadcast_common::{Parse, Serialize};

use crate::aac_asc::AudioSpecificConfig;
use crate::box_types::{BoxHeader, BoxType, UUID_TYPE_SIZE};
use crate::error::{Error, Result};
use crate::media::{Media, TimelineOrigin, Track, relative_decode_times};
use crate::movie_fragment::{
    MediaRunSample, MovieFragmentBox, MovieFragmentHeaderBox, TrackFragmentBox, media_fragment_run,
};
use crate::pipeline::{CodecConfig, Sample};
use crate::segments::{MediaDataBox, SegmentTypeBox};
use quick_xml::Writer;
use quick_xml::events::{BytesDecl, BytesEnd, BytesStart, Event};

/// The Smooth Streaming default manifest time scale — 10 MHz (100 ns ticks),
/// [MS-SSTR] §2.2.2 (`SmoothStreamingMedia@TimeScale`).
pub const SMOOTH_TIMESCALE: u64 = 10_000_000;

/// `SmoothStreamingMedia@MajorVersion` for the manifest this module emits.
const MAJOR_VERSION: u32 = 2;
/// `SmoothStreamingMedia@MinorVersion`.
const MINOR_VERSION: u32 = 0;

/// The `tfxd` `uuid` extended-type — [MS-SSTR] §2.2.4.4
/// (`6d1d9b05-42d5-44e6-80e2-141daff757b2`).
pub const TFXD_UUID: [u8; UUID_TYPE_SIZE] = [
    0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6, 0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2,
];

/// Video FourCC in the Smooth `QualityLevel` (§2.2.2.5) — H.264/AVC.
pub const FOURCC_H264: &str = "H264";
/// Video FourCC alias in the Smooth `QualityLevel` (§2.2.2.5) — H.264/AVC is
/// spelled `AVC1` by some encoders (`H264` is the primary name).
pub const FOURCC_AVC1: &str = "AVC1";
/// Audio FourCC in the Smooth `QualityLevel` (§2.2.2.5) — AAC-LC.
pub const FOURCC_AACL: &str = "AACL";
/// Audio FourCC in the Smooth `QualityLevel` (§2.2.2.5) — HE-AAC.
pub const FOURCC_AACH: &str = "AACH";

/// `AudioTag` for raw AAC in the Smooth `QualityLevel` (§2.2.2.5).
const AUDIO_TAG_AAC: u32 = 255;
/// Bits-per-sample advertised for AAC audio.
const AAC_BITS_PER_SAMPLE: u16 = 16;

/// Annex B start code prefixing each parameter-set NAL in `CodecPrivateData`.
const START_CODE: [u8; 4] = [0x00, 0x00, 0x00, 0x01];

/// The `styp` brand emitted ahead of a self-contained Smooth fragment (kept
/// consistent with the crate's CMAF media segments).
const STYP_MAJOR_BRAND: [u8; 4] = *b"msdh";

/// The media kind of a Smooth `StreamIndex`.
///
/// Determines the `Type` attribute, the FourCC, and which
/// geometry / audio attributes the `QualityLevel` carries.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SmoothStreamType {
    /// Video stream — `Type="video"`, `FourCC="H264"`.
    Video,
    /// Audio stream — `Type="audio"`, `FourCC="AACL"`.
    Audio,
}

impl SmoothStreamType {
    /// The [MS-SSTR] `StreamIndex@Type` token (`"video"` / `"audio"`).
    pub fn name(&self) -> &'static str {
        match self {
            SmoothStreamType::Video => "video",
            SmoothStreamType::Audio => "audio",
        }
    }
}

broadcast_common::impl_spec_display!(SmoothStreamType);

// ---------------------------------------------------------------------------
// tfxd uuid box — [MS-SSTR] §2.2.4.4
// ---------------------------------------------------------------------------

/// The Smooth `TfxdBox` (§2.2.4.4): a `uuid` FullBox (version 1) carrying the
/// fragment's `FragmentAbsoluteTime` + `FragmentDuration`, both in the manifest
/// [`SMOOTH_TIMESCALE`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct TfxdBox {
    /// Fragment absolute (start) time, in [`SMOOTH_TIMESCALE`] ticks.
    pub fragment_absolute_time: u64,
    /// Fragment duration, in [`SMOOTH_TIMESCALE`] ticks.
    pub fragment_duration: u64,
}

impl TfxdBox {
    /// FullBox version — 1 selects the 64-bit time/duration fields (§2.2.4.4).
    const VERSION: u8 = 1;
    /// Payload after the FullBox header: two 64-bit fields.
    const PAYLOAD_LEN: usize = 16;

    /// Build a `tfxd` box for a fragment.
    pub fn new(fragment_absolute_time: u64, fragment_duration: u64) -> Self {
        Self {
            fragment_absolute_time,
            fragment_duration,
        }
    }

    /// Parse a `tfxd` `uuid` box *body* (the bytes after the 8-byte box header
    /// and the 16-byte `usertype`, i.e. the FullBox header + payload).
    pub fn parse_body(body: &[u8]) -> Result<Self> {
        // version(1) + flags(3) + AbsoluteTime(8) + Duration(8)
        let need = 4 + Self::PAYLOAD_LEN;
        if body.len() < need {
            return Err(Error::BufferTooShort {
                need,
                have: body.len(),
                what: "tfxd body",
            });
        }
        let p = &body[4..];
        let fragment_absolute_time =
            u64::from_be_bytes([p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]]);
        let fragment_duration =
            u64::from_be_bytes([p[8], p[9], p[10], p[11], p[12], p[13], p[14], p[15]]);
        Ok(Self {
            fragment_absolute_time,
            fragment_duration,
        })
    }
}

impl Serialize for TfxdBox {
    type Error = Error;

    fn serialized_len(&self) -> usize {
        // box header(8) + usertype(16) + FullBox version/flags(4) + payload(16).
        let hdr = BoxHeader::new(0, BoxType::from_bytes(*b"uuid"), Some(TFXD_UUID));
        hdr.serialized_len() + 4 + Self::PAYLOAD_LEN
    }

    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
        let need = self.serialized_len();
        if buf.len() < need {
            return Err(Error::OutputBufferTooSmall {
                need,
                have: buf.len(),
            });
        }
        // uuid box header (size, "uuid", usertype = TFXD_UUID).
        let hdr = BoxHeader::new(need as u64, BoxType::from_bytes(*b"uuid"), Some(TFXD_UUID));
        let mut c = hdr.serialize_into(buf)?;
        // FullBox header: version + 24-bit flags(0).
        buf[c] = Self::VERSION;
        buf[c + 1] = 0;
        buf[c + 2] = 0;
        buf[c + 3] = 0;
        c += 4;
        buf[c..c + 8].copy_from_slice(&self.fragment_absolute_time.to_be_bytes());
        c += 8;
        buf[c..c + 8].copy_from_slice(&self.fragment_duration.to_be_bytes());
        c += 8;
        Ok(c)
    }
}

// ---------------------------------------------------------------------------
// SmoothPackager
// ---------------------------------------------------------------------------

/// One Smooth fragment: its packaged `moof`+`mdat` bytes plus the timing needed
/// for the manifest `c` element.
#[derive(Debug, Clone)]
pub struct SmoothFragment {
    /// Track ID this fragment belongs to.
    pub track_id: u32,
    /// `mfhd.sequence_number` (1-based, monotonically increasing).
    pub sequence_number: u32,
    /// Fragment start time, in [`SMOOTH_TIMESCALE`] ticks (the `c@t` on the first).
    pub start_time: u64,
    /// Fragment duration, in [`SMOOTH_TIMESCALE`] ticks (the `c@d`).
    pub duration: u64,
    /// The self-contained fragment bytes: `styp` + `moof`(+`tfxd`) + `mdat`.
    pub data: Vec<u8>,
}

/// The Smooth Streaming output: the client Manifest plus every fragment.
#[derive(Debug, Clone)]
pub struct SmoothOutput {
    /// The Smooth client Manifest XML.
    pub manifest: String,
    /// Every Smooth fragment, in emission order (grouped per track).
    pub fragments: Vec<SmoothFragment>,
}

/// Render a [`Media`] as Microsoft Smooth Streaming ([MS-SSTR]).
///
/// Segments each track keyframe-aligned (via [`crate::segmenter::Segmenter`]),
/// emits one Smooth fragment (`moof`+`tfxd`+`mdat`) per segment, and builds a
/// client Manifest whose `c` timeline mirrors the emitted fragments. VOD only
/// (no live `tfrf` look-ahead).
#[derive(Debug, Clone)]
pub struct SmoothPackager {
    /// Target fragment duration, in whole seconds (keyframe-aligned cut target).
    pub target_duration_secs: u32,
}

impl Default for SmoothPackager {
    fn default() -> Self {
        Self {
            target_duration_secs: 2,
        }
    }
}

/// Per-track presentation parameters resolved for the manifest.
struct StreamInfo {
    stream_type: SmoothStreamType,
    fourcc: &'static str,
    /// `CodecPrivateData` bytes (hex-encoded into the manifest).
    codec_private_data: Vec<u8>,
    bitrate: u64,
    /// Video geometry.
    width: Option<u32>,
    height: Option<u32>,
    /// Audio params.
    sampling_rate: Option<u32>,
    channels: Option<u16>,
    /// The track's fragments (index into the output list, resolved at render).
    fragments: Vec<FragmentTiming>,
    /// Sum of fragment durations, in [`SMOOTH_TIMESCALE`] ticks.
    total_duration: u64,
}

/// Timing for one `c` element.
struct FragmentTiming {
    start_time: u64,
    duration: u64,
}

impl SmoothPackager {
    /// Convert a tick count in the track's media timescale to
    /// [`SMOOTH_TIMESCALE`] ticks with integer round-to-nearest (`no_std`-safe).
    fn to_smooth_ticks(ticks: u64, media_timescale: u32) -> u64 {
        let ts = media_timescale.max(1) as u64;
        // round(ticks * SMOOTH_TIMESCALE / ts)
        let num = ticks.saturating_mul(SMOOTH_TIMESCALE);
        (num + ts / 2) / ts
    }

    /// The `CodecPrivateData` bytes for a video track: start-code-prefixed
    /// SPS+PPS NAL units (§2.2.2.5).
    fn video_codec_private_data(config: &crate::avc_config::AVCConfigurationBox) -> Vec<u8> {
        let mut out = Vec::new();
        for sps in &config.config.sps {
            out.extend_from_slice(&START_CODE);
            out.extend_from_slice(&sps.0);
        }
        for pps in &config.config.pps {
            out.extend_from_slice(&START_CODE);
            out.extend_from_slice(&pps.0);
        }
        out
    }

    /// The `CodecPrivateData` bytes for an AAC track: the raw
    /// AudioSpecificConfig carried in the `esds` (§2.2.2.5).
    fn audio_codec_private_data(esds: &crate::mp4esds::EsdsBox) -> Result<Vec<u8>> {
        let dsi = esds.require_decoder_specific_info()?;
        Ok(dsi.to_vec())
    }

    /// Segment one track into Smooth fragments and resolve its manifest info.
    ///
    /// Cuts the track keyframe-aligned into fragments; for each, builds the
    /// `moof`+`tfxd`+`mdat` bytes and records the `c` timing. Every time and
    /// duration — `c@t`/`c@d`, `tfxd`, and the `trun` sample durations and
    /// composition offsets — is in [`SMOOTH_TIMESCALE`]: a client builds the
    /// track's timescale from the manifest (Smooth has no init segment), so
    /// media-timescale `trun` values would play 111x/208x too short (issue
    /// #1022). Times are the samples' own decode times on the `origin` common
    /// to every track, so inter-track offsets survive.
    fn build_track(
        &self,
        track: &Track,
        origin: &TimelineOrigin,
        next_seq: &mut u32,
        fragments_out: &mut Vec<SmoothFragment>,
    ) -> Result<StreamInfo> {
        let media_timescale = track.spec.timescale.max(1);
        let (stream_type, fourcc, codec_private_data, width, height, sampling_rate, channels) =
            resolve_codec(&track.spec.config)?;

        let timeline = smooth_timeline(track, origin, media_timescale)?;

        // Segment keyframe-aligned into groups of samples.
        let groups = segment_samples(&track.samples, media_timescale, self.target_duration_secs);

        let mut fragment_timings = Vec::with_capacity(groups.len());
        let mut total_bytes = 0u64;

        for range in groups {
            let group = &track.samples[range.clone()];
            let times = &timeline[range];
            let start_smooth = times.first().map_or(0, |t| t.start);
            let dur_smooth: u64 = times.iter().map(|t| u64::from(t.duration)).sum();

            let data = build_smooth_fragment(
                track.spec.track_id,
                *next_seq,
                start_smooth,
                dur_smooth,
                group,
                times,
            )?;

            for s in group.iter() {
                total_bytes += s.data.len() as u64;
            }
            fragments_out.push(SmoothFragment {
                track_id: track.spec.track_id,
                sequence_number: *next_seq,
                start_time: start_smooth,
                duration: dur_smooth,
                data,
            });
            fragment_timings.push(FragmentTiming {
                start_time: start_smooth,
                duration: dur_smooth,
            });
            *next_seq += 1;
        }

        let total_duration: u64 = fragment_timings.iter().map(|f| f.duration).sum();

        // bitrate = total coded bits / duration in seconds (integer round);
        // checked_div guards the zero-duration case (→ 0).
        let bitrate = {
            let bits_ts = total_bytes
                .saturating_mul(8)
                .saturating_mul(SMOOTH_TIMESCALE);
            (bits_ts + total_duration / 2)
                .checked_div(total_duration)
                .unwrap_or(0)
        }
        .max(1);

        Ok(StreamInfo {
            stream_type,
            fourcc,
            codec_private_data,
            bitrate,
            width,
            height,
            sampling_rate,
            channels,
            fragments: fragment_timings,
            total_duration,
        })
    }

    /// Build **one** Smooth fragment for a single track at an explicit
    /// smooth-timeline start (issue #1083, W13).
    ///
    /// Unlike [`Package::package`](broadcast_common::Package::package), this
    /// does not segment the track or derive the start from the track's own
    /// decode times: it emits the whole track's samples as a single
    /// `moof`+`tfxd`+`mdat` whose `FragmentAbsoluteTime` is exactly
    /// `start_smooth` (in [`SMOOTH_TIMESCALE`] ticks) and whose
    /// `FragmentDuration` is the sum of the samples' own durations. That lets
    /// a live packager whose manifest `c@t` advertises a cumulative start
    /// serve a fragment whose `tfxd` matches it — the requirement MS-SSTR
    /// §2.2.4 places on a fragment response, and which the per-track
    /// `TimelineOrigin`-based path cannot express (it always starts at `0`).
    ///
    /// `track` must carry at least one sample; `sequence_number` is
    /// `mfhd.sequence_number` (1-based).
    pub fn package_track_fragment(
        &self,
        track: &Track,
        sequence_number: u32,
        start_smooth: u64,
    ) -> Result<SmoothFragment> {
        if track.samples.is_empty() {
            return Err(Error::InvalidInput(
                "cannot package a Smooth fragment from a track with no samples",
            ));
        }
        let media_timescale = track.spec.timescale.max(1);
        // Times relative to the track's own first sample: only the *durations*
        // and composition offsets are used from here (the fragment's absolute
        // start is the caller's `start_smooth`, not the derived one).
        let origin = TimelineOrigin::of(core::iter::once(track));
        let times = smooth_timeline(track, &origin, media_timescale)?;
        let dur_smooth: u64 = times.iter().map(|t| u64::from(t.duration)).sum();
        let data = build_smooth_fragment(
            track.spec.track_id,
            sequence_number,
            start_smooth,
            dur_smooth,
            &track.samples,
            &times,
        )?;
        Ok(SmoothFragment {
            track_id: track.spec.track_id,
            sequence_number,
            start_time: start_smooth,
            duration: dur_smooth,
            data,
        })
    }

    /// Render the Smooth client Manifest XML for the resolved streams.
    fn render_manifest(&self, streams: &[StreamInfo]) -> String {
        let mut writer = new_writer();
        let w = &mut writer;
        declaration(w);

        let duration = streams.iter().map(|s| s.total_duration).max().unwrap_or(0);
        open(
            w,
            "SmoothStreamingMedia",
            &[
                ("MajorVersion", MAJOR_VERSION.to_string()),
                ("MinorVersion", MINOR_VERSION.to_string()),
                ("Duration", duration.to_string()),
                ("TimeScale", SMOOTH_TIMESCALE.to_string()),
            ],
        );

        for s in streams {
            let ty = s.stream_type.name();
            let url = format!("QualityLevels({{bitrate}})/Fragments({ty}={{start time}})");
            open(
                w,
                "StreamIndex",
                &[
                    ("Type", ty.to_string()),
                    ("Subtype", String::new()),
                    ("Chunks", s.fragments.len().to_string()),
                    ("QualityLevels", "1".to_string()),
                    ("Url", url),
                ],
            );

            // QualityLevel
            let mut ql = alloc::vec![
                ("Index", "0".to_string()),
                ("Bitrate", s.bitrate.to_string()),
                ("FourCC", s.fourcc.to_string()),
            ];
            match s.stream_type {
                SmoothStreamType::Video if let (Some(wd), Some(ht)) = (s.width, s.height) => {
                    ql.push(("MaxWidth", wd.to_string()));
                    ql.push(("MaxHeight", ht.to_string()));
                    ql.push((
                        "CodecPrivateData",
                        ::hex::encode_upper(&s.codec_private_data),
                    ));
                }
                SmoothStreamType::Video => {
                    ql.push((
                        "CodecPrivateData",
                        ::hex::encode_upper(&s.codec_private_data),
                    ));
                }
                SmoothStreamType::Audio => {
                    if let Some(sr) = s.sampling_rate {
                        ql.push(("SamplingRate", sr.to_string()));
                    }
                    if let Some(ch) = s.channels {
                        ql.push(("Channels", ch.to_string()));
                    }
                    ql.push(("BitsPerSample", AAC_BITS_PER_SAMPLE.to_string()));
                    ql.push(("AudioTag", AUDIO_TAG_AAC.to_string()));
                    ql.push((
                        "CodecPrivateData",
                        ::hex::encode_upper(&s.codec_private_data),
                    ));
                }
            }
            empty(w, "QualityLevel", &ql);

            // One `c` per fragment: `d` always; `t` on the first only; `n` ordinal.
            for (i, f) in s.fragments.iter().enumerate() {
                let mut c = alloc::vec![("n", i.to_string())];
                if i == 0 {
                    c.push(("t", f.start_time.to_string()));
                }
                c.push(("d", f.duration.to_string()));
                empty(w, "c", &c);
            }

            close(w, "StreamIndex");
        }

        close(w, "SmoothStreamingMedia");
        finish(writer)
    }
}

impl broadcast_common::Package for SmoothPackager {
    type Media = Media;
    type Output = SmoothOutput;
    type Error = Error;

    fn package(&mut self, media: &Media) -> Result<SmoothOutput> {
        if media.tracks.is_empty() {
            return Err(Error::InvalidInput("cannot package a Media with no tracks"));
        }
        let mut fragments = Vec::new();
        let mut streams = Vec::with_capacity(media.tracks.len());
        // Per-track sequence numbering, 1-based (each track's fragments count
        // up independently, as Smooth fragment responses are addressed by
        // start time within a StreamIndex).
        let origin = TimelineOrigin::of(&media.tracks);
        for track in &media.tracks {
            let mut next_seq = 1u32;
            streams.push(self.build_track(track, &origin, &mut next_seq, &mut fragments)?);
        }
        let manifest = self.render_manifest(&streams);
        Ok(SmoothOutput {
            manifest,
            fragments,
        })
    }
}

// ---------------------------------------------------------------------------
// Codec resolution
// ---------------------------------------------------------------------------

type ResolvedCodec = (
    SmoothStreamType,
    &'static str,
    Vec<u8>,
    Option<u32>,
    Option<u32>,
    Option<u32>,
    Option<u16>,
);

/// Resolve the Smooth stream type, FourCC, `CodecPrivateData`, and per-kind
/// parameters for a track's [`CodecConfig`].
///
/// Only the [MS-SSTR]-defined H.264 (video) and AAC-LC (audio) codecs are
/// supported; other codecs return [`Error::InvalidInput`].
fn resolve_codec(config: &CodecConfig) -> Result<ResolvedCodec> {
    match config {
        CodecConfig::Avc { config, .. } => {
            let cpd = SmoothPackager::video_codec_private_data(config);
            // Prefer SPS-decoded geometry (authoritative coded dimensions).
            let (w, h) = config
                .config
                .sps
                .first()
                .and_then(|sps| sps.decode().ok())
                .map(|i| (i.width, i.height))
                .ok_or(Error::InvalidInput(
                    "AVC track has no decodable SPS for Smooth geometry",
                ))?;
            Ok((
                SmoothStreamType::Video,
                FOURCC_H264,
                cpd,
                Some(w),
                Some(h),
                None,
                None,
            ))
        }
        CodecConfig::Aac {
            esds,
            channel_count,
            sample_rate,
            ..
        } => {
            let cpd = SmoothPackager::audio_codec_private_data(esds)?;
            // Prefer the ASC-decoded sampling rate; fall back to the entry.
            let rate = AudioSpecificConfig::parse(&cpd)
                .ok()
                .and_then(|asc| asc.effective_sampling_frequency())
                .unwrap_or(*sample_rate);
            Ok((
                SmoothStreamType::Audio,
                FOURCC_AACL,
                cpd,
                None,
                None,
                Some(rate),
                Some(*channel_count),
            ))
        }
        _ => Err(Error::InvalidInput(
            "Smooth Streaming supports only H.264 video and AAC-LC audio",
        )),
    }
}

// ---------------------------------------------------------------------------
// Segmentation + fragment building
// ---------------------------------------------------------------------------

/// Split a track's samples into keyframe-aligned groups, cutting a new group on
/// a sync sample once the current group has reached the target duration.
///
/// Mirrors the [`Segmenter`](crate::segmenter::Segmenter) anchor-cut policy
/// applied to a single track: every group after the first begins on a
/// random-access point, no sample is dropped or reordered.
fn segment_samples(
    samples: &[Sample],
    media_timescale: u32,
    target_secs: u32,
) -> Vec<core::ops::Range<usize>> {
    let mut groups = Vec::new();
    if samples.is_empty() {
        return groups;
    }
    let target_ticks = (target_secs.max(1) as u64).saturating_mul(media_timescale.max(1) as u64);

    let mut start = 0usize;
    let mut acc_dur = 0u64;
    for (i, s) in samples.iter().enumerate() {
        // Cut before this sample when it is a keyframe past the target.
        if i > start && s.flags.is_sync && acc_dur >= target_ticks {
            groups.push(start..i);
            start = i;
            acc_dur = 0;
        }
        acc_dur += s.duration.unwrap_or(0) as u64;
    }
    groups.push(start..samples.len());
    groups
}

/// One sample's timing in [`SMOOTH_TIMESCALE`] ticks.
#[derive(Debug, Clone, Copy)]
struct SmoothSampleTime {
    /// Decode time on the common origin.
    start: u64,
    /// Decode duration: up to the next sample's decode time (so the `trun`
    /// durations of a fragment sum exactly to its `c@d`, with no per-sample
    /// rounding drift), the last sample's own duration.
    duration: u32,
    /// Composition offset (`pts - dts`).
    composition_offset: i32,
}

/// Rescale a track's per-sample decode times, durations and composition
/// offsets to [`SMOOTH_TIMESCALE`].
fn smooth_timeline(
    track: &Track,
    origin: &TimelineOrigin,
    media_timescale: u32,
) -> Result<Vec<SmoothSampleTime>> {
    let times = relative_decode_times(track, origin);
    let starts: Vec<u64> = times
        .iter()
        .map(|&t| SmoothPackager::to_smooth_ticks(t.max(0) as u64, media_timescale))
        .collect();
    track
        .samples
        .iter()
        .enumerate()
        .map(|(i, s)| {
            let start = starts[i];
            let own_end = SmoothPackager::to_smooth_ticks(
                (times[i].max(0) as u64).saturating_add(u64::from(s.duration.unwrap_or(0))),
                media_timescale,
            );
            let end = match starts.get(i + 1) {
                Some(&next) if next >= start => next,
                _ => own_end,
            };
            let duration = u32::try_from(end - start).map_err(|_| Error::InvalidValue {
                field: "trun sample_duration",
                value: end - start,
                reason: "exceeds 32 bits in the 10 MHz Smooth timescale",
            })?;
            let cto = to_smooth_signed(i64::from(s.composition_offset()), media_timescale);
            let composition_offset = i32::try_from(cto).map_err(|_| Error::InvalidValue {
                field: "trun sample_composition_time_offset",
                value: cto.unsigned_abs(),
                reason: "exceeds 32 bits in the 10 MHz Smooth timescale",
            })?;
            Ok(SmoothSampleTime {
                start,
                duration,
                composition_offset,
            })
        })
        .collect()
}

/// Signed round-to-nearest rescale of `ticks` to [`SMOOTH_TIMESCALE`].
fn to_smooth_signed(ticks: i64, media_timescale: u32) -> i64 {
    let magnitude = SmoothPackager::to_smooth_ticks(ticks.unsigned_abs(), media_timescale);
    let v = i64::try_from(magnitude).unwrap_or(i64::MAX);
    if ticks < 0 { -v } else { v }
}

/// Build one self-contained Smooth fragment: `styp` + `moof`(`mfhd` `traf`(
/// `tfhd` `trun` `tfxd`)) + `mdat`.
///
/// `start_smooth` / `dur_smooth` are in [`SMOOTH_TIMESCALE`] ticks (for the
/// `tfxd`). Smooth fragments carry timing via the `tfxd` box, so no `tfdt` is
/// emitted (the fragment is addressed by its manifest start time).
fn build_smooth_fragment(
    track_id: u32,
    sequence_number: u32,
    start_smooth: u64,
    dur_smooth: u64,
    samples: &[Sample],
    times: &[SmoothSampleTime],
) -> Result<Vec<u8>> {
    let styp = SegmentTypeBox {
        major_brand: STYP_MAJOR_BRAND,
        minor_version: 0,
        compatible_brands: alloc::vec![STYP_MAJOR_BRAND, *b"msix"],
    };

    let (tfhd, trun) = media_fragment_run(
        track_id,
        samples.iter().zip(times).map(|(s, t)| MediaRunSample {
            duration: t.duration,
            size: s.data.len(),
            is_sync: s.flags.is_sync,
            composition_offset: t.composition_offset,
        }),
    )?;
    let tfxd = TfxdBox::new(start_smooth, dur_smooth);

    let mut moof = MovieFragmentBox::new(
        MovieFragmentHeaderBox::new(sequence_number),
        alloc::vec![TrackFragmentBox::new(tfhd, None, alloc::vec![trun])],
    );

    // The tfxd is a uuid box inside the traf, but MovieFragmentBox knows nothing
    // about it, so we assemble the fragment bytes manually: compute the moof
    // size *including* the tfxd, set the trun data_offset from that size, then
    // splice the tfxd into the serialized traf.
    let tfxd_len = tfxd.serialized_len();
    // moof size with tfxd added into the single traf.
    let moof_size = moof.serialized_len() + tfxd_len;
    let mdat_payload_len: u64 = samples.iter().map(|s| s.data.len() as u64).sum();
    let mdat_header =
        BoxHeader::for_payload(BoxType::from_bytes(*b"mdat"), None, mdat_payload_len).header_size();
    let mdat_start = moof_size + mdat_header;
    let data_offset = i32::try_from(mdat_start).map_err(|_| Error::InvalidValue {
        field: "trun data_offset",
        value: mdat_start as u64,
        reason: "moof too large for the signed 32-bit trun data_offset",
    })?;
    moof.traf[0].trun[0].data_offset = Some(data_offset);

    // Serialize the moof (without tfxd), then splice the tfxd in at the end of
    // the traf and patch the two container sizes (moof, traf).
    let base_moof = moof.to_bytes();
    let with_tfxd = splice_tfxd_into_traf(&base_moof, &tfxd)?;
    debug_assert_eq!(with_tfxd.len(), moof_size);

    let mut mdat_data = Vec::new();
    for s in samples {
        mdat_data.extend_from_slice(&s.data);
    }
    let mdat = MediaDataBox { data: mdat_data };

    let total = styp.serialized_len() + with_tfxd.len() + mdat.serialized_len();
    let mut out = alloc::vec![0u8; total];
    let mut c = 0usize;
    c += styp.serialize_into(&mut out[c..])?;
    out[c..c + with_tfxd.len()].copy_from_slice(&with_tfxd);
    c += with_tfxd.len();
    mdat.serialize_into(&mut out[c..])?;
    Ok(out)
}

/// Append a `tfxd` `uuid` box at the end of the (single) `traf` inside a
/// serialized `moof`, patching the `moof` and `traf` container box sizes.
///
/// The serialized `moof` layout is `moof`[`mfhd`, `traf`[`tfhd`, `trun`]]; the
/// `traf` is the last child of the `moof`, so appending the `tfxd` at the very
/// end of the buffer places it as the last child of that `traf`.
fn splice_tfxd_into_traf(moof: &[u8], tfxd: &TfxdBox) -> Result<Vec<u8>> {
    if moof.len() < 8 || &moof[4..8] != b"moof" {
        return Err(Error::UnexpectedBox { expected: "moof" });
    }
    // Locate the traf: walk moof children, it is the box after mfhd.
    let mfhd_size = u32::from_be_bytes([moof[8], moof[9], moof[10], moof[11]]) as usize;
    let traf_off = 8 + mfhd_size;
    if moof.len() < traf_off + 8 || &moof[traf_off + 4..traf_off + 8] != b"traf" {
        return Err(Error::UnexpectedBox { expected: "traf" });
    }
    let old_traf_size = u32::from_be_bytes([
        moof[traf_off],
        moof[traf_off + 1],
        moof[traf_off + 2],
        moof[traf_off + 3],
    ]) as usize;

    let tfxd_bytes = tfxd.to_bytes();
    let mut out = Vec::with_capacity(moof.len() + tfxd_bytes.len());
    out.extend_from_slice(moof);
    // The traf is the last child (mfhd then traf), so the tfxd goes at the end.
    out.extend_from_slice(&tfxd_bytes);

    // Patch moof and traf sizes; both were written in the compact 32-bit form,
    // which has no room for a `largesize` (§4.2), so a size past u32 is refused.
    let too_big = |size: usize| Error::InvalidValue {
        field: "moof/traf box size",
        value: size as u64,
        reason: "exceeds the 32-bit box size of the serialized moof",
    };
    let new_moof_size = u32::try_from(out.len()).map_err(|_| too_big(out.len()))?;
    out[0..4].copy_from_slice(&new_moof_size.to_be_bytes());
    let traf_size = old_traf_size + tfxd_bytes.len();
    let new_traf_size = u32::try_from(traf_size).map_err(|_| too_big(traf_size))?;
    out[traf_off..traf_off + 4].copy_from_slice(&new_traf_size.to_be_bytes());
    Ok(out)
}

// ---------------------------------------------------------------------------
// quick-xml writer plumbing
// ---------------------------------------------------------------------------

/// The manifest writer: a two-space-indenting `quick_xml::Writer`. Every
/// attribute value and text node is escaped by quick-xml. Writing to an
/// in-memory `Vec` cannot fail, so write results are intentionally discarded.
type XmlWriter = Writer<Vec<u8>>;

fn new_writer() -> XmlWriter {
    Writer::new_with_indent(Vec::new(), b' ', 2)
}

/// `<?xml version="1.0" encoding="utf-8"?>`.
fn declaration(w: &mut XmlWriter) {
    let _ = w.write_event(Event::Decl(BytesDecl::new("1.0", Some("utf-8"), None)));
}

fn element_tag<'a>(name: &'a str, attrs: &'a [(&str, String)]) -> BytesStart<'a> {
    let mut start = BytesStart::new(name);
    for (key, value) in attrs {
        start.push_attribute((*key, value.as_str()));
    }
    start
}

/// `<name a="b">`.
fn open(w: &mut XmlWriter, name: &str, attrs: &[(&str, String)]) {
    let _ = w.write_event(Event::Start(element_tag(name, attrs)));
}

/// `<name a="b"/>`.
fn empty(w: &mut XmlWriter, name: &str, attrs: &[(&str, String)]) {
    let _ = w.write_event(Event::Empty(element_tag(name, attrs)));
}

/// `</name>`.
fn close(w: &mut XmlWriter, name: &str) {
    let _ = w.write_event(Event::End(BytesEnd::new(name)));
}

/// The written document plus a trailing newline.
fn finish(w: XmlWriter) -> String {
    let mut out = String::from_utf8_lossy(&w.into_inner()).into_owned();
    out.push('\n');
    out
}

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

    /// Every attribute value and text node goes through quick-xml's escaping:
    /// all five specials, exact output, and the output re-parses to the original.
    #[test]
    fn writer_escapes_attributes_and_text() {
        const SPECIALS: &str = "a&b<c>d\"e'f";
        let mut writer = new_writer();
        let w = &mut writer;
        open(w, "Root", &[("k", SPECIALS.to_string())]);
        empty(w, "Leaf", &[("v", SPECIALS.to_string())]);
        let _ = w.write_event(Event::Start(BytesStart::new("T")));
        let _ = w.write_event(Event::Text(quick_xml::events::BytesText::new(SPECIALS)));
        close(w, "T");
        close(w, "Root");
        let out = finish(writer);
        assert_eq!(
            out,
            concat!(
                "<Root k=\"a&amp;b&lt;c&gt;d&quot;e&apos;f\">\n",
                "  <Leaf v=\"a&amp;b&lt;c&gt;d&quot;e&apos;f\"/>\n",
                "  <T>a&amp;b&lt;c&gt;d&quot;e&apos;f</T>\n",
                "</Root>\n"
            )
        );
        let parsed = crate::smooth_parse::SmoothManifest::parse(&out);
        // Not a Smooth manifest, but it must be well-formed XML: the parser
        // rejects it for its root name, not for syntax.
        assert!(matches!(
            parsed,
            Err(crate::smooth_parse::SmoothParseError::UnexpectedElement { .. })
        ));
    }

    #[test]
    fn tfxd_round_trip() {
        let t = TfxdBox::new(0x0011_2233_4455_6677, 0x0089_ABCD);
        let bytes = t.to_bytes();
        // 8 (box hdr) + 16 (usertype) + 4 (fullbox) + 16 (payload) = 44.
        assert_eq!(bytes.len(), 44);
        assert_eq!(&bytes[4..8], b"uuid");
        assert_eq!(&bytes[8..24], &TFXD_UUID);
        // body = everything after box header(8) + usertype(16) = offset 24.
        let p = TfxdBox::parse_body(&bytes[24..]).unwrap();
        assert_eq!(p, t);
        assert_eq!(p.to_bytes(), bytes);
    }

    #[test]
    fn segment_samples_keyframe_aligned() {
        // 4 samples, timescale 1 tick/sample, target 2s: sync at 0 and 2.
        let mk = |sync: bool| Sample {
            data: alloc::vec![0u8; 4].into(),
            // Grouping is duration-driven; absolute time is irrelevant here.
            dts: None,
            pts: None,
            duration: Some(1),
            flags: crate::ir::SampleFlags::new(sync),
            provenance: None,
        };
        let samples = alloc::vec![mk(true), mk(false), mk(true), mk(false)];
        let groups = segment_samples(&samples, 1, 2);
        assert_eq!(groups.len(), 2);
        assert_eq!(groups[0].len(), 2);
        assert_eq!(groups[1].len(), 2);
    }

    #[test]
    fn to_smooth_ticks_scales() {
        // 1 second at media timescale 90000 → 10_000_000 smooth ticks.
        assert_eq!(SmoothPackager::to_smooth_ticks(90_000, 90_000), 10_000_000);
    }
}