Computer >> 컴퓨터 >  >> 소프트웨어 >> 소프트웨어

FFmpeg 가이드 - 멀티미디어 원스톱 상점

수년 동안 어떤 형태의 멀티미디어 편집을 해야 하는 경우가 많았습니다. 오디오, 비디오, 이름을 지정합니다. 내 Youtube 채널을 위해 재미없는 클립을 만들든, 음악을 추출하거나 변환하든, 자막을 삽입하든, 명령줄에서 ffmpeg를 사용하고 항상 프로세스를 즐기면서 이 겸손한 프로그램의 기능에 미묘하게 놀랐습니다. .

그래서 저는 ffmpeg에 대한 보다 포괄적인 가이드를 작성해야 한다고 생각했습니다. 다양한 작업과 기능을 나열한 다음 실제 예제와 사용 사례를 둘러싸는 가이드입니다. 2008년 플래시 편집 튜토리얼에서 ffmpeg에 대해 처음으로 언급했지만 이제는 최신 기사가 필요합니다. 그것은 커맨드 라인이 될 것이고, 괴상할 것이지만, 또한 재미있을 것입니다. 나를 따르라.

기본

Ffmpeg는 거의 모든 Linux 배포판에서 사용할 수 있으며 Windows 및 Mac용 빌드도 있습니다. 무엇을 할 수 있는지 알고 싶다면 인수 없이 또는 선택적 -hide_banner 플래그를 사용하여 ffmpeg를 실행하여 기능을 확인할 수 있습니다. 또한 주 프로그램과 그 많은 하위 명령에 대한 도움말 옵션을 사용할 수 있습니다. 눈부신 기능의 배열은 위협적일 수 있으므로 천천히 그러나 확실하게 진행하겠습니다. 그런 다음 매우 깔끔한 실제 문서를 잊지 마세요.

변환 및 트랜스코딩

가장 일반적인 작업 중 하나는 파일을 한 형식에서 다른 형식으로 변환하는 것입니다. FLV 클립에서 오디오 파일을 추출하는 방법에 대한 제 예를 기억하십니까? 같은 것. 그러나 카메라에 녹화된 비디오를 MP4와 같은 것으로 변환하거나 OGG 파일을 MP3 등으로 변환할 수 있습니다. 끝없이 다양한 시나리오가 있으며 ffmpeg에는 지원되는 모드와 형식도 끝없이 많습니다. 일반적으로 수행할 작업은 다음과 같습니다.

  • 입력 파일을 지정합니다.
  • 원하는 비디오 및 오디오 코덱을 지정합니다.
  • 출력 파일을 지정합니다.

비디오 스트림을 조작하지 않으려면 복사 코덱을 사용할 수 있습니다. 오디오도 마찬가지입니다. 실제 인코딩을 변경하지 않고 MOV에서 MP4로 이동하는 것과 같이 컨테이너를 변경하려는 경우 이 옵션을 사용할 수 있습니다.

ffmpeg -i MVI_1348.MOV -c:v 복사 -c:a 복사 new.mp4

참고:모든 형식이 모든 코덱과 옵션을 지원하는 것은 아니므로 모든 경우에 작동하지는 않습니다. 좋아요:

[mp4 @ 0x55a21519fb20] 스트림 #0에서 코덱 vp8에 대한 태그를 찾을 수 없습니다. 코덱은 현재 컨테이너에서 지원되지 않습니다. 매핑:
스트림 #0:0 -> #0:0(복사)
스트림 #0:1 -> #0:1(복사)
마지막 메시지 1회 반복

특정 스트림(오디오, 비디오, 자막 또는 데이터)만 추출하려는 경우 다른 스트림의 처리를 억제할 수 있습니다(작업에 필요한 시간 및 CPU 주기 절약). 예를 들어 결합된 오디오-비디오 미디어 파일의 오디오만 원하는 경우 -vn(비디오 없음) 옵션을 사용할 수 있습니다.

ffmpeg -i MVI_1348.MOV -vn -ar 44100 -ab 192k 사운드 전용.mp3

이 뛰어난 유틸리티는 작업 방식에 많은 유연성을 제공합니다. 예를 들어 codec:v, vcodec 및 c:v는 동일하며 원하는 것을 사용할 수 있습니다. 위와 같이 오디오 출력만 원하는 경우 ffmpeg는 -vn도 의미한다고 추측하고 가정합니다. -f 플래그를 사용하여 출력 형식을 강제할 수도 있지만 이 도구는 명령의 최종 결과를 추측하려고 시도합니다. 예를 들어 -f mp3 또는 acodec mp3를 사용할 수 있습니다.

다른 코덱에는 다른 옵션이 있습니다. 예를 들어 오디오 파일의 경우 오디오 샘플링 속도와 오디오 비트 전송률, 채널 수 등을 지정할 수 있습니다. 일부 옵션을 건너뛰면 명령이 실패하거나 기본값이 사용됩니다.

규모 및 품질

또 다른 일반적인 작업은 비디오 크기(해상도)와 스트림 품질을 변경하는 것입니다. Ffmpeg를 사용하면 다양한 방식으로 이를 수행할 수 있습니다. 비율을 강제로 적용하거나(기본 종횡비를 깨거나) 수직 또는 수평 값과 매직 한정자를 지정하여 비율을 유지할 수 있습니다. 비디오 테두리를 자르고 스트림을 다시 인코딩할 수 있습니다. 예시는 이 단계에서 보증됩니다.

ffmpeg -i 입력.avi -c:v mpeg4 -vtag xvid -qscale:v 3 -c:a libmp3lame -qscale:a 4 출력.avi

여기에 무엇이 있습니까? 품질이 3(qscale)으로 설정된 MPEG4 비디오 스트림을 사용하여 AVI 입력 파일을 트랜스코딩하고 있습니다. 일부 코덱의 경우 품질 범위는 1-31이며 1이 가장 높습니다. 여러 일반 입력 파일에 대해 테스트했으며 최고 품질은 일반적으로 크기가 약 두 배인 반면 3 또는 4는 약 20-30% 감소했습니다. Vtag xvid는 MPEG-4 전용 옵션입니다. 마찬가지로 오디오에 LAME을 사용하고 있습니다.

ffmpeg -i MVI_1348.MOV -vfilters scale=1280:-1 -c:a copy scaled.mp4

This example shows video scaling (you can use -vf or -vfilters), with the aspect ratio being preserved through the -1 qualifier. We don't change the quality of the stream. The audio stream is simply being copied into the output container. If your original video has a higher resolution than the stated one, then you will be downscaling, and if it's lower, then you will be upscaling.

Image extraction, combination, GIFs

Ffmpeg can also manipulate pictures, even though it's a media utility. But hey, pictures are media, and essentially, videos are moving pictures, right! Some of the tasks you'd want - extract frames from a video in order to create thumbnails (high-quality ones, too) rather than manually pausing video or creating hectic screenshots. You can also do the opposite - combine stills into a stopmotion video - or a full one. You can also convert videos to animated GIFs, which can be handy for dank memeism around the Web. Once again, we shall demonstrate with some ... dank examples.

ffmpeg -i input.mp4 -r 1 -f image2 thumb-%3d.png

We specify an input file, we specify the rate (in this case we want 1 image per 1 second of video), we specify the format (image2), and we specify the output format. In this case, we're doing something clever. If you've ever seen C language code, this will look familiar. We want the numbering sequence for the thumbnails to have three digits. You can choose any amount of digits, but ideally, you want more than the expected number of extracted images.

FFmpeg 가이드 - 멀티미디어 원스톱 상점

Then, combining images into a video is very similar:

ffmpeg -f image2 -i thumb-%3d.png stopmotion.mp4

You can also specify the rate (you want your video to be something like 24 or 30 FPS), but we will touch on this a bit more later in the guide, when we talk about making video playback slower and/or faster. And since we're talking about images, you can resize them too:

ffmpeg -i thumb-004.png -vf scale=400:-1 test.png

Animated GIFs are really interesting. Also rather simple to create. Just specify an input file and set the output to have a gif extension. Ffmpeg will auto-guess the rest and create nice, high-quality animated GIF for you.

ffmpeg -i MVI_6654.MOV test.gif

FFmpeg 가이드 - 멀티미디어 원스톱 상점

Finally, the opposite of GIFs, you may also want to have a video composed of a single image - a constant preview but then have something like music or a podcast playing in the background. Ffmpeg allows you to do this with a clever trick.

ffmpeg -loop 1 -i thumb-001.png -i sound-only.mp3 -c:v libx264 -shortest video-static-image.mp4

We provide two inputs, with the first being an image set to loop. We're also re-encoding the video. But since the image is set to loop indefinitely, we also need the shortest option, so the operation ends when the shortest clip ends, which would be the video in this case.

Splitting and joining videos

This is another useful scenario. If you have a very big clip, but you only need a few minutes or seconds, ffmpeg can cut out the necessary pieces. Likewise, you can combine multiple files into one stream - both video and audio. Ffmpeg lets you choose the desired start and end timestamps, so you have a lot of leeway in how you do handle the task.

-t duration record or transcode "duration" seconds of audio/video
-to time_stop record or transcode stop time
-fs limit_size set the limit file size in bytes
-ss time_off set the start time offset
-sseof time_off set the start time offset relative to EOF
-seek_timestamp enable/disable seeking by timestamp with -ss
-timestamp time set the recording timestamp ('now' to set the
current time)

So, you may want to try something like:

ffmpeg -i MVI_1348.MOV -ss 4 -t 4 spliced.mp4

This command will extract 4 seconds from the input clip starting at time offset of 4 seconds into the clip. You can use short notation (4 indicates seconds) or use the full one hh:mm:ss.mmm. This gives you accuracy down to one millisecond, which ought to be more than enough for all practical usecases.

Joining files is a bit more complicated. Technically termed concatenation (concat), it works differently from the cutting option. You do not specify the desired parts you want to join on the command line, you put them into a file, using a very specific notation, and then read that file with ffmpeg. 예를 들어:

ffmpeg -f concat -i list.txt -codec copy joined.mp4

The contents of the list.txt file will be:

file 'part-1.mp4'
file 'part-2.mp4'
file 'part-3.mp4'

Please note the usage of the word file and single quotation marks. You can use both absolute and relative paths. If you make a mistake in the file format, you will see an error:

[concat @ 0x555ca89c38c0] Line 1:unknown keyword 'part-1.mp4'
list.txt:Invalid data found when processing input

If you try to provide the list of files on the command line (rather than the text file):

part-1.mp4:Invalid data found when processing input

Embed and extract subtitles

Remember my VLC &subtitles article? Well, if you're not intimidated by the command line, you can do the same thing with ffmpeg. As a trivial example, say you have separate audio and subtitle files. Without any additional processing, you can just use the video filtering option for this:

ffmpeg -i input.avi -vf subtitles=subtitle.srt output.avi

A more complicated use case, the command below will take separate MP4 and subtitle files, and combine them into an output file with video transcoding. The -map options (showing twice, not an error) define the order the streams will be mapped into the output. But then there's a clever and somewhat confusing listing of codecs. Because we have multiple streams, we only want to manipulate the video part - but not audio or subtitles.

To that end, -c copy specifies all codecs should be copied, but using -c:v provides an override to this option, and the video stream will be transcoded. Since we're using the libx264 codec, we're also using Constant Rate Factor (CRF) option for variable bitrate, set to 23 (ranges from lossless 0 to lowest-quality 51) and the veryfast preset, which creates a relatively small output.

ffmpeg -i input.mp4 -i subtitle.srt -map 0 -map 1 -c copy -c:v libx264 -crf 23 -preset veryfast output.mp4

Extracting subtitles takes the following form:

ffmpeg -txt_format text -i input.file out.srt

Speed up and slow videos

This is another interesting usecase. Like any human being, you may want to take any video, speed it up 2x and then add Benny Hill music, and there should be much rejoicing. You could also slow down action, and then, to spice things up, also add smoothing so the slowed sequence does not feel stilted.

For example, we may have our stop motion video - with only say 15-20 thumbnails, it takes only a second to play. So you may want to stretch it to say 5 seconds, but that means each frame will show for five times as long. Instead you could potentially "insert" extra frames to make it look like a smooth slo-mo. We did this with an interior design gallery back in the day. We use AviSynth and VirtualDub for this task.

The video speed filter works by changing the presentation timestamp (PTS) of each video frame. Simply put, fractional values speed up the video, multipliers higher than 1 slow it down. When you speed it up, ffmpeg will drop frames, but you can specify a higher framerate. To preserve the original, you can multiply the FPS in your input by the 1/PTS you're using. So if you double the speed of your 24FPS clip, you should use 48FPS rate.

ffmpeg -i input.mp4 -filter:v "setpts=0.5*PTS" output.mp4

ffmpeg -i input.mp4 -r 96 -filter:v "setpts=0.25*PTS" output.mp4

ffmpeg -i input.mp4 -filter:v "setpts=2*PTS" output.mp4

Smoothing videos is more complicated. I did have to consult the documentation. Essentially, for a video that's slowed down 5 times (and 5 times longer than the original), I'm using video interpolation to create the smoothing effect. Here, too, you need to add FPS, so that ffmpeg has sufficient data to guess the frames in between. In my example, 5x slowed down, you need 5x24 FPS (original speed), ergo 120 FPS.

ffmpeg -i input.mp4 -filter:v "minterpolate='mi_mode=mci:mc_mode=aobmc:vsbmc=1:fps=120'" output.mp4

This is a CPU-intensive task, and it can take a while to finish. I used ffplay to preview videos, and I found the results reasonable, but you can't really magic something from nothing, so while this works, it works well when there's a small amount of data missing (not one frame per second every two seconds or such).

For audio, you can use atempo. This option has a range of 0.5-2.0, which means half or double the speed at most, however, it is possible to chain multiple atempo filters to get additional speed changes. Something like the example below:

ffmpeg -i input.mp4 -filter:a "atempo=2.0,atempo=2.0" -vn output.mp4

And that brings us to the end of this tutorial.

결론

I hope you found this fruitful, enjoyable and relevant. Ffmpeg is the workhorse - no, it's a whole cavalry - of audio and video tweaking in Linux, and it has so many practical tools, options and configurations that getting started can be confusing and maybe even intimidating. Those emotions should have evaporated by now as you've read through this tutorial.

Anyway, we talked about conversion and transcoding, scaling and quality, image extraction, combination and GIF creation, splitting and joining of videos, subtitle extraction and embedding, video speedup and slowdown, and then some. That should keep you happy and busy for a while. If you have any ffmpeg-related requests or questions, fire away, the email is only a click away. Or something. Finally, if this tutorial was truly useful, do give some love back, because why not.

건배.