writing_filters.txt 16 KB

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