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
//! IR-level timeline splice / concatenation → server-side ad insertion (SSAI),
//! operating on the [`Media`] IR before muxing (issue #475).
//!
//! Where [`crate::rebase`] conditions a *single* timeline (rebase-to-zero,
//! offset, 33-bit wrap-unroll, gap insertion), this module *joins* two
//! [`Media`] timelines into one monotonic decode timeline:
//!
//! - [`concat`](fn@concat) — append `b` after `a` on a shared timeline: for each matched
//! track, `b`'s samples follow `a`'s, with `b` rebased so its first sample's
//! decode time equals `a`'s end decode time (contiguous, no gap or overlap).
//! - [`splice_insert`] — SSAI: play `base` up to a splice time, insert `ad`,
//! then resume the remainder of `base` shifted forward by `ad`'s duration.
//!
//! # Timeline model (ISO/IEC 14496-12 `tfdt`)
//!
//! [`Sample`] timing is *absolute* (media plane step 2c): each sample carries
//! its own optional decode time (DTS) and presentation time (PTS =
//! DTS + composition_offset), in the track's media timescale.
//! [`Track::start_decode_time`] — which [`CmafMux`](crate::media::CmafMux)
//! writes as the *first* fragment's `tfdt` `baseMediaDecodeTime` (ISO/IEC
//! 14496-12:2015 §8.8.12) — is the track's start anchor, not a running cursor:
//! a source that re-seeds `tfdt` per fragment (a discontinuous or gapped
//! capture) can leave a real gap between it and a later sample's true `dts`.
//! This module therefore reads each join/snap boundary's absolute `dts`
//! directly rather than reconstructing it as `start_decode_time + Σ
//! durations`, falling back to that reconstruction only where a sample
//! genuinely carries no timestamp (a section-carried sample — SCTE-35/
//! DSM-CC/private sections — which has none to read). Coded sample bytes are
//! preserved byte-for-byte; only timing anchors/durations are recomputed.
//!
//! The same rule applies to the *comparison*: a splice cut taken from the
//! video track is an absolute decode time, so every other track's cut is
//! found by comparing that instant against each sample's own absolute `dts` —
//! never against a position measured from that track's own
//! `start_decode_time`, which would skew the cut by however much the tracks'
//! starts differ (a late audio join, a per-fragment `tfdt` reseed).
//!
//! # Rebasing the spliced-in content (issue #782)
//!
//! Two independently-demuxed assets have unrelated absolute timelines (each
//! anchored on its own `tfdt`/PCR/FLV clock) — simply appending a second
//! [`Media`]'s samples after a join point, keeping their own file's absolute
//! `dts`/`pts`, produces an arbitrary jump instead of a contiguous join. So
//! [`concat`](fn@concat) and [`splice_insert`] shift every incoming sample's
//! `dts`/`pts` (when `Some`) by `join_dts - incoming_reference_start` before
//! placing it:
//!
//! - **One offset per splice, derived from a single reference track** — the
//! video track if either side has one, else the first track that carries a
//! real timestamp (`pick_reference_track`) — and applied uniformly to
//! every matched track, converted into each track's own timescale
//! (`rescale_ticks`). Deriving the shift independently per track instead
//! would silently re-align tracks relative to each other and destroy A/V
//! sync (a track's own boundary sample needn't correspond, wall-clock, to
//! another track's).
//! - **Composition offsets survive exactly**: `dts` and `pts` shift by the
//! same amount (`shift_samples`), so `pts - dts` is unchanged.
//! - **No accumulated rounding across repeated splices**: every splice call
//! rescales the *fresh, already-materialized absolute* reference-track
//! ticks (the join point and the incoming asset's own start) directly into
//! each track's timescale — it never caches and re-rescales an
//! already-rounded delta from a previous splice. A chain of splices reads
//! real integers out of the previous call's result every time, so any
//! sub-tick rounding from one splice can never compound into the next.
//! - **`dts: None` samples are left untouched** — a section-carried sample
//! (SCTE-35/DSM-CC/private sections) has no timestamp to rebase and none is
//! fabricated.
//!
//! The reference track's own contribution lands exactly on the join (no
//! rescale needed, same timescale); a non-reference track's contribution
//! lands within a fraction of a tick of the wall-clock join, preserving
//! whatever real inter-track relationship the incoming asset already had
//! (e.g. a small audio pre-roll ahead of video) rather than forcing every
//! track to butt exactly against its own predecessor.
//!
//! # Keyframe / RAP alignment
//!
//! A splice boundary must fall on a sync sample (random-access point) so the
//! spliced-in content — and the resumed base — can be decoded from the cut.
//! [`concat`](fn@concat) and [`splice_insert`] therefore require the inserted content's
//! first sample to be a sync sample ([`Error::InvalidInput`] otherwise). For
//! [`splice_insert`] the requested splice time is **snapped to the nearest
//! preceding sync sample** of the base's video track via [`snap_to_preceding_sync`]
//! (a helper, so the snap is independently testable); the snapped time is exposed
//! on the returned [`SplicePoint`]s.
//!
//! # Discontinuity signalling
//!
//! Each join is a media-timeline discontinuity (RFC 8216 §4.3.2.3). The result
//! is a [`SpliceResult`] carrying the [`Media`] plus the [`SplicePoint`]s (track
//! id + sample index + presentation time of each join), so a downstream HLS
//! packager / [`Segmenter`](crate::segmenter::Segmenter) can emit
//! `#EXT-X-DISCONTINUITY` before exactly those segments (drive the segmenter's
//! [`mark_discontinuity`](crate::segmenter::Segmenter::mark_discontinuity) at the
//! reported sample indices).
//!
//! # Follow-up
//!
//! Selecting splice *points* from SCTE-35 cue messages (parsing
//! `splice_info_section` `splice_time`/`break_duration` to decide *where* and how
//! long) is a follow-up — it would add a `scte35-splice` (+ `timed-metadata` for
//! PTS wrap handling) dependency. This module does the timeline mechanics for an
//! explicitly supplied time / point; a later transform can compute those points
//! from SCTE-35 and feed them here.
use crateTrackId;
use Vec;
use ;
use crate;
use crate;
use crateSample;
/// A splice / concatenation join point in a resulting [`Media`] track.
///
/// Identifies the first sample of the spliced-in contribution so a downstream
/// packager can mark the containing segment discontinuous
/// (`#EXT-X-DISCONTINUITY`, RFC 8216 §4.3.2.3).
/// The result of a splice / concatenation: the joined [`Media`] plus the join
/// points that should be signalled as discontinuities.
///
/// `discontinuity_points` lists one [`SplicePoint`] per matched track per join
/// (a [`concat`](fn@concat) yields one join, a [`splice_insert`] yields two — the ad-in and
/// the resume), in track then timeline order.
/// The decode time of a track's first sample beyond its last (its **end decode
/// time**).
///
/// Reads the last sample's own absolute `dts` (media plane step 2c) plus its
/// `duration`, when both are known — this is the authoritative value and can
/// legitimately diverge from `start_decode_time + Σ durations` after a
/// per-fragment `tfdt` reseed (`start_decode_time` only ever records the
/// *first* fragment's anchor, see `media.rs::absorb_fragment`), which is
/// exactly the desync this function used to reintroduce one step downstream
/// of that fix. Falls back to the duration-sum from `start_decode_time` only
/// when the last sample genuinely carries no timestamp at all (a
/// section-carried sample — SCTE-35/DSM-CC/private sections — which has no
/// absolute `dts` to read).
/// Match `a.tracks[i]` to a track in `b`: by `track_id` first, else by index.
///
/// Returns, for each track in `a`, the index of its counterpart in `b`. The
/// mapping is injective — each `b` track index is claimed by at most one `a`
/// track — so dual-track content with no distinguishing `track_id` (e.g. two
/// audio tracks both defaulting to id 0, or ids that happen to collide across
/// `a`/`b`) cannot silently map two `a` tracks onto the same `b` track while
/// leaving another `b` track unmatched (issue #992). Errors if the track sets
/// are incompatible (differing counts, no unclaimed match available, or a
/// matched pair whose codec kind or timescale differs).
/// Pick the single track (by index into `a`/`b`, matched via `mapping`) whose
/// timeline anchors the splice offset applied uniformly to every track
/// (issue #782): the video track if either side has one, else the first
/// track that carries at least one real timestamp on either side. `None`
/// when no track anywhere carries a timestamp — there is nothing to align
/// on, so the caller leaves every sample untouched.
///
/// Deliberately a *single* pick, not one per track: computing the offset
/// independently per track would silently re-align tracks relative to each
/// other and destroy A/V sync (see the module-level doc).
/// Rescale an absolute tick value from one track's media timescale into
/// another's, in 128-bit arithmetic to avoid overflow. Truncates toward zero
/// on a non-exact ratio (matching `repackage::rescale_floor`/`ts_mux::rescale`'s
/// existing technique elsewhere in this crate) — timescales are always
/// positive on a real track; an identity is returned for a degenerate zero or
/// an already-equal pair, with no arithmetic at all.
///
/// Used to convert the *single* splice offset derived from one reference
/// track ([`pick_reference_track`]) into every other matched track's own
/// timescale, so mixed-timescale tracks (e.g. 48 kHz audio alongside 90 kHz
/// video) shift by the same real-world amount of time. Callers always feed
/// this the fresh absolute tick values read directly off the current
/// samples — never an already-rescaled delta carried over from a previous
/// splice — which is what keeps sub-tick rounding from compounding across a
/// chain of splices (see the module-level doc).
/// Shift every sample's absolute `dts`/`pts` — when present — by `offset`
/// ticks in the track's own media timescale.
///
/// Both fields move by the same amount, so each sample's composition offset
/// (`pts - dts`) is preserved exactly. A sample with `dts: None` (a
/// section-carried sample — SCTE-35/DSM-CC/private sections) has no
/// timestamp to rebase and is left untouched — never fabricated.
/// The [`Track::start_decode_time`] anchor for a splice/concat result: the
/// first sample's own absolute `dts` when there is one — keeping the anchor
/// in lockstep with the sample it names — else `fallback` (the original
/// track's own anchor, used only when the result has no sample to read one
/// from, or whose first sample is untimed).
/// Append `b` after `a` on a shared, contiguous, monotonic decode timeline.
///
/// Tracks are matched pairwise (by `track_id`, else by index). For each
/// matched track, `b`'s samples follow `a`'s, rebased onto the join by the
/// single reference-track offset described at the module level (issue #782)
/// — `b`'s reference track lands exactly on `a`'s **end decode time**
/// (`a`'s last sample's own absolute `dts` + duration); every other matched
/// track shifts by the same offset, converted into its own timescale.
/// Sample `data` is preserved byte-for-byte; only `dts`/`pts` move, and only
/// when they were `Some` to begin with. The movie timescale is taken from
/// `a`.
///
/// The first sample of each `b` contribution is the splice point and is reported
/// in [`SpliceResult::discontinuity_points`].
///
/// # Errors
/// [`Error::InvalidInput`] if the track sets are incompatible (differing counts,
/// an unmatched id, or a matched pair whose codec kind or timescale differs), or
/// if a matched `b` track's first sample is not a sync sample (a splice boundary
/// must be a random-access point).
/// Snap a requested decode time to the nearest **preceding** sync sample of a
/// track, returning `(snapped_decode_time, sample_index)`.
///
/// A splice boundary must land on a random-access point, so a requested
/// `at_ticks` that falls inside a GOP is pulled back to the decode time of the
/// most recent sync sample at or before it. If `at_ticks` precedes the first
/// sample, it snaps to the first sample (index 0). `at_ticks` is an absolute
/// decode time in `track`'s media timescale (the same units as
/// [`Track::start_decode_time`]).
///
/// Returns `None` when the track has no samples (nothing to snap to).
/// Splice `ad` into `base` at `at_ticks` (server-side ad insertion).
///
/// The result plays `base` up to the splice boundary, then `ad` — rebased
/// from its own file's independent timeline onto the boundary via the single
/// reference-track offset described at the module level (issue #782) — then
/// the remainder of `base`, itself rebased forward so it resumes exactly
/// where the rebased `ad` ends on each track — one monotonic decode timeline
/// across both joins.
///
/// `at_ticks` is an absolute decode time in the base **video** track's media
/// timescale; it is **snapped to the nearest preceding sync sample** of that
/// track (a splice must land on a random-access point). The base's other tracks
/// (audio) are cut at the same *wall-clock* offset corresponding to that video
/// split — the video-timescale offset is rescaled into each other track's own
/// media timescale (audio is virtually never carried on the same timescale as
/// video, e.g. 90 kHz video vs. 44.1/48 kHz audio) before searching for its
/// split sample; audio is not independently RAP-aligned, but every audio sample
/// is itself a sync sample, so the audio cut is always on a RAP. The snapped
/// time is exposed on the returned [`SplicePoint`]s.
///
/// # Errors
/// [`Error::InvalidInput`] if the track sets are incompatible (see [`concat`](fn@concat)),
/// if `base` has no video track to align on, or if a matched `ad` track's first
/// sample is not a sync sample.
/// The decode time of `track`'s natural continuation at `split_index`, in
/// its own media timescale: the boundary sample's own absolute `dts` (media
/// plane step 2c) when there is one — authoritative, and can legitimately
/// diverge from `start_decode_time + Σ durations` after a per-fragment
/// `tfdt` reseed, exactly like `track_end_decode_time`/
/// `snap_to_preceding_sync` above. A past-the-end split (no remaining
/// sample) has no boundary sample to read, so it uses the track's own end
/// decode time instead; a section-carried boundary sample with no absolute
/// `dts` falls back to the duration-sum, same as everywhere else in this
/// module.
/// First sample index of `track` whose **absolute** decode time is at or beyond
/// `cut_ticks`; clamps to the sample count for a past-the-end cut.
///
/// Both sides are absolute (r04-W36 review). The cut comes from the video
/// track's snapped sample, which is an absolute `dts` on the media plane's
/// clock, so it must be compared against each sample's own absolute `dts` —
/// not against a position measured from *this* track's `start_decode_time`.
/// The two differ by exactly the difference in the tracks' starts, so a track
/// that begins later (or earlier) than the video had its cut placed at the
/// wrong instant and A/V desynchronised at the ad boundary.
///
/// The absolute `dts` is used rather than a running sum of `duration`s for the
/// same reason (r04-W36): the two agree only while a track is gap-free, and
/// after a `tfdt` reseed the duration sum cannot recover the real position.
///
/// A sample with no `dts` (section-carried data, which has no timebase of its
/// own) falls back to the duration sum measured from the track's own start,
/// which is the same convention every other boundary read in this module uses.