writing_filters.txt 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. This document is a tutorial/initiation for writing simple filters in
  2. libavfilter.
  3. Foreword: just like everything else in FFmpeg, libavfilter is monolithic, which
  4. means that it is highly recommended that you submit your filters to the FFmpeg
  5. development mailing-list and make sure that they are applied. Otherwise, your filters
  6. are likely to have a very short lifetime due to more or less regular internal API
  7. changes, and a limited distribution, review, and testing.
  8. Bootstrap
  9. =========
  10. Let's say you want to write a new simple video filter called "foobar" which
  11. takes one frame in input, changes the pixels in whatever fashion you fancy, and
  12. outputs the modified frame. The most simple way of doing this is to take a
  13. similar filter. We'll pick edgedetect, but any other should do. You can look
  14. for others using the `./ffmpeg -v 0 -filters|grep ' V->V '` command.
  15. - sed 's/edgedetect/foobar/g;s/EdgeDetect/Foobar/g' libavfilter/vf_edgedetect.c > libavfilter/vf_foobar.c
  16. - edit libavfilter/Makefile, and add an entry for "foobar" following the
  17. pattern of the other filters.
  18. - edit libavfilter/allfilters.c, and add an entry for "foobar" following the
  19. pattern of the other filters.
  20. - ./configure ...
  21. - make -j<whatever> ffmpeg
  22. - ./ffmpeg -i http://samples.ffmpeg.org/image-samples/lena.pnm -vf foobar foobar.png
  23. Note here: you can obviously use a random local image instead of a remote URL.
  24. If everything went right, you should get a foobar.png with Lena edge-detected.
  25. That's it, your new playground is ready.
  26. Some little details about what's going on:
  27. libavfilter/allfilters.c:avfilter_register_all() is called at runtime to create
  28. a list of the available filters, but it's important to know that this file is
  29. also parsed by the configure script, which in turn will define variables for
  30. the build system and the C:
  31. --- after running configure ---
  32. $ grep FOOBAR config.mak
  33. CONFIG_FOOBAR_FILTER=yes
  34. $ grep FOOBAR config.h
  35. #define CONFIG_FOOBAR_FILTER 1
  36. CONFIG_FOOBAR_FILTER=yes from the config.mak is later used to enable the filter in
  37. libavfilter/Makefile and CONFIG_FOOBAR_FILTER=1 from the config.h will be used
  38. for registering the filter in libavfilter/allfilters.c.
  39. Filter code layout
  40. ==================
  41. You now need some theory about the general code layout of a filter. Open your
  42. libavfilter/vf_foobar.c. This section will detail the important parts of the
  43. code you need to understand before messing with it.
  44. Copyright
  45. ---------
  46. First chunk is the copyright. Most filters are LGPL, and we are assuming
  47. vf_foobar is as well. We are also assuming vf_foobar is not an edge detector
  48. filter, so you can update the boilerplate with your credits.
  49. Doxy
  50. ----
  51. Next chunk is the Doxygen about the file. See https://ffmpeg.org/doxygen/trunk/.
  52. Detail here what the filter is, does, and add some references if you feel like
  53. it.
  54. Context
  55. -------
  56. Skip the headers and scroll down to the definition of FoobarContext. This is
  57. your local state context. It is already filled with 0 when you get it so do not
  58. worry about uninitialized reads into this context. This is where you put all
  59. "global" information that you need; typically the variables storing the user options.
  60. You'll notice the first field "const AVClass *class"; it's the only field you
  61. need to keep assuming you have a context. There is some magic you don't need to
  62. care about around this field, just let it be (in the first position) for now.
  63. Options
  64. -------
  65. Then comes the options array. This is what will define the user accessible
  66. options. For example, -vf foobar=mode=colormix:high=0.4:low=0.1. Most options
  67. have the following pattern:
  68. name, description, offset, type, default value, minimum value, maximum value, flags
  69. - name is the option name, keep it simple and lowercase
  70. - description are short, in lowercase, without period, and describe what they
  71. do, for example "set the foo of the bar"
  72. - offset is the offset of the field in your local context, see the OFFSET()
  73. macro; the option parser will use that information to fill the fields
  74. according to the user input
  75. - type is any of AV_OPT_TYPE_* defined in libavutil/opt.h
  76. - default value is an union where you pick the appropriate type; "{.dbl=0.3}",
  77. "{.i64=0x234}", "{.str=NULL}", ...
  78. - min and max values define the range of available values, inclusive
  79. - flags are AVOption generic flags. See AV_OPT_FLAG_* definitions
  80. When in doubt, just look at the other AVOption definitions all around the codebase,
  81. there are tons of examples.
  82. Class
  83. -----
  84. AVFILTER_DEFINE_CLASS(foobar) will define a unique foobar_class with some kind
  85. of signature referencing the options, etc. which will be referenced in the
  86. definition of the AVFilter.
  87. Filter definition
  88. -----------------
  89. At the end of the file, you will find foobar_inputs, foobar_outputs and
  90. the AVFilter ff_vf_foobar. Don't forget to update the AVFilter.description with
  91. a description of what the filter does, starting with a capitalized letter and
  92. ending with a period. You'd better drop the AVFilter.flags entry for now, and
  93. re-add them later depending on the capabilities of your filter.
  94. Callbacks
  95. ---------
  96. Let's now study the common callbacks. Before going into details, note that all
  97. these callbacks are explained in details in libavfilter/avfilter.h, so in
  98. doubt, refer to the doxy in that file.
  99. init()
  100. ~~~~~~
  101. First one to be called is init(). It's flagged as cold because not called
  102. often. Look for "cold" on
  103. http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html for more
  104. information.
  105. As the name suggests, init() is where you eventually initialize and allocate
  106. your buffers, pre-compute your data, etc. Note that at this point, your local
  107. context already has the user options initialized, but you still haven't any
  108. clue about the kind of data input you will get, so this function is often
  109. mainly used to sanitize the user options.
  110. Some init()s will also define the number of inputs or outputs dynamically
  111. according to the user options. A good example of this is the split filter, but
  112. we won't cover this here since vf_foobar is just a simple 1:1 filter.
  113. uninit()
  114. ~~~~~~~~
  115. Similarly, there is the uninit() callback, doing what the name suggests. Free
  116. everything you allocated here.
  117. query_formats()
  118. ~~~~~~~~~~~~~~~
  119. This follows the init() and is used for the format negotiation. Basically
  120. you specify here what pixel format(s) (gray, rgb 32, yuv 4:2:0, ...) you accept
  121. for your inputs, and what you can output. All pixel formats are defined in
  122. libavutil/pixfmt.h. If you don't change the pixel format between the input and
  123. the output, you just have to define a pixel formats array and call
  124. ff_set_common_formats(). For more complex negotiation, you can refer to other
  125. filters such as vf_scale.
  126. config_props()
  127. ~~~~~~~~~~~~~~
  128. This callback is not necessary, but you will probably have one or more
  129. config_props() anyway. It's not a callback for the filter itself but for its
  130. inputs or outputs (they're called "pads" - AVFilterPad - in libavfilter's
  131. lexicon).
  132. Inside the input config_props(), you are at a point where you know which pixel
  133. format has been picked after query_formats(), and more information such as the
  134. video width and height (inlink->{w,h}). So if you need to update your internal
  135. context state depending on your input you can do it here. In edgedetect you can
  136. see that this callback is used to allocate buffers depending on these
  137. information. They will be destroyed in uninit().
  138. Inside the output config_props(), you can define what you want to change in the
  139. output. Typically, if your filter is going to double the size of the video, you
  140. will update outlink->w and outlink->h.
  141. filter_frame()
  142. ~~~~~~~~~~~~~~
  143. This is the callback you are waiting for from the beginning: it is where you
  144. process the received frames. Along with the frame, you get the input link from
  145. where the frame comes from.
  146. static int filter_frame(AVFilterLink *inlink, AVFrame *in) { ... }
  147. You can get the filter context through that input link:
  148. AVFilterContext *ctx = inlink->dst;
  149. Then access your internal state context:
  150. FoobarContext *foobar = ctx->priv;
  151. And also the output link where you will send your frame when you are done:
  152. AVFilterLink *outlink = ctx->outputs[0];
  153. Here, we are picking the first output. You can have several, but in our case we
  154. only have one since we are in a 1:1 input-output situation.
  155. If you want to define a simple pass-through filter, you can just do:
  156. return ff_filter_frame(outlink, in);
  157. But of course, you probably want to change the data of that frame.
  158. This can be done by accessing frame->data[] and frame->linesize[]. Important
  159. note here: the width does NOT match the linesize. The linesize is always
  160. greater or equal to the width. The padding created should not be changed or
  161. even read. Typically, keep in mind that a previous filter in your chain might
  162. have altered the frame dimension but not the linesize. Imagine a crop filter
  163. that halves the video size: the linesizes won't be changed, just the width.
  164. <-------------- linesize ------------------------>
  165. +-------------------------------+----------------+ ^
  166. | | | |
  167. | | | |
  168. | picture | padding | | height
  169. | | | |
  170. | | | |
  171. +-------------------------------+----------------+ v
  172. <----------- width ------------->
  173. Before modifying the "in" frame, you have to make sure it is writable, or get a
  174. new one. Multiple scenarios are possible here depending on the kind of
  175. processing you are doing.
  176. Let's say you want to change one pixel depending on multiple pixels (typically
  177. the surrounding ones) of the input. In that case, you can't do an in-place
  178. processing of the input so you will need to allocate a new frame, with the same
  179. properties as the input one, and send that new frame to the next filter:
  180. AVFrame *out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
  181. if (!out) {
  182. av_frame_free(&in);
  183. return AVERROR(ENOMEM);
  184. }
  185. av_frame_copy_props(out, in);
  186. // out->data[...] = foobar(in->data[...])
  187. av_frame_free(&in);
  188. return ff_filter_frame(outlink, out);
  189. In-place processing
  190. ~~~~~~~~~~~~~~~~~~~
  191. If you can just alter the input frame, you probably just want to do that
  192. instead:
  193. av_frame_make_writable(in);
  194. // in->data[...] = foobar(in->data[...])
  195. return ff_filter_frame(outlink, in);
  196. You may wonder why a frame might not be writable. The answer is that for
  197. example a previous filter might still own the frame data: imagine a filter
  198. prior to yours in the filtergraph that needs to cache the frame. You must not
  199. alter that frame, otherwise it will make that previous filter buggy. This is
  200. where av_frame_make_writable() helps (it won't have any effect if the frame
  201. already is writable).
  202. The problem with using av_frame_make_writable() is that in the worst case it
  203. will copy the whole input frame before you change it all over again with your
  204. filter: if the frame is not writable, av_frame_make_writable() will allocate
  205. new buffers, and copy the input frame data. You don't want that, and you can
  206. avoid it by just allocating a new buffer if necessary, and process from in to
  207. out in your filter, saving the memcpy. Generally, this is done following this
  208. scheme:
  209. int direct = 0;
  210. AVFrame *out;
  211. if (av_frame_is_writable(in)) {
  212. direct = 1;
  213. out = in;
  214. } else {
  215. out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
  216. if (!out) {
  217. av_frame_free(&in);
  218. return AVERROR(ENOMEM);
  219. }
  220. av_frame_copy_props(out, in);
  221. }
  222. // out->data[...] = foobar(in->data[...])
  223. if (!direct)
  224. av_frame_free(&in);
  225. return ff_filter_frame(outlink, out);
  226. Of course, this will only work if you can do in-place processing. To test if
  227. your filter handles well the permissions, you can use the perms filter. For
  228. example with:
  229. -vf perms=random,foobar
  230. Make sure no automatic pixel conversion is inserted between perms and foobar,
  231. otherwise the frames permissions might change again and the test will be
  232. meaningless: add av_log(0,0,"direct=%d\n",direct) in your code to check that.
  233. You can avoid the issue with something like:
  234. -vf format=rgb24,perms=random,foobar
  235. ...assuming your filter accepts rgb24 of course. This will make sure the
  236. necessary conversion is inserted before the perms filter.
  237. Timeline
  238. ~~~~~~~~
  239. Adding timeline support
  240. (http://ffmpeg.org/ffmpeg-filters.html#Timeline-editing) is often an easy
  241. feature to add. In the most simple case, you just have to add
  242. AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC to the AVFilter.flags. You can typically
  243. do this when your filter does not need to save the previous context frames, or
  244. basically if your filter just alters whatever goes in and doesn't need
  245. previous/future information. See for instance commit 86cb986ce that adds
  246. timeline support to the fieldorder filter.
  247. In some cases, you might need to reset your context somehow. This is handled by
  248. the AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL flag which is used if the filter
  249. must not process the frames but still wants to keep track of the frames going
  250. through (to keep them in cache for when it's enabled again). See for example
  251. commit 69d72140a that adds timeline support to the phase filter.
  252. Threading
  253. ~~~~~~~~~
  254. libavfilter does not yet support frame threading, but you can add slice
  255. threading to your filters.
  256. Let's say the foobar filter has the following frame processing function:
  257. dst = out->data[0];
  258. src = in ->data[0];
  259. for (y = 0; y < inlink->h; y++) {
  260. for (x = 0; x < inlink->w; x++)
  261. dst[x] = foobar(src[x]);
  262. dst += out->linesize[0];
  263. src += in ->linesize[0];
  264. }
  265. The first thing is to make this function work into slices. The new code will
  266. look like this:
  267. for (y = slice_start; y < slice_end; y++) {
  268. for (x = 0; x < inlink->w; x++)
  269. dst[x] = foobar(src[x]);
  270. dst += out->linesize[0];
  271. src += in ->linesize[0];
  272. }
  273. The source and destination pointers, and slice_start/slice_end will be defined
  274. according to the number of jobs. Generally, it looks like this:
  275. const int slice_start = (in->height * jobnr ) / nb_jobs;
  276. const int slice_end = (in->height * (jobnr+1)) / nb_jobs;
  277. uint8_t *dst = out->data[0] + slice_start * out->linesize[0];
  278. const uint8_t *src = in->data[0] + slice_start * in->linesize[0];
  279. This new code will be isolated in a new filter_slice():
  280. static int filter_slice(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs) { ... }
  281. Note that we need our input and output frame to define slice_{start,end} and
  282. dst/src, which are not available in that callback. They will be transmitted
  283. through the opaque void *arg. You have to define a structure which contains
  284. everything you need:
  285. typedef struct ThreadData {
  286. AVFrame *in, *out;
  287. } ThreadData;
  288. If you need some more information from your local context, put them here.
  289. In you filter_slice function, you access it like that:
  290. const ThreadData *td = arg;
  291. Then in your filter_frame() callback, you need to call the threading
  292. distributor with something like this:
  293. ThreadData td;
  294. // ...
  295. td.in = in;
  296. td.out = out;
  297. ctx->internal->execute(ctx, filter_slice, &td, NULL, FFMIN(outlink->h, ctx->graph->nb_threads));
  298. // ...
  299. return ff_filter_frame(outlink, out);
  300. Last step is to add AVFILTER_FLAG_SLICE_THREADS flag to AVFilter.flags.
  301. For more example of slice threading additions, you can try to run git log -p
  302. --grep 'slice threading' libavfilter/
  303. Finalization
  304. ~~~~~~~~~~~~
  305. When your awesome filter is finished, you have a few more steps before you're
  306. done:
  307. - write its documentation in doc/filters.texi, and test the output with make
  308. doc/ffmpeg-filters.html.
  309. - add a FATE test, generally by adding an entry in
  310. tests/fate/filter-video.mak, add running make fate-filter-foobar GEN=1 to
  311. generate the data.
  312. - add an entry in the Changelog
  313. - edit libavfilter/version.h and increase LIBAVFILTER_VERSION_MINOR by one
  314. (and reset LIBAVFILTER_VERSION_MICRO to 100)
  315. - git add ... && git commit -m "avfilter: add foobar filter." && git format-patch -1
  316. When all of this is done, you can submit your patch to the ffmpeg-devel
  317. mailing-list for review. If you need any help, feel free to come on our IRC
  318. channel, #ffmpeg-devel on irc.freenode.net.