avio 0.17.0

Video and audio editing engine: build a Timeline of clips, edit with undo/redo, and render to a file
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
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
//! Timeline data type for multi-track composition.
//!
//! This module provides [`Timeline`] and [`TimelineBuilder`], which represent
//! an ordered layout of [`Clip`] instances across video and audio tracks.
//! `Timeline` holds no `FFmpeg` context; all rendering is done in
//! [`Timeline::render()`].

use std::collections::HashMap;
use std::path::Path;
use std::time::{Duration, Instant};

use ff_decode::VideoDecoder;
use ff_encode::VideoEncoder;
use ff_filter::{
    AnimatedValue, AnimationTrack, FilterGraph, FilterStep, MultiTrackAudioMixer,
    MultiTrackComposer, ProxySource, VideoLayer,
};
use ff_format::{AudioFrame, ChannelLayout};

use crate::clip::Clip;
use crate::derive;
use crate::error::TimelineError;
use crate::ids::{ClipId, TrackId};
use crate::marker::Marker;
use crate::track::Track;
use ff_pipeline::EncoderConfig;
use ff_pipeline::Progress;
use ff_pipeline::pipeline::hwaccel_to_hardware_encoder;

/// An ordered layout of [`Clip`] instances across video and audio tracks.
///
/// `Timeline` is a plain Rust value type — it holds no `FFmpeg` context.
/// All rendering happens in [`Timeline::render()`].
///
/// # Construction
///
/// Use [`Timeline::builder()`] to obtain a [`TimelineBuilder`].
///
/// # Examples
///
/// ```
/// use avio::{Clip, Timeline};
/// use std::time::Duration;
///
/// let clip = Clip::new("intro.mp4")
///     .trim(Duration::from_secs(0), Duration::from_secs(5));
///
/// let result = Timeline::builder()
///     .canvas(1920, 1080)
///     .frame_rate(30.0)
///     .video_track(vec![clip])
///     .build();
///
/// assert!(result.is_ok());
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Timeline {
    pub(crate) canvas_width: u32,
    pub(crate) canvas_height: u32,
    /// `true` when the caller set the canvas via [`TimelineBuilder::canvas`] (as
    /// opposed to it being auto-probed from the first clip). Lets consumers such
    /// as the real-time preview know a deliberate output aspect was requested.
    pub(crate) canvas_explicit: bool,
    pub(crate) frame_rate: f64,
    /// `video_tracks[track_idx].clips[clip_idx]`; track 0 = bottom layer.
    pub(crate) video_tracks: Vec<Track>,
    pub(crate) audio_tracks: Vec<Track>,
    /// Next [`ClipId`](crate::ClipId) value to hand out. Monotonic, never reused;
    /// stamped onto clips as they are added. `1` for a fresh document (`0` = unset).
    pub(crate) next_clip_id: u64,
    /// Next [`TrackId`](crate::TrackId) value to hand out (see `next_clip_id`).
    pub(crate) next_track_id: u64,
    /// Next [`MarkerId`](crate::MarkerId) value to hand out (see `next_clip_id`).
    pub(crate) next_marker_id: u64,
    /// Next [`GroupId`](crate::GroupId) value to hand out (see `next_clip_id`).
    pub(crate) next_group_id: u64,
    /// Editorial markers on the timeline. Metadata only — they do not affect
    /// derivation, render, or preview. Addressed by [`MarkerId`](crate::MarkerId).
    pub(crate) markers: Vec<Marker>,
    /// Animation tracks for video layer properties.
    ///
    /// Key format: `"video_{track_index}_{property}"`, e.g. `"video_0_opacity"`.
    ///
    /// Supported properties: `x`, `y`, `scale_x`, `scale_y`, `rotation`, `opacity`.
    pub(crate) video_animations: HashMap<String, AnimationTrack<f64>>,
    /// Animation tracks for audio track properties.
    ///
    /// Key format: `"audio_{track_index}_{property}"`, e.g. `"audio_1_volume"`.
    ///
    /// Supported properties: `volume`, `pan`.
    pub(crate) audio_animations: HashMap<String, AnimationTrack<f64>>,
    /// Optional `lavfi` filtergraph string composited as the topmost video layer.
    ///
    /// When set, a [`VideoLayer`] whose source is
    /// [`LayerSource::Lavfi`](ff_filter::LayerSource) is added above all regular
    /// video tracks. Use `FFmpeg` `drawtext` syntax to render text titles:
    ///
    /// ```text
    /// color=s=1920x1080:c=black@0.0,drawtext=text='Hello':fontsize=48:fontcolor=white
    /// ```
    pub(crate) lavfi_overlay: Option<String>,
    /// Timeline-level (master bus) audio effect chain applied to the final mix on
    /// render. Empty by default (no processing).
    ///
    /// Applied after the multi-track mix, so it operates on the whole program's
    /// audio — the natural place for loudness normalization
    /// ([`FilterStep::LoudnessNormalize`]). Per-track (pre-mix) effects are a
    /// separate feature (see issue #1446).
    ///
    /// Persisted by the `serde` feature (#1452). Compositor-internal steps
    /// (`Blend` / `Composite` / `AlphaMatte`) are not serialized.
    pub(crate) audio_filter: Vec<FilterStep>,
}

impl Timeline {
    /// Returns a new [`TimelineBuilder`].
    pub fn builder() -> TimelineBuilder {
        TimelineBuilder::new()
    }

    /// Returns the canvas width in pixels.
    pub fn canvas_width(&self) -> u32 {
        self.canvas_width
    }

    /// Returns the canvas height in pixels.
    pub fn canvas_height(&self) -> u32 {
        self.canvas_height
    }

    /// Returns the canvas dimensions **only when explicitly set** via
    /// [`TimelineBuilder::canvas`], or `None` when they were auto-probed from the
    /// first clip. Consumers that reframe to a deliberate output aspect (e.g. the
    /// real-time preview) use this to distinguish an intended canvas from a default.
    pub fn explicit_canvas(&self) -> Option<(u32, u32)> {
        if self.canvas_explicit {
            Some((self.canvas_width, self.canvas_height))
        } else {
            None
        }
    }

    /// Returns the frame rate in frames per second.
    pub fn frame_rate(&self) -> f64 {
        self.frame_rate
    }

    /// Returns a slice of all video tracks.
    pub fn video_tracks(&self) -> &[Track] {
        &self.video_tracks
    }

    /// Returns a slice of all audio tracks.
    pub fn audio_tracks(&self) -> &[Track] {
        &self.audio_tracks
    }

    /// Returns the timeline's editorial markers.
    pub fn markers(&self) -> &[Marker] {
        &self.markers
    }

    /// Renders the timeline to an output file.
    ///
    /// Convenience wrapper around [`render_with_progress`](Self::render_with_progress)
    /// that discards progress notifications.
    ///
    /// # Errors
    ///
    /// - [`TimelineError::ClipNotFound`] — a clip's source file is missing
    /// - [`TimelineError::Encode`] — encoder failure
    /// - [`TimelineError::Filter`] — filter graph construction failure
    /// - [`TimelineError::TimelineRenderFailed`] — other structural failure
    pub fn render(
        self,
        output: impl AsRef<Path>,
        config: EncoderConfig,
    ) -> Result<(), TimelineError> {
        self.render_with_progress(output, config, |_| true)
    }

    /// Renders the timeline to an output file, invoking `on_progress` after
    /// each encoded video frame.
    ///
    /// Animation tracks registered via [`TimelineBuilder::video_animation`] and
    /// [`TimelineBuilder::audio_animation`] are forwarded to the corresponding
    /// [`VideoLayer`] / [`AudioTrack`](ff_filter::AudioTrack) fields before the filter graphs are built.
    /// Unrecognised animation keys are ignored and logged as `warn!`.
    ///
    /// `on_progress` receives a [`Progress`] reference after every video frame.
    /// Returning `false` cancels the render and returns
    /// [`TimelineError::Cancelled`]. Audio-only timelines do not invoke the
    /// callback (there are no video frames to report).
    ///
    /// # Example
    ///
    /// ```ignore
    /// let timeline = Timeline::builder()
    ///     .canvas(1920, 1080)
    ///     .frame_rate(30.0)
    ///     .video_track(vec![Clip::new("input.mp4")])
    ///     .build()?;
    ///
    /// timeline.render_with_progress("output.mp4", EncoderConfig::default(), |p| {
    ///     println!("frame {} / {:?}", p.frames_processed, p.total_frames);
    ///     true // return false to cancel
    /// })?;
    /// ```
    ///
    /// # Errors
    ///
    /// - [`TimelineError::ClipNotFound`] — a clip's source file is missing
    /// - [`TimelineError::GeneratedSourceNeedsDuration`] — a generated (Text/Solid)
    ///   clip on an active track has no `out_point` to bound its duration
    /// - [`TimelineError::Cancelled`] — `on_progress` returned `false`
    /// - [`TimelineError::Encode`] — encoder failure
    /// - [`TimelineError::Filter`] — filter graph construction failure
    /// - [`TimelineError::TimelineRenderFailed`] — other structural failure
    pub fn render_with_progress(
        self,
        output: impl AsRef<Path>,
        config: EncoderConfig,
        on_progress: impl Fn(&Progress) -> bool + Send,
    ) -> Result<(), TimelineError> {
        let output = output.as_ref();

        // Compute total expected video frame count from clips with known durations.
        // `None` when any clip runs to end-of-file (out_point not set).
        // Sum clip durations; short-circuits to None if any clip has no out_point.
        // frame_rate and total_dur are always non-negative; max(0.0) + round()
        // guarantees the value fits in u64 for any realistic frame count.
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        let total_frames: Option<u64> = self
            .video_tracks
            .iter()
            .flat_map(|track| track.clips.iter())
            .map(Clip::duration)
            .try_fold(Duration::ZERO, |acc, dur| dur.map(|d| acc + d))
            .map(|total_dur| (total_dur.as_secs_f64() * self.frame_rate).round().max(0.0) as u64);

        let Timeline {
            canvas_width,
            canvas_height,
            canvas_explicit: _,
            frame_rate,
            video_tracks,
            audio_tracks,
            next_clip_id: _,
            next_track_id: _,
            next_marker_id: _,
            next_group_id: _,
            markers: _,
            video_animations,
            audio_animations,
            lavfi_overlay,
            audio_filter,
        } = self;

        let nv = video_tracks.len();
        let na = audio_tracks.len();

        // Solo is scoped per media list; a track is active unless disabled, muted,
        // or shadowed by a solo elsewhere in its list. Computed once here and
        // reused by the pre-check and both derivation loops.
        let any_video_solo = video_tracks.iter().any(|t| t.solo);
        let any_audio_solo = audio_tracks.iter().any(|t| t.solo);

        // 1. Pre-check: sources of active tracks must exist on disk. Inactive
        //    tracks contribute nothing to the render, so an offline source on a
        //    disabled/muted/soloed-out track must not fail the whole export.
        for (track, any_solo) in video_tracks
            .iter()
            .map(|t| (t, any_video_solo))
            .chain(audio_tracks.iter().map(|t| (t, any_audio_solo)))
        {
            if !track.is_active(any_solo) {
                continue;
            }
            for clip in &track.clips {
                match clip.source_path() {
                    // File source: it must exist on disk.
                    Some(path) => {
                        if !path.exists() {
                            return Err(TimelineError::ClipNotFound {
                                path: path.to_string_lossy().into_owned(),
                            });
                        }
                    }
                    // Generated (Text/Solid) source: infinite, so an out_point is
                    // required to bound its duration. Only out_point matters — the
                    // derive emits `Trim { end }` from it (in_point may be unset).
                    None => {
                        if clip.out_point.is_none() {
                            return Err(TimelineError::GeneratedSourceNeedsDuration);
                        }
                    }
                }
            }
        }

        // 2. Warn on unrecognised animation keys.
        let valid_video_props = ["x", "y", "scale_x", "scale_y", "rotation", "opacity"];
        for key in video_animations.keys() {
            let parts: Vec<&str> = key.splitn(3, '_').collect();
            let ok = parts.len() == 3
                && parts[0] == "video"
                && parts[1].parse::<usize>().is_ok()
                && valid_video_props.contains(&parts[2]);
            if !ok {
                log::warn!("unknown animation key key={key}");
            }
        }

        let valid_audio_props = ["volume", "pan"];
        for key in audio_animations.keys() {
            let parts: Vec<&str> = key.splitn(3, '_').collect();
            let ok = parts.len() == 3
                && parts[0] == "audio"
                && parts[1].parse::<usize>().is_ok()
                && valid_audio_props.contains(&parts[2]);
            if !ok {
                log::warn!("unknown animation key key={key}");
            }
        }

        // 3. Build video composition graph.
        let mut video_graph = None;
        if !video_tracks.is_empty() {
            // Per-track end-offset (seconds) of the last clip, used to compute
            // the xfade `offset` arg when the next clip has a transition.
            let mut prev_end_by_track: HashMap<usize, f64> = HashMap::new();

            // Generate the canvas/conform at the timeline rate — the same rate
            // the encoder uses below. A hardcoded mismatch stretches the video
            // relative to the audio for non-30fps timelines.
            let mut composer =
                MultiTrackComposer::new(canvas_width, canvas_height).frame_rate(frame_rate);
            // Inactive tracks (disabled, muted, or shadowed by a solo elsewhere in
            // this list) contribute no layers. The enumerate index is preserved so
            // the timeline animation keys (`video_{idx}_*`) still line up.
            for (track_idx, track) in video_tracks.iter().enumerate() {
                if !track.is_active(any_video_solo) {
                    continue;
                }
                for (clip_idx, clip) in track.clips.iter().enumerate() {
                    let prev_end =
                        (clip_idx > 0).then(|| *prev_end_by_track.get(&track_idx).unwrap_or(&0.0));

                    // When a proxy is set, probe the original source resolution so
                    // the decoded proxy frames can be scaled back up to full size.
                    // If the probe fails the proxy is ignored (original used directly).
                    // A proxy is meaningful only for a file source (generated
                    // sources are rendered at canvas size, nothing to probe).
                    let proxy = clip.proxy.as_ref().zip(clip.source_path()).and_then(
                        |(proxy_path, src)| match VideoDecoder::open(src).build() {
                            Ok(dec) => Some(ProxySource {
                                path: proxy_path.clone(),
                                width: dec.width(),
                                height: dec.height(),
                            }),
                            Err(e) => {
                                log::warn!(
                                    "proxy ignored: cannot probe source {} resolution: {e}",
                                    src.display()
                                );
                                None
                            }
                        },
                    );

                    // Per-clip editorial interpretation → layer lives in `derive`.
                    composer = composer.add_layer(derive::video_layer(
                        clip,
                        track_idx,
                        &video_animations,
                        canvas_width,
                        canvas_height,
                        prev_end,
                        proxy,
                    ));

                    // Track how many seconds this clip contributes, so the next
                    // transition on the same track can compute the correct offset.
                    let end_secs = match clip.duration() {
                        Some(d) => d.as_secs_f64(),
                        None => clip
                            .source_path()
                            .and_then(|src| VideoDecoder::open(src).build().ok())
                            .map_or(0.0, |d| {
                                let total = d.duration().as_secs_f64();
                                match clip.in_point {
                                    Some(ip) => (total - ip.as_secs_f64()).max(0.0),
                                    None => total,
                                }
                            }),
                    };
                    prev_end_by_track.insert(track_idx, end_secs);
                }
            }
            // Lavfi overlay sits above all regular tracks.
            if let Some(ref lavfi_str) = lavfi_overlay {
                use ff_filter::{BlendMode, CompositeOp, LayerSource};
                composer = composer.add_layer(VideoLayer {
                    source: LayerSource::Lavfi(lavfi_str.clone()),
                    proxy: None,
                    x: AnimatedValue::Static(0.0),
                    y: AnimatedValue::Static(0.0),
                    scale_x: AnimatedValue::Static(1.0),
                    scale_y: AnimatedValue::Static(1.0),
                    rotation: AnimatedValue::Static(0.0),
                    opacity: AnimatedValue::Static(1.0),
                    blend_mode: BlendMode::Normal,
                    composite_op: CompositeOp::Over,
                    effects: vec![],
                });
            }

            video_graph = Some(composer.build().map_err(TimelineError::Filter)?);
        }

        // 4. Build audio mix graph.
        //
        //    Two paths share step 7's drain:
        //    * Fast path (no active audio track carries a pre-mix effect chain):
        //      a single source-only mixer over every active clip, streamed to the
        //      encoder (low memory) — the historical behaviour.
        //    * Per-track path (some active track has `audio_effects`): each track
        //      is sub-mixed and run through its own push/pull graph before the
        //      master mix, so a two-pass step (loudness normalization) there
        //      actually fires. Built in step 7 from `audio_tracks`.
        let has_audio = audio_tracks.iter().any(|t| t.is_active(any_audio_solo));
        let has_track_effects = audio_tracks
            .iter()
            .any(|t| t.is_active(any_audio_solo) && !t.audio_effects.is_empty());
        let mut audio_graph = None;
        if has_audio && !has_track_effects {
            let mut mixer = MultiTrackAudioMixer::new(48_000, ChannelLayout::Stereo);
            // Honor mute/solo/enabled: an inactive audio track is silent.
            for (track_idx, track) in audio_tracks.iter().enumerate() {
                if !track.is_active(any_audio_solo) {
                    continue;
                }
                for clip in &track.clips {
                    // Generated (Text/Solid) clips carry no audio; skip them so a
                    // non-File clip never yields an empty-path audio source.
                    if clip.source_path().is_none() {
                        continue;
                    }
                    mixer = mixer.add_track(derive::audio_track(
                        clip,
                        track_idx,
                        &audio_animations,
                        audio_fade_out_eff_dur(clip),
                    ));
                }
            }
            audio_graph = Some(mixer.build().map_err(TimelineError::Filter)?);
        }

        // Timeline-level (master bus) audio effect chain, applied post-mix. Built
        // whenever there is audio to process (both paths route their mixed output
        // through it). A two-pass step (`LoudnessNormalize`) works here because a
        // builder-made `FilterGraph` carries the `steps` its push/pull path keys
        // off — unlike the source-only mixer graph, where it would be inert.
        let master_audio = if has_audio && !audio_filter.is_empty() {
            let mut builder = FilterGraph::builder();
            for step in &audio_filter {
                builder = builder.add_step(step.clone());
            }
            Some(builder.build().map_err(TimelineError::Filter)?)
        } else {
            None
        };

        // 5. Build encoder.
        let hw = hwaccel_to_hardware_encoder(config.hardware);
        let mut enc_builder = VideoEncoder::create(output)
            .video(canvas_width, canvas_height, frame_rate)
            .video_codec(config.video_codec)
            .bitrate_mode(config.bitrate_mode)
            .hardware_encoder(hw);
        if has_audio {
            enc_builder = enc_builder.audio(48_000, 2).audio_codec(config.audio_codec);
        }
        let mut encoder = enc_builder.build().map_err(TimelineError::Encode)?;

        let start = Instant::now();

        // 6. Drain video graph → encoder.
        //    tick() must be called before each pull so that animation entries
        //    registered on the graph update the filter parameters for that frame.
        //    on_progress is invoked after each push; returning false cancels.
        if let Some(mut vgraph) = video_graph {
            let mut video_idx: u32 = 0;
            loop {
                #[allow(clippy::cast_precision_loss)]
                // frame index fits comfortably in f64 mantissa
                let pts = Duration::from_secs_f64(f64::from(video_idx) / frame_rate);
                vgraph.tick(pts);
                match vgraph.pull_video().map_err(TimelineError::Filter)? {
                    Some(frame) => {
                        encoder.push_video(&frame).map_err(TimelineError::Encode)?;
                        video_idx = video_idx.saturating_add(1);
                        let progress = Progress {
                            frames_processed: u64::from(video_idx),
                            total_frames,
                            elapsed: start.elapsed(),
                        };
                        if !on_progress(&progress) {
                            return Err(TimelineError::Cancelled);
                        }
                    }
                    None => break,
                }
            }
        }

        // 7. Drain audio graph → (optional master bus) → encoder.
        //    tick() advances the audio animation clock by the actual duration
        //    of each chunk so PTS stays sample-accurate.
        if let Some(mut agraph) = audio_graph {
            if let Some(mut master) = master_audio {
                // Route the mix through the master effect chain, interleaving pulls
                // so a plain-node chain streams (low memory) rather than buffering
                // the whole program. A two-pass step (loudness normalization) buffers
                // internally and emits nothing until `flush_audio` signals EOF, so
                // the interleaved pull naturally degrades to buffer-all for it; the
                // trailing flush + drain then emits the processed output.
                let mut audio_pts = Duration::ZERO;
                loop {
                    agraph.tick(audio_pts);
                    match agraph.pull_audio().map_err(TimelineError::Filter)? {
                        Some(frame) => {
                            audio_pts += frame.duration();
                            master
                                .push_audio(0, &frame)
                                .map_err(TimelineError::Filter)?;
                            while let Some(out) =
                                master.pull_audio().map_err(TimelineError::Filter)?
                            {
                                encoder.push_audio(&out).map_err(TimelineError::Encode)?;
                            }
                        }
                        None => break,
                    }
                }
                master.flush_audio();
                while let Some(frame) = master.pull_audio().map_err(TimelineError::Filter)? {
                    encoder.push_audio(&frame).map_err(TimelineError::Encode)?;
                }
            } else {
                let mut audio_pts = Duration::ZERO;
                loop {
                    agraph.tick(audio_pts);
                    match agraph.pull_audio().map_err(TimelineError::Filter)? {
                        Some(frame) => {
                            let chunk_dur = frame.duration();
                            encoder.push_audio(&frame).map_err(TimelineError::Encode)?;
                            audio_pts += chunk_dur;
                        }
                        None => break,
                    }
                }
            }
        } else if has_track_effects {
            // Per-track path: each track's audio is sub-mixed and run through its
            // own push/pull effect graph (so a two-pass step fires), then summed.
            let mixed = mix_tracks_with_effects(&audio_tracks, any_audio_solo, &audio_animations)?;
            // Consume `mixed` by value so each frame drops right after it is pushed
            // downstream, freeing the mix buffer as we go (the master bus keeps its
            // own copy for a two-pass step, so holding `mixed` too would double it).
            if let Some(mut master) = master_audio {
                for frame in mixed {
                    master
                        .push_audio(0, &frame)
                        .map_err(TimelineError::Filter)?;
                }
                master.flush_audio();
                while let Some(frame) = master.pull_audio().map_err(TimelineError::Filter)? {
                    encoder.push_audio(&frame).map_err(TimelineError::Encode)?;
                }
            } else {
                for frame in mixed {
                    encoder.push_audio(&frame).map_err(TimelineError::Encode)?;
                }
            }
        }

        // 8. Flush encoder.
        encoder.finish().map_err(TimelineError::Encode)?;

        log::info!(
            "timeline render complete output={} video_tracks={nv} audio_tracks={na}",
            output.display()
        );
        Ok(())
    }
}

/// Resolves a clip's effective duration for a fade-out start offset, probing the
/// source only when a fade-out actually needs it. `None` = no fade-out, or the
/// duration could not be determined.
fn audio_fade_out_eff_dur(clip: &Clip) -> Option<Duration> {
    if clip.fade_out == Duration::ZERO {
        return None;
    }
    clip.duration().or_else(|| {
        clip.source_path()
            .and_then(|src| VideoDecoder::open(src).build().ok())
            .map(|d| {
                let total = d.duration();
                match clip.in_point {
                    Some(ip) => total.saturating_sub(ip),
                    None => total,
                }
            })
    })
}

/// Pulls a source-only audio graph to end-of-stream into a frame buffer, ticking
/// the animation clock by each chunk's duration so any volume automation stays
/// sample-accurate.
fn drain_source_audio(graph: &mut FilterGraph) -> Result<Vec<AudioFrame>, TimelineError> {
    let mut out = Vec::new();
    let mut pts = Duration::ZERO;
    loop {
        graph.tick(pts);
        match graph.pull_audio().map_err(TimelineError::Filter)? {
            Some(frame) => {
                pts += frame.duration();
                out.push(frame);
            }
            None => break,
        }
    }
    Ok(out)
}

/// The per-track (pre-mix) audio path: sub-mix each active track's clips, run the
/// track's [`audio_effects`](Track::audio_effects) chain through its own push/pull
/// [`FilterGraph`] (so a two-pass step such as loudness normalization fires), then
/// sum the processed tracks with an additive `amix`. Returns the mixed program
/// audio (before the timeline master bus).
fn mix_tracks_with_effects(
    audio_tracks: &[Track],
    any_audio_solo: bool,
    audio_animations: &HashMap<String, AnimationTrack<f64>>,
) -> Result<Vec<AudioFrame>, TimelineError> {
    let mut track_buffers: Vec<Vec<AudioFrame>> = Vec::new();
    for (track_idx, track) in audio_tracks.iter().enumerate() {
        if !track.is_active(any_audio_solo) {
            continue;
        }
        // Sub-mix this track's audio-bearing clips (generated clips carry no audio).
        let mut sub = MultiTrackAudioMixer::new(48_000, ChannelLayout::Stereo);
        let mut has_clip = false;
        for clip in &track.clips {
            if clip.source_path().is_none() {
                continue;
            }
            sub = sub.add_track(derive::audio_track(
                clip,
                track_idx,
                audio_animations,
                audio_fade_out_eff_dur(clip),
            ));
            has_clip = true;
        }
        if !has_clip {
            continue;
        }
        let mut sub_graph = sub.build().map_err(TimelineError::Filter)?;

        // No effect chain: the track's contribution is the raw sub-mix. Otherwise
        // route the sub-mix through the track's push/pull effect graph.
        let processed = if track.audio_effects.is_empty() {
            drain_source_audio(&mut sub_graph)?
        } else {
            let mut fx_builder = FilterGraph::builder();
            for step in &track.audio_effects {
                fx_builder = fx_builder.add_step(step.clone());
            }
            let mut fx = fx_builder.build().map_err(TimelineError::Filter)?;
            let mut pts = Duration::ZERO;
            loop {
                sub_graph.tick(pts);
                match sub_graph.pull_audio().map_err(TimelineError::Filter)? {
                    Some(frame) => {
                        pts += frame.duration();
                        fx.push_audio(0, &frame).map_err(TimelineError::Filter)?;
                    }
                    None => break,
                }
            }
            fx.flush_audio();
            let mut out = Vec::new();
            while let Some(frame) = fx.pull_audio().map_err(TimelineError::Filter)? {
                out.push(frame);
            }
            out
        };
        if !processed.is_empty() {
            track_buffers.push(processed);
        }
    }

    // Sum the processed tracks. One (or zero) track needs no mix; several are
    // combined with an additive `amix`, pushed slot-by-slot in frame-index
    // lockstep so the inputs stay aligned and no input reaches EOF early.
    Ok(match track_buffers.len() {
        0 => Vec::new(),
        1 => track_buffers.into_iter().next().unwrap_or_default(),
        n => {
            let mut amix = FilterGraph::builder()
                .amix(n)
                .build()
                .map_err(TimelineError::Filter)?;
            let max_len = track_buffers.iter().map(Vec::len).max().unwrap_or(0);
            let mut mixed = Vec::new();
            for i in 0..max_len {
                for (slot, buf) in track_buffers.iter().enumerate() {
                    if let Some(frame) = buf.get(i) {
                        amix.push_audio(slot, frame)
                            .map_err(TimelineError::Filter)?;
                    }
                }
                while let Some(frame) = amix.pull_audio().map_err(TimelineError::Filter)? {
                    mixed.push(frame);
                }
            }
            amix.flush_audio();
            while let Some(frame) = amix.pull_audio().map_err(TimelineError::Filter)? {
                mixed.push(frame);
            }
            mixed
        }
    })
}

/// Builder for [`Timeline`].
///
/// Obtain one via [`Timeline::builder()`].
pub struct TimelineBuilder {
    canvas_width: Option<u32>,
    canvas_height: Option<u32>,
    frame_rate: Option<f64>,
    video_tracks: Vec<Track>,
    audio_tracks: Vec<Track>,
    video_animations: HashMap<String, AnimationTrack<f64>>,
    audio_animations: HashMap<String, AnimationTrack<f64>>,
    /// See [`TimelineBuilder::lavfi_overlay`].
    lavfi_overlay: Option<String>,
    /// See [`TimelineBuilder::audio_filter`].
    audio_filter: Vec<FilterStep>,
}

impl Default for TimelineBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl TimelineBuilder {
    /// Creates a new builder with no tracks and no canvas/frame-rate set.
    pub fn new() -> Self {
        Self {
            canvas_width: None,
            canvas_height: None,
            frame_rate: None,
            video_tracks: Vec::new(),
            audio_tracks: Vec::new(),
            video_animations: HashMap::new(),
            audio_animations: HashMap::new(),
            lavfi_overlay: None,
            audio_filter: Vec::new(),
        }
    }

    /// Sets the output canvas dimensions in pixels.
    #[must_use]
    pub fn canvas(self, width: u32, height: u32) -> Self {
        Self {
            canvas_width: Some(width),
            canvas_height: Some(height),
            ..self
        }
    }

    /// Sets the output frame rate in frames per second.
    #[must_use]
    pub fn frame_rate(self, fps: f64) -> Self {
        Self {
            frame_rate: Some(fps),
            ..self
        }
    }

    /// Appends a video track holding `clips` (default flags, no name). Track 0
    /// (first call) is the bottom layer.
    ///
    /// Use [`video_track_with`](Self::video_track_with) to append a track with a
    /// name or mute/solo/enabled/lock flags set.
    #[must_use]
    pub fn video_track(self, clips: Vec<Clip>) -> Self {
        self.video_track_with(Track::new(clips))
    }

    /// Appends a preconfigured video [`Track`] (name, mute/solo/enabled/lock).
    #[must_use]
    pub fn video_track_with(self, track: Track) -> Self {
        let mut video_tracks = self.video_tracks;
        video_tracks.push(track);
        Self {
            video_tracks,
            ..self
        }
    }

    /// Appends an audio track holding `clips` (default flags, no name).
    #[must_use]
    pub fn audio_track(self, clips: Vec<Clip>) -> Self {
        self.audio_track_with(Track::new(clips))
    }

    /// Appends a preconfigured audio [`Track`] (name, mute/solo/enabled/lock).
    #[must_use]
    pub fn audio_track_with(self, track: Track) -> Self {
        let mut audio_tracks = self.audio_tracks;
        audio_tracks.push(track);
        Self {
            audio_tracks,
            ..self
        }
    }

    /// Registers a video-layer animation track.
    ///
    /// Key format: `"video_{track_index}_{property}"`, e.g. `"video_0_opacity"`.
    ///
    /// Supported properties: `x`, `y`, `scale_x`, `scale_y`, `rotation`, `opacity`.
    /// Unrecognised keys are stored but emit `log::warn!` during [`Timeline::render()`].
    #[must_use]
    pub fn video_animation(self, key: impl Into<String>, track: AnimationTrack<f64>) -> Self {
        let mut video_animations = self.video_animations;
        video_animations.insert(key.into(), track);
        Self {
            video_animations,
            ..self
        }
    }

    /// Registers an audio-track animation track.
    ///
    /// Key format: `"audio_{track_index}_{property}"`, e.g. `"audio_0_volume"`.
    ///
    /// Supported properties: `volume`, `pan`.
    /// Unrecognised keys are stored but emit `log::warn!` during [`Timeline::render()`].
    #[must_use]
    pub fn audio_animation(self, key: impl Into<String>, track: AnimationTrack<f64>) -> Self {
        let mut audio_animations = self.audio_animations;
        audio_animations.insert(key.into(), track);
        Self {
            audio_animations,
            ..self
        }
    }

    /// Sets an `FFmpeg` `lavfi` filtergraph string that is composited as the topmost
    /// video layer during rendering.
    ///
    /// The string is interpreted by `FFmpeg`'s `lavfi` virtual demuxer via the `movie`
    /// filter's `format_name=lavfi` option. Use `drawtext` to render text titles, or
    /// chain multiple filter expressions with `,`:
    ///
    /// ```ignore
    /// builder.lavfi_overlay(
    ///     "color=s=1920x1080:c=black@0.0,\
    ///      drawtext=text='Hello World':fontsize=48:fontcolor=white:\
    ///      x=(w-text_w)/2:y=(h-text_h)/2"
    /// )
    /// ```
    ///
    /// When not set (the default) no overlay is added and the rendering path is unchanged.
    #[must_use]
    pub fn lavfi_overlay(self, filter: impl Into<String>) -> Self {
        Self {
            lavfi_overlay: Some(filter.into()),
            ..self
        }
    }

    /// Sets a timeline-level (master bus) audio effect chain applied to the final
    /// mix on render.
    ///
    /// The steps run in order on the whole program's mixed audio, after the
    /// multi-track mix and before the encoder — the natural place for loudness
    /// normalization ([`FilterStep::LoudnessNormalize`]). When not set (the
    /// default, an empty chain) the audio path is unchanged. Per-track (pre-mix)
    /// effects are a separate feature (see issue #1446).
    #[must_use]
    pub fn audio_filter(self, steps: Vec<FilterStep>) -> Self {
        Self {
            audio_filter: steps,
            ..self
        }
    }

    /// Builds the [`Timeline`].
    ///
    /// # Errors
    ///
    /// - [`TimelineError::NoInput`] — both track lists are empty
    /// - [`TimelineError::ClipNotFound`] — canvas/fps auto-probe needed but
    ///   the first video clip's source file does not exist
    /// - [`TimelineError::Decode`] — the first video clip could not be opened
    pub fn build(self) -> Result<Timeline, TimelineError> {
        if self.video_tracks.is_empty() && self.audio_tracks.is_empty() {
            return Err(TimelineError::NoInput);
        }

        let canvas_explicit = self.canvas_width.is_some() && self.canvas_height.is_some();
        let (canvas_width, canvas_height, frame_rate) = self.resolve_canvas_and_fps()?;

        // Stamp stable ids from monotonic counters (0 = unset; ids start at 1),
        // video tracks first. The final counter values are stored so later edits
        // (`AddClip` / `AddTrack`) keep minting fresh, never-reused ids.
        let mut next_track_id: u64 = 1;
        let mut next_clip_id: u64 = 1;
        let mut video_tracks = self.video_tracks;
        let mut audio_tracks = self.audio_tracks;
        for track in video_tracks.iter_mut().chain(audio_tracks.iter_mut()) {
            track.id = TrackId::from_raw(next_track_id);
            next_track_id += 1;
            for clip in &mut track.clips {
                clip.id = ClipId::from_raw(next_clip_id);
                next_clip_id += 1;
            }
        }

        Ok(Timeline {
            canvas_width,
            canvas_height,
            canvas_explicit,
            frame_rate,
            video_tracks,
            audio_tracks,
            next_clip_id,
            next_track_id,
            next_marker_id: 1,
            next_group_id: 1,
            markers: Vec::new(),
            video_animations: self.video_animations,
            audio_animations: self.audio_animations,
            lavfi_overlay: self.lavfi_overlay,
            audio_filter: self.audio_filter,
        })
    }

    /// Resolves canvas dimensions and frame rate.
    ///
    /// When all three values are explicitly set, returns them directly.
    /// Otherwise probes the first video clip with `VideoDecoder`. For
    /// audio-only timelines (no video tracks) falls back to 1920×1080 @ 30 fps.
    fn resolve_canvas_and_fps(&self) -> Result<(u32, u32, f64), TimelineError> {
        let need_probe = self.canvas_width.is_none()
            || self.canvas_height.is_none()
            || self.frame_rate.is_none();

        // Probe the first video clip when it is file-backed. A leading generated
        // (Text/Solid) clip has no file to probe (`source_path()` is `None`), so
        // the canvas falls through to the 1920x1080@30 default.
        if need_probe
            && let Some(source) = self
                .video_tracks
                .first()
                .and_then(|t| t.clips.first())
                .and_then(|c| c.source_path())
        {
            if !source.exists() {
                return Err(TimelineError::ClipNotFound {
                    path: source.to_string_lossy().into_owned(),
                });
            }
            let vdec = VideoDecoder::open(source).build()?;
            let w = self.canvas_width.unwrap_or_else(|| vdec.width());
            let h = self.canvas_height.unwrap_or_else(|| vdec.height());
            let fps = self.frame_rate.unwrap_or_else(|| vdec.frame_rate());
            return Ok((w, h, fps));
        }

        // All values explicit, no video tracks (audio-only), or a leading
        // generated clip with no file to probe — fall back for absent values.
        Ok((
            self.canvas_width.unwrap_or(1920),
            self.canvas_height.unwrap_or(1080),
            self.frame_rate.unwrap_or(30.0),
        ))
    }
}

// Timeline -> Scene derivation (real-time preview)

/// Projects one video clip into a [`ScenePlacement`](ff_preview::ScenePlacement).
/// `is_base` selects the V1 base track, where a crossfade transition contributes a
/// `xfade_dur`; overlays force zero (matching the compositor).
#[cfg(feature = "preview")]
fn video_placement(
    clip: &Clip,
    track_idx: usize,
    is_base: bool,
    animations: &HashMap<String, AnimationTrack<f64>>,
    canvas_width: u32,
    canvas_height: u32,
) -> ff_preview::ScenePlacement {
    let xfade_dur = if is_base && clip.transition.is_some() {
        clip.transition_duration
    } else {
        Duration::ZERO
    };
    // Carry the transition kind (not just its duration) so preview renders the
    // actual xfade kind; overlays force no transition (matching the compositor).
    let xfade_kind = if is_base { clip.transition } else { None };
    ff_preview::ScenePlacement {
        // Preview compositing of generated (Text/Solid) sources is deferred; a
        // non-file clip projects an empty path (the preview runner renders nothing).
        source: clip
            .source_path()
            .map(Path::to_path_buf)
            .unwrap_or_default(),
        offset: clip.offset,
        in_point: clip.in_point.unwrap_or(Duration::ZERO),
        out_point: clip.out_point,
        speed: clip.speed.max(0.01),
        xfade_dur,
        xfade_kind,
        opacity: clip.opacity.clamp(0.0, 1.0),
        // The single derive: preview and export build their video layers from the
        // same `avio::derive`, so the timeline-level animations (scale/rotation and
        // the opacity/x/y track-level fallbacks) reach the preview too.
        layer: crate::derive::realtime_descriptor(
            clip,
            track_idx,
            animations,
            canvas_width,
            canvas_height,
        ),
        fade_in: clip.fade_in,
        fade_out: clip.fade_out,
        // V1 clip audio has no dedicated audio-track counterpart in export (which
        // mixes only `audio_tracks`), so its volume is the per-clip merge only.
        volume: crate::derive::audio_volume(clip, 0, &HashMap::new()),
        // The same shared derive as export, so preview pitch matches export.
        pitch: crate::derive::audio_pitch(clip),
    }
}

/// Projects one audio-only clip into a [`SceneAudioPlacement`](ff_preview::SceneAudioPlacement).
/// `track_idx` is the audio track index; `animations` the timeline `audio_animations`.
#[cfg(feature = "preview")]
fn audio_placement(
    clip: &Clip,
    track_idx: usize,
    animations: &HashMap<String, AnimationTrack<f64>>,
) -> ff_preview::SceneAudioPlacement {
    ff_preview::SceneAudioPlacement {
        source: clip
            .source_path()
            .map(Path::to_path_buf)
            .unwrap_or_default(),
        offset: clip.offset,
        in_point: clip.in_point.unwrap_or(Duration::ZERO),
        out_point: clip.out_point,
        speed: clip.speed.max(0.01),
        fade_in: clip.fade_in,
        fade_out: clip.fade_out,
        // The single derive: the volume 3-way merge (incl. the timeline
        // `audio_{idx}_volume` automation) reaches preview, matching export.
        volume: crate::derive::audio_volume(clip, track_idx, animations),
        // The same shared derive as export, so preview pitch matches export.
        pitch: crate::derive::audio_pitch(clip),
    }
}

#[cfg(feature = "preview")]
impl Timeline {
    /// Projects this timeline into a primitive [`Scene`](ff_preview::Scene) for the
    /// real-time preview runner. This is a pure model projection — no probing or
    /// I/O; media-dependent resolution (durations, audio presence, frame size)
    /// happens later in [`ScenePlayer::open`](ff_preview::ScenePlayer::open).
    ///
    /// Video track `0` is the V1 base (crossfade transitions apply); tracks `1..`
    /// are overlays (transitions forced off, matching the compositor).
    #[must_use]
    pub fn to_scene(&self) -> ff_preview::Scene {
        // Inactive tracks (disabled, muted, or shadowed by a solo elsewhere in the
        // list) project no placements, but keep their slot so the base-track
        // (index 0) rule and the `video_{idx}_*` animation keys stay aligned.
        let any_video_solo = self.video_tracks.iter().any(|t| t.solo);
        let video_tracks = self
            .video_tracks
            .iter()
            .enumerate()
            .map(|(track_idx, track)| ff_preview::SceneVideoTrack {
                placements: if track.is_active(any_video_solo) {
                    track
                        .clips
                        .iter()
                        .map(|clip| {
                            video_placement(
                                clip,
                                track_idx,
                                track_idx == 0,
                                &self.video_animations,
                                self.canvas_width,
                                self.canvas_height,
                            )
                        })
                        .collect()
                } else {
                    Vec::new()
                },
            })
            .collect();

        let any_audio_solo = self.audio_tracks.iter().any(|t| t.solo);
        let audio_tracks = self
            .audio_tracks
            .iter()
            .enumerate()
            .map(|(track_idx, track)| ff_preview::SceneAudioTrack {
                placements: if track.is_active(any_audio_solo) {
                    track
                        .clips
                        .iter()
                        .map(|clip| audio_placement(clip, track_idx, &self.audio_animations))
                        .collect()
                } else {
                    Vec::new()
                },
            })
            .collect();

        ff_preview::Scene {
            fps: self.frame_rate().max(1.0),
            canvas: self.explicit_canvas(),
            lavfi_overlay: self.lavfi_overlay.clone(),
            video_tracks,
            audio_tracks,
        }
    }
}

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

    #[cfg(feature = "preview")]
    #[test]
    fn timeline_to_scene_should_project_clip_fields() {
        use ff_filter::XfadeTransition;

        let timeline = Timeline::builder()
            // Explicit canvas + fps so build() does not probe the fake sources.
            .canvas(1920, 1080)
            .frame_rate(30.0)
            .video_track(vec![
                Clip::new("a.mp4")
                    .trim(Duration::from_secs(1), Duration::from_secs(3))
                    .offset(Duration::from_millis(500))
                    .with_opacity(0.5)
                    .with_speed(2.0)
                    .with_volume_track(AnimationTrack::new()),
                Clip::new("b.mp4")
                    .with_transition(XfadeTransition::Fade, Duration::from_millis(750)),
            ])
            .video_track(vec![
                // Overlay: a transition here must project as zero.
                Clip::new("overlay.mp4")
                    .with_transition(XfadeTransition::Fade, Duration::from_millis(400)),
            ])
            .audio_track(vec![
                Clip::new("music.mp3")
                    .with_fade_in(Duration::from_millis(200))
                    .with_fade_out(Duration::from_millis(300))
                    .volume(-6.0),
            ])
            .build()
            .unwrap();

        let scene = timeline.to_scene();

        assert!((scene.fps - 30.0).abs() < f64::EPSILON);
        assert_eq!(scene.canvas, Some((1920, 1080)));
        assert_eq!(scene.video_tracks.len(), 2);
        assert_eq!(scene.audio_tracks.len(), 1);

        let base = &scene.video_tracks[0].placements[0];
        assert_eq!(base.source.to_str(), Some("a.mp4"));
        assert_eq!(base.offset, Duration::from_millis(500));
        assert_eq!(base.in_point, Duration::from_secs(1));
        assert_eq!(base.out_point, Some(Duration::from_secs(3)));
        assert!((base.speed - 2.0).abs() < f64::EPSILON);
        assert!((base.opacity - 0.5).abs() < f32::EPSILON);
        assert_eq!(base.xfade_dur, Duration::ZERO, "clip 0 has no transition");
        assert_eq!(base.xfade_kind, None, "clip 0 has no transition kind");
        assert!(matches!(base.volume, AnimatedValue::Track(_)));
        assert!(
            matches!(base.layer.opacity, AnimatedValue::Static(v) if (v - 0.5).abs() < f64::EPSILON)
        );

        let base1 = &scene.video_tracks[0].placements[1];
        assert_eq!(base1.xfade_dur, Duration::from_millis(750));
        assert_eq!(
            base1.xfade_kind,
            Some(XfadeTransition::Fade),
            "base track carries the xfade kind"
        );

        let overlay = &scene.video_tracks[1].placements[0];
        assert_eq!(
            overlay.xfade_dur,
            Duration::ZERO,
            "overlay transitions must project as zero"
        );
        assert_eq!(
            overlay.xfade_kind, None,
            "overlay transition kind is forced off"
        );

        let audio = &scene.audio_tracks[0].placements[0];
        assert_eq!(audio.source.to_str(), Some("music.mp3"));
        assert_eq!(audio.fade_in, Duration::from_millis(200));
        assert_eq!(audio.fade_out, Duration::from_millis(300));
        assert!(matches!(audio.volume, AnimatedValue::Static(v) if (v + 6.0).abs() < f64::EPSILON));
    }

    #[cfg(feature = "preview")]
    #[test]
    fn to_scene_should_route_timeline_animations_into_the_preview_layer() {
        use ff_filter::{AnimatedValue, Easing, Keyframe};

        // Track 1 (overlay) gets timeline scale_x + rotation animations, and an opacity
        // animation the neutral clip should fall back to (the 3-way merge). The single
        // derive must route all three into the preview placement's layer.
        let timeline = Timeline::builder()
            .canvas(1920, 1080)
            .frame_rate(30.0)
            .video_track(vec![Clip::new("base.mp4")])
            .video_track(vec![Clip::new("overlay.mp4")])
            .video_animation(
                "video_1_scale_x",
                AnimationTrack::new().push(Keyframe::new(Duration::ZERO, 0.5, Easing::Linear)),
            )
            .video_animation(
                "video_1_rotation",
                AnimationTrack::new().push(Keyframe::new(Duration::ZERO, 45.0, Easing::Linear)),
            )
            .video_animation(
                "video_1_opacity",
                AnimationTrack::new().push(Keyframe::new(Duration::ZERO, 1.0, Easing::Linear)),
            )
            .build()
            .unwrap();

        let scene = timeline.to_scene();
        let overlay = &scene.video_tracks[1].placements[0];
        assert!(matches!(overlay.layer.scale_x, AnimatedValue::Track(_)));
        assert!(matches!(overlay.layer.rotation, AnimatedValue::Track(_)));
        assert!(matches!(overlay.layer.opacity, AnimatedValue::Track(_)));
    }

    #[cfg(feature = "preview")]
    #[test]
    fn to_scene_should_carry_lavfi_overlay() {
        let timeline = Timeline::builder()
            .canvas(1920, 1080)
            .frame_rate(30.0)
            .video_track(vec![Clip::new("a.mp4")])
            .lavfi_overlay("color=s=1920x1080:c=black@0.0")
            .build()
            .unwrap();
        let scene = timeline.to_scene();
        assert_eq!(
            scene.lavfi_overlay.as_deref(),
            Some("color=s=1920x1080:c=black@0.0")
        );
    }

    #[test]
    fn timeline_default_audio_filter_should_be_empty() {
        let timeline = Timeline::builder()
            .canvas(1920, 1080)
            .frame_rate(30.0)
            .video_track(vec![Clip::new("a.mp4")])
            .build()
            .unwrap();
        assert!(timeline.audio_filter.is_empty());
    }

    #[test]
    fn timeline_builder_audio_filter_should_set_chain() {
        let timeline = Timeline::builder()
            .canvas(1920, 1080)
            .frame_rate(30.0)
            .video_track(vec![Clip::new("a.mp4")])
            .audio_filter(vec![FilterStep::Volume(-6.0)])
            .build()
            .unwrap();
        assert_eq!(timeline.audio_filter.len(), 1);
        assert!(matches!(
            timeline.audio_filter[0],
            FilterStep::Volume(v) if (v - (-6.0)).abs() < 1e-9
        ));
    }

    #[cfg(feature = "preview")]
    #[test]
    fn to_scene_should_carry_audio_speed_and_merged_volume() {
        use ff_filter::{Easing, Keyframe};

        let timeline = Timeline::builder()
            .canvas(1920, 1080)
            .frame_rate(30.0)
            .video_track(vec![Clip::new("v.mp4")])
            .audio_track(vec![Clip::new("a.mp3").with_speed(2.0)]) // neutral volume
            .audio_animation(
                "audio_0_volume",
                AnimationTrack::new().push(Keyframe::new(Duration::ZERO, -3.0, Easing::Linear)),
            )
            .build()
            .unwrap();
        let scene = timeline.to_scene();
        let audio = &scene.audio_tracks[0].placements[0];
        assert!((audio.speed - 2.0).abs() < f64::EPSILON);
        // The neutral clip volume falls back to the timeline `audio_0_volume` automation.
        assert!(matches!(audio.volume, AnimatedValue::Track(_)));
    }

    #[cfg(feature = "preview")]
    #[test]
    fn to_scene_should_carry_pitch() {
        use ff_filter::{Easing, Keyframe};

        let timeline = Timeline::builder()
            .canvas(1920, 1080)
            .frame_rate(30.0)
            .video_track(vec![Clip::new("v.mp4").with_pitch(3.0)])
            .audio_track(vec![Clip::new("a.mp3").with_pitch(1.0).with_pitch_track(
                AnimationTrack::new().push(Keyframe::new(Duration::ZERO, 5.0, Easing::Linear)),
            )])
            .build()
            .unwrap();
        let scene = timeline.to_scene();
        // Video-clip audio carries the static per-clip pitch.
        assert!((scene.video_tracks[0].placements[0].pitch - 3.0).abs() < f64::EPSILON);
        // Audio-only clip: a set pitch_track wins over the static pitch, at t=0.
        assert!((scene.audio_tracks[0].placements[0].pitch - 5.0).abs() < f64::EPSILON);
    }

    #[cfg(feature = "preview")]
    #[test]
    fn to_scene_should_drop_disabled_video_track_placements() {
        let timeline = Timeline::builder()
            .canvas(1920, 1080)
            .frame_rate(30.0)
            .video_track_with(Track::new(vec![Clip::new("base.mp4")]).enabled(false))
            .video_track(vec![Clip::new("overlay.mp4")])
            .build()
            .unwrap();
        let scene = timeline.to_scene();
        assert_eq!(scene.video_tracks.len(), 2, "track slots are preserved");
        assert!(
            scene.video_tracks[0].placements.is_empty(),
            "a disabled track projects no placements"
        );
        assert_eq!(scene.video_tracks[1].placements.len(), 1);
    }

    #[cfg(feature = "preview")]
    #[test]
    fn to_scene_should_drop_muted_video_track_placements() {
        let timeline = Timeline::builder()
            .canvas(1920, 1080)
            .frame_rate(30.0)
            .video_track_with(Track::new(vec![Clip::new("base.mp4")]).muted(true))
            .build()
            .unwrap();
        let scene = timeline.to_scene();
        assert!(scene.video_tracks[0].placements.is_empty());
    }

    #[cfg(feature = "preview")]
    #[test]
    fn to_scene_solo_should_keep_only_soloed_video_tracks() {
        let timeline = Timeline::builder()
            .canvas(1920, 1080)
            .frame_rate(30.0)
            .video_track(vec![Clip::new("base.mp4")]) // not soloed
            .video_track_with(Track::new(vec![Clip::new("overlay.mp4")]).soloed(true))
            .build()
            .unwrap();
        let scene = timeline.to_scene();
        assert!(
            scene.video_tracks[0].placements.is_empty(),
            "a non-soloed track is shadowed when another is soloed"
        );
        assert_eq!(scene.video_tracks[1].placements.len(), 1);
    }

    #[cfg(feature = "preview")]
    #[test]
    fn to_scene_should_drop_muted_audio_track_placements() {
        let timeline = Timeline::builder()
            .canvas(1920, 1080)
            .frame_rate(30.0)
            .video_track(vec![Clip::new("v.mp4")])
            .audio_track_with(Track::new(vec![Clip::new("a.mp3")]).muted(true))
            .build()
            .unwrap();
        let scene = timeline.to_scene();
        assert!(scene.audio_tracks[0].placements.is_empty());
    }

    #[cfg(feature = "preview")]
    #[test]
    fn to_scene_should_drop_disabled_audio_track_placements() {
        let timeline = Timeline::builder()
            .canvas(1920, 1080)
            .frame_rate(30.0)
            .video_track(vec![Clip::new("v.mp4")])
            .audio_track_with(Track::new(vec![Clip::new("a.mp3")]).enabled(false))
            .build()
            .unwrap();
        let scene = timeline.to_scene();
        assert!(scene.audio_tracks[0].placements.is_empty());
    }

    #[cfg(feature = "preview")]
    #[test]
    fn to_scene_solo_should_keep_only_soloed_audio_tracks() {
        let timeline = Timeline::builder()
            .canvas(1920, 1080)
            .frame_rate(30.0)
            .video_track(vec![Clip::new("v.mp4")])
            .audio_track(vec![Clip::new("a.mp3")]) // not soloed
            .audio_track_with(Track::new(vec![Clip::new("b.mp3")]).soloed(true))
            .build()
            .unwrap();
        let scene = timeline.to_scene();
        assert!(
            scene.audio_tracks[0].placements.is_empty(),
            "a non-soloed audio track is shadowed when another is soloed"
        );
        assert_eq!(scene.audio_tracks[1].placements.len(), 1);
    }

    #[test]
    fn timeline_builder_should_err_when_no_tracks() {
        let result = Timeline::builder().build();
        assert!(matches!(result, Err(TimelineError::NoInput)));
    }

    #[test]
    fn render_should_reject_generated_clip_without_out_point() {
        use ff_format::TextSpec;
        // A Text clip with no out_point is infinite; the render pre-check must
        // reject it before touching FFmpeg (deterministic on any machine).
        let timeline = Timeline::builder()
            .canvas(1920, 1080)
            .frame_rate(30.0)
            .video_track(vec![Clip::text(TextSpec::new("no out_point"))])
            .build()
            .unwrap();
        let out = std::env::temp_dir().join("avio_generated_no_outpoint_test.mp4");
        let result = timeline.render(out, EncoderConfig::builder().build());
        assert!(matches!(
            result,
            Err(TimelineError::GeneratedSourceNeedsDuration)
        ));
    }

    #[test]
    fn render_should_accept_generated_clip_with_out_point_only() {
        use ff_format::Color;
        // Only out_point bounds a generated source (in_point may be unset); the
        // derive emits `Trim { end }` from it. The pre-check must NOT reject this
        // valid, bounded clip. Deterministic on any machine: whatever the render
        // outcome, it must not be GeneratedSourceNeedsDuration.
        let mut clip = Clip::solid(Color::rgb(0, 0, 0));
        clip.out_point = Some(Duration::from_secs(1));
        assert!(clip.in_point.is_none());
        let timeline = Timeline::builder()
            .canvas(160, 90)
            .frame_rate(30.0)
            .video_track(vec![clip])
            .build()
            .unwrap();
        let out = std::env::temp_dir().join("avio_generated_outpoint_only_test.mp4");
        let result = timeline.render(out, EncoderConfig::builder().build());
        assert!(
            !matches!(result, Err(TimelineError::GeneratedSourceNeedsDuration)),
            "an out_point-only generated clip must not be rejected"
        );
    }

    #[test]
    fn build_should_default_canvas_when_first_clip_is_generated() {
        use ff_format::Color;
        // A leading generated clip has no file to probe, so the canvas falls
        // through to the 1920x1080@30 default without any I/O.
        let timeline = Timeline::builder()
            .video_track(vec![
                Clip::solid(Color::rgb(0, 0, 0)).trim(Duration::ZERO, Duration::from_secs(1)),
            ])
            .build()
            .unwrap();
        assert_eq!(timeline.canvas_width, 1920);
        assert_eq!(timeline.canvas_height, 1080);
        assert!((timeline.frame_rate - 30.0).abs() < f64::EPSILON);
    }

    #[test]
    fn timeline_builder_should_succeed_with_video_track() {
        let clip = Clip::new("video.mp4");
        let timeline = Timeline::builder()
            .canvas(1920, 1080)
            .frame_rate(30.0)
            .video_track(vec![clip])
            .build()
            .unwrap();

        assert_eq!(timeline.canvas_width, 1920);
        assert_eq!(timeline.canvas_height, 1080);
        assert!((timeline.frame_rate - 30.0).abs() < f64::EPSILON);
        assert_eq!(timeline.video_tracks.len(), 1);
        assert!(timeline.audio_tracks.is_empty());
    }

    #[test]
    fn timeline_builder_should_store_video_animation_track() {
        use ff_filter::{AnimationTrack, Easing, Keyframe};
        use std::time::Duration;

        let track = AnimationTrack::new()
            .push(Keyframe::new(Duration::ZERO, 1.0_f64, Easing::Linear))
            .push(Keyframe::new(
                Duration::from_secs(2),
                0.0_f64,
                Easing::Linear,
            ));

        let timeline = Timeline::builder()
            .canvas(1920, 1080)
            .frame_rate(30.0)
            .video_track(vec![Clip::new("video.mp4")])
            .video_animation("video_0_opacity", track)
            .build()
            .unwrap();

        assert_eq!(timeline.video_animations.len(), 1);
        assert!(timeline.video_animations.contains_key("video_0_opacity"));
    }

    #[test]
    fn timeline_builder_should_store_audio_animation_track() {
        use ff_filter::{AnimationTrack, Easing, Keyframe};
        use std::time::Duration;

        let track = AnimationTrack::new()
            .push(Keyframe::new(Duration::ZERO, 0.0_f64, Easing::Linear))
            .push(Keyframe::new(
                Duration::from_secs(2),
                -6.0_f64,
                Easing::Linear,
            ));

        let timeline = Timeline::builder()
            .canvas(1920, 1080)
            .frame_rate(30.0)
            .audio_track(vec![Clip::new("audio.mp4")])
            .audio_animation("audio_0_volume", track)
            .build()
            .unwrap();

        assert_eq!(timeline.audio_animations.len(), 1);
        assert!(timeline.audio_animations.contains_key("audio_0_volume"));
    }
}