[Libav-user] FFmpeg thread safety
nfxjfg at googlemail.com
Tue Aug 19 19:36:34 CEST 2014
On Tue, 19 Aug 2014 01:09:44 -0700
J Decker <d3ck0r at gmail.com> wrote:
> On Mon, Aug 18, 2014 at 2:30 PM, wm4 <nfxjfg at googlemail.com> wrote:
> > All functions that are specific to a certain context (like
> > AVCodecContext) are by default not thread-safe. Of course using
> > different contexts at the same time from different threads should be
> > perfectly fine.
> > However, many codecs use some global data that is usually constant, but
> > needs to be initialized once. That's why av_lockmgr_register() exists.
> > It's a very messy way to allocate mutexes that are supposed to
> > coordinate this initialization.
> So if I have lots of videos, and want to play multiple videos at the same
> time, using separate contexts for each is OK? Or is it not OK because the
> codecs use globals?
The globals are things like huge tables, which are constant, but it's
easier/smaller to initialize them at startup, instead of hardcoding
them into the binary. So, on opening the codec context, these tables
are initialized (if they aren't already).
So it should be ok, as long as initialization doesn't go wrong.
Supporting threads is a huge mess, partly because ffmpeg supports many
legacy architectures. The "lock manager" stuff was probably meant to
allow the user to plugin exotic threading APIs (pure non-sense if you
ask me). Now there's a default "lock manager". It's usually enabled by
default, but AFAIK depends on threading support within ffmpeg. So make
sure you didn't accidentally disable threading.
If you're using Libav (the ffmpeg fork shipped with Ubuntu, Debian),
or if you're using an ancient version of ffmpeg, be aware that it won't
have that default lock manager.
Functions like avcodec_register_all() still need to be synchronized.
> Or I have to put critical sections around every call to the library suite?
No, you just have to synchronize access to each context. Generally,
ffmpeg code do any locking for the user. (It only does locking to
coordinate internal threads, not more.)
> A semi-off-topic question? Why does avcodec-56 allocate so many threads?
> Why does it need any more threads than the thread I call a decode with?
libavcodec supports multithreaded decoding. I forgot, maybe it's
> In the example code, decoding audio and video in separate threads didn't
> require locks? What if I have a thread per video and play 32 on the screen
> at once?
That should work fine.
More information about the Libav-user