-
Notifications
You must be signed in to change notification settings - Fork 0
/
hevcmeup2
executable file
·662 lines (624 loc) · 25.6 KB
/
hevcmeup2
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
#!/usr/bin/env bash
usage() {
cat - <<EOF
Usage: ${0##*/} -i <INPUT FILE> -o <OUTPUT FILE>
-h|--help: show this help message
-i|--input: file name for input
-o|--output: file name for output
--start: start time for encode (default: unset)
--duration: duration of encode (default: unset)
--crf: crf value (default varies with input res, 2160:16, 1080:18, 720: 22, 480: 26)
--melton: use Don Melton's trickeration for bitrate control
--mbitrate: if using --melton, use this bitrate cap
--preset: x265 preset value (default: medium)
--tune: x265 tune value (default: unset)
--params: x265 parameters string (default: unset)
--crop: enable crop detection (default: no)
--oprofile: output profile [1080, 720, 480]
--vf: custom videofilter input
--sdr: best effort 2020->709 color fix
--yadif: deinterlace with yadif
--yadifmode: set yadif to specific mode (default: 1, send frame per field)
--nnedi: use the power of ai to deinterlace
--ivtc: Perform detelecine via specified method [ivtc (default), fieldmatch]
--bitdepth: Bitdepth for pixel format (8, 10 or 12, default: 10)
--audio: transcode lossless audio tracks to selected codec [flac, opus, aac]
--square: convert anamorphic to square pixels which make sense
--forcelossy: transcode all audio tracks to selected codec
--copyhdr: copy HDR metadata (probably doesn't work, who knows, fuck ffmpeg forever)
--dovi-bl: attempt to set parameters that produce Dolby Vision-compatible base-layer output
--dovi-el: attempt to set parameters that produce Dolby Vision-compatible enhancement-layer output
--fps: for inputs that do not have framerate metadata attach, provide it with this
--debug: output commands to be run, run nothing
EOF
}
while [ $# -gt 0 ]; do
OPT="$1"
case "${OPT}" in
-i|--input)
shift
INPUT="${1}"
shift;;
-o|--output)
shift
OUTPUT="${1}"
shift;;
--start)
shift
START="${1}"
shift;;
--duration)
shift
DURATION="${1}"
shift;;
--crf)
shift
CRF="${1}"
shift;;
--melton)
MELTON=1
shift;;
--mbitrate)
shift
MELTON_BITRATE="${1}"
shift;;
--preset)
shift
PRESET="${1}"
shift;;
--tune)
shift
TUNE="${1}"
shift;;
--params)
shift
EXTRA_PARAMS="${1}"
shift;;
--crop)
CROP=1
shift;;
--debug)
DEBUG=1
shift;;
--oprofile)
shift
OPROFILE="${1}"
shift;;
--vf)
shift
VIDEOFILTER="${1}"
shift;;
--sdr)
SDR=1
shift;;
--yadif)
YADIF=1
shift;;
--yadifmode)
shift
YADIFMODE="${1}"
shift;;
--nnedi)
NNEDI=1
shift;;
--ivtc)
if [ "${2-hate}" == "hate" ] || [[ "${2}" =~ ^-- ]]; then
IVTC="ivtc"
else
shift
IVTC="${1}"
fi
shift;;
--audio)
shift
AUDIO="${1}"
shift;;
--forcelossy)
FORCE_LOSSY=1
shift;;
--bitdepth)
shift
BITDEPTH="${1}"
shift;;
--square)
SQUARE=1
shift;;
--dovi-bl)
DOVIBL=1
shift;;
--dovi-el)
DOVIEL=1
shift;;
--fps)
shift
FPS="${1}"
shift;;
-h|--help)
usage
exit;;
*)
echo "$0: invalid option ${1}"
echo "$0 -h for usage options"
usage
exit 1;;
esac
done
# Check for tool dependencies
SELF_FULLPATH=`realpath $0`
SELF_DIR=`dirname $SELF_FULLPATH`
TOOLS=(ffmpeg ffprobe mkvpropedit mkvmerge mediainfo jq bc tr sed grep awk x265 base64)
if [ ! -r $SELF_DIR/toolchecker ]; then
echo "## toolchecker not found."
exit 1
else
. $SELF_DIR/toolchecker
fi
if [ -z "$INPUT" ] || [ -z "$OUTPUT" ]; then
echo "## Insufficient options provided."
echo "## Must supply input (-i/--input) and output (-o/--output) at minimum"
usage
exit 1
fi
if [ ! -s "$INPUT" ] && [[ "$INPUT" != *"%"* ]]; then
echo "## Error reading input file: $INPUT"
exit 1
elif [ -f "$OUTPUT" ]; then
echo "## Output file exists."
exit 1
fi
INPUT_WIDTH=`$MEDIAINFO --Output=JSON "${INPUT}" | $JQ -r '.media.track[] | select(."@type" == "Video" ).Width'`
INPUT_HEIGHT=`$MEDIAINFO --Output=JSON "${INPUT}" | $JQ -r '.media.track[] | select(."@type" == "Video" ).Height'`
PRESET=${PRESET:="medium"}
if [[ "${PRESET}" != @(ultrafast|superfast|veryfast|faster|fast|medium|slow|slower|veryslow|placebo) ]]; then
echo "## Invalid preset \"${PRESET}\" for x265."
exit 1
elif [[ "${PRESET}" == "placebo" ]]; then
echo "## You may not use placebo. It's a placebo. This was a test and you failed."
exit 2
fi
if [ -z "$CRF" -a -z "$OPROFILE" ]; then
if [ "$INPUT_WIDTH" -gt 1920 ]; then
CRF=16
elif [ "$INPUT_WIDTH" -gt 1280 ]; then
CRF=18
elif [ "$INPUT_WIDTH" -gt 854 ]; then
CRF=22
else
CRF=26
fi
fi
if [ $SQUARE ]; then
VF="scale=iw*sar:ih,setsar=1:1"
fi
if [ ! -z "$OPROFILE" ]; then
case "${OPROFILE}" in
1080)
VF="${VF:+${VF},}scale=1920:-1"
OP_CRF=18;;
900)
VF="${VF:+${VF},}scale=1600:-1"
OP_CRF=19;;
810)
VF="${VF:+${VF},}scale=1440:-1"
OP_CRF=20;;
720)
VF="${VF:+${VF},}scale=1280:-1"
OP_CRF=22;;
480)
VF="${VF:+${VF},}scale=720:-1"
OP_CRF=26;;
1440)
VF="${VF:+${VF},}scale=-1:1080,crop=1440:1080:240:0"
OP_CRF=18;;
960)
VF="${VF:+${VF},}scale=-1:720,crop=960:720:160:0"
OP_CRF=22;;
*)
echo "## Not a recognized output profile name."
exit 1;;
esac
if [ -z "$CRF" ]; then
CRF=$OP_CRF
fi
fi
BITDEPTH=${BITDEPTH:=10}
case "${BITDEPTH}" in
12)
PIXEL_FORMAT="yuv420p12le";;
10)
PIXEL_FORMAT="yuv420p10le";;
8)
PIXEL_FORMAT="yuv420p";;
*)
echo "## Bitdepth ${BITDEPTH} is invalid."
exit 1;;
esac
VIDEO_TRACKS=`$MEDIAINFO --output=JSON "$INPUT" | $JQ -r '.media.track[] | select (."@type"=="Video") | @base64'`
IFS=$'\n'
for TRACK in ${VIDEO_TRACKS}; do
TRACK_HDR_FORMAT=`echo "${TRACK}" | ${BASE64} --decode | $JQ -r '.HDR_Format'`
if [[ "$TRACK_HDR_FORMAT" != "null" ]]; then
[ $DEBUG ] && echo "HDR format video detected: $TRACK_HDR_FORMAT"
[[ "$TRACK_HDR_FORMAT" =~ Dolby ]] && echo "Dolby Vision detected. Note that preserving Dolby Vision is beyond the scope of this script."
if [ $SDR ]; then
NPL=100
METHOD="mobius"
DESAT=4
RANGE="limited"
TONEMAP="zscale=t=linear:npl=${NPL},format=gbrpf32le,tonemap=${METHOD}:param=0.4:desat=${DESAT},zscale=p=bt709:t=bt709:m=bt709:r=${RANGE}"
VF="${TONEMAP}${VF:+,${VF}}"
else
COPY_HDR=1
fi
fi
done
IFS="$O_IFS"
if [ $DOVIBL ] && [ $DOVIEL ]; then
echo "Cannot be both a BL and an EL, ass."
exit 1
elif [ $DOVIBL ]; then
if [ $CROP ]; then
echo "Cannot crop Dolby Vision streams, disabling crop"
unset CROP
fi
## implies copyhdr so we're gonna force it on here just in case we missed it
COPY_HDR=1
## Probably working with elementary streams in this mode, so we need to set the framerate explicitly
[ $FPS ] || FPS=$($MEDIAINFO ${INPUT} --output=JSON | jq -r '.media.track[] | select(."@type" == "Video" ).FrameRate')
if [ "${FPS}" == "null" ]; then
echo "framerate not provided and could not be determined from input elementary stream."
exit 1
fi
paramsmunge "level-idc=5.1:high-tier=1:hrd=1:hrd-concat=1:info=1:fps=${FPS}:vbv-bufsize=85000:vbv-maxrate=85000:uhd-bd=1"
elif [ $DOVIEL ]; then
if [ $CROP ]; then
echo "Cannot crop Dolby Vision streams, disabling crop"
unset CROP
fi
## implies copyhdr so we're gonna force it on here just in case
COPY_HDR=1
## Probably working with elementary streams in this mode, so we need to set the framerate explicitly
[ $FPS ] || FPS=$($MEDIAINFO ${INPUT} --output=JSON | jq -r '.media.track[] | select(."@type" == "Video" ).FrameRate')
if [ "${FPS}" == "null" ]; then
echo "framerate not provided and could not be determined from input elementary stream."
exit 1
fi
paramsmunge "level-idc=5.1:high-tier=1:hrd=1:hrd-concat=1:info=1:fps=${FPS}:vbv-bufsize=10000:vbv-maxrate=10000:uhd-bd=1"
fi
if [ $CROP ]; then
echo "## Finding crop..."
SEGMENTS=10
CFOUTPUT=$($CROPFINDER -i "$INPUT" -s $SEGMENTS -d)
[ $DEBUG ] && echo "$CFOUTPUT"
CROP=$(echo "$CFOUTPUT" | tail -n1)
IFS=':' read width height left top <<< "$(echo "$CROP" | ${AWK} -F= '{print $2}')"
if [ $INPUT_WIDTH -eq $width ] && [ $INPUT_HEIGHT -eq $height ]; then
echo "## No crop detected"
else
if [ $height -eq 1072 ]; then
[ $DEBUG ] && echo "The dumb eight pixel height crop, ignoring"
height=1080
top=0
CROP="crop=$width:1080:$left:0"
fi
if [ $width -eq 1904 ] && [ $INPUT_WIDTH -ne 1904 ]; then
[ $DEBUG ] && echo "The dumb sixteen pixel width crop, ignoring"
width=1920
left=0
CROP="crop=$width:$height:$left:$top"
fi
if [ $width -ne $INPUT_WIDTH ] && [ $height -ne $INPUT_HEIGHT ]; then
[ $DEBUG ] && echo "Crop detected in both dimensions, that's not great"
if [ $left -gt $top ]; then
[ $DEBUG ] && echo "Maintaining input height ($INPUT_HEIGHT)"
if [ $(( $height + 2 * $top )) -ne $INPUT_HEIGHT ]; then
GUTTERS=$(( ($INPUT_HEIGHT - $height) / 2 ))
PAD="pad=$width:$INPUT_HEIGHT:0:$GUTTERS"
CROP="$CROP,$PAD"
[ $DEBUG ] && echo "Evenly padding crop height ($height) back to input height ($INPUT_HEIGHT) with gutters ($GUTTERS)"
else
width=$INPUT_WIDTH
CROP="crop=$width:$INPUT_HEIGHT:$left:0"
[ $DEBUG ] && echo "Using original input height ($INPUT_HEIGHT)"
fi
elif [ $top -gt $left ]; then
[ $DEBUG ] && echo "Maintaining input width ($INPUT_WIDTH)"
if [ $(( $width + 2 * $left )) -ne $INPUT_WIDTH ]; then
GUTTERS=$(( ($INPUT_WIDTH - $width) / 2 ))
PAD="pad=$INPUT_WIDTH:$height:$GUTTERS:$top"
CROP="$CROP,$PAD"
[ $DEBUG ] && echo "Evenly padding crop width ($width) back to input width ($INPUT_WIDTH) with gutters ($GUTTERS)"
else
width=$INPUT_WIDTH
CROP="crop=$INPUT_WIDTH:$height:0:$top"
[ $DEBUG ] && echo "Using original input width ($INPUT_WIDTH)"
fi
else
echo "## Ran out of cropping ideas. Look at this crop with your eyes, type it in with your hands."
echo "## This is what cropfinder delivered: ${CROP}"
exit 1
fi
fi
if [ $INPUT_WIDTH -eq $width ] && [ $INPUT_HEIGHT -eq $height ]; then
echo "## After much consideration, no crop required"
else
echo "## ${CROP}"
VF="${CROP}${VF:+,${VF}}"
fi
fi
fi
if [ $AUDIO ]; then
NL=$'\n'
AUDIO_TRACK_META=""
TRACKS=`$MEDIAINFO --output=JSON "$INPUT" | $JQ -r '.media.track[] | select (."@type"=="Audio") | @base64'`
IFS=$'\n'
for TRACK in ${TRACKS}; do
TRACK_NUMBER=`echo "${TRACK}" | ${BASE64} --decode | $JQ -r '.StreamOrder'`
TRACK_CODEC=`echo "${TRACK}" | ${BASE64} --decode | $JQ -r '.CodecID'`
TRACK_BITRATE=`echo "${TRACK}" | ${BASE64} --decode | $JQ -r '.BitRate'`
TRACK_LAYOUT=`echo "${TRACK}" | ${BASE64} --decode | $JQ -r '.ChannelLayout'`
[ "${TRACK_LAYOUT}" == null ] && TRACK_LAYOUT=`echo "${TRACK}" | ${BASE64} --decode | ${JQ} -r '.ChannelLayout_Original'`
TRACK_CHANNELS=`echo "${TRACK}" | ${BASE64} --decode | $JQ -r '.Channels'`
TRACK_CHANNELS_ORIGINAL=`echo "${TRACK}" | ${BASE64} --decode | ${JQ} -r '.Channels_Original'`
[ "${TRACK_CHANNELS_ORIGINAL}" != null ] && TRACK_CHANNELS=${TRACK_CHANNELS_ORIGINAL}
TRACK_COMPMODE=`echo "${TRACK}" | ${BASE64} --decode | $JQ -r '.Compression_Mode'`
TRACK_FORMAT=`echo "${TRACK}" | ${BASE64} --decode | $JQ -r '.Format'`
TRACK_FORMAT_COMMERCIAL_IFANY=`echo "${TRACK}" | ${BASE64} --decode | $JQ -r '.Format_Commercial_IfAny'`
[[ "$TRACK_FORMAT_COMMERCIAL_IFANY" =~ Atmos|DTS:X ]] && TRACK_OBJFORMAT=1 || TRACK_OBJFORMAT=0
if [ "$TRACK_LAYOUT" = "null" ] && [ "$TRACK_CHANNELS" = "null" ]; then
TRACK_LAYOUT=`echo "${TRACK}" | ${BASE64} --decode | $JQ -r '.ChannelLayout_Original'`
TRACK_CHANNELS=`echo "${TRACK}" | ${BASE64} --decode | $JQ -r '.Channels_Original'`
fi
TRACK_META="${TRACK_NUMBER},${TRACK_CODEC},${TRACK_BITRATE},${TRACK_CHANNELS},${TRACK_LAYOUT},${TRACK_FORMAT},${TRACK_COMPMODE},${TRACK_OBJFORMAT}${NL}"
AUDIO_TRACK_META="${AUDIO_TRACK_META}${TRACK_META}"
done
IFS="$O_IFS"
AUDIO_TRACK_META=`echo "$AUDIO_TRACK_META" | ${SED} 's/^$//g'`
if [ $DEBUG ]; then
echo
echo "## Input Audio Tracks"
echo "------------------"
echo "Track,Codec,BitRate,Channels,Layout,Format,CompMode,ObjFormat${NL}${AUDIO_TRACK_META}" | column -t -s, -o " | "
echo
fi
case "${AUDIO}" in
flac)
while read -r i; do
IFS=, read -r TRACK_NUMBER TRACK_CODEC TRACK_BITRATE TRACK_CHANNELS TRACK_LAYOUT TRACK_FORMAT TRACK_COMPMODE<<< $( echo "$i" )
if [[ $FORCE_LOSSY ]] || [[ "$TRACK_COMPMODE" =~ "Lossless" ]] || [[ "$TRACK_FORMAT" =~ "PCM" ]] && [[ "$TRACK_FORMAT" != "FLAC" ]]; then
FLAC_FLAGS="-c:a:${TRACK_NUMBER} flac $FLAC_FLAGS"
OUTPUT_TRACK_META="${OUTPUT_TRACK_META}${TRACK_NUMBER},flac,${TRACK_BITRATE},${TRACK_LAYOUT},n/a${NL}"
else
FLAC_FLAGS="-c:a:${TRACK_NUMBER} copy $FLAC_FLAGS"
OUTPUT_TRACK_META="${OUTPUT_TRACK_META}${TRACK_NUMBER},copy,${TRACK_BITRATE},${TRACK_LAYOUT},n/a${NL}"
fi
done < <(echo "$AUDIO_TRACK_META")
echo "## Output Audio Tracks"
echo "------------------"
echo "Track,Codec,BitRate,Channels,Layout${NL}${OUTPUT_TRACK_META}" | column -t -s, -o " | "
echo
unset IFS
AUDIO_FLAGS="$AUDIO_FLAGS ${FLAC_FLAGS:0:-1}";;
opus)
while read -r i; do
IFS=, read -r TRACK_NUMBER TRACK_CODEC TRACK_BITRATE TRACK_CHANNELS TRACK_LAYOUT TRACK_FORMAT TRACK_COMPMODE TRACK_OBJFORMAT<<< $( echo "$i" )
TRACK_NUMBER=`echo "$TRACK_NUMBER - 1" | ${BC}`
if ([[ $FORCE_LOSSY ]] || [[ "$TRACK_COMPMODE" =~ "Lossless" ]] || [[ "$TRACK_FORMAT" =~ "PCM" ]]) && [ $TRACK_OBJFORMAT -eq 0 ]; then
BR=$(echo "$TRACK_LAYOUT" | ${SED} -e 's~Rss\|Lss\|Rsr\|Lsr\|Rb\|Lb\|Rs\|Ls\|Rw\|Lw\|LFE~64~g' -e 's~Cb\|C\|Cs\|M\|L\|Lt\|R\|Rt~128~g' | ${TR} -s ' ' '+' | ${BC})
if [ $BR -eq 0 ]; then
case $TRACK_CHANNELS in
8|7) BR=704;;
6|5) BR=576;;
4) BR=512;;
3) BR=384;;
2) BR=256;;
1) BR=128;;
*) BR=576;;
esac
fi
TRACK_BITRATE="${BR}k"
#TRACK_FLAGS="-ab:${TRACK_NUMBER} ${TRACK_BITRATE} -metadata:${TRACK_NUMBER} title=\"Opus from ${TRACK_CODEC}\" "
TRACK_FLAGS="-c:a:${TRACK_NUMBER} libopus -filter:a:${TRACK_NUMBER} aformat=channel_layouts='7.1|5.1|stereo|mono' -b:a:${TRACK_NUMBER} ${TRACK_BITRATE} "
OPUS_FLAGS="${OPUS_FLAGS}${TRACK_FLAGS}"
OUTPUT_TRACK_META="${OUTPUT_TRACK_META}${TRACK_NUMBER},opus,${TRACK_BITRATE},${TRACK_CHANNELS},${TRACK_LAYOUT}${NL}"
else
OPUS_FLAGS="-c:a:${TRACK_NUMBER} copy $OPUS_FLAGS"
OUTPUT_TRACK_META="${OUTPUT_TRACK_META}${TRACK_NUMBER},copy,${TRACK_BITRATE},${TRACK_CHANNELS},${TRACK_LAYOUT}${NL}"
fi
done < <(echo "$AUDIO_TRACK_META")
echo "## Output Audio Tracks"
echo "------------------"
echo "Track,Codec,BitRate,Channels,Layout${NL}${OUTPUT_TRACK_META}" | column -t -s, -o " | "
echo
unset IFS
AUDIO_FLAGS="$AUDIO_FLAGS ${OPUS_FLAGS:0:-1}"
;;
aac)
while read -r i; do
IFS=, read -r TRACK_NUMBER TRACK_CODEC TRACK_BITRATE TRACK_CHANNELS TRACK_LAYOUT TRACK_FORMAT TRACK_COMPMODE<<< $( echo "$i" )
TRACK_NUMBER=`echo "$TRACK_NUMBER - 1" | ${BC}`
if [[ $FORCE_LOSSY ]] || [[ "$TRACK_COMPMODE" =~ "Lossless" ]] || [[ "$TRACK_FORMAT" =~ "PCM" ]]; then
BR=$(echo "$TRACK_LAYOUT" | ${SED} -e 's~Rss\|Lss\|Lsr\|Rsr\|Rb\|Lb\|Rs\|Ls\|LFE~64~g' -e 's~Cb\|C\|L\|R~128~g' | ${TR} -s ' ' '+' | ${BC})
if [ $BR -eq 0 ]; then
case $TRACK_CHANNELS in
8|7) BR=704;;
6|5) BR=576;;
4) BR=512;;
3) BR=384;;
2) BR=256;;
1) BR=128;;
*) BR=576;;
esac
fi
TRACK_BITRATE="${BR}k"
#TRACK_FLAGS="-ab:${TRACK_NUMBER} ${TRACK_BITRATE} -metadata:${TRACK_NUMBER} title=\"Opus from ${TRACK_CODEC}\" "
TRACK_FLAGS="-c:a:${TRACK_NUMBER} libfdk_aac -b:a:${TRACK_NUMBER} ${TRACK_BITRATE} "
AAC_FLAGS="${AAC_FLAGS}${TRACK_FLAGS}"
OUTPUT_TRACK_META="${OUTPUT_TRACK_META}${TRACK_NUMBER},aac,${TRACK_BITRATE},${TRACK_CHANNELS},${TRACK_LAYOUT}${NL}"
else
AAC_FLAGS="-c:a:${TRACK_NUMBER} copy $AAC_FLAGS"
OUTPUT_TRACK_META="${OUTPUT_TRACK_META}${TRACK_NUMBER},copy,${TRACK_BITRATE},${TRACK_CHANNELS},${TRACK_LAYOUT}${NL}"
fi
done < <(echo "$AUDIO_TRACK_META")
echo "## Output Audio Tracks"
echo "------------------"
echo "Track,Codec,BitRate,Channels,Layout${NL}${OUTPUT_TRACK_META}" | column -t -s, -o " | "
echo
unset IFS
AUDIO_FLAGS="$AUDIO_FLAGS ${AAC_FLAGS:0:-1}"
;;
*)
echo "Unknown codec: ${AUDIO}"
exit 1;;
esac
else
AUDIO_FLAGS="-c:a copy"
fi
if [ $MELTON ]; then
echo "I'm disabling this for now cause I never use it and I don't want to account for it anymore. Sorry."
#if [ ! -z "${MELTON_BITRATE}" ]; then
# CRFMAX=25
# VBVMAX=${MELTON_BITRATE}
# VBVBUF=$(expr $MELTON_BITRATE \* 2)
# QPMAX=34
#elif [ "$INPUT_WIDTH" -gt 1280 ]; then
# CRFMAX=25
# VBVMAX=24000
# VBVBUF=48000
# QPMAX=34
#elif [ "$INPUT_WIDTH" -gt 854 ]; then
# CRFMAX=29
# VBVMAX=3000
# VBVBUF=6000
# QPMAX=34
#else
# CRFMAX=33
# VBVMAX=1500
# VBVBUF=3000
# QPMAX=34
#fi
#PARAMS="crf=1:vbv-maxrate=${VBVMAX}:vbv-bufsize=${VBVBUF}:crf-max=${CRFMAX}:qpmax=${QPMAX}:log-level=error"
else
paramsmunge "crf=${CRF}"
fi
if [ $COPY_HDR ]; then
## REFERENCES
# https://codecalamity.com/encoding-uhd-4k-hdr10-videos-with-ffmpeg/
## THIS IS A DANK ASS TRICK THAT MAKES VARIABLES OUT OF ALL THE VIDEO METADATA
eval "$($FFPROBE -hide_banner -loglevel warning -select_streams v -print_format json -show_frames -read_intervals "%+#1" -show_entries "frame=hdr_format,color_range,color_space,color_primaries,color_transfer,side_data_list,pix_fmt" -i "${INPUT}" | ${GREP} -v -e frames -e '{' -e '\[' -e '}' -e '\]' -e 'side' -e 'application version' | ${SED} -e 's/^\ *//g' -e 's/^"//g' -e 's/\":/:/g' -e 's/:\ /=/g' -e 's/,//g' -e 's/^/video_/g' -e 's/^.*=/\U&/g')"
paramsmunge "hdr-opt=1:repeat-headers=1:colorprim=${VIDEO_COLOR_PRIMARIES}:transfer=${VIDEO_COLOR_TRANSFER}:colormatrix=${VIDEO_COLOR_SPACE}:master-display=G(${VIDEO_GREEN_X%/*},${VIDEO_GREEN_Y%/*})B(${VIDEO_BLUE_X%/*},${VIDEO_BLUE_Y%/*})R(${VIDEO_RED_X%/*},${VIDEO_RED_Y%/*})WP(${VIDEO_WHITE_POINT_X%/*},${VIDEO_WHITE_POINT_Y%/*})L(${VIDEO_MAX_LUMINANCE%/*},${VIDEO_MIN_LUMINANCE%/*}):max-cll=${VIDEO_MAX_CONTENT},${VIDEO_MAX_AVERAGE}"
## I'm sneaky forcing the fast analysis preset cause the only HDR I encode is 4k and 4k is so painfully slow already that I'll take the half-point drop in VMAF to shave 40% off the encoding time
PRESET="fast"
fi
if [ ! -z "$EXTRA_PARAMS" ]; then
paramsmunge "${EXTRA_PARAMS}" after
fi
MAPS="-map 0 -map -0:d"
VIDEO="-c:V libx265 -pix_fmt $PIXEL_FORMAT -preset $PRESET -x265-params $PARAMS"
TRAILERS="-c:s copy -max_muxing_queue_size 9999"
if [ ! -z "$TUNE" ]; then
VIDEO="$VIDEO -tune:V $TUNE"
fi
ENCODE_FLAGS="${MAPS} ${VIDEO} ${AUDIO_FLAGS} ${TRAILERS}"
if [ ! -z "$DURATION" ]; then
ENCODE_FLAGS="$ENCODE_FLAGS -t $DURATION"
fi
if [ ! -z "$START" ]; then
FFMPEG="$FFMPEG -ss $START"
fi
if [ -n "${DEINT}" ] && [ -n "${IVTC}" ]; then
echo "## Don't deinterlace and also detelecine, that's bad."
exit 1
fi
## DEINTERLACING SHENANIGANS
SCANTYPE=`$MEDIAINFO "$INPUT" | ${GREP} "Scan type " | ${AWK} -F:\ '{print $2}'`
SCANORDER=`$MEDIAINFO "$INPUT" | ${GREP} "Scan order " | ${AWK} -F:\ '{print $2}'`
DEINT_SUM=$(( ${YADIF:-0} + ${NNEDI:-0} ))
if [ $DEINT_SUM -gt 1 ]; then
echo "Pick one deinterlace option, not more than one."
exit 1
elif [ $(( ${DEINT_SUM:-0} + ${IVTC:-0} + ${IVTC_FIELDMATCH:-0} )) -gt 1 ]; then
echo "Don't deinterlace and also detelecine, that's bad."
exit 1
elif [ $YADIFMODE ] && [ -z "$YADIF" ]; then
echo "Don't set yadifmode if you're not using yadif."
exit 1
elif [ $YADIF ]; then
YADIFMODE=${YADIFMODE:=1}
if [ "$SCANTYPE" = "Interlaced" ] || [ "$SCANTYPE" = "MBAFF" ] || [ "$SCANTYPE" = "PAFF" ]; then
if [ "$SCANORDER" = "Top Field First" ]; then
VF="yadif=${YADIFMODE}:0:0${VF:+,${VF}}"
else
VF="yadif=${YADIFMODE}:1:0${VF:+,${VF}}"
fi
else
if [ $DEBUG ]; then
echo "Input video is not interlaced, skipping deint"
fi
fi
elif [ $NNEDI ]; then
## This lets me send this path in with an environment variable, but otherwise, welp
[ -n "${NNEDI_WEIGHTS}" ] || NNEDI_WEIGHTS=${FFMPEG_PREFIX}/etc/nnedi3_weights.bin
NN_DEINT="all"
FIELD="af"
PLANES="7"
NSIZE="s48x6"
NNS="n64"
QUAL="slow"
ETYPE="a"
PSCRN="new3"
THREADS=16
VF="nnedi=$NNEDI_WEIGHTS:deint=$NN_DEINT:field=$FIELD:planes=$PLANES:nsize=$NSIZE:nns=$NNS:qual=$QUAL:etype=$ETYPE:pscrn=${PSCRN}:threads=${THREADS}${VF:+,${VF}}"
fi
## DETELECINE SHENANIGANS
if [ -n "${IVTC}" ]; then
case ${IVTC-"false"} in
ivtc|pulldown)
VF="pullup,dejudder${VF:+,${VF}} -r 24000/1001";;
fieldmatch)
if [ "$SCANORDER" = "Top Field First" ]; then
VF="fieldmatch=order=tff:combmatch=full,yadif=deint=interlaced,decimate${VF:+,${VF}}"
else
VF="fieldmatch=order=bff:combmatch=full,yadif=deint=interlaced,decimate${VF:+,${VF}}"
fi;;
*) echo "## unrecognized ivtc method '${IVTC}'. exiting."; exit 1;;
esac
fi
if [ ! -z "$VIDEOFILTER" ]; then
VF="$VIDEOFILTER${VF:+,${VF}}"
fi
if [ ! -z "$VF" ]; then
ENCODE_FLAGS="$ENCODE_FLAGS -vf $VF"
fi
if [ $DEBUG ]; then
echo "COMMANDS:"
[[ "${INPUT##*.}" = ".mkv" ]] && echo "$STRIPCOVERS \"${INPUT}\""
echo "nice -n 5 $FFMPEG -i \"$INPUT\" $ENCODE_FLAGS \"$OUTPUT\""
[[ "${OUTPUT##*.}" = ".mkv" ]] && echo "$STRIPTAGS \"${OUTPUT}\""
[[ "${OUTPUT##*.}" = ".mkv" ]] && echo "$ADDSTATS \"${OUTPUT}\""
#exit
read -p "Press y to encode, any other key to exit..." confirm
case $confirm in
[Yy] ) true;;
* ) exit;;
esac
fi
if [[ "${INPUT##*.}" = ".mkv" ]]; then
echo "## Stripping covers from input file..."
## This exits 1 on both errors and also if there are no covers to remove, so blind fire
set -x
$STRIPCOVERS "${INPUT}"
{ set +x; } 2>/dev/null
fi
echo "## Starting encode..."
set -x
nice -n 5 $FFMPEG -analyzeduration 100 -probesize 100M -i "$INPUT" $ENCODE_FLAGS "$OUTPUT" && echo "## encode complete" || fail "## encoding error."
{ set +x; } 2>/dev/null
if [[ "${OUTPUT##*.}" = ".mkv" ]]; then
echo "## Stripping tags from \"${OUTPUT}\"..."
echo "$STRIPTAGS $(printf "%q" "${OUTPUT}")"
$STRIPTAGS "${OUTPUT}" && echo "## Tags stripped from \"${OUTPUT}\"" || fail "## error stripping tags from \"${OUTPUT}\""
echo "## Adding stats to \"${OUTPUT}\"..."
echo "$ADDSTATS $(printf "%q" "${OUTPUT}")"
$ADDSTATS "${OUTPUT}" && echo "## Stats added to \"${OUTPUT}\"" || fail "## error adding stats to \"${OUTPUT}\""
fi