\input texinfo @c -*- texinfo -*-

@settitle Developer Documentation
@titlepage
@center @titlefont{Developer Documentation}
@end titlepage

@top

@contents

@chapter Developers Guide

@section API
@itemize @bullet
@item libavcodec is the library containing the codecs (both encoding and
decoding). Look at @file{libavcodec/apiexample.c} to see how to use it.

@item libavformat is the library containing the file format handling (mux and
demux code for several formats). Look at @file{avplay.c} to use it in a
player. See @file{libavformat/output-example.c} to use it to generate
audio or video streams.

@end itemize

@section Integrating libav in your program

Shared libraries should be used whenever is possible in order to reduce
the effort distributors have to pour to support programs and to ensure
only the public api is used.

You can use Libav in your commercial program, but you must abide to the
license, LGPL or GPL depending on the specific features used, please refer
to @uref{http://libav.org/legal.html, our legal page} for a quick checklist and to
the following links for the exact text of each license:
@uref{http://git.libav.org/?p=libav.git;a=blob;f=COPYING.GPLv2, GPL version 2},
@uref{http://git.libav.org/?p=libav.git;a=blob;f=COPYING.GPLv3, GPL version 3},
@uref{http://git.libav.org/?p=libav.git;a=blob;f=COPYING.LGPLv2.1, LGPL version 2.1},
@uref{http://git.libav.org/?p=libav.git;a=blob;f=COPYING.LGPLv3, LGPL version 3}.
Any modification to the source code can be suggested for inclusion.
The best way to proceed is to send your patches to the
@uref{https://lists.libav.org/mailman/listinfo/libav-devel, libav-devel}
mailing list.

@anchor{Coding Rules}
@section Coding Rules

@subsection Code formatting conventions
The code is written in K&R C style. That means the following:
@itemize @bullet
@item
The control statements are formatted by putting space between the statement
and parenthesis in the following way:
@example
for (i = 0; i < filter->input_count; i++) @{
@end example
@item
The case statement is always located at the same level as the switch itself:
@example
switch (link->init_state) @{
case AVLINK_INIT:
    continue;
case AVLINK_STARTINIT:
    av_log(filter, AV_LOG_INFO, "circular filter chain detected");
    return 0;
@end example
@item
Braces in function declarations are written on the new line:
@example
const char *avfilter_configuration(void)
@{
    return LIBAV_CONFIGURATION;
@}
@end example
@item
Do not check for NULL values by comparison, @samp{if (p)} and
@samp{if (!p)} are correct; @samp{if (p == NULL)} and @samp{if (p != NULL)}
are not.
@item
In case of a single-statement if, no curly braces are required:
@example
if (!pic || !picref)
    goto fail;
@end example
@item
Do not put spaces immediately inside parentheses. @samp{if (ret)} is
a valid style; @samp{if ( ret )} is not.
@end itemize

There are the following guidelines regarding the indentation in files:
@itemize @bullet
@item
Indent size is 4.
@item
The TAB character is forbidden outside of Makefiles as is any
form of trailing whitespace. Commits containing either will be
rejected by the git repository.
@item
You should try to limit your code lines to 80 characters; however, do so if
and only if this improves readability.
@end itemize
The presentation is one inspired by 'indent -i4 -kr -nut'.

The main priority in Libav is simplicity and small code size in order to
minimize the bug count.

@subsection Comments
Use the JavaDoc/Doxygen  format (see examples below) so that code documentation
can be generated automatically. All nontrivial functions should have a comment
above them explaining what the function does, even if it is just one sentence.
All structures and their member variables should be documented, too.

Avoid Qt-style and similar Doxygen syntax with @code{!} in it, i.e. replace
@code{//!} with @code{///} and similar.  Also @@ syntax should be employed
for markup commands, i.e. use @code{@@param} and not @code{\param}.

@example
/**
 * @@file
 * MPEG codec.
 * @@author ...
 */

/**
 * Summary sentence.
 * more text ...
 * ...
 */
typedef struct Foobar@{
    int var1; /**< var1 description */
    int var2; ///< var2 description
    /** var3 description */
    int var3;
@} Foobar;

/**
 * Summary sentence.
 * more text ...
 * ...
 * @@param my_parameter description of my_parameter
 * @@return return value description
 */
int myfunc(int my_parameter)
...
@end example

@subsection C language features

Libav is programmed in the ISO C90 language with a few additional
features from ISO C99, namely:
@itemize @bullet
@item
the @samp{inline} keyword;
@item
@samp{//} comments;
@item
designated struct initializers (@samp{struct s x = @{ .i = 17 @};})
@item
compound literals (@samp{x = (struct s) @{ 17, 23 @};})
@end itemize

These features are supported by all compilers we care about, so we will not
accept patches to remove their use unless they absolutely do not impair
clarity and performance.

All code must compile with recent versions of GCC and a number of other
currently supported compilers. To ensure compatibility, please do not use
additional C99 features or GCC extensions. Especially watch out for:
@itemize @bullet
@item
mixing statements and declarations;
@item
@samp{long long} (use @samp{int64_t} instead);
@item
@samp{__attribute__} not protected by @samp{#ifdef __GNUC__} or similar;
@item
GCC statement expressions (@samp{(x = (@{ int y = 4; y; @})}).
@end itemize

@subsection Naming conventions
All names are using underscores (_), not CamelCase. For example,
@samp{avfilter_get_video_buffer} is a valid function name and
@samp{AVFilterGetVideo} is not. The only exception from this are structure
names; they should always be in the CamelCase

There are following conventions for naming variables and functions:
@itemize @bullet
@item
For local variables no prefix is required.
@item
For variables and functions declared as @code{static} no prefixes are required.
@item
For variables and functions used internally by the library, @code{ff_} prefix
should be used.
For example, @samp{ff_w64_demuxer}.
@item
For variables and functions used internally across multiple libraries, use
@code{avpriv_}. For example, @samp{avpriv_aac_parse_header}.
@item
For exported names, each library has its own prefixes. Just check the existing
code and name accordingly.
@end itemize

@subsection Miscellanous conventions
@itemize @bullet
@item
fprintf and printf are forbidden in libavformat and libavcodec,
please use av_log() instead.
@item
Casts should be used only when necessary. Unneeded parentheses
should also be avoided if they don't make the code easier to understand.
@end itemize

@subsection Editor configuration
In order to configure Vim to follow Libav formatting conventions, paste
the following snippet into your @file{.vimrc}:
@example
" indentation rules for libav: 4 spaces, no tabs
set expandtab
set shiftwidth=4
set softtabstop=4
set cindent
set cinoptions=(0
" allow tabs in Makefiles
autocmd FileType make set noexpandtab shiftwidth=8 softtabstop=8
" Trailing whitespace and tabs are forbidden, so highlight them.
highlight ForbiddenWhitespace ctermbg=red guibg=red
match ForbiddenWhitespace /\s\+$\|\t/
" Do not highlight spaces at the end of line while typing on that line.
autocmd InsertEnter * match ForbiddenWhitespace /\t\|\s\+\%#\@@<!$/
@end example

For Emacs, add these roughly equivalent lines to your @file{.emacs.d/init.el}:
@example
(c-add-style "libav"
             '("k&r"
               (c-basic-offset . 4)
               (indent-tabs-mode nil)
               (show-trailing-whitespace t)
               (c-offsets-alist
                (statement-cont . (c-lineup-assignments +)))
               )
             )
(setq c-default-style "libav")
@end example

@section Development Policy

@enumerate
@item
   Contributions should be licensed under the LGPL 2.1, including an
   "or any later version" clause, or the MIT license.  GPL 2 including
   an "or any later version" clause is also acceptable, but LGPL is
   preferred.
@item
   All the patches MUST be reviewed in the mailing list before they are
   committed.
@item
   The Libav coding style should remain consistent. Changes to
   conform will be suggested during the review or implemented on commit.
@item
   Patches should be generated using @code{git format-patch} or directly sent
   using @code{git send-email}.
   Please make sure you give the proper credit by setting the correct author
   in the commit.
@item
   The commit message should have a short first line in the form of
   @samp{topic: short description} as header, separated by a newline
   from the body consting in few lines explaining the reason of the patch.
   Referring to the issue on the bug tracker does not exempt to report an
   excerpt of the bug.
@item
   Work in progress patches should be sent to the mailing list with the [WIP]
   or the [RFC] tag.
@item
   Branches in public personal repos are advised as way to
   work on issues collaboratively.
@item
   You do not have to over-test things. If it works for you and you think it
   should work for others, send it to the mailing list for review.
   If you have doubt about portability please state it in the submission so
   people with specific hardware could test it.
@item
   Do not commit unrelated changes together, split them into self-contained
   pieces. Also do not forget that if part B depends on part A, but A does not
   depend on B, then A can and should be committed first and separate from B.
   Keeping changes well split into self-contained parts makes reviewing and
   understanding them on the commit log mailing list easier. This also helps
   in case of debugging later on.
@item
   Patches that change behavior of the programs (renaming options etc) or
   public API or ABI should be discussed in depth and possible few days should
   pass between discussion and commit.
   Changes to the build system (Makefiles, configure script) which alter
   the expected behavior should be considered in the same regard.
@item
   When applying patches that have been discussed (at length) on the mailing
   list, reference the thread in the log message.
@item
    Subscribe to the
    @uref{https://lists.libav.org/mailman/listinfo/libav-devel, libav-devel} and
    @uref{https://lists.libav.org/mailman/listinfo/libav-commits, libav-commits}
    mailing lists.
    Bugs and possible improvements or general questions regarding commits
    are discussed on libav-devel. We expect you to react if problems with
    your code are uncovered.
@item
    Update the documentation if you change behavior or add features. If you are
    unsure how best to do this, send an [RFC] patch to libav-devel.
@item
    All discussions and decisions should be reported on the public developer
    mailing list, so that there is a reference to them.
    Other media (e.g. IRC) should be used for coordination and immediate
    collaboration.
@item
    Never write to unallocated memory, never write over the end of arrays,
    always check values read from some untrusted source before using them
    as array index or other risky things. Always use valgrind to doublecheck.
@item
    Remember to check if you need to bump versions for the specific libav
    parts (libavutil, libavcodec, libavformat) you are changing. You need
    to change the version integer.
    Incrementing the first component means no backward compatibility to
    previous versions (e.g. removal of a function from the public API).
    Incrementing the second component means backward compatible change
    (e.g. addition of a function to the public API or extension of an
    existing data structure).
    Incrementing the third component means a noteworthy binary compatible
    change (e.g. encoder bug fix that matters for the decoder).
@item
    Compiler warnings indicate potential bugs or code with bad style.
    If it is a bug, the bug has to be fixed. If it is not, the code should
    be changed to not generate a warning unless that causes a slowdown
    or obfuscates the code.
    If a type of warning leads to too many false positives, that warning
    should be disabled, not the code changed.
@item
    If you add a new file, give it a proper license header. Do not copy and
    paste it from a random place, use an existing file as template.
@end enumerate

We think our rules are not too hard. If you have comments, contact us.

Note, some rules were borrowed from the MPlayer project.

@section Submitting patches

First, read the @ref{Coding Rules} above if you did not yet, in particular
the rules regarding patch submission.

As stated already, please do not submit a patch which contains several
unrelated changes.
Split it into separate, self-contained pieces. This does not mean splitting
file by file. Instead, make the patch as small as possible while still
keeping it as a logical unit that contains an individual change, even
if it spans multiple files. This makes reviewing your patches much easier
for us and greatly increases your chances of getting your patch applied.

Use the patcheck tool of Libav to check your patch.
The tool is located in the tools directory.

Run the @ref{Regression Tests} before submitting a patch in order to verify
it does not cause unexpected problems.

Patches should be posted as base64 encoded attachments (or any other
encoding which ensures that the patch will not be trashed during
transmission) to the
@uref{https://lists.libav.org/mailman/listinfo/libav-devel, libav-devel}
mailing list.

It also helps quite a bit if you tell us what the patch does (for example
'replaces lrint by lrintf'), and why (for example '*BSD isn't C99 compliant
and has no lrint()'). This kind of explanation should be the body of the
commit message.

Also please if you send several patches, send each patch as a separate mail,
do not attach several unrelated patches to the same mail.

Use @code{git send-email} when possible since it will properly send patches
without requiring extra care.

Your patch will be reviewed on the mailing list. You will likely be asked
to make some changes and are expected to send in an improved version that
incorporates the requests from the review. This process may go through
several iterations. Once your patch is deemed good enough, it will be
committed to the official Libav tree.

Give us a few days to react. But if some time passes without reaction,
send a reminder by email. Your patch should eventually be dealt with.


@section New codecs or formats checklist

@enumerate
@item
    Did you use av_cold for codec initialization and close functions?
@item
    Did you add a long_name under NULL_IF_CONFIG_SMALL to the AVCodec or
    AVInputFormat/AVOutputFormat struct?
@item
    Did you bump the minor version number (and reset the micro version
    number) in @file{libavcodec/version.h} or @file{libavformat/version.h}?
@item
    Did you register it in @file{allcodecs.c} or @file{allformats.c}?
@item
    Did you add the CodecID to @file{avcodec.h}?
@item
    If it has a fourcc, did you add it to @file{libavformat/riff.c},
    even if it is only a decoder?
@item
    Did you add a rule to compile the appropriate files in the Makefile?
    Remember to do this even if you are just adding a format to a file that
    is already being compiled by some other rule, like a raw demuxer.
@item
    Did you add an entry to the table of supported formats or codecs in
    @file{doc/general.texi}?
@item
    Did you add an entry in the Changelog?
@item
    If it depends on a parser or a library, did you add that dependency in
    configure?
@item
    Did you @code{git add} the appropriate files before committing?
@item
    Did you make sure it compiles standalone, i.e. with
    @code{configure --disable-everything --enable-decoder=foo}
    (or @code{--enable-demuxer} or whatever your component is)?
@end enumerate


@section patch submission checklist

@enumerate
@item
    Does @code{make check} pass with the patch applied?
@item
    Is the patch against latest Libav git master branch?
@item
    Are you subscribed to the
    @uref{https://lists.libav.org/mailman/listinfo/libav-devel, libav-devel}
    mailing list? (Only list subscribers are allowed to post.)
@item
    Have you checked that the changes are minimal, so that the same cannot be
    achieved with a smaller patch and/or simpler final code?
@item
    If the change is to speed critical code, did you benchmark it?
@item
    If you did any benchmarks, did you provide them in the mail?
@item
    Have you checked that the patch does not introduce buffer overflows or
    other security issues?
@item
    Did you test your decoder or demuxer against damaged data? If no, see
    tools/trasher and the noise bitstream filter. Your decoder or demuxer
    should not crash or end in a (near) infinite loop when fed damaged data.
@item
    Does the patch not mix functional and cosmetic changes?
@item
    Did you add tabs or trailing whitespace to the code? Both are forbidden.
@item
    Is the patch attached to the email you send?
@item
    Is the mime type of the patch correct? It should be text/x-diff or
    text/x-patch or at least text/plain and not application/octet-stream.
@item
    If the patch fixes a bug, did you provide a verbose analysis of the bug?
@item
    If the patch fixes a bug, did you provide enough information, including
    a sample, so the bug can be reproduced and the fix can be verified?
    Note please do not attach samples >100k to mails but rather provide a
    URL, you can upload to ftp://upload.libav.org
@item
    Did you provide a verbose summary about what the patch does change?
@item
    Did you provide a verbose explanation why it changes things like it does?
@item
    Did you provide a verbose summary of the user visible advantages and
    disadvantages if the patch is applied?
@item
    Did you provide an example so we can verify the new feature added by the
    patch easily?
@item
    If you added a new file, did you insert a license header? It should be
    taken from Libav, not randomly copied and pasted from somewhere else.
@item
    You should maintain alphabetical order in alphabetically ordered lists as
    long as doing so does not break API/ABI compatibility.
@item
    Lines with similar content should be aligned vertically when doing so
    improves readability.
@item
    Make sure you check the return values of function and return appropriate
    error codes. Especially memory allocation functions like @code{malloc()}
    are notoriously left unchecked, which is a serious problem.
@end enumerate

@section Patch review process

All patches posted to the
@uref{https://lists.libav.org/mailman/listinfo/libav-devel, libav-devel}
mailing list will be reviewed, unless they contain a
clear note that the patch is not for the git master branch.
Reviews and comments will be posted as replies to the patch on the
mailing list. The patch submitter then has to take care of every comment,
that can be by resubmitting a changed patch or by discussion. Resubmitted
patches will themselves be reviewed like any other patch. If at some point
a patch passes review with no comments then it is approved, that can for
simple and small patches happen immediately while large patches will generally
have to be changed and reviewed many times before they are approved.
After a patch is approved it will be committed to the repository.

We will review all submitted patches, but sometimes we are quite busy so
especially for large patches this can take several weeks.

When resubmitting patches, if their size grew or during the review different
issues arisen please split the patch so each issue has a specific patch.

@anchor{Regression Tests}
@section Regression Tests

Before submitting a patch (or committing to the repository), you should at
least make sure that it does not break anything.

If the code changed has already a test present in FATE you should run it,
otherwise it is advised to add it.

Improvements to codec or demuxer might change the FATE results. Make sure
to commit the update reference with the change and to explain in the comment
why the expected result changed.

Please refer to @url{fate.html}.

@bye