-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathepisodesplit.sh
More file actions
executable file
·491 lines (400 loc) · 11.7 KB
/
Copy pathepisodesplit.sh
File metadata and controls
executable file
·491 lines (400 loc) · 11.7 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
#!/bin/bash
#This requires FFMPEG
#check if FFMPEG installed
if ! type ffmpeg &> /dev/null
then
echo "ffmpeg is not installed"
exit 1
fi
#default values
blackduration="0.5"
blackthreshold="0.0"
midindex=unset
function=split
codeccopy=unset
if [ -z "$*" ]
then
function=help
fi
for z in "$@"
do
case $z in
-p=*)
showdir="${z#*=}"
shift # past argument=value
;;
--split)
function=split
shift # past argument with no value
;;
--index)
function=index
shift # past argument with no value
;;
--indexfull)
function=indexfull
shift # past argument with no value
;;
--test)
function=testrun
shift # past argument with no value
;;
--examples)
function=example
shift # past argument with no value
;;
-m=*)
midindex="${z#*=}"
shift # past argument=value
;;
-l=*)
blackduration="${z#*=}"
shift # past argument=value
;;
-b=*)
blackthreshold="${z#*=}"
shift # past argument=value
;;
-c=*)
c="${z#*=}"
shift # past argument=value
;;
*)
function=help # unknown option
;;
esac
done
help_screen() {
echo ""
echo " This script will split an episode into 2 parts, keeping the opening and closing credits."
echo " It will append the opening and closing to the appropriate missing piece."
echo " This is mostly designed because of many kids shows having 2 parts in 1 episode."
echo " but TVDB admins refuse to accept that and make each episode separate"
echo ""
echo " Episodes must be named \"Show Name - SxxExxExx.ext\""
echo " Example usage: ./episide_splitter.sh -p=\"/path/to/dir/\" [-c=action] [--test]"
echo " Arguments:"
echo " -p=\"/path/to/dir\" Path to single or multiple files"
echo " must include include quotes and trailing / for directories"
echo " eg - -p=\"/path/to/dir/\" or -p=\"/path/to/file.exe\""
echo " -c= [c or r] c is copy. r is remux. depending on your version of ffmpeg, you may either have to copy or remux"
echo " Copy may not cut perfectly on black spots, remux may not work if the version of ffmepg cant read the codec well"
echo " --test Enables test mode to output detected times and index numbers"
echo " --index provides the index numbers for black parts the file/files. Cannot be used with test or split"
echo " --indexfull like index, but provides all the numbers, start,end,length of black parts"
echo " --split default value. not needed Cannot be used with test or index"
echo " -m=x Index number for midpoint. You will pick this after running index"
echo " This only works on a single episode"
echo " -b=x 0.0-0.9 black depth threshold. 0.0-0.2 should cut it. default 0.0"
echo " -l=x seconds for black duration 0.0-99.0. 0.3-0.7 should cut it. default 0.5"
echo " --examples Displays examples of commands"
echo " Requires ffmpeg"
echo " Use test to see outputs. Should be 12 minimum numbers"
echo " Adjust black duration & threshold if you dont get 12 or more numbers"
echo " Will output files to current directory if permissions to write exist."
echo " Cuts may not be perfect. It is all best guess."
echo ""
exit
}
if [ "$function" = "example" ]
then
echo " Examples of commands:"
echo ""
echo " Split a folder of episodes: (ffmpeg copy)"
echo " ./episode_splitter.sh -p=\"/tvshows/show name/\" -c=c"
echo ""
echo " Split a single episode: (ffmpeg remux)"
echo " ./episode_splitter.sh -p=\"/tvshows/show name/show name.ext\" -c=r"
echo ""
echo " Test a folder to see how each episode would process:"
echo " ./episode_splitter.sh -p=\"/tvshows/show name/\" --test "
echo ""
echo " List indexes of each black segment to force an episode split at a certain time point"
echo " ./episode_splitter.sh -p=\"/tvshows/show name/\" --index -c=c"
echo ""
echo " List full index information of each black segment start, stop, duration"
echo " ./episode_splitter.sh -p=\"/tvshows/show name/\" --index -c=c"
echo ""
echo " Override the default black depth. check ffmpeg documention"
echo " ./episode_splitter.sh -p=\"/tvshows/show name/\" -b=0.2 -c=r"
echo ""
echo " Override the black length. check ffmpeg documention"
echo " ./episode_splitter.sh -p=\"/tvshows/show name/\" -l=0.3 -c=c"
fi
if [ "$function" = "help" ]
then
help_screen
fi
convertsecs() {
if [[ $1 =~ \. ]];
then
wholesec=$(echo ${1} | cut -f1 -d.)
millisec=$(echo ${1} | cut -f2 -d.)
else
wholesec=$(echo ${1} | cut -f1 -d.)
millisec=0
fi
((h=${wholesec}/3600))
((m=(${wholesec}%3600)/60))
((s=${wholesec}%60))
printf "%02d:%02d:%02d.$millisec\n" $h $m $s
}
gettimes(){
ffmpeg -i "$1" -vf blackdetect=d=$2:pix_th=$3 -an -f null - 2>&1 | grep 'Duration\|blackdetect' | sed 's/.*black_start:\(\S*\).*black_end:\(\S*\).*black_duration:\(\S*\).*/\1 \2 \3/;s/Duration: / /;s/, start: / /;s/, bitrate: / /;s/ kb\/s/ /' | tr '\n' ' '
}
#Checks if file or directory
if [[ -d "$showdir" ]]
then
type=directory
elif [[ -f "$showdir" ]]
then
type=file
else
echo "$showdir is not a valid file or path"
help_screen
exit 1
fi
#Validates if remux or copy
if [[ $c = "c" ]]
then
codeccopy="-c copy"
elif [[ $c = "r" ]]
then
codeccopy=" "
fi
if [ "$function" = "split" ] && [ ! "$codeccopy" = "unset" ]
then
echo "ffmpeg action (-c) not set properly."
help_screen
exit 1
fi
#check if midpoint is being used on a directory
if [ "$type" = "directory" ] && [ ! "$midindex" = "unset" ]
then
echo "Cannot set a midpoint on directory listing"
exit 1
fi
if [[ ! -x "$PWD" ]]
then
echo "cannot write to $PWD"
exit 1
fi
#Validate inputs - blackduration, depth, midpoint
bdpattern='^([0-9]){1,2}\.([0-9]){1,2}$'
[[ $blackduration =~ $bdpattern ]]
if [[ $? != 0 ]]
then
echo "black duration ($blackduration) not valid."
help_screen
exit 1
fi
btpattern='^0\.([0-9]){1,2}$'
[[ $blackthreshold =~ $bdpattern ]]
if [[ $? != 0 ]]
then
echo "black depth threshold ($blackthreshold) not valid."
help_screen
exit 1
fi
if [ ! "$midindex" = "unset" ]
then
indexpattern='^([0-9]){1,2}$'
[[ $midindex =~ $indexpattern ]]
if [[ $? != 0 ]]
then
echo "Index number ($midindex) not valid."
help_screen
exit 1
fi
fi
for show in "$showdir"*
do
filename=$(basename -- "$show")
extension="${filename##*.}"
filename="${filename%.*}"
showpattern='(.+)(S[0-9]+)(E[0-9]+)(E[0-9]+)(.*)'
[[ $filename =~ $showpattern ]]
if [[ $? != 0 ]]
then
echo "$show has an invalid file name"
echo "Episode must be named \"Show Name - SxxExxExx.ext\""
continue
fi
showname="${BASH_REMATCH[1]}"
season="${BASH_REMATCH[2]}"
episode1="${BASH_REMATCH[3]}"
episode2="${BASH_REMATCH[4]}"
episodetimes=`gettimes "$show" $blackduration $blackthreshold`
#Create times into array
breaktimes=( $episodetimes )
#Count array elemets
breakcount=${#breaktimes[@]}
if [ "$function" = "index" ]
then
echo "$show"
v=3
while [ $v -lt $breakcount ]
do
echo -n "index $v: $(convertsecs ${breaktimes[v]}) "
((v=v+3))
done
echo ""
continue
fi
if [ "$function" = "indexfull" ]
then
echo "$show"
v=3
while [ $v -lt $breakcount ]
do
echo -n "index $v: $(convertsecs ${breaktimes[v]}) "
((v=v+1))
done
echo ""
continue
fi
#assign known elements to variables
totaltime=${breaktimes[0]}
starttime=${breaktimes[1]}
bitrate=${breaktimes[2]}
if [ $breakcount -lt 12 ]
then
echo "$show - element count too low - episode not trimmable. Check black depth, then length"
continue
fi
#checks for proper elment count. must be interval of 3
n=`expr $breakcount % 3`
if [ $n -ne 0 ]
then
echo "$show - element count not multiple of 3 - episode not trimmable.Check black depth, then length"
continue
fi
#If breaks are correct, assign to final array
if [ $breakcount -eq 12 ]
then
msg="Correct number of black segments found"
finalarray=("${breaktimes[@]}")
fi
#If array count not correct, assign known first 3 elements.
if [ $breakcount -gt 12 ]
then
msg="more than 3 black segments found"
#Find opening credits. First scene to be longer than 15 seconds
#Establishes start time of 0 seconds. Increments by 3, so skips over first 3 tokens
i=0
oplength=0
until [ $oplength -gt "15" ]
do
((i=i+3))
oplength=`echo ${breaktimes[$i]} | sed 's/\([0-9]\+\)\.[0-9]\+/\1/'`
done
#Find ending credits. First scene from end to be longer than 15 seconds
#Establishes start time of 0 seconds. decriments by 3
totaltimesec=`echo $totaltime | awk -F: '{ print ($1 * 3600) + ($2 * 60) + $3 }' | sed 's/\([0-9]\+\)\.[0-9]\+/\1/'`
j=$breakcount
endlength=0
until [ $endlength -gt "15" ]
do
((j=j-3))
endblackstart=`echo ${breaktimes[$j]} | sed 's/\([0-9]\+\)\.[0-9]\+/\1/'`
endlength=$((totaltimesec - endblackstart))
done
#Find midpoint seconds
estmidpoint=$(( $totaltimesec / 2 ))
#extremely high 'diff' to have something to measure against for the first value
midpointdiff=9999999
#check each index between opening and closing creds to find midpoint
k=$(($i + 3))
while [ $k -lt $j ]; do
#black start time of current index
currtime=`echo ${breaktimes[k]} | sed 's/\([0-9]\+\)\.[0-9]\+/\1/'`
#Determine time diff, getting absolute value. (cheating by stripping the minus sign)
currtimediff=`echo $((estmidpoint - currtime)) | tr -d -`
if [[ $currtimediff -lt $midpointdiff ]]
then
midpointdiff=$currtimediff
midindexnum=$k
fi
k=$(($k + 3))
done
if [ ! "$midindex" = "unset" ]
then
midindexnum=$midindex
fi
finalarray=( "${breaktimes[@]:0:3}" "${breaktimes[@]:$i:3}" "${breaktimes[@]:$midindexnum:3}" "${breaktimes[@]:$j:3}")
fi
openingstartblack=${finalarray[3]}
openingendblack=${finalarray[4]}
openingduration=${finalarray[5]}
ep1blackstart=${finalarray[6]}
ep1blackend=${finalarray[7]}
ep1blackdur=${finalarray[8]}
ep2blackstart=${finalarray[9]}
ep2blackend=${finalarray[10]}
ep2blackdur=${finalarray[11]}
if [ "$function" = "testrun" ]
then
echo "$show - $msg"
echo "Opening: 00:00:00 - $(convertsecs $openingstartblack), Ep1: 00:00:00 - $(convertsecs $ep1blackstart), Ep2: $(convertsecs $ep1blackend) - $totaltime, Closing: $(convertsecs $ep2blackend) - $totaltime"
echo ""
fi
if [ "$function" = "split" ]
then
echo "$show - $msg"
#Extract Opening Credits
ffmpeg -y -nostdin -loglevel quiet -ss 00:00:00 -i "$show" -t $openingstartblack $codeccopy "opening.$extension"
if [[ $? != 0 ]]
then
echo "error writing $show opening credits"
echo "moving on to next file"
continue
fi
#Extract Closing Credits
ffmpeg -y -nostdin -loglevel quiet -ss $ep2blackend -i "$show" $codeccopy "closing.$extension"
if [[ $? != 0 ]]
then
echo "error writing $show closing credits"
echo "moving on to next file"
continue
fi
#Create first segment. (Missing end credits)
ffmpeg -y -nostdin -loglevel quiet -ss 00:00:00 -i "$show" -t $ep1blackstart $codeccopy "firstep.$extension"
if [[ $? != 0 ]]
then
echo "error writing $show first segment"
echo "moving on to next file"
continue
fi
#Create second segment (Missing opening credits)
ffmpeg -y -nostdin -loglevel quiet -ss $ep1blackend -i "$show" $codeccopy "secondep.$extension"
if [[ $? != 0 ]]
then
echo "error writing $show second segment"
echo "moving on to next file"
continue
fi
#Create merge file
echo "file firstep.$extension" > merge.txt
echo "file closing.$extension" >> merge.txt
#Create first proper episode
ffmpeg -nostdin -loglevel quiet -f concat -i merge.txt $codeccopy "$showname$season$episode1.$extension"
if [[ $? != 0 ]]
then
echo "error writing $showname$season$episode1.$extension"
fi
#Create merge file
echo "file opening.$extension" > merge.txt
echo "file secondep.$extension" >> merge.txt
#Create second proper episode
ffmpeg -nostdin -loglevel quiet -f concat -i merge.txt $codeccopy "$showname$season$episode2.$extension"
if [[ $? != 0 ]]
then
echo "error writing $showname$season$episode2.$extension"
fi
rm "opening.$extension"
rm "closing.$extension"
rm "firstep.$extension"
rm "secondep.$extension"
rm merge.txt
fi
done