-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmedia.nu
More file actions
2287 lines (1996 loc) · 85.8 KB
/
Copy pathmedia.nu
File metadata and controls
2287 lines (1996 loc) · 85.8 KB
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
export def "media help" [] {
print ([
"media manipulation and visualization tools: ffmpeg, sox, subsync and mpv required."
"METHODS:"
"- media video-info"
"- media mpv-info"
"- media sub-sync"
"- media remove-noise"
"- media remove-audio-noise"
"- media screen-record"
"- media remove-audio"
"- media cut-video"
"- media split-video"
"- media cut-audio"
"- media extract-audio"
"- media merge-videos"
"- media merge-videos-auto"
"- media compress-video"
"- media delete-non-compressed"
"- media find"
"- media myt"
"- media delete-mps"
"- media crop-video"
"- media auto-remove-logo"
"- media repeat"
"- media add-audio"
"- mpv (alias)"
"- media to"
]
| str join "\n"
| nu-highlight
)
}
#add audio track to video file
export def "media add-audio" [
video_file: string # input video file
audio_file: string # input audio file
--volume-factor(-v): float = 0.5 # volume factor for background audio
--output(-o): string # optional output filename
--notify(-n) # notify to android via join/tasker
] {
let v_info = media video-info $video_file
let v_duration = $v_info.format.duration | into float
let v_has_audio = $v_info.streams | where codec_type == "audio" | is-not-empty
let a_duration = ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 $audio_file | str trim | into float
let v_ext = $video_file | path parse | get extension
let v_stem = $video_file | path parse | get stem
let ofile = if ($output | is-empty) {
$"($v_stem)_merged.($v_ext)"
} else {
$output
}
mut final_audio = $audio_file
mut temp_files = []
# Logic for duration adjustment
if $a_duration < ($v_duration - 0.1) {
# Case B: Looping audio
let n_repeats = $v_duration / $a_duration | math ceil | into int
let looped_audio = $"tmp_looped_($v_stem).($audio_file | path parse | get extension)"
$temp_files = ($temp_files | append $looped_audio)
media repeat $audio_file $n_repeats --output $looped_audio
$final_audio = $looped_audio
# Trim the looped audio to match video length
let trimmed_audio = $"tmp_trimmed_($v_stem).($audio_file | path parse | get extension)"
$temp_files = ($temp_files | append $trimmed_audio)
media cut-audio $final_audio $trimmed_audio 0 ($v_duration | math round | into int)
$final_audio = $trimmed_audio
} else if $a_duration > ($v_duration + 0.1) {
# Case A: Trimming longer audio
let trimmed_audio = $"tmp_trimmed_($v_stem).($audio_file | path parse | get extension)"
$temp_files = ($temp_files | append $trimmed_audio)
media cut-audio $audio_file $trimmed_audio 0 ($v_duration | math round | into int)
$final_audio = $trimmed_audio
}
print (echo-g $"Merging audio into video ($video_file)...")
# Case C vs D: Mixing vs Simple Add
let filter = if $v_has_audio {
$"[1:a]volume=($volume_factor)[a1];[0:a][a1]amix=inputs=2:duration=first"
} else {
""
}
# Final audio path for the try/catch blocks (must be immutable for capture)
let final_audio_frozen = $final_audio
let filter_frozen = $filter
let ofile_frozen = $ofile
try {
print (echo-g "Trying with my-ffmpeg...")
if $v_has_audio {
my-ffmpeg -i $video_file -i $final_audio_frozen -filter_complex $filter_frozen -map 0:v -c:v copy -c:a aac -b:a 128k $ofile_frozen -y
} else {
my-ffmpeg -i $video_file -i $final_audio_frozen -map 0:v -map 1:a -c:v copy -c:a aac -b:a 128k $ofile_frozen -y
}
} catch {
print (echo-y "my-ffmpeg failed, falling back to standard ffmpeg...")
if $v_has_audio {
ffmpeg -i $video_file -i $final_audio_frozen -filter_complex $filter_frozen -map 0:v -c:v copy -c:a aac -b:a 128k $ofile_frozen -y
} else {
ffmpeg -i $video_file -i $final_audio_frozen -map 0:v -map 1:a -c:v copy -c:a aac -b:a 128k $ofile_frozen -y
}
}
# Cleanup temp files
for f in $temp_files {
if ($f | path exists) { rm $f }
}
if ($ofile | path exists) {
print (echo-g $"SUCCESS: Audio merged. Output: ($ofile)")
if $notify { "Audio merge finished!" | tasker send-notification }
} else {
return-error "FFmpeg failed to produce output file."
}
}
#repeat audio file n times
export def "media repeat" [
file: string # audio file name
n: int # number of times to repeat
--output(-o): string # output file name
--notify(-n) # notify to android via join/tasker
] {
let filename = $file | path parse | get stem
let ext = $file | path parse | get extension
let ofile = if ($output | is-empty) {
$"($filename)_repeated_($n).($ext)"
} else {
$output
}
print (echo-g $"Repeating audio ($file) ($n) times...")
# stream_loop uses 0 for infinite, -1 for no loop?
# Actually, -stream_loop N means loop N times. 0 means loop 0 times (play once). 1 means loop once (play twice).
let loops = $n - 1
try {
print (echo-g "Trying with my-ffmpeg...")
my-ffmpeg -stream_loop $loops -i $file -c copy $ofile -y
} catch {
print (echo-y "my-ffmpeg failed, falling back to standard ffmpeg...")
ffmpeg -stream_loop $loops -i $file -c copy $ofile -y
}
if ($ofile | path exists) {
print (echo-g $"SUCCESS: Audio repeated ($n) times. Output: ($ofile)")
if $notify { "Audio repeat finished!" | tasker send-notification }
} else {
return-error "FFmpeg failed to produce output file."
}
}
#cuda ffmpeg
export def --wrapped my-ffmpeg [...rest] {
let ffmpeg = if (sys host | get name | str lowercase) == "windows" { "ffmpeg.exe" } else { ($env.HOME | path join "software" "nvidia" "ffmpeg" "ffmpeg") }
^$ffmpeg -hwaccel cuda ...$rest
}
#video info
export def "media video-info" [file?] {
let video = if ($file | is-empty) {$in | get name} else {$file}
ffprobe -v quiet -print_format json -show_format -show_streams $video | from json
}
#video info via mpv
export def "media mpv-info" [file?] {
let video = if ($file | is-empty) {$in | get name} else {$file}
^mpv -vo null -ao null -frames 0 $video
}
#sync subtitles
#
#Examples
#sub-sync file.srt "-4"
#sub-sync file.srt "-4" --t1 00:02:33
#sub-sync file.srt "-4" --no_backup 1
export def "media sub-sync" [
file:string #subtitle file name to process
d1:string #delay at the beginning or at time specified by t1 (<0 adelantar, >0 retrasar)
--t1:string #time position of delay d1 (hh:mm:ss)
--d2:string #delay at the end or at time specified by t2
--t2:string #time position of delay d2 (hh:mm:ss)t
--no_backup:int #whether to not backup $file or yes (export default no:0, ie, it will backup)
] {
if not ($env.PWD | path join $file | path exists) {
return-error $"subtitle file ($file) doesn't exist in (pwd-short)"
}
if ($no_backup | is-empty) or $no_backup == 0 {
cp $file $"($file).backup"
}
let t1 = get-input "@" $t1
let d2 = get-input "" $d2
let t2 = if ($d2 | is-empty) {""} else {get-input "@" $t2}
bash -c $"subsync -e latin1 ($t1)($d1) ($t2)($d2) < \"($file)\" > output.srt; cp output.srt \"($file)\""
rm output.srt | ignore
}
const formats = ["mp3", "wav"]
#remove audio noise
export def "media remove-noise" [
file #audio file name with extension
start #start (hh:mm:ss) of audio noise (no speaker)
end #end (hh:mm:ss) of audio noise (no speaker)
noiseLevel #level reduction adjustment (0.2-0.3)
output? #output file name without extension, wav or mp3 produced
--delete(-d) = true #whether to delete existing tmp files or not
--outExt(-E):string@$formats = "wav" #output format, mp3 or wav
--notify(-n) #notify to android via join/tasker
] {
if $delete {
try {
ls ([$env.PWD tmp*] | path join) | rm-pipe
}
}
let filename = $file | path parse | get stem
let ext = $file | path parse | get extension
if $ext not-like "wav" {
print (echo-g "converting input file to wav format...")
my-ffmpeg -loglevel 1 -i $file $"($filename).wav"
}
let output = if ($output | is-empty) {
$"($filename)-clean.wav"
} else {
$"($output).wav"
}
print (echo-g "extracting noise segment...")
my-ffmpeg -loglevel 1 -i $"($filename).wav" -acodec pcm_s16le -ar 128k -vn -ss $start -t $end $"tmpSeg($filename).wav"
print (echo-g "creating noise profile...")
sox $"tmpSeg($filename).wav" -n noiseprof $"tmp($filename).prof"
print (echo-g "cleaning noise from audio file...")
sox $"($filename).wav" $output noisered $"tmp($filename).prof" $noiseLevel
if $outExt like "mp3" {
print (echo-g "converting output file to mp3 format...")
ffmpeg -loglevel 1 -i $output -acodec libmp3lame -ab 128k -vn $"($output | path parse | get stem).mp3"
mv $output $"tmp($output)"
}
if $ext not-like "wav" {
mv $"($filename).wav" $"tmp($filename).wav"
}
notify-send "noise removal done!"
if $notify {"noise removal finished!" | tasker send-notification}
}
#remove audio noise from video
export def "media remove-audio-noise" [
file #video file name with extension
start #start (hh:mm:ss) of audio noise (no speaker)
end #end (hh:mm:ss) of audio noise (no speaker)
noiseLevel #level reduction adjustment (0.2-0.3)
output? #output file name with extension (same extension as $file)
--merge = true #whether to merge clean audio with video
--notify(-n) #notifua to android via join/tasker
] {
try {
ls ([$env.PWD tmp*] | path join) | rm-pipe
}
let filename = $file | path parse | get stem
let ext = $file | path parse | get extension
let output = if ($output | is-empty) {
$"($filename)-clean.($ext)"
} else {
$output
}
let outputA = $"tmp($filename)-clean.wav"
print (echo-g "extracting video...")
my-ffmpeg -loglevel 1 -i $"($file)" -vcodec copy -an $"tmp($file)"
print (echo-g "extracting audio...")
my-ffmpeg -loglevel 1 -i $"($file)" -acodec pcm_s16le -ar 128k -vn $"tmp($filename).wav"
media remove-noise $"tmp($filename).wav" $start $end $noiseLevel $outputA --delete false
if $merge {
print (echo-g "merging clean audio with video file...")
my-ffmpeg -loglevel 1 -i $file -i $outputA -map 0:v -map 1:a -c:v copy -c:a aac -b:a 128k $output
}
print (echo-g "done!")
notify-send "noise removal done!"
if $notify {"noise removal finished!" | tasker send-notification}
}
# Helper to resolve PulseAudio/PipeWire sink monitor and source input
export def resolve-screen-record-audio [] {
mut sink_monitor = "@DEFAULT_SINK@.monitor"
mut source_input = "@DEFAULT_SOURCE@"
mut sink_name = ""
try {
let raw_sink = (pactl get-default-sink | str trim)
if ($raw_sink | is-not-empty) {
$sink_name = $raw_sink
$sink_monitor = $"($raw_sink).monitor"
}
} catch {
# Fallback to virtual alias @DEFAULT_SINK@.monitor
}
try {
let raw_source = (pactl get-default-source | str trim)
if ($raw_source | is-not-empty) {
$source_input = $raw_source
}
} catch {
# Fallback to virtual alias @DEFAULT_SOURCE@
}
{
sink_monitor: $sink_monitor,
source_input: $source_input,
sink_name: $sink_name
}
}
# Helper to build screen recording arguments for FFmpeg
export def build-screen-record-args [
resolution: string
display: string
file: string
audio: bool = true
no_mic: bool = false
no_system: bool = false
separate_tracks: bool = false
sink_monitor: string = "@DEFAULT_SINK@.monitor"
source_input: string = "@DEFAULT_SOURCE@"
use_nvenc: bool = true
] {
let ofile = $"($file).mp4"
let video_input = [-thread_queue_size 1024 -video_size $resolution -framerate 24 -f x11grab -i $"($display).0+0,0"]
let video_encode = if $use_nvenc {
[-c:v h264_nvenc -preset p4 -cq 18 -pix_fmt yuv420p]
} else {
[-c:v libx264 -preset veryfast -crf 18 -pix_fmt yuv420p]
}
let capture_system = ($audio and (not $no_system))
let capture_mic = ($audio and (not $no_mic))
if ($capture_system and $capture_mic) {
if $separate_tracks {
[
...$video_input
-thread_queue_size 1024 -f pulse -ac 2 -i $sink_monitor
-thread_queue_size 1024 -f pulse -ac 2 -i $source_input
-map 0:v -map 1:a -map 2:a
...$video_encode
-c:a aac -b:a 192k -strict experimental
$ofile
]
} else {
[
...$video_input
-thread_queue_size 1024 -f pulse -ac 2 -i $sink_monitor
-thread_queue_size 1024 -f pulse -ac 2 -i $source_input
-filter_complex "[1:a][2:a]amix=inputs=2:duration=longest:dropout_transition=0[aout]"
-map 0:v -map "[aout]"
...$video_encode
-c:a aac -b:a 192k -strict experimental
$ofile
]
}
} else if $capture_system {
[
...$video_input
-thread_queue_size 1024 -f pulse -ac 2 -i $sink_monitor
-map 0:v -map 1:a
...$video_encode
-c:a aac -b:a 192k -strict experimental
$ofile
]
} else if $capture_mic {
[
...$video_input
-thread_queue_size 1024 -f pulse -ac 2 -i $source_input
-map 0:v -map 1:a
...$video_encode
-c:a aac -b:a 192k -strict experimental
$ofile
]
} else {
[
...$video_input
...$video_encode
$ofile
]
}
}
#screen record
export def "media screen-record" [
file: string = "video" # output filename without extension
--audio = true # whether to record with audio or not
--no-mic # do not record microphone (computer/system audio only)
--no-system # do not record computer/system audio (microphone only)
--separate-tracks # record computer audio and microphone into separate audio streams
--output(-o): string # specific monitor/output to record on Hyprland (e.g. HDMI-A-1, DP-5)
--select(-s) # interactively select a window or region to record (via slurp on Hyprland)
--choose(-c) # interactively choose which screen/monitor to record
] {
let is_hyprland = (($env.XDG_CURRENT_DESKTOP? | default "") == "Hyprland")
if $is_hyprland {
mut output_args = []
if $select {
try {
let geometry = (slurp | str trim)
if ($geometry | is-not-empty) {
$output_args = [-g $geometry]
}
} catch {}
} else if $choose {
let monitors = try { hyprctl monitors -j | from json } catch { [] }
if ($monitors | is-not-empty) {
let options = ($monitors | each { |m| $"($m.name) - ($m.description)" })
let chosen = ($options | input list "Select screen to record:")
if ($chosen | is-not-empty) {
let mon_name = ($chosen | split row " - " | first)
$output_args = [-o $mon_name]
}
}
} else if ($output | is-not-empty) {
$output_args = [-o $output]
} else {
let focused_output = try {
hyprctl monitors -j | from json | where focused | get 0.name
} catch {
try {
hyprctl monitors -j | from json | get 0.name
} catch {
""
}
}
if ($focused_output | is-not-empty) {
$output_args = [-o $focused_output]
}
}
if ($audio and (not ($no_mic and $no_system))) {
print (echo-g "recording screen with audio for Hyprland...")
let audio_info = resolve-screen-record-audio
print (echo-g $"[screen-record] Sink Monitor: ($audio_info.sink_monitor)")
print (echo-g $"[screen-record] Mic Source: ($audio_info.source_input)")
if $no_mic {
# Computer audio only
wf-recorder ...$output_args $"--audio=($audio_info.sink_monitor)" -C aac -P b=192k -x yuv420p -f $"($file).mp4"
} else if $no_system {
# Microphone only
wf-recorder ...$output_args $"--audio=($audio_info.source_input)" -C aac -P b=192k -x yuv420p -f $"($file).mp4"
} else {
# Dual audio: mix sink monitor and microphone via dynamic PipeWire null-sink
let mix_name = $"sr_mix_(random chars -l 6)"
let sink_mod = (pactl load-module module-null-sink $"sink_name=($mix_name)" | str trim)
let lb_sink_mod = (pactl load-module module-loopback $"source=($audio_info.sink_monitor)" $"sink=($mix_name)" latency_msec=20 | str trim)
let lb_src_mod = (pactl load-module module-loopback $"source=($audio_info.source_input)" $"sink=($mix_name)" latency_msec=20 | str trim)
try {
wf-recorder ...$output_args $"--audio=($mix_name).monitor" -C aac -P b=192k -x yuv420p -f $"($file).mp4"
} catch { |e|
# recording completed or interrupted by Ctrl+C
}
# Cleanup PipeWire modules
try { pactl unload-module $lb_src_mod } catch {}
try { pactl unload-module $lb_sink_mod } catch {}
try { pactl unload-module $sink_mod } catch {}
}
} else {
print (echo-g "recording screen without audio for Hyprland...")
wf-recorder ...$output_args -x yuv420p -f $"($file).mp4"
}
} else {
let resolution = try {
xrandr | grep '*' | awk '{print $1}' | lines | first
} catch {
"1920x1080"
}
let display = ($env.DISPLAY? | default ":0")
if ($audio and (not ($no_mic and $no_system))) {
print (echo-g "recording screen with audio for Gnome/X11...")
let audio_info = resolve-screen-record-audio
print (echo-g $"[screen-record] Sink Monitor: ($audio_info.sink_monitor)")
print (echo-g $"[screen-record] Mic Source: ($audio_info.source_input)")
let args_nvenc = build-screen-record-args $resolution $display $file $audio $no_mic $no_system $separate_tracks $audio_info.sink_monitor $audio_info.source_input true
let args_cpu = build-screen-record-args $resolution $display $file $audio $no_mic $no_system $separate_tracks $audio_info.sink_monitor $audio_info.source_input false
try {
ffmpeg ...$args_nvenc
} catch {
print (echo-y "NVENC encode failed, falling back to CPU libx264...")
ffmpeg ...$args_cpu
}
} else {
print (echo-g "recording screen without audio for Gnome/X11...")
let args_nvenc = build-screen-record-args $resolution $display $file false false false false "" "" true
let args_cpu = build-screen-record-args $resolution $display $file false false false false "" "" false
try {
ffmpeg ...$args_nvenc
} catch {
ffmpeg ...$args_cpu
}
}
}
print (echo-g "recording finished...")
}
#remove audio from video file
export def "media remove-audio" [
input_file: string #the input file
output_file? #the output file
--notify(-n) #notify to android via join/tasker
] {
let output_file = get-input $"($input_file | path parse | get stem)-noaudio.($input_file | path parse | get extension)" $output_file
try {
echo-g "trying myffmpeg..."
my-ffmpeg -n -loglevel 0 -i $input_file -c copy -an $output_file
} catch {
echo-r "trying ffmpeg..."
ffmpeg -n -loglevel 0 -i $input_file -c copy -an $output_file
}
if $notify {"summary finished!" | tasker send-notification}
}
#cut segment of video file
export def "media cut-video" [
file #video file name
SEGSTART #timestamp of the start of the segment (hh:mm:ss)
SEGEND #timestamp of the end of the segment (hh:mm:ss)
--output_file(-o):string #output file
--append(-a):string = "cutted" #append to file name
--notify(-n) #notify to android via join/tasker
--reencode(-r) #reencode video
--audio-track: int #audio stream index to include (0-based)
--subtitle-track: int #subtitle stream index to include (0-based)
] {
let ext = $file | path parse | get extension
let name = $file | path parse | get stem
let ofile = get-input $"($name)_($append).($ext)" $output_file
mut audio_idx = $audio_track
mut sub_idx = $subtitle_track
if ($audio_idx | is-empty) or ($sub_idx | is-empty) {
let info = media video-info $file
if ($audio_idx | is-empty) { $audio_idx = resolve-audio-track $info null }
if ($sub_idx | is-empty) { $sub_idx = resolve-subtitle-track $info null }
}
let args = build-cut-args $file $SEGSTART $SEGEND $ofile $reencode $audio_idx $sub_idx
let fallback_args = build-cut-args $file $SEGSTART $SEGEND $ofile $reencode null null
try {
echo-g "trying myffmpeg..."
try {
my-ffmpeg ...$args
} catch {
print (echo-y "requested track(s) not available; falling back to video-only")
my-ffmpeg ...$fallback_args
}
} catch {
echo-r "trying ffmpeg..."
try {
ffmpeg ...$args
} catch {
print (echo-y "requested track(s) not available; falling back to video-only")
ffmpeg ...$fallback_args
}
}
if $notify {"summary finished!" | tasker send-notification}
}
#build ffmpeg argument list for a cut with selected streams
def build-cut-args [
file: string
start: string
end: string
ofile: string
reencode: bool
audio_idx: any
sub_idx: any
] {
mut args = ["-i", $file, "-ss", $start, "-to", $end]
$args = ($args | append ["-map", "0:0"])
if ($audio_idx | is-not-empty) {
$args = ($args | append ["-map", $"0:($audio_idx)"])
}
if ($sub_idx | is-not-empty) {
$args = ($args | append ["-map", $"0:($sub_idx)"])
}
if not $reencode {
$args = ($args | append ["-c:v", "copy"])
if ($audio_idx | is-not-empty) { $args = ($args | append ["-c:a", "copy"]) }
if ($sub_idx | is-not-empty) { $args = ($args | append ["-c:s", "copy"]) }
}
$args | append ["-y", $ofile]
}
#split video file
export def "media split-video" [
file #video file name
--number_segments(-n):int #number of pieces to generate (takes precedence over -d)
--duration(-d):duration #duration of each segment except probably the last one
--delta:duration = 10sec #duration of overlaping beetween segments
--notify(-n) #notify to android via join/tasker
--audio-track: int #audio stream index to include (0-based)
--subtitle-track: int #subtitle stream index to include (0-based)
] {
let info = media video-info $file
let audio_idx = resolve-audio-track $info $audio_track
let sub_idx = resolve-subtitle-track $info $subtitle_track
let full_length = $info
| get format
| get duration
def format-hhmmss [dur?: duration] {
let dur_val = if ($dur | is-empty) { $in } else { $dur }
let total_secs = ($dur_val / 1sec | math floor | into int)
let hours = ($total_secs / 3600 | math floor | into int)
let mins = (($total_secs mod 3600) / 60 | math floor | into int)
let secs = ($total_secs mod 60 | into int)
$"($hours | fill -a right -c '0' -w 2):($mins | fill -a right -c '0' -w 2):($secs | fill -a right -c '0' -w 2)"
}
let full_secs = ($full_length + "sec") | into duration
let full_hhmmss = $full_secs | format-hhmmss
let n_segments = if not ($number_segments | is-empty) {
$number_segments
} else {
$full_secs / $duration + 1 | into int
}
let seg_duration = $full_secs / $n_segments
let seg_end = $seg_duration
for $it in 1..($n_segments - 1) {
let segment_start = (($it - 1) * $seg_duration) | format-hhmmss
let segment_end = ($seg_end + ($it - 1) * $seg_duration + $delta) | format-hhmmss
print (echo-g $"generating part ($it): ($segment_start) - ($segment_end)...")
media cut-video $file $segment_start $segment_end -a ($it | into string) --audio-track $audio_idx --subtitle-track $sub_idx
}
let segment_start = (($n_segments - 1) * $seg_duration) | format-hhmmss
print (echo-g $"generating part ($n_segments): ($segment_start) - ($full_hhmmss)...")
media cut-video $file $segment_start $full_hhmmss -a ($n_segments | into string) --audio-track $audio_idx --subtitle-track $sub_idx
if $notify {"video split finished!" | tasker send-notification}
}
#convert media files recursively to specified format
#
#Examples (make sure there are only compatible files in all subdirectories)
#media-to mp4 (avi/mkv to mp4)
#media-to mp4 -v libx265 (avi/mkv to mp4)
#media-to mp4 -c (avi to mp4)
#media-to aac (audio files to aac)
#media-to mp3 (audio files to mp3)
export def "media to" [
to:string #destination format (aac, mp3 or mp4)
--copy(-c) #copy video codec and audio to mp3 (for mp4 only)
--mkv(-m) #include mkv files (for mp4 only)
--file(-f):string #specify unique file to convert
--vcodec(-v):string = "libx264" #video codec (for single file only)
--notify(-n) #notify to android via join/tasker
] {
if ($file | is-empty) {
#to aac or mp3
if $to like "aac" or $to like "mp3" {
let n_files = bash -c $'find . -type f -not -name "*.part" -not -name "*.srt" -not -name "*.mkv" -not -name "*.mp4" -not -name "*.txt" -not -name "*.url" -not -name "*.jpg" -not -name "*.png" -not -name "*.3gp" -not -name "*.($to)"'
| lines
| length
print (echo-g $"($n_files) audio files found...")
if $n_files > 0 {
bash -c $'find . -type f -not -name "*.part" -not -name "*.srt" -not -name "*.mkv" -not -name "*.mp4" -not -name "*.txt" -not -name "*.url" -not -name "*.jpg" -not -name "*.png" -not -name "*.3gp" -not -name "*.($to)" -print0 | parallel -0 --eta ffmpeg -n -loglevel 0 -i {} -c:a ($to) -b:a 64k {.}.($to)'
let aacs = ls **/*
| insert "ext" {||
$in.name | path parse | get extension
}
| where ext like $to
| length
if $n_files == $aacs {
print (echo-g $"audio conversion to ($to) done")
} else {
return-error $"audio conversion to ($to) done, but something might be wrong"
}
}
#to mp4
} else if $to like "mp4" {
let n_files = ls **/*
| insert "ext" {|f|
$f.name | path parse | get extension
}
| where ext like "avi|webm"
| length
print (echo-g $"($n_files) avi/webm files found...")
if $n_files > 0 {
if $copy {
bash -c 'find . -type f \( -name "*.avi" -o -name "*.webm" \) -print0 | parallel -0 --eta ffmpeg -n -loglevel 0 -i {} -c:v copy -c:a mp3 {.}.mp4'
} else {
bash -c 'find . -type f \( -name "*.avi" -o -name "*.webm" \) -print0 | parallel -0 --eta ffmpeg -n -loglevel 0 -i {} -c:v libx264 -c:a aac {.}.mp4'
}
let aacs = ls **/*
| insert "ext" {||
$in.name | path parse | get extension
}
| where ext like "mp4"
| length
if $n_files == $aacs {
print (echo-g $"avi video conversion to mp4 done")
} else {
return-error "video conversion to mp4 done, but something might be wrong"
}
}
if $mkv {
let n_files = ls **/*
| insert "ext" {|f|
$f.name | path parse | get extension
}
| where ext like "mkv"
| length
print (echo-g $"($n_files) mkv files found...")
if $n_files > 0 {
if $copy {
bash -c 'find . -type f -name "*.mkv" -print0 | parallel -0 --eta ffmpeg -n -loglevel 0 -i {} -c:v copy -c:a mp3 -c:s mov_text {.}.mp4'
} else {
bash -c 'find . -type f -name "*.mkv" -print0 | parallel -0 --eta ffmpeg -n -loglevel 0 -i {} -c:v libx264 -c:a aac -c:s mov_text {.}.mp4'
}
let aacs = ls **/*
| insert "ext" {||
$in.name | path parse | get extension
}
| where ext like "mp4"
| length
if $n_files == $aacs {
print (echo-g $"mkv video conversion to mp4 done")
} else {
return-error "video conversion to mp4 done, but something might be wrong"
}
}
}
}
return
}
let filename = $file | path parse | get stem
let ext = $file | path parse | get extension
if $to like "aac" or $to like "mp3" {
ffmpeg -n -loglevel 48 -i $file -c:a $to -b:a 64k $"($filename).($to)"
} else if $to like "mp4" {
if $copy {
if $ext like "mkv" {
ffmpeg -n -loglevel 48 -i $file -c:v copy -c:a mp3 -c:s mov_text $"($filename).($to)"
} else {
ffmpeg -n -loglevel 48 -i $file -c:v copy -c:a mp3 $"($filename).($to)"
}
} else {
if $ext like "mkv" {
ffmpeg -n -loglevel 48 -i $file -c:v $vcodec -c:a aac -c:s mov_text $"($filename).($to)"
} else {
ffmpeg -n -loglevel 48 -i $file -c:v $vcodec -c:a aac $"($filename).($to)"
}
}
}
if $notify {"conversion finished!" | tasker send-notification}
}
#cut segment from audio file
#
#Example: cut 10s starting at second 60
#cut_audio input.ext output.ext 60 10
export def "media cut-audio" [
infile:string #input audio file
outfile:string #output audio file
start:int #start of the piece to extract (s)
duration:int #duration of the piece to extract (s)
--notify(-n) #notify to android via join/tasker
] {
try {
my-ffmpeg -ss $start -i $"($infile)" -t $duration -c copy $"($outfile)"
} catch {
ffmpeg -ss $start -i $"($infile)" -t $duration -c copy $"($outfile)"
}
if $notify {"cut finished!" | tasker send-notification}
}
#merge subs to mkv video
export def "media merge-subs" [
filename #name (without extencion) of both subtitle and mkv file
--notify(-n) #notify to android via join/tasker
] {
mkvmerge -o myoutput.mkv $"($filename).mkv" --language "0:spa" --track-name $"0:($filename)" $"($filename).srt"
mv myoutput.mkv $"($filename).mkv"
rm $"($filename).srt" | ignore
if $notify {"subs merge finished!" | tasker send-notification}
}
#merge videos
#
#To get a functional output, all audio sample rate must be the same
#check with video-info video_file
#
#The file with the list must have the following structure:
#
#~~~
#file '/path/to/file/file1'"
#.
#.
#.
#file '/path/to/file/fileN'"
#~~~
export def "media merge-videos" [
list #text file with list of videos to merge
output #output file
--notify(-n) #notify to android via join/tasker
] {
print (echo-g "merging videos...")
my-ffmpeg -f concat -safe 0 -i $"($list)" -c copy $"($output)"
print (echo-g "done!")
notify-send "video merge done!"
if $notify {"video merge finished!" | tasker send-notification}
}
#auto merge all videos in dir
#
#To get a functional output, all audio sample rate must be the same
#check with video-info video_file
export def "media merge-videos-auto" [
ext #unique extension of all videos to merge
output #output file
--notify(-n) #notify to android via join/tasker
] {
let list = $env.PWD | path join "list.txt"
if not ($list | path exists) {
touch $"($list)"
} else {
"" | save -f $list
}
ls ($"*.($ext)" | into glob)
| where type == file
| get name
| each {|file|
("file \'" + ($env.PWD | path join $file) + "\'\n") | save --append list.txt
}
print (echo-g "merging videos...")
my-ffmpeg -f concat -safe 0 -i list.txt -c copy $"($output).($ext)"
print (echo-g "done!")
notify-send "video merge done!"
if $notify {"video merge finished!" | tasker send-notification}
}
const vcodecs = ["libx264", "libx265"]
#reduce size of video files recursively, to mp4 x265
#
#Considers only mp4 and webm files
#
#media compress-video
#media compress-video -m
#media compress-video -l 1
#media compress-video -c 20
#media compress-video -v libx264
#
#After ensuring that the conversions are ok, run
#
#media delete-non-compressed
#
#to delete original files
export def "media compress-video" [
--file(-f):string #single file
--level(-l):int #level of recursion (-maxdepth in ^find, minimun = 1).
--crf(-c):int = 18 #compression rate, range 0-51, sane range 18-28.
--vcodec(-v):string@$vcodecs = "libx265" #video codec: libx264 | libx265.
--append(-a):string = "com" # what to append to compressed file names
--jobs(-j):int = 2 #number of jobs to run in parallel
--mkv(-m) #include mkv files
--notify(-n) #notify to android via join/tasker
] {
if ($file | is-empty) {
let n_files = if ($level | is-empty) {
if not $mkv {
bash -c $"find . -type f (char -i 92)(char lparen) -iname '*.mp4' -o -iname '*.webm' (char -i 92)(char rparen) -not -name '*($append)*'"
} else {
bash -c $"find . -type f (char -i 92)(char lparen) -iname '*.mp4' -o -iname '*.webm' -o -iname '*.mkv' (char -i 92)(char rparen) -not -name '*($append)*'"
}
} else {
if not $mkv {
bash -c $"find . -maxdepth ($level) -type f (char -i 92)(char lparen) -iname '*.mp4' -o -iname '*.webm' (char -i 92)(char rparen) -not -name '*($append)*'"
} else {
bash -c $"find . -maxdepth ($level) -type f (char -i 92)(char lparen) -iname '*.mp4' -o -iname '*.webm' -o -iname '*.mkv' (char -i 92)(char rparen) -not -name '*($append)*'"
}
}
| lines
| length
if $n_files == 0 {return-error "no files found..."}
print (echo-g $"($n_files) video files found...")
if ($level | is-empty) {
if not $mkv {
try {
print (echo-g "trying myffmpeg...")
bash -c $"find . -type f (char -i 92)(char lparen) -iname '*.mp4' -o -iname '*.webm' (char -i 92)(char rparen) -not -name '*($append)*' -print0 | parallel -0 --eta --jobs ($jobs) myffmpeg -n -loglevel 0 -i {} -map 0:v -map 0:a -map 0:s? -vcodec ($vcodec) -crf ($crf) -c:a aac {.}_($append).mp4"
} catch {
print (echo-r "failed myffmpeg...")
print (echo-g "trying ffmpeg...")
bash -c $"find . -type f (char -i 92)(char lparen) -iname '*.mp4' -o -iname '*.webm' (char -i 92)(char rparen) -not -name '*($append)*' -print0 | parallel -0 --eta --jobs ($jobs) ffmpeg -n -loglevel 0 -i {} -map 0:v -map 0:a -map 0:s? -vcodec ($vcodec) -crf ($crf) -c:a aac {.}_($append).mp4"
}
} else {
try {
print (echo-g "trying myffmpeg...")
bash -c $"find . -type f (char -i 92)(char lparen) -iname '*.mp4' -o -iname '*.webm' -o -iname '*.mkv' (char -i 92)(char rparen) -not -name '*($append)*' -print0 | parallel -0 --eta --jobs ($jobs) myffmpeg -n -loglevel 0 -i {} -map 0:v -map 0:a -map 0:s? -vcodec ($vcodec) -crf ($crf) -c:a aac -c:s mov_text {.}_($append).mp4"
} catch {
print (echo-r "failed myffmpeg...")
print (echo-g "trying ffmpeg...")
bash -c $"find . -type f (char -i 92)(char lparen) -iname '*.mp4' -o -iname '*.webm' -o -iname '*.mkv' (char -i 92)(char rparen) -not -name '*($append)*' -print0 | parallel -0 --eta --jobs ($jobs) ffmpeg -n -loglevel 0 -i {} -map 0:v -map 0:a -map 0:s? -vcodec ($vcodec) -crf ($crf) -c:a aac -c:s mov_text {.}_($append).mp4"
}
}
} else {
if not $mkv {
try {
print (echo-g "trying myffmpeg...")
bash -c $"find . -maxdepth ($level) -type f (char -i 92)(char lparen) -iname '*.mp4' -o -iname '*.webm' (char -i 92)(char rparen) -not -name '*($append)*' -print0 | parallel -0 --eta --jobs ($jobs) myffmpeg -n -loglevel 0 -i {} -map 0:v -map 0:a -map 0:s? -vcodec ($vcodec) -crf ($crf) -c:a aac {.}_($append).mp4"
} catch {
print (echo-r "failed myffmpeg...")
print (echo-g "trying ffmpeg...")
bash -c $"find . -maxdepth ($level) -type f (char -i 92)(char lparen) -iname '*.mp4' -o -iname '*.webm' (char -i 92)(char rparen) -not -name '*($append)*' -print0 | parallel -0 --eta --jobs ($jobs) ffmpeg -n -loglevel 0 -i {} -map 0:v -map 0:a -map 0:s? -vcodec ($vcodec) -crf ($crf) -c:a aac {.}_($append).mp4"
}
} else {
try {
print (echo-g "trying myffmpeg...")
bash -c $"find . -maxdepth ($level) -type f (char -i 92)(char lparen) -iname '*.mp4' -o -iname '*.webm' -o -iname '*.mkv' (char -i 92)(char rparen) -not -name '*($append)*' -print0 | parallel -0 --eta --jobs ($jobs) myffmpeg -n -loglevel 0 -i {} -map 0:v -map 0:a -map 0:s? -vcodec ($vcodec) -crf ($crf) -c:a aac -c:s mov_text {.}_($append).mp4"
} catch {
print (echo-r "failed myffmpeg...")
print (echo-g "trying ffmpeg...")
bash -c $"find . -maxdepth ($level) -type f (char -i 92)(char lparen) -iname '*.mp4' -o -iname '*.webm' -o -iname '*.mkv' (char -i 92)(char rparen) -not -name '*($append)*' -print0 | parallel -0 --eta --jobs ($jobs) ffmpeg -n -loglevel 0 -i {} -map 0:v -map 0:a -map 0:s? -vcodec ($vcodec) -crf ($crf) -c:a aac -c:s mov_text {.}_($append).mp4"