forked from mediamicroservices/mm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmmfunctions
executable file
·770 lines (702 loc) · 28.5 KB
/
mmfunctions
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
# assign variables
SCRIPTNAME=$(basename "${0}")
SCRIPTDIR=$(dirname "${0}")
CONFIG_FILE="${SCRIPTDIR}/mm.conf"
WHAT_IS_THIS="mediamicroservices"
# load configuration file
if [ -f "${CONFIG_FILE}" ] ; then
. "${CONFIG_FILE}"
elif [ ! "${CONFIG}" = "Y" -a "${requireconfig}" = "Y" ] ; then
echo "The configuration file is not set. You amust first create ${CONFIG_FILE} by running mmconfig." 1>&2
exit 1
fi
get_iso8601(){
date +%FT%T
}
get_iso8601_c(){
date +%Y%m%d-%I%M%S
}
_unset_ffreport(){
if [ "${FFREPORT}" ] ; then
unset FFREPORT
fi
}
_mkdir2(){
local dir2make=""
while [ "${*}" != "" ] ; do
dir2make="${1}"
if [ ! -d "${dir2make}" ] ; then
mkdir -p "${dir2make}"
if [ "${?}" -ne 0 ]; then
report -wt "${0}: Can't create directory at ${dir2make}"
exit 1
fi
fi
shift
done
}
_log(){
mmlogname="mm.log"
mmlogdir="${CUSTOM_LOG_DIR:-/tmp}"
mmlogfile="${mmlogdir}/${mmlogname}"
if [ ! -d "${mmlogdir}" ] ; then
_mkdir2 "${mmlogdir}"
if [ "${?}" -ne 0 ]; then
echo "${0}: Can't create log directory at ${mmlogdir}, exiting... Use mmconfig to change logging directory."
exit 1
fi
fi
OPTIND=1
while getopts ":beac" opt; do
case "${opt}" in
b) status="start" ;; # script is beginning
e) status="end" ;; # script is ending
a) status="abort" ;; # script is aborted
c) status="comment" ;; # comment about what script is doing
w) status+"warning" ;; # warning information
esac
done
shift $(( ${OPTIND} - 1 ))
note="${1}"
echo $(get_iso8601)", $(basename "${0}"), ${status}, ${op}, ${mediaid}, ${note}" >> "${mmlogfile}"
}
report(){
local RED="$(tput setaf 1)" # Red - For Warnings
local GREEN="$(tput setaf 2)" # Green - For Declarations
local BLUE="$(tput setaf 4)" # Blue - For Questions
local NC="$(tput sgr0)" # No Color
local color=""
local startmessage=""
local endmessage=""
local echoopt=""
local log_message=""
OPTIND=1
while getopts ":qdwstn" opt; do
case "${opt}" in
q) color="${BLUE}" ;; # question mode, use color blue
d) color="${GREEN}" ;; # declaration mode, use color green
w) color="${RED}" ; log_message="Y";; # warning mode, use color red
s) startmessage+=([$(basename "${0}")] ) ;; # prepend scriptname to the message
t) startmessage+=($(get_iso8601) '- ' ) ;; # prepend timestamp to the message
n) echoopt="-n" ;; # to avoid line breaks after echo
esac
done
shift $(( ${OPTIND} - 1 ))
message="${1}"
echo $echoopt "${color}${startmessage[@]}${message}${NC}"
[ "$log_message" = "Y" ] && _log -w "${message}"
}
_writeingestlog(){
if [ "${ingestlog}" ] ; then
key="${1}"
value="$2"
# need to add yaml style escaping
echo "$key: ${value}" >> "${ingestlog}"
else
report -wt "The _writeingestlog function was called but the ingestlog file (${ingestlog}) is not declared."
fi
}
_readingestlog(){
if [ -f "${ingestlog}" ] ; then
key="${1}"
# need to add yaml style escaping
grep "^${1}:" "${ingestlog}" | cut -d: -f2- | sed 's/ //g'
else
report -wt "The _readingestlog function was called but the ingestlog file (${ingestlog}) is not declared."
fi
}
_run(){
run_err=""
report -sdt "Running: ${*}"
if [[ ! "${DRYRUN}" == true ]] ; then
"${@}"
fi
run_err="${?}"
if [[ "${run_err}" != 0 ]] ; then
report -wts "Error: Running: \"${*}\" gave an Error Code - ${run_err}"
fi
}
_run_critical(){
_run "${@}"
if [[ "${run_err}" != 0 ]] ; then
report -wts "The process ran into a critical error and can not proceed."
exit 1
fi
}
black_at_ends(){
input_movie="${1}"
name=$(basename "${input_movie}")
analysis_head_seconds=10
analysis_tail_seconds=10
report -dt "Analyzing ${name} for excessive black at head or tail."
duration=$(ffprobe "${1}" -show_format 2> /dev/null | grep "^duration=" | cut -d= -f2 | cut -d. -f1)
tail_start=$(echo "${duration} - ${analysis_tail_seconds}" | bc)
head_black=$(ffmpeg -t "${analysis_head_seconds}" -i "${1}" -an -vf blackdetect=pix_th=0.05 -loglevel debug -f null - 2>&1 | grep -c -o picture_black_ratio:1)
report -dt "Black frames in first ${analysis_head_seconds} seconds: ${head_black}."
tail_black=$(ffmpeg -ss "${tail_start}" -i "${1}" -an -vf blackdetect=pix_th=0.05 -loglevel debug -f null - 2>&1 | grep -c -o picture_black_ratio:1)
report -dt "Black frames in last ${analysis_head_seconds} seconds: ${tail_black}."
}
maketemp(){
mktemp -q "/tmp/$(basename "${0}").XXXXXX"
if [ "${?}" -ne 0 ]; then
echo "${0}: Can't create temp file, exiting..."
exit 1
fi
}
ask_operator(){
if [ -z "${op}" ] ; then
report -qn "Enter the name of the operator or 'q' to quit: "
read -e op
[ -z "${op}" ] && ask_operator || log+="operator: ${op}\n"
[ "${op}" == "q" ] && exit 0
fi
}
ask_mediaid(){
if [ -z "${mediaid}" ] ; then
report -qn "Enter a unique MEDIA ID: "
read -e mediaid
[ -z "${mediaid}" ] && ask_mediaid
# option to quit
[ "${mediaid}" == "q" ] && exit 0
# validate id and perhaps fail with exit
[ -z "${mediaid}" ] && { report -wt "ERROR You must enter a valid MEDIA ID" ; exit ;};
[ ! -z $(echo "${mediaid}" | grep -v "^[A-Z0-9_-]*$") ] && { report -wt "ERROR The MEDIA ID must only contain capital letters, letters, hyphen and underscore" ; exit 1 ;};
fi
[ ! -z "${mediaid}" ] && log+="mediaid: ${mediaid}\n"
}
ask_input(){
if [ -z "${input}" ] ; then
report -qn "Drag in the file: "
read -e input
[ -z "${input}" ] && ask_input
[ "${input}" == "q" ] && exit 0
basename=$(basename "${input}")
[ ! -z "${input}" ] && log+="input: ${input}\n"
fi
}
ask_trimmed_materials(){
report -qn "Drag in any trimmed materials: "
read -e -a trimmed
[ "$trimmed[0]" == "q" ] && exit 0
[ ! -z "${trimmed}" ] && log+="trimmed_materials: ${trimmed}\n"
}
_ask_intime(){
# TIME_REGEX tests for either S.mmm or HH:MM:SS.mmm time formats where HH is two digit hour, MM is two digit minute, S is number of seconds, SS is two digit seconds, and .mmm is milliseconds from between 0 and 3 decimals
TIME_REGEX="^\([0-9]\+\(\.[0-9]\{1,3\}\)\?\|[0-9]\{2\}:[0-5][0-9]:[0-5][0-9]\(\.[0-9]\{1,3\}\)\?\)$"
while [[ ! $(echo "$intime" | grep "${TIME_REGEX}") ]] ; do
report -q "Enter point of time to start transcoding."
report -q "Enter no value if no intime for transcoding is needed. Transcoding will then start from the beginning."
report -q "Must be in HH:MM:SS.mmm or S.mmm format. Note mmm is milliseconds and not frames."
report -qn "Intime: "
read intime
if [[ "${intime}" == "" ]] ; then
break
elif [[ ! $(echo "$intime" | grep "${TIME_REGEX}") ]] ; then
report -w "In time must be in seconds or in HH:MM:SS.mmm format."
fi
done
}
_ask_outtime(){
# TIME_REGEX tests for either S.mmm or HH:MM:SS.mmm time formats where HH is two digit hour, MM is two digit minute, S is number of seconds, SS is two digit seconds, and .mmm is milliseconds from between 0 and 3 decimals
TIME_REGEX="^\([0-9]\+\(\.[0-9]\{1,3\}\)\?\|[0-9]\{2\}:[0-5][0-9]:[0-5][0-9]\(\.[0-9]\{1,3\}\)\?\)$"
while [[ ! $(echo "$outtime" | grep "${TIME_REGEX}") ]] ; do
report -q "Enter point of time to stop transcoding."
report -q "Enter no value if no outtime for transcoding is needed. Transcoding will proceed to the end."
report -q "Must be in HH:MM:SS.mmm or S.mmm format. Note mmm is milliseconds and not frames."
report -qn "Outtime: "
read outtime
if [[ "${outtime}" == "" ]] ; then
break
elif [[ ! $(echo "$outtime" | grep "${TIME_REGEX}") ]] ; then
report -w "Out time must be in seconds or in HH:MM:SS.mmm format."
fi
done
}
check_dependencies(){
deps_ok=YES
while [ "${*}" != "" ] ; do
dependency="${1}"
if [ ! $(which "${dependency}") ] ; then
report -wt "This script requires ${dependency} to run but it is not installed"
report -wt "If you are running ubuntu or debian you might be able to install ${dependency} with the following command"
report -wt "sudo apt-get install ${dependency}"
report -wt "If you are running mac you might be able to install ${dependency} with the following command"
report -wt "brew install ${dependency}"
deps_ok=NO
fi
shift
done
if [[ "${deps_ok}" == "NO" ]]; then
report -wt "Unmet dependencies"
report -wt "Aborting!"
exit 1
else
return 0
fi
}
_initialize_make(){
check_dependencies "${dependencies[@]}"
unset dependencies
deliverdir=""
DRYRUN=false
emailaddress=""
outputdir_forced=""
cleanup(){
_log -a "Process aborted"
echo
report -wts "THE PROCESS WAS ABORTED"
exit 1
}
trap cleanup SIGHUP SIGINT SIGTERM
}
check_deliverdir(){
if [ ! -d "${deliverdir}" ] ; then
report -wt "The delivery directory, ${deliverdir}, does not exist. Can not deliver the output of $(basename "${0}")."
fi
}
_check_outputdir_forced(){
if [ ! -d "${1}" ] ; then
report -wt "The directory, ${1}, does not exist. Can not write the output of $(basename "${0}")."
fi
}
check_emailaddress(){
emailregex="^((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*([,])*)*$"
if ! $(echo "${1}" | grep -Eq "^((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*([,])*)*$") ; then
report -wt "${1} is not a valid email address."
fi
}
_get_duration(){
ffduration=$(ffprobe "${1}" -show_format -pretty 2> /dev/null | grep "^duration=" | cut -d= -f2)
}
_get_seconds(){
seconds=$(ffprobe "${1}" -show_format 2> /dev/null | grep "^duration=" | cut -d= -f2)
}
email_delivery(){
emailto="${1}"
if [ "${emailto}" ] ; then
[ -d "${input}" ] && logdir="${input}/metadata/submissionDocumentation/logs"
[ -f "${input}" ] && logdir="$(dirname "${input}")/service/logs"
ingestlog="${logdir}/capture.log"
_get_duration "${output}"
if [[ -f "${ingestlog}" ]] ; then
FROMLOG="Operator: $(_readingestlog "operator")\n
Processing Computer: $(_readingestlog "computer_name")
Audio Peak (dB): $(_readingestlog "voldet_max_volume")
Integrated Loudness: $(_readingestlog "r128_integrated_loudness")
Audio Adjustment: $(_readingestlog "audio_adjustment")
Loudness Range: $(_readingestlog "r128_loudness_range")"
fi
echo -e "Subject: [delivery] $(basename "${output}")\n
A file has been delivered to ${deliverdir}.\n
Process: $(basename "${0}")
MediaID: ${mediaid}\n
Filename: ${output}
Sourcefile: ${sourcefile}
Duration: ${ffduration}\n
Decoding_options: ${inputoptions[@]}
Encoding_options: ${middleoptions[@]}\n
Delivery Exit Status: ${DELIVER_EXIT_STATUS}\n
${FROMLOG}
\n
Enjoy!" | sendmail -f "${EMAIL_FROM}" -F "${emailto}" "${emailto}"
fi
}
_deliver_output(){
# argument 1 if used should be the email to report delivery to
emailto="${1}"
if [ "${deliverdir}" ] ; then
echo DELIVERING OUTPUT ACTIVITED with "${deliverdir}"
report -dt "Delivering ${output} to ${deliverdir}"
_run cp -av "${output}" "${deliverdir}/"
DELIVER_EXIT_STATUS="$?"
email_delivery "$emailto"
fi
}
ask(){
# This function requires 3 arguments
# 1) A prompt
# 2) The label for the metadata value
read -e -p "${1}" response
if [ -z "${response}" ] ; then
ask "${1}" "${2}"
else
log+="${2}: ${response}\n"
fi
echo
}
offerChoice(){
# This function requires 3 arguments
# 1) A prompt
# 2) The label for the metadata value
# 3) A vocabulary list
PS3="${1}"
label="${2}"
eval set "${3}"
select option in "${@}"
do
break
done
log+="${label}: ${option}\n"
echo
}
make_mezz_for_xdcam(){
som="${1}"
dur="${2}"
tmc_ms=$(mediainfo --inform="Video;%Delay%" "${3}")
tmc_smp=$(mediainfo --inform="Video;%Delay/String3%" "${3}")
tmc_sec=$(echo "${tmc_ms} * 0.001" | bc)
som_h=$(echo "${som}" | cut -c 1-2)
som_m=$(echo "${som}" | cut -c 4-5)
som_s=$(echo "${som}" | cut -c 7-8)
som_f=$(echo "${som}" | cut -c 10-11)
som_fc=$(echo "scale=3; (((((3600 * ${som_h})+(60 * ${som_m})+ ${som_s} ) * 30)+ ${som_f} ) - ( 2 * (((60 * ${som_h})+ ${som_m} ) - (((60 * ${som_h})+ ${som_m} ) / 10 )))) / 29.97" | bc)
dur_h=$(echo "$dur" | cut -c 1-2)
dur_m=$(echo "$dur" | cut -c 4-5)
dur_s=$(echo "$dur" | cut -c 7-8)
dur_f=$(echo "$dur" | cut -c 10-11)
dur_fc=$(echo "scale=3; (((((3600 * $dur_h)+(60 * $dur_m)+ $dur_s ) * 30)+ $dur_f ) - ( 2 * (((60 * $dur_h)+ $dur_m ) - (((60 * $dur_h)+ $dur_m ) / 10 )))) / 29.97" | bc)
rel_start=$(echo "scale=3; $som_fc - $tmc_sec" | bc)
pushd $(dirname "$4")
report -dt "Starting ffmpeg to trim mxf file at $(date) This will take a few minutes..."
ffmpeg 2</dev/null -report -y -ss "$rel_start" -t "$dur_fc" -i "$3" -map 0:v -map 0:a:0 -map 0:a:1 -c copy "$4"
popd
}
_find_input (){
concatsource=""
sourcefile=""
isobject=""
[ -d "${1}" ] && [ -d "$1/objects/service" ] && isobject="N" && sourcefile=$(find "$1/objects/service" -maxdepth 1 -mindepth 1 -type f \( -iname "*.mov" -o -iname "*.mxf" -o -iname "*.mp4" -o -iname "*.dv" -o -iname "*.mpeg" -o -iname "*.iso" -o -iname "*.mkv" \) ! -name ".*" | head -n 1)
[ -f "${1}" ] && sourcefile="${1}"
[ ! "$sourcefile" ] && [ -d "$1/objects" ] && isobject="Y" && sourcefile=$(find "$1/objects" -maxdepth 1 -mindepth 1 -type f \( -iname "*.mov" -o -iname "*.mxf" -o -iname "*.mp4" -o -iname "*.dv" -o -iname "*.mpeg" -o -iname "*.iso" -o -iname "*.mkv" \) ! -name ".*" | head -n 1)
[ ! "$sourcefile" ] && { report -wt "A valid source file isn't found." ; exit 1 ;};
log+="sourcefile: ${sourcefile}\n"
if [ "${sourcefile#*.}" == "iso" ] ; then
report -dt "Detecting iso input and hoping its a dvd image"
if [[ $(uname -s) == "Darwin" ]] ; then
mountpath=$(hdiutil mount "${sourcefile}" | cut -d " " -f 2- | sed 's/^[ \t]*//' )
report -dt "Mounting iso at $mountpath"
else
mountpath="/tmp/temporary_dvd_path"
rm -rfv "${mountpath}"
if [ ! -d "${mountpath}" ] ; then
mkdir -p "${mountpath}"
fi
7z e -r -o"${mountpath}" "${sourcefile}"
fi
oldsourcefile="${sourcefile}"
concatsource="concat:$(find "${mountpath}" -iname "VTS*[1-9].VOB" | sort | sed -e :a -e '$!N;s/\n/|/;ta')"
sourcefile=$(find "${mountpath}" -iname "VTS_*_1.VOB" | head -1)
report -dt "Using ${concatsource} for transcoding."
report -dt "Using ${sourcefile} for assessment."
report -wt "Extracting to ${mountpath}. Please delete ${mountpath} later"
if [ "${concatsource}" == "" ] ; then
report -wt "ERROR: Can not mount iso or find vob files to concatenate within ${oldsourcefile}. Exiting."
exit
fi
fi
}
get_width(){
width=$(ffprobe "${1}" -show_streams -select_streams v:0 2> /dev/null | grep "^width=" | cut -d = -f 2)
}
get_height(){
height=$(ffprobe "${1}" -show_streams -select_streams v:0 2> /dev/null | grep "^height=" | cut -d = -f 2)
}
get_dar(){
dar=$(ffprobe "${1}" -show_streams -select_streams v:0 2> /dev/null | grep "^display_aspect_ratio=" | cut -d = -f 2 | sed 's|:|/|g')
if [ "$dar" = "0/1" ] ; then
get_width "${1}"
get_height "${1}"
dar="${width}/${height}"
fi
}
get_sar(){
sar=$(ffprobe "${1}" -show_streams -select_streams v:0 2> /dev/null | grep "^sample_aspect_ratio=" | cut -d = -f 2 | sed 's|:|/|g')
if [ "$sar" = "0/1" ] ; then
sar="1/1"
fi
}
has_first_two_tracks_mono(){
[ $(ffprobe 2>/dev/null "${1}" -show_streams | grep -c "codec_type=audio") -ge 2 ] && \
[ $(ffprobe 2>/dev/null "${1}" -show_streams -select_streams a:0 | grep "^channels=" | cut -d= -f2) = "1" ] && \
[ $(ffprobe 2>/dev/null "${1}" -show_streams -select_streams a:1 | grep "^channels=" | cut -d= -f2) = "1" ] && \
MULTIMONO=true
}
get_audio_index(){
# get ffmpeg's index value of the first audio stream. Useful for do custom channel mappings.
audio_index_1=$(ffprobe "${1}" -show_streams -select_streams a:0 2> /dev/null | grep "^index=" | cut -d = -f 2)
audio_index_2=$(ffprobe "${1}" -show_streams -select_streams a:1 2> /dev/null | grep "^index=" | cut -d = -f 2)
}
get_audio_channels(){
# get ffmpeg's channel count of the first audio stream.
audio_channels=$(ffprobe "${1}" -show_streams -select_streams a 2> /dev/null | grep "^channels=" | cut -d = -f 2 | head -n 1)
}
get_channel_layout(){
# get ffmpeg's channel count of the first audio stream.
channel_layout=$(ffprobe "${1}" -show_streams -select_streams a 2> /dev/null | grep "^channel_layout=" | cut -d = -f 2 | head -n 1)
}
get_audio_mapping(){
get_audio_index "${1}"
get_audio_channels "${1}"
get_channel_layout "${1}"
has_first_two_tracks_mono "${1}"
if [[ "${MULTIMONO}" == true ]] ; then
report -wt "The first two audio tracks are both mono. Considering track 1 for left and track 2 for right."
audiomapping_ffmpeg=(-map_channel "0.${audio_index_1}.0" -map_channel "0.${audio_index_2}.0")
elif [[ "$audio_channels" -gt 2 && "$channel_layout" == "unknown" ]] ; then
report -wt "The first audio track has more than 2 channels. Considering channel 1 for left and channel 2 for right and ignoring the rest."
audiomapping_ffmpeg=(-map_channel "0.${audio_index_1}.0" -map_channel "0.${audio_index_1}.1")
else
audiomapping_ffmpeg=()
fi
}
get_codectagstring(){
codec_tag_string=$(ffprobe "${1}" -show_streams -select_streams v:0 2> /dev/null | grep "^codec_tag_string=" | cut -d = -f 2)
if [ "$codec_tag_string" = "FFV1" ] ; then
ffv1_version=$(ffmpeg -debug 1 -i "${1}" -t 0.1 -f null - </dev/null 2>&1 | grep -o "ver:[0-9]*" | tail -n1 | cut -d: -f2)
else
ffv1_version=""
fi
}
get_fieldorder(){
fieldorder=$(ffprobe-bc "${1}" -show_streams 2> /dev/null | grep "\(progressive\|interlaced=\)" | cut -d = -f 2)
}
get_pix_fmt(){
pixfmt=$(ffprobe "${1}" -show_streams -select_streams v:0 2> /dev/null | grep "^pix_fmt=" | cut -d = -f 2)
}
get_duration(){
DURATION=$(ffprobe "${1}" -show_format 2> /dev/null | grep "^duration=" | cut -d = -f 2)
}
get_videostreamcount(){
VIDEOSTREAMCOUNT=$(ffprobe "${1}" -select_streams v -show_entries stream=index -of flat 2>/dev/null | awk 'END { print NR }')
}
get_audiostreamcount(){
AUDIOSTREAMCOUNT=$(ffprobe "${1}" -select_streams a -show_entries stream=index -of flat 2>/dev/null | awk 'END { print NR }')
}
_get_timecode(){
TIMECODE=$(ffprobe "${1}" -select_streams v -show_streams -of flat 2>/dev/null | grep "timecode=[0-9]" | head -n 1 | cut -d = -f 2 | sed 's/"//g')
}
_get_timecode_overlay(){
_get_timecode "${1}"
if [[ "${TIMECODE}" ]] ; then
TIMECODEESACPE=$(echo "${TIMECODE}" | sed 's|:|\\:|g')
else
TIMECODEESACPE="01\\:00\\:00;00"
fi
TIMECODEOVERLAY=",drawtext=fontfile=/System/Library/Fonts/Monaco.dfont:timecode='${TIMECODEESACPE}':r=30000/1001:fontcolor=white:fontsize=24:shadowx=2:shadowy=2:box=1:[email protected]:x=w/2-tw/2:y=h*0.8"
}
get_maxdvdbitrate(){
get_duration "${1}"
local DVDCAPACITY=33840000000 # in bits, minus 10%
local CAPDVDBITRATE=6000000 # in bits/second
MAXDVDBITRATE=$(echo "($DVDCAPACITY - ( $DURATION * 224000 )) / $DURATION" | bc)
report -dt "Data rate could be up to $MAXDVDBITRATE"
if ! [[ "$MAXDVDBITRATE" =~ ^[0-9]+$ ]] ; then
report -wt "Calculation of dvd bitrate failed. Evaluated to ${MAXDVDBITRATE}. Using 4000000 as bitrate instead."
MAXDVDBITRATE=4000000
elif [ "$MAXDVDBITRATE" -gt "$CAPDVDBITRATE" ] ; then
MAXDVDBITRATE="$CAPDVDBITRATE"
fi
report -dt "Data rate for DVD is evaluated to $MAXDVDBITRATE"
}
is_video(){
# use ffmpeg's index value and stream specifier to determine if the input is a recognized as a video file by ffmpeg
ffprobe "${1}" -show_streams -select_streams v:0 2> /dev/null | grep "^index="
}
get_volume_adjustment(){
reference=-24
integrated_loudness=""
loudness_range=""
voldet_mean_volume=""
voldet_max_volume=""
VOLADJ=""
input_movie="${1}"
report -dt "Getting volume data for $(basename "${input_movie}") ..."
VOLDETTEMP=$(maketemp)
volume_data=$(ffprobe -of compact=p=0:nk=1:s=',' -show_entries frame_tags=lavfi.r128.I,lavfi.r128.LRA -f lavfi "amovie='${input_movie}',ebur128=metadata=1,volumedetect" 2>"${VOLDETTEMP}")
volume_exit_code="$?"
if [ "${volume_exit_code}" -ne 0 ] ; then
report -wt "Volume analysis for $input_movie exited with ${volume_exit_code}."
else
for i in $(echo "$volume_data"); do
audioframe_I=$(echo "${i}" | cut -d, -f1)
audioframe_LRA=$(echo "${i}" | cut -d, -f2)
[ "$audioframe_I" != "" ] && integrated_loudness="${audioframe_I}"
[ "$audioframe_LRA" != "" ] && loudness_range="${audioframe_LRA}"
done
voldet_mean_volume=$(grep "mean_volume" "${VOLDETTEMP}" | cut -d: -f 2 | awk '{print $1}')
voldet_max_volume=$(grep "max_volume" "${VOLDETTEMP}" | cut -d: -f 2 | awk '{print $1}')
VOLADJ=$(echo "$reference - $integrated_loudness" | bc)
# test to see if adjustment is at least 2dB, else skip
report -dt "Loudness range is ${loudness_range}dB."
if [[ -f "${ingestlog}" ]] ; then
_writeingestlog "audio_adjustment" "${VOLADJ}"
_writeingestlog "r128_loudness_reference" "${reference}"
_writeingestlog "r128_loudness_range" "${loudness_range}"
_writeingestlog "r128_integrated_loudness" "${integrated_loudness}"
_writeingestlog "voldet_mean_volume" "${voldet_mean_volume}"
_writeingestlog "voldet_max_volume" "${voldet_max_volume}"
fi
fi
}
get_cropdetection(){
input_movie="${1}"
report -dt "Getting cropping data for $(basename "$input_movie") ..."
crop_data=$(ffmpeg -i "${input_movie}" -an -vf cropdetect -f null - 2>&1 | grep -o "crop=[0-9:]*")
crop_err="$?"
[ "$crop_err" -ne 0 ] && { report -wt "Crop detection analysis for $input_movie exited with $crop_err." ; exit ;};
for i in $(echo "$crop_data"); do
[ "$i" != "" ] && CROPADJ="$i"
done
report -dt "Crop detection complete. Will crop by ${CROPADJ} (width,height,from_left,from_top) before scaling."
}
free_space(){
#this should give the free space in gigabytes
local space="${1}" #This value represents the space in gigabytes required for the script to run
local outputdir="$2"
[ ! -d "$outputdir" ] && { report -wt "The output directory [$outputdir] that free-space function is seeking does not exist." ; exit 1 ;};
[[ ! $space =~ ^-?[0-9]+$ ]] && { report -wt "Number is not an integer." ; exit 1 ;};
freespace=$(df -g "$outputdir" | awk '{ print $4; }' | tail -n 1)
if [ $freespace -lt $space ]; then
report -wts "ERROR only $freespace gb free in this directory. This script requires at least $space gigabytes"
exit 1
fi
}
_summarize_make(){
report -dt "$(basename "${output}") is done."
}
_prep_ffmpeg_log(){
OPTIND=1
while getopts ":q" opt ; do
case "${opt}" in
q) nolog="Y";;
*) echo "bad option -$OPTARG" ; usage ;;
:) echo "Option -$OPTARG requires an argument" ; exit 1 ;;
esac
done
shift $(( ${OPTIND} - 1 ))
unset inputoptions
if [ "${logdir}" != "" ] ; then
_mkdir2 "${logdir}"
if [ "${nolog}" = "Y" ] ; then
_unset_ffreport
else
export FFREPORT="file=${logdir}/%p_%t_$(basename "${0}")_${version}.txt"
fi
inputoptions+=(-v info)
inputoptions+=(-hide_banner)
inputoptions+=(-stats)
else
_unset_ffreport
fi
}
emailoutcome(){
# fail only at the moment
MESSAGETEMPFILE=$(maketemp)
echo -e "To: $EMAIL_OUTCOME_TO" > $MESSAGETEMPFILE
echo -e "Subject: ${PACKAGE} failed during ${SCRIPTNAMESHORT}" >> $MESSAGETEMPFILE
echo -e ":(" >> $MESSAGETEMPFILE
sendmail -t < $MESSAGETEMPFILE
rm -f $MESSAGETEMPFILE
}
_get_filesystem(){
if [ -f "${1}" -o -d "${1}" ] ; then
df "${1}" | tail -n1 | cut -d " " -f1
else
report -wt "_get_filesystem was expecting a file or directory but got a ${1}"
fi
}
set_accesstimes(){
# set in and out times if used
ingestlog="${logdir}/capture.log"
if [[ -f "${ingestlog}" && "${isobject}" = "Y" ]] ; then
intime=$(_readingestlog "intime")
outtime=$(_readingestlog "outtime")
if [[ "${intime}" ]] ; then
report -dt "ATTENTION: Transcoding will use intime (${intime}) during transcoding."
middleoptions+=(-ss "${intime}")
fi
if [[ "${outtime}" ]] ; then
report -dt "ATTENTION: Transcoding will use outtime (${outtime}) during transcoding."
middleoptions+=(-to "${outtime}")
fi
fi
}
_set_up_output(){
# set up output
_log -b
output="${outputdir}/${mediaid%.*}${suffix}.${extension}"
if [ -s "${output}" ] ; then
report -wt "WARNING ${output} already exists, skipping transcode"
shift
continue
fi
_mkdir2 "${outputdir}"
}
_prep_volume_adjustment(){
unset VOLADJ
if [ "${VOLADJUST}" = "Y" ] ; then
if [[ -f "${ingestlog}" ]] ; then
VOLADJ=$(_readingestlog "audio_adjustment")
fi
if [ "${VOLADJ}" ] ; then
middleoptions+=(-af volume=${VOLADJ}dB)
else
get_volume_adjustment "${sourcefile}"
if [ "${VOLADJ}" ] ; then
if [ $(echo "$VOLADJ < 2" |bc) -eq 1 -a $(echo "$VOLADJ > -2" |bc) -eq 1 ] ; then
report -dt "Integrated loudness for $(basename "${input_movie}") is ${integrated_loudness}dB. Reference is ${reference}dB. No adjustment is needed, skipping."
else
report -dt "Integrated loudness for $(basename "${input_movie}") is ${integrated_loudness}dB. Reference is ${reference}dB. Will adjust by ${VOLADJ}dB."
middleoptions+=(-af volume=${VOLADJ}dB)
fi
fi
fi
fi
}
pashua_run() {
# Wrapper function for interfacing to Pashua. Written by Carsten
# Bluem <[email protected]> in 10/2003, modified in 12/2003 (including
# a code snippet contributed by Tor Sigurdsson), 08/2004 and 12/2004.
# Write config file
# Find Pashua binary. We do search both . and dirname "$0"
# , as in a doubleclickable application, cwd is /
# BTW, all these quotes below are necessary to handle paths
# containing spaces.
bundlepath="Pashua.app/Contents/MacOS/Pashua"
mypath=`dirname "$0"`
for searchpath in "$mypath/Pashua" "$mypath/$bundlepath" "./$bundlepath" \
"/Applications/$bundlepath" "$HOME/Applications/$bundlepath"
do
if [ -f "$searchpath" -a -x "$searchpath" ]
then
pashuapath=$searchpath
break
fi
done
if [ ! "$pashuapath" ] ; then
echo "Error: Pashua is used to edit but is not found."
if [[ "${pashuainstall}" == "" ]] ; then
echo "Attempting to run: brew cask install pashua"
if [[ "${pashuainstall}" != "Y" ]] ; then
brew cask install pashua
pashuainstall="Y"
pashua_run
else
break 2
fi
fi
else
encoding=""
# Get result
result=`"$pashuapath" $encoding $pashua_configfile | sed 's/ /;;;/g'`
# Parse result
for line in $result
do
key=`echo $line | sed 's/^\([^=]*\)=.*$/\1/'`
value=`echo $line | sed 's/^[^=]*=\(.*\)$/\1/' | sed 's/;;;/ /g'`
varname=$key
varvalue="$value"
eval $varname='$varvalue'
done
fi
} # pashua_run()