writing_filters.txt 16 KB

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