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
|
#!/bin/sh
set -eu
prog="${0##*/}"
usage() {
cat <<EOF
${prog} - cut and concat video files with ffmpeg
Usage:
${prog} [-j | concat] [-o <output>] <file>
${prog} -c | cut [-o <output>] <file> <start> [<end|duration>]
${prog} -h | --help
Concat (default mode):
Combines all video files matching '<base>*.*' into '<base>_combine.<ext>'.
Mixed container extensions (e.g. .mp4 + .mkv) are allowed; the output
then uses .mkv. Streams are checked with ffprobe first: all files must
share the same video codec/resolution and audio codec/rate/channels.
Previous '*_combine.*' outputs are excluded from matching.
Examples:
${prog} clip_cut.mp4
${prog} -j clip_cut.mp4 -o joined.mp4
Cut:
<start> uses HH:MM:SS (e.g. 00:01:30).
Third argument is auto-detected:
contains ':' -> end position (ffmpeg -to)
pure number -> duration in seconds (ffmpeg -t)
omitted -> cut to end of video
Default output: '<base>_cut.<ext>', auto-incremented if it exists.
Examples:
${prog} -c movie.mp4 00:12:30 # 12:30 -> end
${prog} -c movie.mp4 00:12:30 00:15:00 # 12:30 -> 15:00
${prog} -c movie.mp4 00:12:30 90 -o trim.mp4
Output (-o):
May appear before or after the file argument.
If <output> has no extension, the input's extension is appended.
If the resolved output exists, you'll be asked whether to overwrite;
declining (default) auto-increments to '<name>_NN.<ext>'. Non-interactive
runs always auto-increment.
EOF
}
die() {
printf '%s: %s\n' "$prog" "$1" >&2
exit 1
}
require_ffmpeg() {
command -v ffmpeg >/dev/null 2>&1 || die "ffmpeg not found in PATH"
command -v ffprobe >/dev/null 2>&1 || die "ffprobe not found in PATH"
}
# Extensions eligible for concat matching; keeps sidecar files
# (.srt, .txt, ...) out of the glob results.
is_video_ext() {
case "$1" in
mp4|mkv|webm|mov|avi|ts|m2ts|flv|wmv|m4v) return 0 ;;
*) return 1 ;;
esac
}
# stream_sig <file>
# Prints a comparable signature of the first video/audio streams.
# Files must share a signature to be concat-able with -c copy.
stream_sig() {
_v=$(ffprobe -v error -select_streams v:0 \
-show_entries stream=codec_name,width,height -of csv=p=0 "$1") || return 1
_a=$(ffprobe -v error -select_streams a:0 \
-show_entries stream=codec_name,sample_rate,channels -of csv=p=0 "$1") || return 1
printf 'video=%s audio=%s' "$_v" "$_a"
}
# Globals set by resolve_output (avoids subshell variable loss):
# RESOLVED_OUTPUT - final output path
# FF_OVERWRITE - '-y' if user chose overwrite, '' otherwise
RESOLVED_OUTPUT=""
FF_OVERWRITE=""
increment_name() {
_base="${1%.*}"
_ext="${1##*.}"
_n=1
while [ -e "${_base}_$(printf '%02d' "$_n").${_ext}" ]; do
_n=$((_n + 1))
done
printf '%s_%02d.%s' "$_base" "$_n" "$_ext"
}
# resolve_output <user-output> <default-extension>
# Sets globals RESOLVED_OUTPUT and FF_OVERWRITE. Must run in current shell
# (NOT inside $(...)) to propagate FF_OVERWRITE to the caller.
resolve_output() {
_out="$1"
_default_ext="$2"
FF_OVERWRITE=""
[ -n "$_out" ] || die "-o requires a non-empty argument"
case "$_out" in
*/) die "output cannot be a directory: $_out" ;;
*.*) ;;
*) _out="${_out}.${_default_ext}" ;;
esac
if [ -e "$_out" ]; then
if [ -t 0 ] && [ -t 2 ]; then
printf '%s: %s exists. Overwrite? [y/N] ' "$prog" "$_out" >&2
_ans=""
read _ans || _ans=""
case "$_ans" in
[yY]|[yY][eE][sS]) FF_OVERWRITE="-y" ;;
*) _out=$(increment_name "$_out") ;;
esac
else
_out=$(increment_name "$_out")
fi
fi
RESOLVED_OUTPUT="$_out"
}
cmd_concat() {
require_ffmpeg
input_file="$1"
user_output="$2"
pattern="${input_file%.*}"
extension="${input_file##*.}"
[ "$pattern" != "$input_file" ] || die "input file must have an extension: $input_file"
set +e
set -- "${pattern}"*.*
set -e
# Unmatched glob remains literal in POSIX sh; check via -e on the first entry.
if [ ! -e "$1" ]; then
die "no files match '${pattern}*.*'"
fi
# Rotate args: keep only video files, dropping previous combine outputs.
i=$#
while [ "$i" -gt 0 ]; do
candidate="$1"
shift
i=$((i - 1))
case "$candidate" in
*_combine.*|*_combine_[0-9]*.*) continue ;;
esac
is_video_ext "${candidate##*.}" || continue
set -- "$@" "$candidate"
done
if [ $# -eq 0 ]; then
die "no video files match '${pattern}*.*'"
fi
if [ $# -eq 1 ]; then
printf '%s: warning: only one file matches (%s); nothing to concat\n' \
"$prog" "$1" >&2
exit 1
fi
# Mixed container extensions break the concat demuxer's timestamp
# offsetting even with identical codecs, so non-mkv inputs are first
# remuxed (lossless stream copy) into the one container that holds
# anything: mkv. The output then uses mkv too.
mixed=""
output_ext="$extension"
for video do
if [ "${video##*.}" != "$extension" ]; then
mixed=1
output_ext="mkv"
break
fi
done
# Refuse mismatched streams up front; -c copy would produce a broken
# file instead of erroring.
ref_sig=""
ref_file=""
for video do
sig=$(stream_sig "$video") || die "ffprobe failed on: $video"
if [ -z "$ref_sig" ]; then
ref_sig="$sig"
ref_file="$video"
elif [ "$sig" != "$ref_sig" ]; then
die "stream mismatch, cannot concat with stream copy:
$ref_file: $ref_sig
$video: $sig"
fi
done
if [ -n "$user_output" ]; then
resolve_output "$user_output" "$output_ext"
output_file="$RESOLVED_OUTPUT"
else
output_file="${pattern}_combine.${output_ext}"
FF_OVERWRITE=""
fi
file_list=$(mktemp)
remux_dir=""
[ -n "$mixed" ] && remux_dir=$(mktemp -d)
trap 'rm -rf "$file_list" ${remux_dir:+"$remux_dir"}' EXIT INT HUP TERM
n=0
for video do
n=$((n + 1))
if [ -n "$mixed" ] && [ "${video##*.}" != "mkv" ]; then
printf '%s: remuxing %s -> mkv for concat\n' "$prog" "$video" >&2
full_path="$remux_dir/$(printf '%03d' "$n").mkv"
ffmpeg -hide_banner -v error -i "$video" -c copy "$full_path"
else
full_path=$(realpath "$video")
fi
# concat demuxer: escape single quotes by closing/reopening.
escaped=$(printf '%s' "$full_path" | sed "s/'/'\\\\''/g")
printf "file '%s'\n" "$escaped" >>"$file_list"
done
count=$#
set -- ffmpeg -hide_banner
[ -n "$FF_OVERWRITE" ] && set -- "$@" "$FF_OVERWRITE"
set -- "$@" -f concat -safe 0 -i "$file_list" -c copy "$output_file"
"$@"
printf 'Combined %d files into %s\n' "$count" "$output_file"
}
cmd_cut() {
require_ffmpeg
file="$1"
start="$2"
end_or_dur="$3"
user_output="$4"
[ -f "$file" ] || die "file not found: $file"
base="${file%.*}"
ext="${file##*.}"
[ "$base" != "$file" ] || die "input file must have an extension: $file"
if [ -n "$user_output" ]; then
resolve_output "$user_output" "$ext"
out="$RESOLVED_OUTPUT"
else
FF_OVERWRITE=""
if [ -f "${base}_cut.${ext}" ]; then
n=1
while [ -f "${base}_cut_$(printf '%02d' "$n").${ext}" ]; do
n=$((n + 1))
done
out="${base}_cut_$(printf '%02d' "$n").${ext}"
else
out="${base}_cut.${ext}"
fi
fi
# -ss / -to / -t go BEFORE -i so they apply as input options against the
# source's absolute timestamps. Placed after -i, -to/-t use the output's
# reset timeline and cut for the entire END value instead of START->END.
set -- ffmpeg -hide_banner
[ -n "$FF_OVERWRITE" ] && set -- "$@" "$FF_OVERWRITE"
set -- "$@" -ss "$start"
if [ -n "$end_or_dur" ]; then
case "$end_or_dur" in
*:*) set -- "$@" -to "$end_or_dur" ;;
*[!0-9.]*) die "invalid end/duration: $end_or_dur" ;;
*) set -- "$@" -t "$end_or_dur" ;;
esac
fi
set -- "$@" -i "$file" -c copy "$out"
"$@"
printf 'Created %s\n' "$out"
}
# ---- Argument parsing ----
[ $# -eq 0 ] && { usage; exit 0; }
mode_explicit=""
out_override=""
# Rotate args: separate flags from positionals while preserving original order
# of positionals. After the loop, $@ holds positional args only.
i=$#
while [ "$i" -gt 0 ]; do
arg="$1"
shift
i=$((i - 1))
case "$arg" in
-h|--help)
usage; exit 0 ;;
-j|concat)
[ -z "$mode_explicit" ] || die "mode specified twice"
mode_explicit="concat" ;;
-c|cut)
[ -z "$mode_explicit" ] || die "mode specified twice"
mode_explicit="cut" ;;
-o)
[ "$i" -gt 0 ] || die "-o requires an argument"
out_override="$1"
shift
i=$((i - 1))
[ -n "$out_override" ] || die "-o requires a non-empty argument" ;;
-o=*)
out_override="${arg#-o=}"
[ -n "$out_override" ] || die "-o requires a non-empty argument" ;;
-*)
die "unknown option: $arg" ;;
*)
set -- "$@" "$arg" ;;
esac
done
if [ -z "$mode_explicit" ]; then
case $# in
1) mode_explicit="concat" ;;
2|3) mode_explicit="cut" ;;
*) usage >&2; exit 1 ;;
esac
fi
case "$mode_explicit" in
concat)
[ $# -eq 1 ] || die "concat takes 1 file argument, got $#"
cmd_concat "$1" "$out_override"
;;
cut)
case $# in
2) cmd_cut "$1" "$2" "" "$out_override" ;;
3) cmd_cut "$1" "$2" "$3" "$out_override" ;;
*) die "cut takes 2 or 3 positional arguments, got $#" ;;
esac
;;
esac
|