maolan 0.2.0

Rust DAW application for recording, editing, routing, automation, export, and plugin hosting
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
use crate::cli::support::{ExportMetadata, ExportSessionData, ExportTrack};
use maolan_engine::{kind::Kind, message::AudioClipData};
use std::{
    collections::{BTreeSet, HashMap},
    fmt, fs, io,
    io::Write,
    path::{Path, PathBuf},
    time::Duration,
};

use ebur128::{EbuR128, Mode as LoudnessMode};
use ffmpeg_next::{
    Dictionary,
    codec::{Context as CodecContext, Id as CodecId},
    format::output,
    frame::Audio,
};
use flacenc::bitsink::ByteSink;
use flacenc::component::BitRepr;
use flacenc::error::Verify;
pub const STANDARD_EXPORT_SAMPLE_RATES: [u32; 12] = [
    8000, 11025, 16000, 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 384000,
];
pub const EXPORT_MP3_BITRATES_KBPS: [u16; 7] = [96, 128, 160, 192, 224, 256, 320];

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExportFormat {
    Wav,
    Mp3,
    Ogg,
    Flac,
}

impl fmt::Display for ExportFormat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Wav => write!(f, "WAV"),
            Self::Mp3 => write!(f, "MP3"),
            Self::Ogg => write!(f, "OGG"),
            Self::Flac => write!(f, "FLAC"),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExportMp3Mode {
    Cbr,
    Vbr,
}

impl fmt::Display for ExportMp3Mode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Cbr => write!(f, "CBR"),
            Self::Vbr => write!(f, "VBR"),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExportNormalizeMode {
    Peak,
    Loudness,
}

impl fmt::Display for ExportNormalizeMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Peak => write!(f, "Peak"),
            Self::Loudness => write!(f, "Loudness"),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExportRenderMode {
    Mixdown,
    StemsPostFader,
    StemsPreFader,
}

impl fmt::Display for ExportRenderMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Mixdown => write!(f, "Mixdown"),
            Self::StemsPostFader => write!(f, "Stems (Post-Fader)"),
            Self::StemsPreFader => write!(f, "Stems (Pre-Fader)"),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExportBitDepth {
    Int16,
    Int24,
    Int32,
    Float32,
}

impl fmt::Display for ExportBitDepth {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Int16 => write!(f, "16-bit PCM"),
            Self::Int24 => write!(f, "24-bit PCM"),
            Self::Int32 => write!(f, "32-bit PCM"),
            Self::Float32 => write!(f, "32-bit float"),
        }
    }
}

pub const EXPORT_MP3_MODE_ALL: [ExportMp3Mode; 2] = [ExportMp3Mode::Cbr, ExportMp3Mode::Vbr];
pub const EXPORT_RENDER_MODE_ALL: [ExportRenderMode; 3] = [
    ExportRenderMode::Mixdown,
    ExportRenderMode::StemsPostFader,
    ExportRenderMode::StemsPreFader,
];
pub const EXPORT_BIT_DEPTH_ALL: [ExportBitDepth; 4] = [
    ExportBitDepth::Int16,
    ExportBitDepth::Int24,
    ExportBitDepth::Int32,
    ExportBitDepth::Float32,
];
pub const EXPORT_NORMALIZE_MODE_ALL: [ExportNormalizeMode; 2] =
    [ExportNormalizeMode::Peak, ExportNormalizeMode::Loudness];

#[derive(Debug, Clone)]
pub struct ExportSettings {
    pub sample_rate_hz: u32,
    pub format_wav: bool,
    pub format_mp3: bool,
    pub format_ogg: bool,
    pub format_flac: bool,
    pub bit_depth: ExportBitDepth,
    pub mp3_mode: ExportMp3Mode,
    pub mp3_bitrate_kbps: u16,
    pub ogg_quality: f32,
    pub render_mode: ExportRenderMode,
    pub hw_out_ports: BTreeSet<usize>,
    pub realtime_fallback: bool,
    pub normalize: bool,
    pub normalize_mode: ExportNormalizeMode,
    pub normalize_dbfs: f32,
    pub normalize_lufs: f32,
    pub normalize_dbtp: f32,
    pub normalize_tp_limiter: bool,
    pub master_limiter: bool,
    pub master_limiter_ceiling_dbtp: f32,
}

impl ExportSettings {
    pub fn new(default_sample_rate_hz: u32, hw_output_channels: usize) -> Self {
        Self {
            sample_rate_hz: default_sample_rate_hz,
            format_wav: true,
            format_mp3: false,
            format_ogg: false,
            format_flac: false,
            bit_depth: ExportBitDepth::Int24,
            mp3_mode: ExportMp3Mode::Cbr,
            mp3_bitrate_kbps: 320,
            ogg_quality: 0.6,
            render_mode: ExportRenderMode::Mixdown,
            hw_out_ports: default_hw_out_ports(hw_output_channels),
            realtime_fallback: false,
            normalize: false,
            normalize_mode: ExportNormalizeMode::Peak,
            normalize_dbfs: 0.0,
            normalize_lufs: -23.0,
            normalize_dbtp: -1.0,
            normalize_tp_limiter: true,
            master_limiter: true,
            master_limiter_ceiling_dbtp: -1.0,
        }
    }

    pub fn selected_formats(&self) -> Vec<ExportFormat> {
        let mut formats = Vec::new();
        if self.format_wav {
            formats.push(ExportFormat::Wav);
        }
        if self.format_mp3 {
            formats.push(ExportFormat::Mp3);
        }
        if self.format_ogg {
            formats.push(ExportFormat::Ogg);
        }
        if self.format_flac {
            formats.push(ExportFormat::Flac);
        }
        formats
    }

    pub fn normalize_hw_out_ports(&mut self, hw_output_channels: usize) {
        let available: BTreeSet<usize> = (0..hw_output_channels).collect();
        self.hw_out_ports.retain(|port| available.contains(port));
        if self.hw_out_ports.is_empty() {
            self.hw_out_ports = default_hw_out_ports(hw_output_channels);
        }
    }
}

fn default_hw_out_ports(hw_output_channels: usize) -> BTreeSet<usize> {
    (0..hw_output_channels).take(2).collect()
}

pub fn export_bit_depth_options(formats: &[ExportFormat]) -> Vec<ExportBitDepth> {
    if formats
        .iter()
        .any(|f| matches!(f, ExportFormat::Wav | ExportFormat::Flac))
    {
        EXPORT_BIT_DEPTH_ALL.to_vec()
    } else {
        vec![ExportBitDepth::Float32]
    }
}

pub fn export_mp3_supported(settings: &ExportSettings, session: &ExportSessionData) -> bool {
    export_max_channels(settings, session) <= 2
}

pub fn export_max_channels(settings: &ExportSettings, session: &ExportSessionData) -> usize {
    if matches!(settings.render_mode, ExportRenderMode::Mixdown) {
        settings.hw_out_ports.len()
    } else {
        session
            .tracks
            .iter()
            .map(|track| track.output_ports.max(1))
            .max()
            .unwrap_or(0)
    }
}

pub fn validate_export_settings(
    settings: &ExportSettings,
    session: &ExportSessionData,
) -> Result<(), String> {
    if settings.selected_formats().is_empty() {
        return Err("Select at least one export format".to_string());
    }
    if settings.format_mp3 && !export_mp3_supported(settings, session) {
        return Err("MP3 export supports only mono or stereo".to_string());
    }
    if matches!(settings.render_mode, ExportRenderMode::Mixdown) && settings.hw_out_ports.is_empty()
    {
        return Err("Select at least one hw:out port for mixdown export".to_string());
    }
    if !(-20.0..=0.0).contains(&settings.master_limiter_ceiling_dbtp) {
        return Err("Master limiter ceiling must be between -20.0 and 0.0 dBTP".to_string());
    }
    if !(-0.1..=1.0).contains(&settings.ogg_quality) {
        return Err("OGG quality must be between -0.1 and 1.0".to_string());
    }
    if settings.normalize {
        match settings.normalize_mode {
            ExportNormalizeMode::Peak => {
                if !(-60.0..=0.0).contains(&settings.normalize_dbfs) {
                    return Err("Normalize target must be between -60.0 and 0.0 dBFS".to_string());
                }
            }
            ExportNormalizeMode::Loudness => {
                if !(-70.0..=-5.0).contains(&settings.normalize_lufs) {
                    return Err("LUFS target must be between -70.0 and -5.0".to_string());
                }
                if !(-20.0..=0.0).contains(&settings.normalize_dbtp) {
                    return Err("dBTP ceiling must be between -20.0 and 0.0".to_string());
                }
            }
        }
    }
    if session.tracks.is_empty() {
        return Err("No tracks found. Nothing to export.".to_string());
    }
    Ok(())
}

pub fn default_export_base_path(session_dir: &Path) -> PathBuf {
    session_dir.join("export")
}

pub async fn export_session<F>(
    session: &ExportSessionData,
    session_root: &Path,
    export_base_path: &Path,
    settings: &ExportSettings,
    mut progress_callback: F,
) -> io::Result<Vec<PathBuf>>
where
    F: FnMut(f32, Option<String>),
{
    let mut tracks = session.tracks.clone();
    let connections = session.connections.clone();
    let total_length = tracks
        .iter()
        .flat_map(|track| track.audio_clips.iter())
        .map(audio_clip_end)
        .max()
        .unwrap_or(0);
    if total_length == 0 {
        return Err(io::Error::other("No audio clips found. Nothing to export."));
    }

    let export_formats = settings.selected_formats();
    let codec = ExportCodecSettings {
        mp3_mode: settings.mp3_mode,
        mp3_bitrate_kbps: settings.mp3_bitrate_kbps,
        ogg_quality: settings.ogg_quality,
    };
    let has_solo = tracks.iter().any(|track| track.soloed);
    let metadata = session.metadata.clone();

    progress_callback(0.0, Some("Analyzing tracks".to_string()));
    tokio::task::yield_now().await;

    if matches!(settings.render_mode, ExportRenderMode::Mixdown) {
        let output_ports: Vec<usize> = settings.hw_out_ports.iter().copied().collect();
        let output_channels = output_ports.len().max(1);
        let hw_out_channel_map: HashMap<usize, usize> = output_ports
            .iter()
            .enumerate()
            .map(|(channel_idx, port)| (*port, channel_idx))
            .collect();
        let mut mixed_buffer = vec![0.0_f32; total_length * output_channels];
        let track_count = tracks.len().max(1);
        for (track_idx, track) in tracks.iter_mut().enumerate() {
            if track.muted || (has_solo && !track.soloed) {
                continue;
            }
            let progress_start = 0.1 + (track_idx as f32 / track_count as f32) * 0.7;
            let progress_span = 0.7 / track_count as f32;
            progress_callback(
                progress_start,
                Some(format!("Processing track: {}", track.name)),
            );
            tokio::task::yield_now().await;

            let routed_ports: Vec<(usize, usize)> = connections
                .iter()
                .filter(|conn| {
                    conn.kind == Kind::Audio
                        && conn.from_track == track.name
                        && conn.to_track == "hw:out"
                })
                .filter_map(|conn| {
                    hw_out_channel_map
                        .get(&conn.to_port)
                        .map(|dest_idx| (conn.from_port, *dest_idx))
                })
                .collect();
            if routed_ports.is_empty() {
                continue;
            }
            let track_buffer = mix_track_clips_to_channels(
                &track.audio_clips,
                session_root,
                total_length,
                track.output_ports,
                track.level,
                track.balance,
                true,
            )?;
            for frame in 0..total_length {
                let track_base = frame * track.output_ports.max(1);
                let mixed_base = frame * output_channels;
                for (source_port, dest_channel) in &routed_ports {
                    if *source_port >= track.output_ports.max(1) {
                        continue;
                    }
                    mixed_buffer[mixed_base + *dest_channel] +=
                        track_buffer[track_base + *source_port];
                }
            }
            progress_callback(
                progress_start + progress_span,
                Some(format!("Finished: {}", track.name)),
            );
        }

        if settings.realtime_fallback {
            progress_callback(0.82, Some("Real-time fallback pacing".to_string()));
            let seconds = (total_length as f64 / settings.sample_rate_hz.max(1) as f64).max(0.0);
            tokio::time::sleep(Duration::from_secs_f64(seconds)).await;
        }

        if settings.normalize {
            apply_export_normalization(
                &mut mixed_buffer,
                ExportNormalizeParams {
                    mode: settings.normalize_mode,
                    target_dbfs: settings.normalize_dbfs,
                    target_lufs: settings.normalize_lufs,
                    true_peak_dbtp: settings.normalize_dbtp,
                    tp_limiter: settings.normalize_tp_limiter,
                    sample_rate: settings.sample_rate_hz as i32,
                    output_channels,
                },
            )?;
        }
        apply_master_limiter(
            &mut mixed_buffer,
            settings.master_limiter,
            settings.master_limiter_ceiling_dbtp,
        );

        let base_path = export_base_path.to_path_buf();
        let write_span = 0.1 / export_formats.len().max(1) as f32;
        let mut written = Vec::new();
        for (format_idx, format) in export_formats.iter().enumerate() {
            progress_callback(
                (0.9 + write_span * format_idx as f32).clamp(0.0, 0.99),
                Some(format!("Writing {} ({})", format, settings.bit_depth)),
            );
            let out_path = base_path.with_extension(export_format_extension(*format));
            write_export_audio(ExportWriteRequest {
                export_path: &out_path,
                mixed_buffer: &mixed_buffer,
                sample_rate: settings.sample_rate_hz as i32,
                output_channels,
                bit_depth: settings.bit_depth,
                format: *format,
                codec,
                metadata: &metadata,
            })?;
            written.push(out_path);
        }
        progress_callback(1.0, Some("Complete".to_string()));
        return Ok(written);
    }

    let stem_mode_label = if matches!(settings.render_mode, ExportRenderMode::StemsPreFader) {
        "pre"
    } else {
        "post"
    };
    let export_parent = export_base_path.parent().unwrap_or_else(|| Path::new("."));
    let export_stem = export_base_path
        .file_stem()
        .and_then(|stem| stem.to_str())
        .unwrap_or("export");
    let stem_dir = export_parent.join(format!("{export_stem}_stems"));
    fs::create_dir_all(&stem_dir)?;

    let selected_tracks: Vec<&ExportTrack> = tracks
        .iter()
        .filter(|track| !track.muted && (!has_solo || track.soloed))
        .collect();
    if selected_tracks.is_empty() {
        return Err(io::Error::other("No tracks are eligible for stem export"));
    }

    let mut written = Vec::new();
    for (idx, track) in selected_tracks.iter().enumerate() {
        progress_callback(
            0.1 + (idx as f32 / selected_tracks.len().max(1) as f32) * 0.75,
            Some(format!("Rendering stem: {}", track.name)),
        );
        let output_channels = track.output_ports.max(1);
        let mut stem_buffer = mix_track_clips_to_channels(
            &track.audio_clips,
            session_root,
            total_length,
            output_channels,
            track.level,
            track.balance,
            matches!(settings.render_mode, ExportRenderMode::StemsPostFader),
        )?;
        if settings.normalize {
            apply_export_normalization(
                &mut stem_buffer,
                ExportNormalizeParams {
                    mode: settings.normalize_mode,
                    target_dbfs: settings.normalize_dbfs,
                    target_lufs: settings.normalize_lufs,
                    true_peak_dbtp: settings.normalize_dbtp,
                    tp_limiter: settings.normalize_tp_limiter,
                    sample_rate: settings.sample_rate_hz as i32,
                    output_channels,
                },
            )?;
        }
        apply_master_limiter(
            &mut stem_buffer,
            settings.master_limiter,
            settings.master_limiter_ceiling_dbtp,
        );
        for format in &export_formats {
            let stem_file = stem_dir.join(format!(
                "{}_{}.{}",
                sanitize_export_component(&track.name),
                stem_mode_label,
                export_format_extension(*format)
            ));
            write_export_audio(ExportWriteRequest {
                export_path: &stem_file,
                mixed_buffer: &stem_buffer,
                sample_rate: settings.sample_rate_hz as i32,
                output_channels,
                bit_depth: settings.bit_depth,
                format: *format,
                codec,
                metadata: &metadata,
            })?;
            written.push(stem_file);
        }
        if settings.realtime_fallback {
            let seconds = (total_length as f64 / settings.sample_rate_hz.max(1) as f64).max(0.0);
            tokio::time::sleep(Duration::from_secs_f64(seconds)).await;
        }
    }
    progress_callback(1.0, Some("Complete".to_string()));
    Ok(written)
}

fn audio_clip_end(clip: &AudioClipData) -> usize {
    if !clip.grouped_clips.is_empty() {
        clip.grouped_clips
            .iter()
            .map(audio_clip_end)
            .max()
            .unwrap_or(0)
    } else {
        clip.start + clip.length
    }
}

fn mix_track_clips_to_channels(
    clips: &[AudioClipData],
    session_root: &Path,
    total_length: usize,
    output_channels: usize,
    level_db: f32,
    balance: f32,
    apply_fader: bool,
) -> io::Result<Vec<f32>> {
    let output_channels = output_channels.max(1);
    let mut mixed = vec![0.0_f32; total_length * output_channels];
    let channel_gains = if apply_fader {
        let level_amp = 10.0_f32.powf(level_db / 20.0);
        if output_channels == 2 {
            vec![
                if balance <= 0.0 {
                    level_amp
                } else {
                    level_amp * (1.0 - balance)
                },
                if balance >= 0.0 {
                    level_amp
                } else {
                    level_amp * (1.0 + balance)
                },
            ]
        } else {
            vec![level_amp; output_channels]
        }
    } else {
        vec![1.0; output_channels]
    };
    for clip in clips {
        mix_clip_into_buffer(
            clip,
            session_root,
            &mut mixed,
            total_length,
            output_channels,
            &channel_gains,
        )?;
    }
    Ok(mixed)
}

fn mix_clip_into_buffer(
    clip: &AudioClipData,
    session_root: &Path,
    mixed: &mut [f32],
    total_length: usize,
    output_channels: usize,
    channel_gains: &[f32],
) -> io::Result<()> {
    if clip.muted {
        return Ok(());
    }
    if !clip.grouped_clips.is_empty() {
        for child in &clip.grouped_clips {
            mix_clip_into_buffer(
                child,
                session_root,
                mixed,
                total_length,
                output_channels,
                channel_gains,
            )?;
        }
        return Ok(());
    }
    let clip_path = resolve_audio_clip_path(clip, session_root);
    let (samples, clip_channels, _) = decode_audio_to_f32_interleaved_sync(&clip_path)?;
    if samples.is_empty() {
        return Ok(());
    }
    let clip_frames = samples.len() / clip_channels;
    let offset_frame = clip.offset.min(clip_frames);
    let length_frames = clip.length.min(clip_frames.saturating_sub(offset_frame));
    for frame_idx in 0..length_frames {
        let src_frame = offset_frame + frame_idx;
        let dst_frame = clip.start + frame_idx;
        if dst_frame >= total_length {
            break;
        }
        let src_idx = src_frame * clip_channels;
        let dst_idx = dst_frame * output_channels;
        for out_ch in 0..output_channels {
            let source_sample = if clip_channels == 1 {
                samples[src_idx]
            } else {
                samples[src_idx + out_ch.min(clip_channels.saturating_sub(1))]
            };
            mixed[dst_idx + out_ch] += source_sample * channel_gains[out_ch];
        }
    }
    Ok(())
}

fn resolve_audio_clip_path(clip: &AudioClipData, session_root: &Path) -> PathBuf {
    let name = clip
        .preview_name
        .as_ref()
        .or(clip.source_name.as_ref())
        .unwrap_or(&clip.name);
    let path = PathBuf::from(name);
    if path.is_absolute() {
        path
    } else {
        session_root.join(path)
    }
}

fn apply_master_limiter(samples: &mut [f32], enabled: bool, ceiling_dbtp: f32) {
    if !enabled {
        return;
    }
    let ceiling_amp = 10.0_f32.powf(ceiling_dbtp / 20.0).clamp(0.0, 1.0);
    maolan_engine::simd::clamp_inplace(samples, -ceiling_amp, ceiling_amp);
}

fn export_format_extension(format: ExportFormat) -> &'static str {
    match format {
        ExportFormat::Wav => "wav",
        ExportFormat::Mp3 => "mp3",
        ExportFormat::Ogg => "ogg",
        ExportFormat::Flac => "flac",
    }
}

fn sanitize_export_component(value: &str) -> String {
    let mut out = String::with_capacity(value.len());
    for ch in value.chars() {
        if ch.is_ascii_alphanumeric() || ch == '_' || ch == '-' {
            out.push(ch);
        } else {
            out.push('_');
        }
    }
    if out.is_empty() {
        "track".to_string()
    } else {
        out
    }
}

#[derive(Clone, Copy)]
struct ExportCodecSettings {
    mp3_mode: ExportMp3Mode,
    mp3_bitrate_kbps: u16,
    ogg_quality: f32,
}

struct ExportWriteRequest<'a> {
    export_path: &'a Path,
    mixed_buffer: &'a [f32],
    sample_rate: i32,
    output_channels: usize,
    bit_depth: ExportBitDepth,
    format: ExportFormat,
    codec: ExportCodecSettings,
    metadata: &'a ExportMetadata,
}

#[derive(Clone, Copy)]
struct ExportNormalizeParams {
    mode: ExportNormalizeMode,
    target_dbfs: f32,
    target_lufs: f32,
    true_peak_dbtp: f32,
    tp_limiter: bool,
    sample_rate: i32,
    output_channels: usize,
}

fn write_export_audio(req: ExportWriteRequest<'_>) -> io::Result<()> {
    let export_path = req.export_path;
    let tmp_path = export_path.with_extension(format!(
        "{}.tmp",
        export_path
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("export")
    ));
    let result = match req.format {
        ExportFormat::Wav => write_wav_with_bit_depth(
            &tmp_path,
            req.mixed_buffer,
            req.sample_rate,
            req.output_channels,
            req.bit_depth,
        ),
        ExportFormat::Flac => write_flac_with_bit_depth(
            &tmp_path,
            req.mixed_buffer,
            req.sample_rate,
            req.output_channels,
            req.bit_depth,
        ),
        ExportFormat::Mp3 => write_mp3(
            &tmp_path,
            req.mixed_buffer,
            req.sample_rate,
            req.output_channels,
            req.codec,
            req.metadata,
        ),
        ExportFormat::Ogg => write_ogg_vorbis(
            &tmp_path,
            req.mixed_buffer,
            req.sample_rate,
            req.output_channels,
            req.codec,
            req.metadata,
        ),
    };
    if result.is_ok() {
        fs::rename(&tmp_path, export_path)?;
    }
    result
}

fn write_wav_with_bit_depth(
    export_path: &Path,
    mixed_buffer: &[f32],
    sample_rate: i32,
    output_channels: usize,
    bit_depth: ExportBitDepth,
) -> io::Result<()> {
    let bits_per_sample = match bit_depth {
        ExportBitDepth::Int16 => 16u16,
        ExportBitDepth::Int24 => 24u16,
        ExportBitDepth::Int32 => 32u16,
        ExportBitDepth::Float32 => 32u16,
    };
    let is_float = matches!(bit_depth, ExportBitDepth::Float32);
    write_wav_pcm(
        export_path,
        mixed_buffer,
        output_channels.max(1),
        sample_rate as u32,
        bits_per_sample,
        is_float,
    )
}

fn write_wav_pcm(
    path: &Path,
    samples: &[f32],
    channels: usize,
    sample_rate: u32,
    bits_per_sample: u16,
    is_float: bool,
) -> io::Result<()> {
    let bytes_per_sample = usize::from(bits_per_sample / 8);
    let block_align = (channels * bytes_per_sample) as u16;
    let byte_rate = sample_rate * u32::from(block_align);
    let data_size = samples
        .len()
        .checked_mul(bytes_per_sample)
        .ok_or_else(|| io::Error::other("WAV data too large"))? as u32;
    let riff_size = 36u32
        .checked_add(data_size)
        .ok_or_else(|| io::Error::other("WAV file too large"))?;

    let mut file = fs::File::create(path)?;
    file.write_all(b"RIFF")?;
    file.write_all(&riff_size.to_le_bytes())?;
    file.write_all(b"WAVE")?;
    file.write_all(b"fmt ")?;
    file.write_all(&16u32.to_le_bytes())?;
    let audio_format: u16 = if is_float { 3 } else { 1 };
    file.write_all(&audio_format.to_le_bytes())?;
    file.write_all(&(channels as u16).to_le_bytes())?;
    file.write_all(&sample_rate.to_le_bytes())?;
    file.write_all(&byte_rate.to_le_bytes())?;
    file.write_all(&block_align.to_le_bytes())?;
    file.write_all(&bits_per_sample.to_le_bytes())?;
    file.write_all(b"data")?;
    file.write_all(&data_size.to_le_bytes())?;

    for &sample in samples {
        let s = sample.clamp(-1.0, 1.0);
        match (is_float, bits_per_sample) {
            (true, 32) => file.write_all(&s.to_le_bytes())?,
            (false, 16) => {
                let q = (s * i16::MAX as f32).round() as i16;
                file.write_all(&q.to_le_bytes())?;
            }
            (false, 24) => {
                let q = (s * 8_388_607.0).round() as i32;
                let b = q.to_le_bytes();
                file.write_all(&b[..3])?;
            }
            (false, 32) => {
                let q = (s * i32::MAX as f32).round() as i32;
                file.write_all(&q.to_le_bytes())?;
            }
            _ => return Err(io::Error::other("Unsupported WAV format")),
        }
    }
    Ok(())
}

fn decode_audio_to_f32_interleaved_sync(path: &Path) -> io::Result<(Vec<f32>, usize, u32)> {
    use ffmpeg_next::{format::sample::Type as SampleType, media::Type};

    ffmpeg_init().map_err(|e| io::Error::other(format!("FFmpeg init failed: {e}")))?;
    let mut ictx = ffmpeg_next::format::input(path)
        .map_err(|e| io::Error::other(format!("Failed to open '{}': {e}", path.display())))?;
    let stream = ictx
        .streams()
        .best(Type::Audio)
        .ok_or_else(|| io::Error::other(format!("No audio stream in '{}'", path.display())))?;
    let stream_index = stream.index();
    let mut decoder = ffmpeg_next::codec::Context::from_parameters(stream.parameters())
        .map_err(|e| io::Error::other(format!("Decoder init failed: {e}")))?
        .decoder()
        .audio()
        .map_err(|e| io::Error::other(format!("Audio decoder init failed: {e}")))?;
    let sample_rate = decoder.rate() as u32;
    let channels = decoder.channels().max(1) as usize;
    let mut samples = Vec::<f32>::new();
    let mut raw_frame = ffmpeg_next::frame::Audio::empty();
    let append_frame = |frame: &ffmpeg_next::frame::Audio,
                        channels: usize,
                        out: &mut Vec<f32>|
     -> io::Result<()> {
        let frame_samples = frame.samples();
        match frame.format() {
            ffmpeg_next::format::Sample::F32(SampleType::Packed) => {
                let plane = frame.plane::<f32>(0);
                out.extend_from_slice(plane);
            }
            ffmpeg_next::format::Sample::F32(SampleType::Planar) => {
                let start = out.len();
                out.resize(start + frame_samples * channels, 0.0);
                for ch in 0..channels {
                    let plane = frame.plane::<f32>(ch);
                    for i in 0..frame_samples {
                        out[start + i * channels + ch] = plane[i];
                    }
                }
            }
            ffmpeg_next::format::Sample::I16(SampleType::Packed) => {
                let plane = frame.plane::<i16>(0);
                out.extend(plane.iter().map(|&v| v as f32 / 32768.0));
            }
            ffmpeg_next::format::Sample::I16(SampleType::Planar) => {
                let start = out.len();
                out.resize(start + frame_samples * channels, 0.0);
                for ch in 0..channels {
                    let plane = frame.plane::<i16>(ch);
                    for i in 0..frame_samples {
                        out[start + i * channels + ch] = plane[i] as f32 / 32768.0;
                    }
                }
            }
            ffmpeg_next::format::Sample::I32(SampleType::Packed) => {
                let plane = frame.plane::<i32>(0);
                out.extend(plane.iter().map(|&v| v as f32 / 2_147_483_648.0));
            }
            ffmpeg_next::format::Sample::I32(SampleType::Planar) => {
                let start = out.len();
                out.resize(start + frame_samples * channels, 0.0);
                for ch in 0..channels {
                    let plane = frame.plane::<i32>(ch);
                    for i in 0..frame_samples {
                        out[start + i * channels + ch] = plane[i] as f32 / 2_147_483_648.0;
                    }
                }
            }
            other => {
                return Err(io::Error::other(format!(
                    "Unsupported decoded sample format: {other:?}"
                )));
            }
        }
        Ok(())
    };
    for (stream, packet) in ictx.packets() {
        if stream.index() != stream_index {
            continue;
        }
        decoder
            .send_packet(&packet)
            .map_err(|e| io::Error::other(format!("Failed to send packet: {e}")))?;
        while decoder.receive_frame(&mut raw_frame).is_ok() {
            append_frame(&raw_frame, channels, &mut samples)?;
        }
    }
    let _ = decoder.send_eof();
    while decoder.receive_frame(&mut raw_frame).is_ok() {
        append_frame(&raw_frame, channels, &mut samples)?;
    }
    if samples.is_empty() {
        return Err(io::Error::other(format!(
            "Audio file '{}' contains no samples",
            path.display()
        )));
    }
    Ok((samples, channels, sample_rate))
}

fn quantize_samples_for_bit_depth(
    mixed_buffer: &[f32],
    bit_depth: ExportBitDepth,
) -> (Vec<i32>, u8) {
    let (scale, min, max, bits_per_sample) = match bit_depth {
        ExportBitDepth::Int16 => (i16::MAX as f32, i16::MIN as f32, i16::MAX as f32, 16),
        ExportBitDepth::Int24 => (8_388_607.0, -8_388_608.0, 8_388_607.0, 24),
        ExportBitDepth::Int32 => (i32::MAX as f32, i32::MIN as f32, i32::MAX as f32, 32),
        ExportBitDepth::Float32 => (8_388_607.0, -8_388_608.0, 8_388_607.0, 24),
    };

    #[cfg(any(target_arch = "x86_64", target_arch = "x86"))]
    {
        use wide::{f32x4, i32x4};
        let mut quantized = Vec::with_capacity(mixed_buffer.len());
        let n = mixed_buffer.len() / 4;
        let vmin_f = f32x4::splat(min);
        let vmax_f = f32x4::splat(max);
        let scale_f = f32x4::splat(scale);
        let vmin_i = i32x4::splat(min as i32);
        let vmax_i = i32x4::splat(max as i32);
        for i in 0..n {
            let chunk = &mixed_buffer[i * 4..(i + 1) * 4];
            let v: f32x4 = [chunk[0], chunk[1], chunk[2], chunk[3]].into();
            let clamped = v.clamp(vmin_f, vmax_f);
            let scaled = clamped * scale_f;
            let rounded = scaled.round_int();
            let clamped_i = rounded.max(vmin_i).min(vmax_i);
            quantized.extend_from_slice(&clamped_i.to_array());
        }
        for s in &mixed_buffer[n * 4..] {
            quantized.push(
                (*s).clamp(-1.0, 1.0)
                    .mul_add(scale, 0.0)
                    .round()
                    .clamp(min, max) as i32,
            );
        }
        (quantized, bits_per_sample)
    }
    #[cfg(not(any(target_arch = "x86_64", target_arch = "x86")))]
    {
        (
            mixed_buffer
                .iter()
                .map(|s| (s.clamp(-1.0, 1.0) * scale).round().clamp(min, max) as i32)
                .collect(),
            bits_per_sample,
        )
    }
}

fn write_flac_with_bit_depth(
    export_path: &Path,
    mixed_buffer: &[f32],
    sample_rate: i32,
    output_channels: usize,
    bit_depth: ExportBitDepth,
) -> io::Result<()> {
    let (quantized, bits_per_sample) = quantize_samples_for_bit_depth(mixed_buffer, bit_depth);
    let config = flacenc::config::Encoder::default()
        .into_verified()
        .map_err(|e| io::Error::other(format!("Invalid FLAC encoder config: {e:?}")))?;
    let source = flacenc::source::MemSource::from_samples(
        &quantized,
        output_channels,
        bits_per_sample as usize,
        sample_rate.max(1) as usize,
    );
    let stream = flacenc::encode_with_fixed_block_size(&config, source, config.block_size)
        .map_err(|e| io::Error::other(format!("FLAC encode failed: {e}")))?;
    let mut sink = ByteSink::new();
    stream
        .write(&mut sink)
        .map_err(|e| io::Error::other(format!("FLAC bitstream write failed: {e}")))?;
    fs::write(export_path, sink.as_slice()).map_err(|e| {
        io::Error::other(format!(
            "Failed to write '{}': {}",
            export_path.display(),
            e
        ))
    })
}

fn write_mp3(
    export_path: &Path,
    mixed_buffer: &[f32],
    sample_rate: i32,
    output_channels: usize,
    codec: ExportCodecSettings,
    metadata: &ExportMetadata,
) -> io::Result<()> {
    if output_channels != 1 && output_channels != 2 {
        return Err(io::Error::other(format!(
            "MP3 export supports only mono/stereo, got {} channels",
            output_channels
        )));
    }

    ffmpeg_init().map_err(|e| io::Error::other(format!("FFmpeg init failed: {e}")))?;

    let mut octx = output(export_path.to_str().unwrap_or("output.mp3"))
        .map_err(|e| io::Error::other(format!("Failed to create output context: {e}")))?;

    let codec_id = CodecId::MP3;
    let encoder_codec = ffmpeg_next::codec::encoder::find(codec_id)
        .ok_or_else(|| io::Error::other("MP3 encoder not found"))?;

    let encoder_ctx = CodecContext::new_with_codec(encoder_codec);

    let mut encoder = encoder_ctx
        .encoder()
        .audio()
        .map_err(|e| io::Error::other(format!("Failed to create audio encoder: {e}")))?;

    encoder.set_rate(sample_rate);

    encoder.set_format(ffmpeg_next::format::Sample::F32(
        ffmpeg_next::format::sample::Type::Planar,
    ));
    encoder.set_channel_layout(match output_channels {
        1 => ffmpeg_next::channel_layout::ChannelLayout::MONO,
        _ => ffmpeg_next::channel_layout::ChannelLayout::STEREO,
    });

    let bitrate = (codec.mp3_bitrate_kbps as usize) * 1000;
    encoder.set_bit_rate(bitrate);

    if matches!(codec.mp3_mode, ExportMp3Mode::Vbr) {
        encoder.set_quality(2usize);
    }

    let mut metadata_dict = Dictionary::new();
    if !metadata.author.is_empty() {
        metadata_dict.set("artist", &metadata.author);
    }
    if !metadata.album.is_empty() {
        metadata_dict.set("album", &metadata.album);
    }
    if let Some(year) = metadata.year {
        metadata_dict.set("date", &year.to_string());
    }
    if let Some(track_number) = metadata.track_number {
        metadata_dict.set("track", &track_number.to_string());
    }
    if !metadata.genre.is_empty() {
        metadata_dict.set("genre", &metadata.genre);
    }

    let mut output_stream = octx
        .add_stream(encoder_codec)
        .map_err(|e| io::Error::other(format!("Failed to add stream: {e}")))?;

    output_stream.set_parameters(&encoder);

    let mut encoder = encoder
        .open_as(encoder_codec)
        .map_err(|e| io::Error::other(format!("Failed to open encoder: {e}")))?;

    octx.write_header()
        .map_err(|e| io::Error::other(format!("Failed to write header: {e}")))?;

    let frame_size = 1152;

    for chunk_start in (0..mixed_buffer.len()).step_by(frame_size * output_channels) {
        let chunk_end = (chunk_start + frame_size * output_channels).min(mixed_buffer.len());
        let chunk = &mixed_buffer[chunk_start..chunk_end];
        let actual_frames = chunk.len() / output_channels;

        if actual_frames == 0 {
            continue;
        }

        let mut frame = Audio::empty();
        frame.set_format(encoder.format());
        frame.set_channel_layout(encoder.channel_layout());
        frame.set_rate(encoder.rate());
        frame.set_samples(actual_frames);

        unsafe {
            ffmpeg_next::ffi::av_frame_get_buffer(frame.as_mut_ptr(), 0);
        }

        for ch in 0..output_channels {
            let data_ptr = frame.data_mut(ch).as_mut_ptr() as *mut f32;
            for frame_idx in 0..actual_frames {
                let src_idx = frame_idx * output_channels + ch;
                if src_idx < chunk.len() {
                    unsafe {
                        *data_ptr.add(frame_idx) = chunk[src_idx];
                    }
                }
            }
        }

        match encoder.send_frame(&frame) {
            Ok(()) => {}
            Err(e) => return Err(io::Error::other(format!("Failed to send frame: {e}"))),
        }

        let mut packet = ffmpeg_next::packet::Packet::empty();
        while encoder.receive_packet(&mut packet).is_ok() {
            packet.set_stream(0);
            packet
                .write_interleaved(&mut octx)
                .map_err(|e| io::Error::other(format!("Failed to write packet: {e}")))?;
        }
    }

    encoder
        .send_eof()
        .map_err(|e| io::Error::other(format!("Failed to send EOF: {e}")))?;

    let mut packet = ffmpeg_next::packet::Packet::empty();
    while encoder.receive_packet(&mut packet).is_ok() {
        packet.set_stream(0);
        packet
            .write_interleaved(&mut octx)
            .map_err(|e| io::Error::other(format!("Failed to write packet: {e}")))?;
    }

    octx.write_trailer()
        .map_err(|e| io::Error::other(format!("Failed to write trailer: {e}")))?;

    Ok(())
}

fn write_ogg_vorbis(
    export_path: &Path,
    mixed_buffer: &[f32],
    sample_rate: i32,
    output_channels: usize,
    codec: ExportCodecSettings,
    metadata: &ExportMetadata,
) -> io::Result<()> {
    ffmpeg_init().map_err(|e| io::Error::other(format!("FFmpeg init failed: {e}")))?;

    let mut octx = output(export_path.to_str().unwrap_or("output.ogg"))
        .map_err(|e| io::Error::other(format!("Failed to create output context: {e}")))?;

    let codec_id = CodecId::VORBIS;
    let encoder_codec = ffmpeg_next::codec::encoder::find(codec_id)
        .ok_or_else(|| io::Error::other("Vorbis encoder not found"))?;

    let encoder_ctx = CodecContext::new_with_codec(encoder_codec);

    let mut encoder = encoder_ctx
        .encoder()
        .audio()
        .map_err(|e| io::Error::other(format!("Failed to create audio encoder: {e}")))?;

    encoder.set_rate(sample_rate);

    encoder.set_format(ffmpeg_next::format::Sample::F32(
        ffmpeg_next::format::sample::Type::Planar,
    ));
    encoder.set_channel_layout(match output_channels {
        1 => ffmpeg_next::channel_layout::ChannelLayout::MONO,
        _ => ffmpeg_next::channel_layout::ChannelLayout::STEREO,
    });

    let quality = ((codec.ogg_quality + 0.1) * 10.0).clamp(0.0, 10.0) as i32;
    encoder.set_quality(quality as usize);

    let mut metadata_dict = Dictionary::new();
    if !metadata.author.is_empty() {
        metadata_dict.set("artist", &metadata.author);
    }
    if !metadata.album.is_empty() {
        metadata_dict.set("album", &metadata.album);
    }
    if let Some(year) = metadata.year {
        metadata_dict.set("date", &year.to_string());
    }
    if let Some(track_number) = metadata.track_number {
        metadata_dict.set("track", &track_number.to_string());
    }
    if !metadata.genre.is_empty() {
        metadata_dict.set("genre", &metadata.genre);
    }

    let mut output_stream = octx
        .add_stream(encoder_codec)
        .map_err(|e| io::Error::other(format!("Failed to add stream: {e}")))?;

    output_stream.set_parameters(&encoder);

    let mut encoder = encoder
        .open_as(encoder_codec)
        .map_err(|e| io::Error::other(format!("Failed to open encoder: {e}")))?;

    octx.write_header()
        .map_err(|e| io::Error::other(format!("Failed to write header: {e}")))?;

    let frame_size = 1024;

    for chunk_start in (0..mixed_buffer.len()).step_by(frame_size * output_channels) {
        let chunk_end = (chunk_start + frame_size * output_channels).min(mixed_buffer.len());
        let chunk = &mixed_buffer[chunk_start..chunk_end];
        let actual_frames = chunk.len() / output_channels;

        if actual_frames == 0 {
            continue;
        }

        let mut frame = Audio::empty();
        frame.set_format(encoder.format());
        frame.set_channel_layout(encoder.channel_layout());
        frame.set_rate(encoder.rate());
        frame.set_samples(actual_frames);

        unsafe {
            ffmpeg_next::ffi::av_frame_get_buffer(frame.as_mut_ptr(), 0);
        }

        for ch in 0..output_channels {
            let data_ptr = frame.data_mut(ch).as_mut_ptr() as *mut f32;
            for frame_idx in 0..actual_frames {
                let src_idx = frame_idx * output_channels + ch;
                if src_idx < chunk.len() {
                    unsafe {
                        *data_ptr.add(frame_idx) = chunk[src_idx];
                    }
                }
            }
        }

        match encoder.send_frame(&frame) {
            Ok(()) => {}
            Err(e) => return Err(io::Error::other(format!("Failed to send frame: {e}"))),
        }

        let mut packet = ffmpeg_next::packet::Packet::empty();
        while encoder.receive_packet(&mut packet).is_ok() {
            packet.set_stream(0);
            packet
                .write_interleaved(&mut octx)
                .map_err(|e| io::Error::other(format!("Failed to write packet: {e}")))?;
        }
    }

    encoder
        .send_eof()
        .map_err(|e| io::Error::other(format!("Failed to send EOF: {e}")))?;

    let mut packet = ffmpeg_next::packet::Packet::empty();
    while encoder.receive_packet(&mut packet).is_ok() {
        packet.set_stream(0);
        packet
            .write_interleaved(&mut octx)
            .map_err(|e| io::Error::other(format!("Failed to write packet: {e}")))?;
    }

    octx.write_trailer()
        .map_err(|e| io::Error::other(format!("Failed to write trailer: {e}")))?;

    Ok(())
}

fn ffmpeg_init() -> Result<(), ffmpeg_next::Error> {
    static RESULT: std::sync::OnceLock<Result<(), ffmpeg_next::Error>> = std::sync::OnceLock::new();
    *RESULT.get_or_init(ffmpeg_next::init)
}

fn measure_lufs_and_true_peak(
    samples: &[f32],
    channels: usize,
    sample_rate: i32,
) -> io::Result<(f32, f32)> {
    let mut meter = EbuR128::new(
        channels as u32,
        sample_rate as u32,
        LoudnessMode::I | LoudnessMode::TRUE_PEAK,
    )
    .map_err(|e| io::Error::other(format!("Failed to initialize loudness meter: {e}")))?;
    meter
        .add_frames_f32(samples)
        .map_err(|e| io::Error::other(format!("Loudness analysis failed: {e}")))?;
    let lufs = meter
        .loudness_global()
        .map_err(|e| io::Error::other(format!("Failed to get integrated loudness: {e}")))?
        as f32;
    if !lufs.is_finite() {
        return Err(io::Error::other("Integrated loudness is not finite"));
    }
    let mut tp = 0.0_f32;
    for ch in 0..channels as u32 {
        tp = tp.max(
            meter
                .true_peak(ch)
                .map_err(|e| io::Error::other(format!("Failed to get true peak: {e}")))?
                as f32,
        );
    }
    Ok((lufs, tp))
}

fn apply_export_normalization(
    samples: &mut [f32],
    params: ExportNormalizeParams,
) -> io::Result<()> {
    match params.mode {
        ExportNormalizeMode::Peak => {
            let peak = maolan_engine::simd::peak_abs(samples);
            if peak > 0.0 {
                let target_amp = 10.0_f32.powf(params.target_dbfs / 20.0).clamp(0.0, 1.0);
                let gain = target_amp / peak;
                maolan_engine::simd::mul_inplace(samples, gain);
            }
        }
        ExportNormalizeMode::Loudness => {
            let (measured_lufs, measured_tp_amp) =
                measure_lufs_and_true_peak(samples, params.output_channels, params.sample_rate)?;
            let gain_loudness_db = params.target_lufs - measured_lufs;
            let gain_loudness = 10.0_f32.powf(gain_loudness_db / 20.0);
            let ceiling_amp = 10.0_f32.powf(params.true_peak_dbtp / 20.0).clamp(0.0, 1.0);
            let gain_tp = if measured_tp_amp > 0.0 {
                ceiling_amp / measured_tp_amp
            } else {
                gain_loudness
            };
            let applied_gain = if params.tp_limiter {
                gain_loudness
            } else {
                gain_loudness.min(gain_tp)
            };
            maolan_engine::simd::mul_inplace(samples, applied_gain);
            if params.tp_limiter {
                let predicted_tp = measured_tp_amp * applied_gain;
                if predicted_tp > ceiling_amp && ceiling_amp > 0.0 {
                    maolan_engine::simd::clamp_inplace(samples, -ceiling_amp, ceiling_amp);
                }
            }
        }
    }
    Ok(())
}