add Forum inability to register solution
[goodguy/cin-manual-latex.git] / parts / FFmpeg.tex
1 \chapter{FFmpeg Interactions}%
2 \label{cha:ffmpeg_interactions}
3 \index{ffmpeg}
4
5 \CGG{} uses ffmpeg for decoding and encoding media, thus there are many opportunities available to manipulate options.
6
7 \section{FFmpeg Early Probe Explanation}%
8 \label{sec:ffmpeg_early_probe_explanation}
9 \index{ffmpeg!early probe}
10 \index{ffmpeg!try first}
11 \index{ffmpeg!try last}
12
13 When you open media, a series of libraries and codec functions are used to \textit{probe} the data, to see if it can determine the type of file format and codec parameters needed to correctly decode the file.  If ffmpeg probes early -- \textit{Try FFMpeg first} is in effect for the FF button (green icon) -- it will usually find some way to try to decode just about any contemporary media file.  But there are some times that the built in codecs are actually a better choice.  A lot of this may fall into the category of personal preference.  For example, some may prefer the mpeg library in the \CGG{} code over the ffmpeg code because it has more decoding capability and seems to be more robust when the media is damaged.  In that case you will want the FF button to read \textit{Try FFMpeg last}.
14
15 To summarize, if ffmpeg probes early, you will never get to use the built in libraries, and if you want to skip over buggy old libraries, use ffmpeg early probe enabled so that the newest code will be tried first.
16 The green icon is located in the upper right hand corner of the main window.
17
18 When the icon is green, ffmpeg probes early is enabled and you will see it reads
19  \textit{Currently: Try FFMpeg first} when moving over the icon button in the upper 
20 right hand corner of the screen.  When the icon is capital "C", ffmpeg probes early is disabled so that 
21 ffmpeg probes late and it reads \textit{Currently: Try FFMpeg last}.  The initial default state of 
22 the icon is on, that is, ffmpeg probes first. Suggestion is to leave it on except in a few special 
23 cases where it may be better to have early probes disabled.  When you mouse over the main menu icon 
24 toggle button, the text displays ffmpeg's \textit{Currently} set position.  Just left mouse click to change to the other setting.
25 The ffmpeg early probe state is saved between sessions and is also affected by choices made in Probe Order (refer to section~\nameref{sub:probe_order_loading_media}). It is important to note that the various file indexes may need to be rebuilt if you change which codec is being used to decode the file.  There is a warning popup to remind you when you change the default ffmpeg early probe state (unless you have checked the box to no longer show the warning).  You can easily rebuild the index for a specific media file by going to the Resources window, right mouse click on that media, and choose \texttt{Rebuild Index} from the popup choices.
26
27 Figure~\ref{fig:ff} shows (1) greenish colored icon in upper right hand corner of main window indicating
28 that ffmpeg early probes is enabled; (2) \textit{Try FFMpeg last}  indicator message for ffmpeg early probes enabled (note that the icon is different because you highlighted the icon); and (3) "C"  icon indicates ffmpeg will be used last and you are changing the behavior so that \CGG{} warns you accordingly.
29
30 \begin{figure}[htpb]
31     \centering
32     \includegraphics[width=0.9\linewidth]{ff.png}
33     \caption{The three icons of \textit{FF Probe}}
34     \label{fig:ff}
35 \end{figure}
36
37 \section{How to Create FFmpeg Options Files}%
38 \label{sec:create_ffmpeg_options_files}
39 \index{ffmpeg!options files}
40
41 AppImage does not provide this capability. This section describes how the FFmpeg options files work for decoding and encoding and goes into great detail.  It will make more sense if you look at \CGG{}'s ffmpeg config directory and the \CGG{} menus at the same time.  
42 It is meant to include everything necessary for complete understanding.  You will be able to personalize your own options files without knowing all of the information included below if you know the basics.  The word encoding is used interchangeably with the word rendering.
43 The possible combinations for ffmpeg options files are literally combinatorial -- that is a lot (factorial!).  The allowed media file format / codec choices are much more flexible than you might realize.  When the ffmpeg design was initially added, some parameter files which describe the choices which the program uses had to be created.  There are way too many to enumerate in the deliverable \CGG{} package.  Some quite detailed information for how ffmpeg options work is given here and hopefully, enough basics for simple understanding.  It may all seem complicated at first, but will become obvious.
44
45 \subsection{File naming convention}%
46 \label{sub:file_naming_convention}
47
48 AppImage does not provide this capability. In \CGG{}'s ffmpeg configuration directory you will see files as listed and described below.  File type and extension names are the key for \CGG{}'s use of ffmpeg.  Basically the \texttt{.opts} file extension represents options; \texttt{.dfl} represents defaults; and all the rest are media types.  For example one media type is quicktime so that \texttt{*.qt} file names would be the \textit{quicktime} choices.  In the file names below, \textit{ext} refers to a set of files with file names matching the \texttt{*.ext} file extension.  And \textit{typ} refers to a type of format / codec combination used, that is, the media type.
49
50 In the ffmpeg configuration directory there are a series of options files used when encoding or decoding audio or video.  They are read in the order from top to bottom and only the files needed for the current operation are added to the active configuration.
51
52 \begin{center}
53     \small
54     \begin{tabular}{l m{25em}}
55         \toprule
56         ffmpeg/ffmpeg.opts & global ffmpeg options, always used \\
57         ffmpeg/decode.opts & global decoder options, used when opening existing files for decoding \\
58         ffmpeg/encode.opts & global encoder options, used when creating new files for encoding \\
59         ffmpeg/audio/audio.opts & audio encoder options, used when creating audio streams \\
60         ffmpeg/video/video.opts & video encoder options, used when creating video streams \\
61         ffmpeg/plugin.opts & parameters for ffmpeg filters as audio/video plugins \\
62         \bottomrule
63     \end{tabular}
64 \end{center}
65
66 \paragraph{Decoder options:} \index{ffmpeg!decoder options} Normally, only \texttt{ffmpeg.opts} and \texttt{decode.opts} are used when reading/decoding files, but may be specialized if a \texttt{<path>/media.opts} exists for a given \texttt{<path>/media.ext} file.  For example, if you want to only fail on fatal errors and to always use the video filter, edgedetect, when working with your media file \texttt{dreaming.y4m}, then create a file \texttt{dreaming.opts} in the same directory with the contents of \textit{loglevel=fatal} on the first line and \textit{video\_filter=edgedetect} on the next.  These specialized settings will override the defaults.  The fatal loglevel is especially handy for lesser quality media.
67
68 \paragraph{Encoder Options:} \index{ffmpeg!encoder options} Within the audio/video subdirectories of the first level ffmpeg directory, the \texttt{typ.ext} files are for encoder (rendering) setups.
69
70 \begin{center}
71     \begin{longtable}{l p{23em}}
72         \toprule
73         ffmpeg/audio & directory of audio encoder settings \\
74         \midrule
75         audio.opts & options used by all audio encoders \\
76         typ1.ext, typ2.ext, … & are all *.ext type choices for encoding audio \\
77         ext.dfl & contains the default selection used when ext is first selected \\
78         \midrule
79         ffmpeg/video & directory of video encoder settings \\
80         \midrule
81         video.opts & options used by all video encoders \\
82         typ1.ext, typ2.ext, … & are all *.ext type choices for encoding video \\
83         ext.dfl & contains the default selection used when ext is first selected \\
84         \midrule
85         ffmpeg/format & presets needed to initialize audio / video formats \\
86         \bottomrule
87     \end{longtable}
88 \end{center}
89
90 \subsection{Option File Format / Content}%
91 \label{sub:option_file_format_content}
92 \index{ffmpeg!option file format}
93
94 AppImage does not provide this capability.  For the option files a specific format must be followed in creating the file content.
95 In \texttt{typ.ext} encoder parameter files, the first line is defined as:
96
97 \begin{lstlisting}[style=sh]
98       muxer codec
99 (or)    muxer codec | bitstream filter [ bitstream filter options ]
100 \end{lstlisting}
101
102 where the | represents piping the codec data through the bitstream filter. The rest of the lines in the file should look as follows:
103
104 \begin{lstlisting}[style=sh]
105       # in column one is a comment
106       id1   value1
107 (or)    id2 = value2
108 \end{lstlisting}
109
110 Only one equals sign is allowed and it is just for readability.  There may be any number of id/value pair lines in a media definition, including zero. A typical line might be:
111
112 \begin{lstlisting}[style=sh]
113       bitrate 4000000
114 (or)    bitrate = 5000000
115 \end{lstlisting}
116
117 There are 4 special id's recognized by \CGG{} which cause special processing.  They are:
118
119 \begin{description}
120     \item[duration] overrides the probe duration when opening media for decoding
121     \item[video\_filter] adds a video stream filter, eg.\ edgedetect,\dots at the stream level
122     \item[audio\_filter] adds an audio stream filter, eg.\ echo,\dots at the stream level
123     \item[loglevel] sets the library logging level, as quiet, panic, \dots verbose, debug
124 \end{description}
125
126 All other id's should be in the ffmpeg documentation, and correspond to the global, muxer, and codec option names and values used by ffmpeg.  For example to set the aspect ratio to 4:3, use:
127
128 \begin{lstlisting}[style=sh]
129 aspect 4:3
130 \end{lstlisting}
131
132 Below shows an example:  \texttt{decode.opts} which is used when the ffmpeg decoder is initialized.
133
134 \begin{lstlisting}[style=sh]
135 # apply at init decode
136 loglevel=fatal
137 formatprobesize=5000000
138 scan_all_pmts=1
139 threads=auto
140 \end{lstlisting}
141
142 The encoder options you see in the \CGG{} menus depend on the files in these directories, \textsc{NOT THE CODE}.  If you add files, you will get to use more variety.
143
144 In the \textit{\CGG{}} directory, which contains the ffmpeg configuration folder, there are the choices the program uses.  When you open an ffmpeg format popup dialog, the listbox contains all of the codec types which are identified by the \texttt{file.ext} extensions.  Decoding has only a few options, since the ffmpeg file probes determine most of the options by looking at the media being opened, but encoding media requires a lot of setup.  Below are some of the folders and files used to determine the configurations used by ffmpeg to decode and encode files.
145
146 These extensions create audio / video media classes:
147
148 \texttt{dvd \quad  m2ts \quad  mkv \quad  mp3 \quad  mp4 \quad  mpeg  \quad qt \quad  pro}
149
150 which become the choices in the render pulldown menu.
151
152 So if you want to create a \textit{mov} codec class, add two new files to the ffmpeg configuration directory:
153
154 \texttt{audio/aud.mov}  and  \texttt{video/vid.mov}
155
156 Now you will see this as what you can choose in the rendering choices for ffmpeg.
157 Inside the file you will see that the first line is special.  It is the muxer and codec.  For example:
158
159 \begin{lstlisting}[style=sh]
160 h264     libx265
161 \end{lstlisting}
162
163 The contents may be something like:
164
165 \begin{lstlisting}[style=sh]
166 # <path>/video/vid.mov 
167 mp4 libx265
168 bitrate 4000000
169 \end{lstlisting}
170
171 This will code an mp4 formatted file using the \textit{lib264} codec encoder.
172
173 For audio and video together, the mux format must agree between the aud.mov and vid.mov files when they are to be used together.  The stream muxer must be the same for all the streams in the file being written.
174 For example:
175
176 \begin{lstlisting}[style=sh]
177 # <path>/audio/aud.mov
178 mp4 pcm_mulaw
179 \end{lstlisting}
180
181 This will create mp4 media using audio format \textit{pcm\_mulaw} coding.
182
183 Both the audio and the video are using mp4 mux format, and so there will be 2 streams:
184 \begin{enumerate}
185     \item x265 video
186     \item pcm\_mulaw audio
187 \end{enumerate}
188
189 When the menu popup is created, there may be many choices for that class type, so you may want defaults.  That can be specified as:
190
191 \texttt{audio/<class>.dfl}  and  \texttt{video/<class>.dfl}
192
193 \begin{lstlisting}[style=sh]
194 # audio/mov.dft
195 aud.mov
196 \end{lstlisting}
197
198 \begin{lstlisting}[style=sh]
199 # video/mov.dft =
200 vid.mov
201 \end{lstlisting}
202
203 The above will be the default choice when the menu opens.  
204
205 When you see problems in using the new options files you have created and put into place, add the following line to \texttt{ffmpeg/encoder.opts}:
206
207 \begin{lstlisting}[style=sh]
208 loglevel=verbose
209 \end{lstlisting}
210
211 sometimes that will be enough to see what has caused a failure, or even catch unexpected results.
212
213 There is an \textsc{EXCEPTION} to all of the above because of a conflict between ffmpeg and the x264 person making the detection of default ffmpeg settings terminate with an error.  If you get this error, you must workaround this termination by including parameters that don't match $5$ or more of the normal expected values.  So you just have to change a few parameters to avoid the probe detection.  Here is an example where you will notice the \textit{x264-params} line tweaking values to throw off the detection/error termination code.
214
215 \begin{lstlisting}[style=sh]
216 # <path>/ffmpegvideo/test.mp4
217 mp4 libx264
218 preset=slow
219 x264-params keyint=25:min-keyint=4:qpmin=3:qpmax=33:qp_step=4:merange=8
220 crf 20
221 \end{lstlisting}
222
223 For more examples, look around the ffmpeg directory for examples which may be close to what you are trying to use, and see if the parameters look usable. 
224
225 This is quite complicated, but that is because ffmpeg has a lot of parameters and history.  Good results are not that hard to create.  Initially you should mostly use the defaults.  
226 If you send any new options files to \href{mailto:cin@lists.cinelerra-gg.org}{cin@lists.cinelerra-gg.org}, it will be given consideration to being added to the baseline for future deliverables.
227
228 To get a listing of the current ffmpeg supported formats and codecs that can be made to work with \CGG{}, provided there are option files added, run the following commands.  This should be done from the \texttt{<build>} directory substituting the location of \texttt{<build>} where you have installed \CGG{} on your system and the ffmpeg may be a different version than $4.2$ as used below.  Then look at the output created in \texttt{/tmp/ff-formats.txt} and \texttt{codecs.txt}.
229
230 \begin{lstlisting}[style=sh]
231 /<build>/cinelerra-5.1/thirdparty/ffmpeg-4.2/ffmpeg -formats > /tmp/ff-formats.txt
232 /<build>/cinelerra-5.1/thirdparty/ffmpeg-4.2/ffmpeg -codecs > /tmp/ff-codecs.txt
233 \end{lstlisting}
234
235 \subsection{Complete Options File Example}%
236 \label{sub:complete_options_file_example}
237
238 For illustrative purposes, here is an example of the options files that need to be added for using the ffmpeg \textit{ProRes 422} format. This makes it possible to transcode to \texttt{h264.mov} with FFmpeg retaining \textit{10-bit yuv422p} from the source to the target output video.
239
240 Add the file named  \texttt{./ffmpeg/audio/aac256k.pro} which contains the following lines:
241
242 \begin{lstlisting}[style=sh]
243 mov aac
244 strict -2
245 b 256000
246 \end{lstlisting}
247
248 (Note that in the example above, even though the bitrate is set here to $256000$, it can be     overridden by the render menu settings).
249
250 Add the file named \texttt{./ffmpeg/audio/pro.dfl} which contains the following lines:
251
252 \begin{lstlisting}[style=sh]
253 aac256k.pro
254 \end{lstlisting}
255
256 Add the file named \texttt{./ffmpeg/video/prores.pro} which contains the following lines:
257
258 \begin{lstlisting}[style=sh]
259 mov prores
260 profile=2
261 # lines of comments
262 \end{lstlisting}
263
264 Add the file named \texttt{./ffmpeg/video/pro.dfl} which contains the following lines:
265
266 \begin{lstlisting}[style=sh]
267 prores.pro
268 \end{lstlisting}
269
270 Then to use and to get 10 bit depth and preserve depth from decode to encode:
271
272 \begin{enumerate}
273     \item load media
274     \item use \texttt{settings $\rightarrow$ format} to set the frame rate, sample rate/channels, aspect ratio, 
275     color model = rgb\_float or rgba\_float if blending
276     \item press Shift-R and select FFmpeg format type \textit{pro}
277     \item select target path
278     \item check OK, and watch for messages in the terminal window
279 \end{enumerate}
280
281 \subsection{Modifying FFmpeg Format Options inside \CGG{}}%
282 \label{sub:modifying_ffmpeg_cinelerra}
283 \index{ffmpeg!option file format}
284 \index{ffmpeg!wrench}
285 \index{ffmpeg!private options}
286
287 There are thousands of options for using ffmpeg.  Now it is possible to \textit{view} the available options for a particular video and audio choice by using the \textit{wrench icon} and then clicking on the \textit{view} box.  FFmpeg has to be the selected file format for this feature to be visible.  It makes it a lot easier since only the applicable options show up as opposed to everything that ffmpeg can do.  These options are just \textit{Hints} and some may be missing due to the way that ffmpeg options are coded -- \CGG{} shows the option data ffmpeg has exposed.
288
289 As an example, instead of reading the entire 264 library
290 information, you only have to look at the shown available options.
291 Both the video and the audio are browsable. The options visible in
292 the \textit{Audio/Video Preset} textbox are the final values which
293 are used when rendering once you have checked OK\@.  For assistance
294 in choosing the options you want, use the view popup to see the
295 objects that go with the selected format tool, highlight the option,
296 modify the parameter value in the box at the top of the
297 \textit{Options} window based on what you want, and then click
298 apply.  Updated parameter values or new parameters will be appended
299 at the bottom.  Note that when you highlight an option, a tooltip
300 will show up when available in the lower right hand corner which
301 describes the option.  Also note that the Format and Codec types are
302 shown on the top line of the Options window.
303
304 Parameters exist in 3 layers: ffmpeg, codec, and an interface layer.  You can apply parameters to each layer.  The top 2 layers are accessed with the Kind popup menu. The ffmpeg layer is topmost, and is selected as Kind: ffmpeg.  It can specify many of the more common parameters, such as the bitrate, quality, and so on.  The middle layer is selected as Kind: codec.  These options can specialize your choices, and frequently includes presets and profiles useful for coding well known parameter sets, like \textit{profile=high422}, \textit{preset=medium}, or \textit{tune=film}, etc.   The interface layer may or may not be available.  It is usually accessible only by an \textit{opts} parameter, like \texttt{x264-params key=value:key=value}:\dots  These options are passed directly to the low level codec library.
305
306 With the \textit{format} button we can access further parameters, called \textit{Private Options}. A window opens that contains a new view button. More details in the section: \nameref{sub:extra_cin_option_ffmpeg}
307
308 Figure~\ref{fig:video-preset} shows \textit{ffmpeg} video as the Kind. Note the x264opts (should actually be x264-params now) in the Video Preset window immediately below. There is also the \textit{format} window with private options.
309
310 \begin{figure}[htpb]
311     \centering
312     \includegraphics[width=1.0\linewidth]{video-preset.png}
313     \caption{FFmpeg wrench, video preset, view and format options}
314     \label{fig:video-preset}
315 \end{figure}
316
317 Figure~\ref{fig:audio-preset02} shows \textit{ffmpeg} video for the Kind. Note the colored tooltip in the lower right hand corner describing the highlighted option.  Also note the allowed \textit{Range} values above the box provided for keyins. There is also the \textit{format} window with private options.
318
319 \begin{figure}[htpb]
320     \centering
321     \includegraphics[width=1.0\linewidth]{audio-preset02.png}
322     \caption{FFmpeg wrench, audio preset, view and format options}
323     \label{fig:audio-preset02}
324 \end{figure}
325
326 \section{The FFmpeg Image2 Streams}%
327 \label{sec:ffmpeg_image2_streams}
328 \index{ffmpeg!image2 streams}
329
330 AppImage does not provide this capability. Another feature gained from using ffmpeg in \CGG{} takes advantage of what is being referred to as the \textit{\%d trick}.  This trick uses the ffmpeg muxer image2 and a filename template to create a series of image files of a given type.  A specific example is described below.
331
332 To encode a series of $48$\,bit tiff output image files, add a file to the \CGG{} data ffmpeg/video subdirectory as in:
333
334 \begin{lstlisting}[style=sh]
335 # \dots/ffmpeg/video/tiff.dfl
336 tiff48.tif
337 \end{lstlisting}
338
339 Then create an ffmpeg video encoder parameters file in the same directory:
340
341 \begin{lstlisting}[style=sh]
342 # \dots/ffmpeg/video/tiff48.tiff
343 image2 tiff
344 pixel_format=rgb48
345 \end{lstlisting}
346
347 This will define a new ffmpeg encoder format which is a video image file format that uses the tiff codec for encoding, and a pixel\_format of \textit{rgb48} (or a similar equivalent such as rgb48le).  Next load up your project and set up for a Render using \texttt{File $\rightarrow$ Render} in the usual way.  Now the tricky part; the output file name should contain a \texttt{\%d} which will be the frame number used in the image output filename as in:  Select a file to render to  \texttt{/tmp/tiff\_images/img\%03d.tiff}.  You will get multiple files as output -- one for each frame!
348
349 The resulting directory of images can be opened for reading by simply opening the template path.  As in: \texttt{File $\rightarrow$ Load Files} \texttt{/tmp/tiff\_images/img\%03d.tiff}.  You will notice a file named the same as the template, which has been automatically created, is empty, is needed, and has to remain with the set.
350
351 \section{Raw Input Opts File for Video/Audio}%
352 \label{sec:raw_input_opts_video_audio}
353 \index{ffmpeg!raw input options}
354
355 Raw video is not affected by decoding on read in.  This makes it very attractive to provide raw image data for editing and rendering media.  A wide variety of raw formats are available via the ffmpeg file interface.  To load media in a raw format, select \textit{try ffmpeg first} and create an accompanying \textit{opts} file.  The opts files must be in the same directory as your media, with the same base name, and the \texttt{.opts} extension.  The opts file contents should reflect your video setup.  An example follows:
356
357 \begin{lstlisting}[style=sh]
358 # Video file name:    /tmp/buddy.mov
359 # Opts file name:     /tmp/buddy.opts
360 # Contents of opts file:
361
362 format=rawvideo
363 codec=rawvideo
364 video_size=352x240
365 pixel_format=yuv420p
366 duration=90.25
367 \end{lstlisting}
368
369 \section{FFmpeg Items of Note}%
370 \label{sec:ffmpeg_items_note}
371 \index{ffmpeg!notes}
372
373 \begin{description}
374     \item[Quality Option when rendering:] FFmpeg responds variably to the quality option in the render option but seems to respond well to bitrate. The subranges used by quality even seem to vary somewhat depending on how old the codec is. Some use $0$ to $35$, some use $0$ to $500$ or so.  The quality is supposed to cause the codec to output data until the noise level is below a limit determined by the quality setting. Your specific results may vary.
375     \item[Previous Changes when rendering:] With ffmpeg there are 2 cases that the defaults will be used.  The first time when you have nothing set up and any other time when you reset the render File Format in the Render Menu.  Otherwise with ffmpeg, if you change a video compression type for the render (for example \texttt{h264.mp4} to \texttt{h265.mp4}), the settings will be from the previous session settings.
376     \item[Outstanding Issues with ffmpeg:] There are some problems that need to be addressed by the ffmpeg developer group that adversely affect \CGG{}.  These are stated below with the hopes that that group will fix them as time permits.
377     \begin{itemize}
378         \item Make all the default parameters operational.  When they are not, the \CGG{} plugins can't be initialized since the initial state of the filter is not operational.  If that is not possible, then provide a set of nominal parameters for each plugin, so that they can be used as the plugins initial default state.
379         \item Make the filter config function project the new parameter data into the filter function at any point
380         during filter operation.  This is so that continuous updates can be done as the plugin operates.
381         \item Improve seek codec restarts.  The past predictor must be reset or reconstructed after a seek.  The  only documented way to seek is open/seek/play.  Reopening the format layer is very expensive.
382     \end{itemize}
383 \end{description}