How do I flip only a subsection of a video using ffmpeg
?
Here, -filter_complex
is your friend, as it can create chains of filtered input. We will still be using the hflip
filter mentioned in the question in the filtergraph.
You can apply to a subsection like so:
ffmpeg -i input.mp4 -filter_complex "[0:v]trim=start=0:duration=90[a];\
[0:v]trim=start=90:duration=30,setpts=PTS-STARTPTS[b];\
[b]hflip[c];\
[a][c]concat[d];\
[0:v]trim=start=120:duration=60,setpts=PTS-STARTPTS[e];\
[d][e]concat[out1]" -map [out1] flip.mp4
One line for easy copy + pasting:
ffmpeg -i input.mp4 -filter_complex "[0:v]trim=start=0:duration=90[a];[0:v]trim=start=90:duration=30,setpts=PTS-STARTPTS[b];[b]hflip[c];[a][c]concat[d];[0:v]trim=start=120:duration=60,setpts=PTS-STARTPTS[e];[d][e]concat[out1]" -map [out1] flip.mp4
Explanation:
Using a filtergraph is a bit like creating a chain of actions, and there is a nice visual explanation1 of this in the 'Filtering Introduction' section of the filters documentation. Filters work with inputs - that's the bit you see before the filter, eg [0:v]
(video of first input stream) or [a]
(a created output named a
) - and outputs. That is to say, an input or inputs are transformed according to a filter
and then output either as an output or outputs.
We have a simple set of actions here, and if we go through those in sequence we can build up a filtergraph of inputs and outputs.
Segments
Create 3 segments of video (from input [0:v]
) using trim
:
- First segment (90 seconds), do nothing to (output as
[a]
)
- Second segment (30 seconds),
hflip
and setpts
to avoid duration issues (output trim as [b]
and pass that to hflip
to output as [c]
)
These two are then concat
ed together to make the output [a]+[c] -> [d]
(duration: 120 s)
- Third segment (60 seconds), set PTS again (output as
[e]
)
Join segments to make output [d] + [e] -> [out1]
, and -map
that to final output in file.
That gives you a video of the same duration as the original (180 s), but with a section of 30 seconds in the middle which are horizontally flipped2.
1:
In libavfilter
, a filter can have multiple inputs and multiple outputs. To illustrate the sorts of things that are possible, we consider the following filtergraph.
[main]
input --> split ---------------------> overlay --> output
| ^
|[tmp] [flip]|
+-----> crop --> vflip -------+
This filtergraph splits the input stream in two streams, then sends one stream through the crop filter and the vflip filter, before merging it back with the other stream by overlaying it on top.
2 Tested using ffmpeg version N-72939-g5b0f55a