File size: 33,677 Bytes
2156b71
5beeefc
2156b71
 
a8673cc
2156b71
5beeefc
a8673cc
 
5beeefc
2156b71
a8673cc
2156b71
 
 
 
5beeefc
 
 
 
a8673cc
 
 
 
 
5beeefc
2156b71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8673cc
 
 
 
 
 
 
 
 
5beeefc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8673cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2156b71
 
 
5beeefc
2156b71
5beeefc
 
a8673cc
 
 
 
 
 
 
5beeefc
2156b71
 
 
 
 
 
5beeefc
a8673cc
 
 
 
 
 
 
 
 
 
2156b71
 
5beeefc
 
 
2156b71
 
 
a8673cc
5beeefc
a8673cc
 
 
 
 
 
 
5beeefc
 
 
 
 
 
 
a8673cc
5beeefc
 
 
 
 
 
 
 
 
 
 
a8673cc
 
5beeefc
 
 
 
 
 
 
 
 
 
 
 
 
a8673cc
 
2156b71
a8673cc
 
2156b71
a8673cc
2156b71
a8673cc
 
 
 
 
 
5beeefc
2156b71
a8673cc
 
 
5beeefc
a8673cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2156b71
a8673cc
2156b71
a8673cc
65bc393
a8673cc
 
 
 
 
65bc393
 
 
a8673cc
5beeefc
 
a8673cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5beeefc
2156b71
 
a8673cc
 
5beeefc
 
a8673cc
 
 
2156b71
a8673cc
 
 
 
 
 
 
 
 
 
 
 
2156b71
a8673cc
5beeefc
 
 
a8673cc
5beeefc
 
 
 
a8673cc
2156b71
a8673cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2156b71
a8673cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2156b71
 
a8673cc
 
 
 
 
 
2156b71
a8673cc
2156b71
a8673cc
 
 
 
 
 
 
2156b71
 
 
a8673cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2156b71
 
5beeefc
a8673cc
5beeefc
 
a8673cc
2156b71
 
a8673cc
5beeefc
 
a8673cc
 
5beeefc
 
 
 
 
a8673cc
 
5beeefc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8673cc
 
 
5beeefc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2156b71
 
5beeefc
2156b71
 
a8673cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2156b71
65bc393
5beeefc
 
 
a8673cc
5beeefc
65bc393
a8673cc
5beeefc
 
 
65bc393
 
 
 
a8673cc
65bc393
 
 
 
a8673cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2156b71
 
 
5beeefc
2156b71
5beeefc
 
 
 
 
a8673cc
 
 
 
 
5beeefc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2156b71
 
5beeefc
 
 
 
 
 
 
 
 
 
 
 
2156b71
5beeefc
 
2156b71
5beeefc
 
 
 
2156b71
 
 
5beeefc
51913a2
a8673cc
 
 
5beeefc
 
 
a8673cc
5beeefc
 
 
 
a8673cc
 
 
5beeefc
51913a2
5beeefc
 
 
 
 
 
 
 
 
 
65bc393
a8673cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65bc393
 
a8673cc
 
 
 
 
 
 
 
 
 
 
 
65bc393
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8673cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65bc393
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
use tokio::process::Command;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
use fred::interfaces::KeysInterface;
use anyhow::{Result, anyhow};
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::process::Stdio;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use tokio::fs;
use tokio::task::JoinSet;
use crate::storage::StorageManager;
use crate::models::{UserTier, TaskStatus};
use crate::queue::WeightedScheduler;

/// Redis key TTL for live encode progress (seconds).
const JOB_PROGRESS_TTL_SECS: i64 = 300;
/// Minimum gap between progress Redis writes.
const PROGRESS_REPORT_INTERVAL: Duration = Duration::from_secs(1);
/// Target HLS segment length.
const HLS_SEGMENT_SECS: u32 = 6;
/// Progress band: encode starts at 15% and may not exceed this.
const ENCODE_BASE_PCT: u32 = 15;
const ENCODE_SPAN_PCT: u32 = 75;

pub struct TranscodingConfig {
    pub preset: String,
    pub crf: String,
}

impl TranscodingConfig {
    pub fn for_tier(tier: &UserTier) -> Self {
        match tier {
            UserTier::Free => Self {
                preset: "ultrafast".to_string(),
                crf: "26".to_string(), // Slightly lower quality for space/speed
            },
            UserTier::Pro => Self {
                preset: "medium".to_string(),
                crf: "23".to_string(), // Better quality
            },
        }
    }
}

/// Highest rendition we consider a "passthrough" candidate per tier. A source
/// that already fits the cap and is H.264/AAC does not need re-encoding at all.
fn passthrough_cap(tier: &UserTier) -> i32 {
    match tier {
        UserTier::Free => 720,
        UserTier::Pro => 1080,
    }
}

fn job_progress_key(job_id: &str) -> String {
    format!("job:progress:{}", job_id)
}

/// Write live encode progress `0..=100` to `job:progress:{job_id}` (fred Redis client).
pub async fn set_job_progress(sched: &WeightedScheduler, job_id: &str, percent: u32) {
    let pct = percent.min(100);
    let _: () = sched
        .client()
        .set(
            job_progress_key(job_id),
            pct.to_string(),
            Some(fred::types::Expiration::EX(JOB_PROGRESS_TTL_SECS)),
            None,
            false,
        )
        .await
        .unwrap_or_default();
}

/// Remove progress key so failed jobs do not leave a stale percentage.
pub async fn clear_job_progress(sched: &WeightedScheduler, job_id: &str) {
    let _: () = sched
        .client()
        .del(job_progress_key(job_id))
        .await
        .unwrap_or_default();
}

/// Everything one ffprobe invocation can tell us about the source.
#[derive(Debug, Clone)]
struct Probe {
    width: i32,
    height: i32,
    has_audio: bool,
    duration: f64,
    video_codec: String,
    audio_codec: Option<String>,
}

impl Probe {
    /// True when the video/audio streams can be copied into HLS untouched.
    fn copy_safe(&self) -> bool {
        self.video_codec.eq_ignore_ascii_case("h264")
            && self
                .audio_codec
                .as_deref()
                .map(|c| c.eq_ignore_ascii_case("aac"))
                .unwrap_or(true)
    }
}

/// One output rendition.
#[derive(Debug, Clone)]
struct Variant {
    name: String,
    height: i32,
    bitrate: &'static str,
}

fn bitrate_for(height: i32) -> &'static str {
    if height >= 1080 {
        "5000k"
    } else if height >= 720 {
        "2800k"
    } else {
        "1200k"
    }
}

fn label_for(height: i32) -> &'static str {
    if height >= 1080 {
        "1080p"
    } else if height >= 720 {
        "720p"
    } else {
        "480p"
    }
}

/// Decide the rendition set.
///
/// Rules, in priority order:
/// 1. Source already H.264/AAC and inside the tier cap → single passthrough
///    variant at native resolution (no encode at all).
/// 2. Flash → single variant at native resolution ("original").
/// 3. Otherwise → ladder capped by tier, filtered against the source so we
///    never upscale. Free tier produces a single rendition; Pro keeps the
///    1080/720/480 ladder.
fn plan_variants(format: &str, tier: &UserTier, probe: &Probe) -> (Vec<Variant>, bool) {
    let cap = passthrough_cap(tier);

    if probe.copy_safe() && probe.height <= cap {
        let name = if format == "flash" {
            "original".to_string()
        } else {
            label_for(probe.height).to_string()
        };
        return (
            vec![Variant {
                name,
                height: probe.height,
                bitrate: bitrate_for(probe.height),
            }],
            true,
        );
    }

    if format == "flash" {
        return (
            vec![Variant {
                name: "original".to_string(),
                height: probe.height,
                bitrate: bitrate_for(probe.height),
            }],
            false,
        );
    }

    let top = match tier {
        UserTier::Pro => 1080,
        UserTier::Free => 720,
    };

    // Free tier: one rendition at the source height, capped. Encoding the whole
    // ladder is what made 2-vCPU Spaces crawl.
    if matches!(tier, UserTier::Free) {
        let h = probe.height.min(top).max(2);
        return (
            vec![Variant {
                name: label_for(h).to_string(),
                height: h,
                bitrate: bitrate_for(h),
            }],
            false,
        );
    }

    let mut variants: Vec<Variant> = Vec::new();
    for h in [1080, 720, 480] {
        if h <= top && probe.height >= h {
            variants.push(Variant {
                name: format!("{}p", h),
                height: h,
                bitrate: bitrate_for(h),
            });
        }
    }

    // Source smaller than every ladder step: keep one rendition at the source
    // height (never upscale) and name it after the bucket it falls into.
    if variants.is_empty() {
        let h = probe.height.min(top).max(2);
        variants.push(Variant {
            name: label_for(h).to_string(),
            height: h,
            bitrate: bitrate_for(h),
        });
    }

    (variants, false)
}

/// Encode (or remux) into HLS, uploading segments while ffmpeg is still running,
/// then generate the cover. Returns the output directory.
#[allow(clippy::too_many_arguments)]
pub async fn process(
    _video_id: String, // Platform ID
    video_path: &str, // Local filesystem path
    format: &str,
    tier: UserTier,
    skip_thumbnail: bool,
    scheduler: Option<WeightedScheduler>,
    task_id: String,
    storage: Arc<StorageManager>,
) -> Result<(String, Vec<String>)> {
    println!(
        "Starting processing for task_id={} video_path={}",
        task_id, video_path
    );

    // Check if file exists
    if !Path::new(video_path).exists() {
        return Err(anyhow!("Video file not found at path: {}", video_path));
    }

    let config = TranscodingConfig::for_tier(&tier);

    status(
        scheduler.as_ref(),
        &task_id,
        5,
        "Analyzing video streams and metadata...",
    )
    .await;

    let probe = match probe_video(video_path).await {
        Ok(p) => p,
        Err(e) => {
            eprintln!("Metadata extraction failed for {}: {}", video_path, e);
            if let Some(ref sched) = scheduler {
                clear_job_progress(sched, &task_id).await;
            }
            return Err(e);
        }
    };

    println!(
        "Metadata: width={} height={} has_audio={} duration={:.3}s codec={} audio={:?}",
        probe.width,
        probe.height,
        probe.has_audio,
        probe.duration,
        probe.video_codec,
        probe.audio_codec
    );

    // ── Orientation validation ────────────────────────────────────────────────
    // Reject jobs whose declared format (home/flash) does not match actual pixel
    // dimensions.  Square-ish videos (aspect 0.9–1.1) always pass regardless of
    // declared type.  This catches client-side bypasses (devtools, direct API).
    {
        let ratio = probe.width as f64 / probe.height as f64;
        let is_squareish = ratio >= 0.9 && ratio <= 1.1;
        if !is_squareish {
            let mismatch = match format {
                "flash" => ratio > 1.1,  // declared flash but video is landscape
                "home" => ratio < 0.9,   // declared home but video is portrait
                _ => false,
            };
            if mismatch {
                let msg = format!(
                    "Video orientation doesn't match the selected format: \
                     video is {}x{} ({} {}) but format is \"{}\"",
                    probe.width,
                    probe.height,
                    if ratio > 1.1 { "landscape" } else { "portrait" },
                    ratio,
                    format,
                );
                eprintln!("{}", msg);
                if let Some(ref sched) = scheduler {
                    clear_job_progress(sched, &task_id).await;
                }
                return Err(anyhow!("{}", msg));
            }
        }
    }

    // 2. Prep Output — wipe leftovers from a previous attempt so a retry can
    // never upload stale segments alongside fresh ones.
    let output_dir = format!("{}_hls", video_path);
    if Path::new(&output_dir).exists() {
        fs::remove_dir_all(&output_dir).await.ok();
    }
    fs::create_dir_all(&output_dir).await?;

    let (variants, copy) = plan_variants(format, &tier, &probe);
    let variant_names: Vec<String> = variants.iter().map(|v| v.name.clone()).collect();
    println!(
        "Plan: variants={:?} mode={}",
        variant_names,
        if copy { "remux" } else { "encode" }
    );

    // 3. Start uploading segments as they appear — no post-encode tail.
    let s3_prefix = format!("videos/{}", task_id);
    let uploader = DirUploader::start(storage.clone(), output_dir.clone(), s3_prefix.clone());

    status(
        scheduler.as_ref(),
        &task_id,
        ENCODE_BASE_PCT,
        if copy {
            "Packaging video into adaptive streams..."
        } else {
            "Compressing and optimizing video..."
        },
    )
    .await;

    let args = build_args(video_path, &output_dir, &probe, &variants, copy, &config);
    let encode_res = run_ffmpeg_with_progress(
        &args,
        probe.duration,
        scheduler.as_ref(),
        &task_id,
        ENCODE_BASE_PCT,
        ENCODE_SPAN_PCT,
    )
    .await;

    // Drain whatever ffmpeg just wrote (playlists land at the end).
    let upload_res = uploader.finish().await;

    if let Err(e) = encode_res {
        if let Some(ref sched) = scheduler {
            clear_job_progress(sched, &task_id).await;
        }
        return Err(e);
    }
    upload_res?;

    // 4. Thumbnail next to the source (legacy path; auto-cover is handled by the worker)
    if !skip_thumbnail {
        status(scheduler.as_ref(), &task_id, 92, "Generating thumbnail...").await;
        if let Err(e) = generate_thumbnail(video_path).await {
            eprintln!("Legacy thumbnail generation failed: {}", e);
        }
    }

    Ok((output_dir, variant_names))
}

async fn status(
    scheduler: Option<&WeightedScheduler>,
    task_id: &str,
    progress: u32,
    message: &str,
) {
    if let Some(sched) = scheduler {
        let status = TaskStatus {
            progress,
            status: "processing".to_string(),
            message: message.to_string(),
            cover_url: None,
            cover_source: None,
            variants: None,
        };
        let status_json = serde_json::to_string(&status).unwrap_or_default();
        let _: () = sched
            .client()
            .set(
                format!("task:status:{}", task_id),
                status_json,
                Some(fred::types::Expiration::EX(86400)),
                None,
                false,
            )
            .await
            .unwrap_or_default();
    }
}

/// Build the ffmpeg invocation for either a remux (`copy = true`) or a real encode.
fn build_args(
    input: &str,
    output_dir: &str,
    probe: &Probe,
    variants: &[Variant],
    copy: bool,
    config: &TranscodingConfig,
) -> Vec<String> {
    let n = variants.len();
    let mut args: Vec<String> = vec!["-i".into(), input.into()];

    if !copy {
        args.extend([
            "-preset".to_string(),
            config.preset.clone(),
            "-crf".to_string(),
            config.crf.clone(),
        ]);
    }

    args.extend([
        "-f".into(),
        "hls".into(),
        "-hls_time".into(),
        HLS_SEGMENT_SECS.to_string(),
        "-hls_playlist_type".into(),
        "vod".into(),
        "-master_pl_name".into(),
        "master.m3u8".into(),
    ]);

    // Threads per encoder: with several renditions in one process, letting each
    // x264 instance spawn for every core oversubscribes a 2-vCPU Space.
    let cores = std::thread::available_parallelism()
        .map(|c| c.get())
        .unwrap_or(2);
    let threads_per_variant = (cores / n.max(1)).max(1);

    if copy {
        args.extend(["-map".into(), "0:v:0".into()]);
        args.extend(["-c".into(), "copy".into()]);
    } else if n == 1 {
        let filter = format!("[0:v]scale=w=-2:h={}[v0out]", variants[0].height);
        args.extend(["-filter_complex".into(), filter]);
        args.extend([
            "-map".into(),
            "[v0out]".into(),
            "-c:v:0".into(),
            "libx264".into(),
            "-b:v:0".into(),
            variants[0].bitrate.to_string(),
            "-threads:v:0".to_string(),
            threads_per_variant.to_string(),
        ]);
    } else {
        let mut filter = format!("[0:v]split={}", n);
        for i in 0..n {
            filter.push_str(&format!("[v{}]", i));
        }
        filter.push(';');
        for i in 0..n {
            filter.push_str(&format!(
                " [v{}]scale=w=-2:h={}[v{}out];",
                i, variants[i].height, i
            ));
        }
        args.extend(["-filter_complex".into(), filter]);

        for (i, variant) in variants.iter().enumerate() {
            args.extend([
                "-map".to_string(),
                format!("[v{}out]", i),
                format!("-c:v:{}", i),
                "libx264".to_string(),
                format!("-b:v:{}", i),
                variant.bitrate.to_string(),
                format!("-threads:v:{}", i),
                threads_per_variant.to_string(),
            ]);
        }
    }

    // ── Audio ────────────────────────────────────────────────────────────────
    // Each HLS variant needs its OWN audio output stream. Map the source audio
    // once per variant with unique a:N so the muxer writes independent AAC
    // streams into each segment set. Copy mode keeps the source audio codec.
    if probe.has_audio {
        for _ in 0..n {
            args.push("-map".into());
            args.push("0:a:0".into());
        }
        if !copy {
            for i in 0..n {
                args.push(format!("-c:a:{}", i));
                args.push("aac".into());
                args.push(format!("-b:a:{}", i));
                args.push("128k".into());
            }
        }
    }

    // ── HLS naming ───────────────────────────────────────────────────────────
    let stream_map = if probe.has_audio {
        variants
            .iter()
            .enumerate()
            .map(|(i, v)| format!("v:{},a:{},name:{}", i, i, v.name))
            .collect::<Vec<_>>()
            .join(" ")
    } else {
        variants
            .iter()
            .enumerate()
            .map(|(i, v)| format!("v:{},name:{}", i, v.name))
            .collect::<Vec<_>>()
            .join(" ")
    };

    args.extend([
        "-hls_segment_filename".to_string(),
        format!("{}/%v_%03d.ts", output_dir),
        "-var_stream_map".to_string(),
        stream_map,
        format!("{}/%v.m3u8", output_dir),
    ]);

    args
}

/// Spawn ffmpeg with `-progress pipe:1`, map `out_time` onto the `base..base+span`
/// progress band, and throttle Redis writes to ~1/sec.
async fn run_ffmpeg_with_progress(
    args: &[String],
    duration_secs: f64,
    scheduler: Option<&WeightedScheduler>,
    task_id: &str,
    base: u32,
    span: u32,
) -> Result<()> {
    // Machine-readable progress on stdout; keep stderr for errors (drained so the pipe never blocks).
    let mut full_args: Vec<String> = vec![
        "-nostats".into(),
        "-progress".into(),
        "pipe:1".into(),
    ];
    full_args.extend(args.iter().cloned());

    let mut child = Command::new("ffmpeg")
        .args(&full_args)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()?;

    let stdout = child
        .stdout
        .take()
        .ok_or_else(|| anyhow!("ffmpeg stdout not captured"))?;
    let stderr = child
        .stderr
        .take()
        .ok_or_else(|| anyhow!("ffmpeg stderr not captured"))?;

    let stderr_task = tokio::spawn(async move {
        let mut buf = Vec::new();
        let mut reader = BufReader::new(stderr);
        let _ = reader.read_to_end(&mut buf).await;
        String::from_utf8_lossy(&buf).to_string()
    });

    let mut lines = BufReader::new(stdout).lines();
    let mut last_report = Instant::now()
        .checked_sub(PROGRESS_REPORT_INTERVAL)
        .unwrap_or_else(Instant::now);
    let mut current_out_us: u64 = 0;

    while let Some(line) = lines.next_line().await? {
        let line = line.trim();
        if let Some(v) = line.strip_prefix("out_time_us=") {
            if let Ok(us) = v.parse::<u64>() {
                current_out_us = us;
            }
        } else if let Some(v) = line.strip_prefix("out_time_ms=") {
            // Historical ffmpeg key: value is microseconds despite the name.
            if let Ok(us) = v.parse::<u64>() {
                current_out_us = us;
            }
        } else if line.starts_with("progress=") {
            let force = line == "progress=end";
            if force || last_report.elapsed() >= PROGRESS_REPORT_INTERVAL {
                if duration_secs > 0.0 {
                    let current_time_seconds = current_out_us as f64 / 1_000_000.0;
                    let ratio = (current_time_seconds / duration_secs).clamp(0.0, 1.0);
                    // Stay below base+span until process exit confirms success.
                    let progress_percent = base + (ratio * span as f64) as u32;
                    if let Some(sched) = scheduler {
                        set_job_progress(sched, task_id, progress_percent).await;
                    }
                }
                last_report = Instant::now();
            }
        }
    }

    let status = child.wait().await?;
    let err_text = stderr_task.await.unwrap_or_default();

    if !status.success() {
        eprintln!("FFmpeg Error: {}", err_text);
        if let Some(sched) = scheduler {
            clear_job_progress(sched, task_id).await;
        }
        return Err(anyhow!("FFmpeg failed: {}", err_text));
    }

    Ok(())
}

/// Background directory watcher: uploads each HLS artifact as soon as its size
/// stops changing, so S3 transfer overlaps the encode instead of following it.
struct DirUploader {
    stop: Arc<AtomicBool>,
    handle: tokio::task::JoinHandle<Result<()>>,
}

impl DirUploader {
    fn start(storage: Arc<StorageManager>, dir: String, prefix: String) -> Self {
        let stop = Arc::new(AtomicBool::new(false));
        let handle = tokio::spawn({
            let stop = stop.clone();
            async move { run_dir_uploader(storage, dir, prefix, stop).await }
        });
        Self { stop, handle }
    }

    async fn finish(self) -> Result<()> {
        self.stop.store(true, Ordering::Relaxed);
        match self.handle.await {
            Ok(res) => res,
            Err(e) => Err(anyhow!("segment uploader panicked: {}", e)),
        }
    }
}

async fn run_dir_uploader(
    storage: Arc<StorageManager>,
    dir: String,
    prefix: String,
    stop: Arc<AtomicBool>,
) -> Result<()> {
    let concurrency = std::env::var("UPLOAD_CONCURRENCY")
        .ok()
        .and_then(|v| v.parse::<usize>().ok())
        .filter(|v| *v > 0)
        .unwrap_or(12);

    // name -> last observed size. A file is uploaded once its size is stable
    // across two polls (i.e. ffmpeg has finished writing it).
    let mut sizes: HashMap<String, u64> = HashMap::new();
    let mut queued: HashSet<String> = HashSet::new();
    let mut inflight: JoinSet<Result<()>> = JoinSet::new();
    let mut first_err: Option<anyhow::Error> = None;

    loop {
        while let Some(res) = inflight.try_join_next() {
            match res {
                Ok(Ok(())) => {}
                Ok(Err(e)) => {
                    if first_err.is_none() {
                        first_err = Some(e);
                    }
                }
                Err(e) => {
                    if first_err.is_none() {
                        first_err = Some(anyhow!("upload task failed: {}", e));
                    }
                }
            }
        }

        let stopping = stop.load(Ordering::Relaxed);

        if inflight.len() < concurrency {
            if let Ok(mut entries) = fs::read_dir(&dir).await {
                loop {
                    let entry = match entries.next_entry().await {
                        Ok(Some(e)) => e,
                        Ok(None) => break,
                        Err(_) => break,
                    };
                    let path = entry.path();
                    if !path.is_file() {
                        continue;
                    }
                    let name = match path.file_name().and_then(|n| n.to_str()) {
                        Some(n) => n.to_string(),
                        None => continue,
                    };
                    if queued.contains(&name) {
                        continue;
                    }

                    let size = entry.metadata().await.map(|m| m.len()).unwrap_or(0);
                    let stable = sizes.get(&name) == Some(&size);
                    sizes.insert(name.clone(), size);

                    // Skip files ffmpeg is still growing (and empty placeholders).
                    if (!stable && !stopping) || size == 0 {
                        continue;
                    }

                    queued.insert(name.clone());
                    let storage = storage.clone();
                    let key = format!("{}/{}", prefix, name);
                    inflight.spawn(async move { storage.upload_file(&path, &key).await });
                }
            }
        }

        if stopping && inflight.is_empty() {
            break;
        }

        tokio::time::sleep(Duration::from_millis(250)).await;
    }

    match first_err {
        Some(e) => Err(e),
        None => Ok(()),
    }
}

/// Probe width/height/audio/duration/codecs in a single ffprobe invocation.
async fn probe_video(video_path: &str) -> Result<Probe> {
    let output = Command::new("ffprobe")
        .args([
            "-v",
            "error",
            "-show_entries",
            "stream=codec_type,codec_name,width,height:format=duration",
            "-of",
            "json",
            video_path,
        ])
        .output()
        .await?;

    if !output.status.success() {
        return Err(anyhow!(
            "ffprobe failed for {}: {}",
            video_path,
            String::from_utf8_lossy(&output.stderr).trim()
        ));
    }

    let raw = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&raw)
        .map_err(|e| anyhow!("Invalid ffprobe JSON ({}): {}", e, raw.trim()))?;

    let duration = json
        .get("format")
        .and_then(|f| f.get("duration"))
        .and_then(|d| d.as_str())
        .and_then(|d| d.parse::<f64>().ok())
        .filter(|d| d.is_finite() && *d > 0.0)
        .unwrap_or(0.0);

    let streams = json
        .get("streams")
        .and_then(|v| v.as_array())
        .ok_or_else(|| anyhow!("ffprobe returned no streams: {}", raw.trim()))?;

    let mut width = 0i32;
    let mut height = 0i32;
    let mut video_codec = String::new();
    let mut audio_codec: Option<String> = None;
    let mut has_audio = false;

    for stream in streams {
        let kind = stream.get("codec_type").and_then(|v| v.as_str()).unwrap_or("");
        match kind {
            "video" if width == 0 => {
                let w = stream.get("width").and_then(|v| v.as_i64()).unwrap_or(0);
                let h = stream.get("height").and_then(|v| v.as_i64()).unwrap_or(0);
                if w > 0 && h > 0 {
                    width = w as i32;
                    height = h as i32;
                    video_codec = stream
                        .get("codec_name")
                        .and_then(|v| v.as_str())
                        .unwrap_or("")
                        .to_string();
                }
            }
            "audio" if !has_audio => {
                has_audio = true;
                audio_codec = stream
                    .get("codec_name")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string());
            }
            _ => {}
        }
    }

    if width == 0 || height == 0 {
        return Err(anyhow!(
            "ffprobe returned no usable width/height: {}",
            raw.trim()
        ));
    }

    Ok(Probe {
        width,
        height,
        has_audio,
        duration,
        video_codec,
        audio_codec,
    })
}

/// Pick the first width/height pair from `ffprobe -of json -show_entries stream=width,height`.
///
/// JSON is used instead of `-of csv=s=x:p=0` because the CSV writer can emit
/// extra sections/fields depending on the container (e.g. QuickTime timecode
/// tracks and MPEG-TS programs produce multiple lines, and some files end with
/// a bare separator like `1080x1080x`). Splitting the whole stdout on 'x' then
/// rejects perfectly valid values.
#[cfg(test)]
fn parse_dimensions(stdout: &[u8]) -> Result<(i32, i32)> {
    let raw = String::from_utf8_lossy(stdout);
    let json: serde_json::Value = serde_json::from_str(&raw)
        .map_err(|e| anyhow!("Invalid ffprobe JSON ({}): {}", e, raw.trim()))?;

    let streams = json
        .get("streams")
        .and_then(|v| v.as_array())
        .ok_or_else(|| anyhow!("ffprobe returned no streams: {}", raw.trim()))?;

    for stream in streams {
        let width = stream.get("width").and_then(|v| v.as_i64());
        let height = stream.get("height").and_then(|v| v.as_i64());
        if let (Some(w), Some(h)) = (width, height) {
            if w > 0 && h > 0 {
                return Ok((w as i32, h as i32));
            }
        }
    }

    Err(anyhow!(
        "ffprobe returned no usable width/height: {}",
        raw.trim()
    ))
}

async fn generate_thumbnail(video_path: &str) -> Result<()> {
    // Legacy path (thumbnails next to source). Prefer generate_and_upload_auto_cover.
    let thumb_path = format!("{}.jpg", video_path);
    extract_cover_frame(video_path, &thumb_path, 0.1).await
}

/// Seek ~`pct` into the video (default 10%) and write a single JPEG frame.
pub async fn extract_cover_frame(video_path: &str, out_jpg: &str, pct: f64) -> Result<()> {
    let duration = probe_video(video_path)
        .await
        .map(|p| p.duration)
        .unwrap_or(0.0);

    let seek_secs = if duration > 0.5 {
        (duration * pct).clamp(0.0, (duration - 0.05).max(0.0))
    } else {
        0.0
    };
    let seek_arg = format!("{:.3}", seek_secs);

    println!(
        "Extracting cover frame from {} at {}s ({:.0}% of {:.2}s) → {}",
        video_path,
        seek_arg,
        pct * 100.0,
        duration,
        out_jpg
    );

    let status = Command::new("ffmpeg")
        .args(&[
            "-ss",
            &seek_arg,
            "-i",
            video_path,
            "-frames:v",
            "1",
            "-update",
            "1",
            "-q:v",
            "2",
            "-y",
            out_jpg,
        ])
        .status()
        .await?;
    if !status.success() {
        return Err(anyhow!("Cover frame extraction failed"));
    }
    if !Path::new(out_jpg).exists() {
        return Err(anyhow!("Cover JPEG was not written: {}", out_jpg));
    }
    Ok(())
}

/// Auto cover: frame at ~10% duration → JPEG → S3 `thumbnails/{task_id}.jpg`.
///
/// Prefers pulling the frame out of an already-encoded HLS segment (cheap, and
/// the bytes are already local) and only falls back to re-reading the source.
/// Returns the S3 key for inclusion in the Redis completion payload.
pub async fn generate_and_upload_auto_cover(
    video_path: &str,
    output_dir: &str,
    task_id: &str,
    storage: &StorageManager,
) -> Result<String> {
    let cover_local = format!("{}_cover.jpg", video_path);

    let source = pick_cover_source(video_path, output_dir).await;
    extract_cover_frame(&source, &cover_local, 0.1).await?;

    let cover_key = format!("thumbnails/{}.jpg", task_id);
    storage
        .upload_file(Path::new(&cover_local), &cover_key)
        .await?;

    // Best-effort cleanup of local JPEG
    let _ = fs::remove_file(&cover_local).await;

    println!("Auto cover uploaded: {}", cover_key);
    Ok(cover_key)
}

/// Choose the cheapest file that contains a representative frame.
async fn pick_cover_source(video_path: &str, output_dir: &str) -> String {
    let entries = match fs::read_dir(output_dir).await {
        Ok(e) => e,
        Err(_) => return video_path.to_string(),
    };

    let mut segments: Vec<(u32, std::path::PathBuf)> = Vec::new();
    let mut entries = entries;
    while let Ok(Some(entry)) = entries.next_entry().await {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("ts") {
            continue;
        }
        let name = match path.file_name().and_then(|n| n.to_str()) {
            Some(n) => n,
            None => continue,
        };
        // "<variant>_<index>.ts"
        if let Some(idx) = name
            .rsplit_once('_')
            .and_then(|(_, tail)| tail.trim_end_matches(".ts").parse::<u32>().ok())
        {
            segments.push((idx, path));
        }
    }

    if segments.is_empty() {
        return video_path.to_string();
    }

    // Roughly 10% into the video, expressed in segments.
    let total = segments.iter().map(|(i, _)| *i).max().unwrap_or(0) + 1;
    let target = (total / 10).min(total.saturating_sub(1));
    segments.sort_by_key(|(idx, _)| idx.abs_diff(target));

    segments
        .into_iter()
        .next()
        .map(|(_, p)| p.to_string_lossy().to_string())
        .unwrap_or_else(|| video_path.to_string())
}

#[cfg(test)]
mod tests {
    use super::{label_for, parse_dimensions, plan_variants, Probe, UserTier};

    fn probe(height: i32, codec: &str) -> Probe {
        Probe {
            width: (height as f64 * 16.0 / 9.0) as i32,
            height,
            has_audio: true,
            duration: 60.0,
            video_codec: codec.to_string(),
            audio_codec: Some("aac".to_string()),
        }
    }

    #[test]
    fn picks_first_stream_with_dimensions() {
        // `programs` is emitted too for some containers; top-level `streams` wins.
        let out = br#"{
            "programs":[{"streams":[{"width":640,"height":480}]}],
            "streams":[{"width":1080,"height":1080},{"codec_type":"audio"}]
        }"#;
        assert_eq!(parse_dimensions(out).unwrap(), (1080, 1080));
    }

    #[test]
    fn skips_streams_without_dimensions() {
        let out = br#"{"streams":[{"codec_type":"video"},{"width":720,"height":1280}]}"#;
        assert_eq!(parse_dimensions(out).unwrap(), (720, 1280));
    }

    #[test]
    fn rejects_zero_dimensions() {
        let out = br#"{"streams":[{"width":0,"height":0}]}"#;
        assert!(parse_dimensions(out).is_err());
    }

    #[test]
    fn rejects_non_json_output() {
        assert!(parse_dimensions(b"1080x1080x").is_err());
    }

    #[test]
    fn h264_within_cap_is_passthrough() {
        let (variants, copy) = plan_variants("home", &UserTier::Free, &probe(720, "h264"));
        assert!(copy);
        assert_eq!(variants.len(), 1);
        assert_eq!(variants[0].name, "720p");
    }

    #[test]
    fn h264_above_cap_must_encode() {
        let (variants, copy) = plan_variants("home", &UserTier::Free, &probe(1080, "h264"));
        assert!(!copy);
        assert_eq!(variants.len(), 1);
        assert_eq!(variants[0].height, 720);
    }

    #[test]
    fn low_resolution_source_is_never_upscaled() {
        let (variants, _) = plan_variants("home", &UserTier::Free, &probe(360, "hevc"));
        assert_eq!(variants.len(), 1);
        assert_eq!(variants[0].height, 360);
    }

    #[test]
    fn pro_keeps_the_ladder() {
        let (variants, _) = plan_variants("home", &UserTier::Pro, &probe(1080, "hevc"));
        let names: Vec<_> = variants.iter().map(|v| v.name.as_str()).collect();
        assert_eq!(names, vec!["1080p", "720p", "480p"]);
    }

    #[test]
    fn labels_bucket_by_height() {
        assert_eq!(label_for(1080), "1080p");
        assert_eq!(label_for(720), "720p");
        assert_eq!(label_for(360), "480p");
    }
}