Commit 37b00b47 authored by Alexander Strange's avatar Alexander Strange Committed by Ronald S. Bultje
Browse files

Frame-based multithreading framework using pthreads



See doc/multithreading.txt for details on use in codecs.
Signed-off-by: default avatarRonald S. Bultje <rsbultje@gmail.com>
parent c2bd7578
......@@ -13,6 +13,11 @@ libavutil: 2009-03-08
API changes, most recent first:
2011-02-09 - XXXXXXX - lavc 52.111.0 - threading API
Add CODEC_CAP_FRAME_THREADS with new restrictions on get_buffer()/
release_buffer()/draw_horiz_band() callbacks for appropriate codecs.
Add thread_type and active_thread_type fields to AVCodecContext.
2011-02-08 - 3940caa - lavf 52.98.0 - av_probe_input_buffer
Add av_probe_input_buffer() to avformat.h for probing format from a
ByteIOContext.
......
FFmpeg multithreading methods
==============================================
FFmpeg provides two methods for multithreading codecs.
Slice threading decodes multiple parts of a frame at the same time, using
AVCodecContext execute() and execute2().
Frame threading decodes multiple frames at the same time.
It accepts N future frames and delays decoded pictures by N-1 frames.
The later frames are decoded in separate threads while the user is
displaying the current one.
Restrictions on clients
==============================================
Slice threading -
* The client's draw_horiz_band() must be thread-safe according to the comment
in avcodec.h.
Frame threading -
* Restrictions with slice threading also apply.
* For best performance, the client should set thread_safe_callbacks if it
provides a thread-safe get_buffer() callback.
* There is one frame of delay added for every thread beyond the first one.
Clients must be able to handle this; the pkt_dts and pkt_pts fields in
AVFrame will work as usual.
Restrictions on codec implementations
==============================================
Slice threading -
None except that there must be something worth executing in parallel.
Frame threading -
* Codecs can only accept entire pictures per packet.
* Codecs similar to ffv1, whose streams don't reset across frames,
will not work because their bitstreams cannot be decoded in parallel.
* The contents of buffers must not be read before ff_thread_await_progress()
has been called on them. reget_buffer() and buffer age optimizations no longer work.
* The contents of buffers must not be written to after ff_thread_report_progress()
has been called on them. This includes draw_edges().
Porting codecs to frame threading
==============================================
Find all context variables that are needed by the next frame. Move all
code changing them, as well as code calling get_buffer(), up to before
the decode process starts. Call ff_thread_finish_setup() afterwards. If
some code can't be moved, have update_thread_context() run it in the next
thread.
If the codec allocates writable tables in its init(), add an init_thread_copy()
which re-allocates them for other threads.
Add CODEC_CAP_FRAME_THREADS to the codec capabilities. There will be very little
speed gain at this point but it should work.
Call ff_thread_report_progress() after some part of the current picture has decoded.
A good place to put this is where draw_horiz_band() is called - add this if it isn't
called anywhere, as it's useful too and the implementation is trivial when you're
doing this. Note that draw_edges() needs to be called before reporting progress.
Before accessing a reference frame or its MVs, call ff_thread_await_progress().
......@@ -1694,6 +1694,7 @@ static int input_init(AVFilterContext *ctx, const char *args, void *opaque)
codec->get_buffer = input_get_buffer;
codec->release_buffer = input_release_buffer;
codec->reget_buffer = input_reget_buffer;
codec->thread_safe_callbacks = 1;
}
priv->frame = avcodec_alloc_frame();
......
......@@ -32,7 +32,7 @@
#include "libavutil/cpu.h"
#define LIBAVCODEC_VERSION_MAJOR 52
#define LIBAVCODEC_VERSION_MINOR 110
#define LIBAVCODEC_VERSION_MINOR 111
#define LIBAVCODEC_VERSION_MICRO 0
#define LIBAVCODEC_VERSION_INT AV_VERSION_INT(LIBAVCODEC_VERSION_MAJOR, \
......@@ -728,6 +728,10 @@ typedef struct RcOverride{
* Codec is able to deal with negative linesizes
*/
#define CODEC_CAP_NEG_LINESIZES 0x0800
/**
* Codec supports frame-level multithreading.
*/
#define CODEC_CAP_FRAME_THREADS 0x1000
//The following defines may change, don't expect compatibility if you use them.
#define MB_TYPE_INTRA4x4 0x0001
......@@ -1027,7 +1031,20 @@ typedef struct AVPanScan{
* - decoding: Read by user.\
*/\
int64_t pkt_dts;\
\
/**\
* the AVCodecContext which ff_thread_get_buffer() was last called on\
* - encoding: Set by libavcodec.\
* - decoding: Set by libavcodec.\
*/\
struct AVCodecContext *owner;\
\
/**\
* used by multithreading to store frame-specific info\
* - encoding: Set by libavcodec.\
* - decoding: Set by libavcodec.\
*/\
void *thread_opaque;
#define FF_QSCALE_TYPE_MPEG1 0
#define FF_QSCALE_TYPE_MPEG2 1
......@@ -1239,6 +1256,10 @@ typedef struct AVCodecContext {
* decoder to draw a horizontal band. It improves cache usage. Not
* all codecs can do that. You must check the codec capabilities
* beforehand.
* When multithreading is used, it may be called from multiple threads
* at the same time; threads might draw different parts of the same AVFrame,
* or multiple AVFrames, and there is no guarantee that slices will be drawn
* in order.
* The function is also used by hardware acceleration APIs.
* It is called at least once during frame decoding to pass
* the data needed for hardware render.
......@@ -1492,6 +1513,9 @@ typedef struct AVCodecContext {
* if CODEC_CAP_DR1 is not set then get_buffer() must call
* avcodec_default_get_buffer() instead of providing buffers allocated by
* some other means.
* If frame multithreading is used and thread_safe_callbacks is set,
* it may be called from a different thread, but not from more than one at once.
* Does not need to be reentrant.
* - encoding: unused
* - decoding: Set by libavcodec, user can override.
*/
......@@ -1501,6 +1525,8 @@ typedef struct AVCodecContext {
* Called to release buffers which were allocated with get_buffer.
* A released buffer can be reused in get_buffer().
* pic.data[*] must be set to NULL.
* May be called from a different thread if frame multithreading is used,
* but not by more than one thread at once, so does not need to be reentrant.
* - encoding: unused
* - decoding: Set by libavcodec, user can override.
*/
......@@ -1804,6 +1830,7 @@ typedef struct AVCodecContext {
#define FF_DEBUG_VIS_QP 0x00002000
#define FF_DEBUG_VIS_MB_TYPE 0x00004000
#define FF_DEBUG_BUFFERS 0x00008000
#define FF_DEBUG_THREADS 0x00010000
/**
* debug
......@@ -2827,6 +2854,44 @@ typedef struct AVCodecContext {
* - encoding: unused
*/
AVPacket *pkt;
/**
* Whether this is a copy of the context which had init() called on it.
* This is used by multithreading - shared tables and picture pointers
* should be freed from the original context only.
* - encoding: Set by libavcodec.
* - decoding: Set by libavcodec.
*/
int is_copy;
/**
* Which multithreading methods to use.
* Use of FF_THREAD_FRAME will increase decoding delay by one frame per thread,
* so clients which cannot provide future frames should not use it.
*
* - encoding: Set by user, otherwise the default is used.
* - decoding: Set by user, otherwise the default is used.
*/
int thread_type;
#define FF_THREAD_FRAME 1 //< Decode more than one frame at once
#define FF_THREAD_SLICE 2 //< Decode more than one part of a single frame at once
/**
* Which multithreading methods are in use by the codec.
* - encoding: Set by libavcodec.
* - decoding: Set by libavcodec.
*/
int active_thread_type;
/**
* Set by the client if its custom get_buffer() callback can be called
* from another thread, which allows faster multithreaded decoding.
* draw_horiz_band() will be called from other threads regardless of this setting.
* Ignored if the default get_buffer() is used.
* - encoding: Set by user.
* - decoding: Set by user.
*/
int thread_safe_callbacks;
} AVCodecContext;
/**
......@@ -2879,6 +2944,26 @@ typedef struct AVCodec {
uint8_t max_lowres; ///< maximum value for lowres supported by the decoder
AVClass *priv_class; ///< AVClass for the private context
const AVProfile *profiles; ///< array of recognized profiles, or NULL if unknown, array is terminated by {FF_PROFILE_UNKNOWN}
/**
* @defgroup framethreading Frame-level threading support functions.
* @{
*/
/**
* If defined, called on thread contexts when they are created.
* If the codec allocates writable tables in init(), re-allocate them here.
* priv_data will be set to a copy of the original.
*/
int (*init_thread_copy)(AVCodecContext *);
/**
* Copy necessary context variables from a previous thread context to the current one.
* If not defined, the next thread will start automatically; otherwise, the codec
* must call ff_thread_finish_setup().
*
* dst and src will (rarely) point to the same context, in which case memcpy should be skipped.
*/
int (*update_thread_context)(AVCodecContext *dst, const AVCodecContext *src);
/** @} */
} AVCodec;
/**
......
......@@ -250,6 +250,7 @@ static const AVOption options[]={
{"vis_qp", "visualize quantization parameter (QP), lower QP are tinted greener", 0, FF_OPT_TYPE_CONST, FF_DEBUG_VIS_QP, INT_MIN, INT_MAX, V|D, "debug"},
{"vis_mb_type", "visualize block types", 0, FF_OPT_TYPE_CONST, FF_DEBUG_VIS_MB_TYPE, INT_MIN, INT_MAX, V|D, "debug"},
{"buffers", "picture buffer allocations", 0, FF_OPT_TYPE_CONST, FF_DEBUG_BUFFERS, INT_MIN, INT_MAX, V|D, "debug"},
{"thread_ops", "threading operations", 0, FF_OPT_TYPE_CONST, FF_DEBUG_THREADS, INT_MIN, INT_MAX, V|D, "debug"},
{"vismv", "visualize motion vectors (MVs)", OFFSET(debug_mv), FF_OPT_TYPE_INT, DEFAULT, 0, INT_MAX, V|D, "debug_mv"},
{"pf", "forward predicted MVs of P-frames", 0, FF_OPT_TYPE_CONST, FF_DEBUG_VIS_MV_P_FOR, INT_MIN, INT_MAX, V|D, "debug_mv"},
{"bf", "forward predicted MVs of B-frames", 0, FF_OPT_TYPE_CONST, FF_DEBUG_VIS_MV_B_FOR, INT_MIN, INT_MAX, V|D, "debug_mv"},
......@@ -431,6 +432,9 @@ static const AVOption options[]={
{"cholesky", NULL, 0, FF_OPT_TYPE_CONST, AV_LPC_TYPE_CHOLESKY, INT_MIN, INT_MAX, A|E, "lpc_type"},
{"lpc_passes", "number of passes to use for Cholesky factorization during LPC analysis", OFFSET(lpc_passes), FF_OPT_TYPE_INT, -1, INT_MIN, INT_MAX, A|E},
{"slices", "number of slices, used in parallelized decoding", OFFSET(slices), FF_OPT_TYPE_INT, 0, 0, INT_MAX, V|E},
{"thread_type", "select multithreading type", OFFSET(thread_type), FF_OPT_TYPE_INT, FF_THREAD_SLICE|FF_THREAD_FRAME, 0, INT_MAX, V|E|D, "thread_type"},
{"slice", NULL, 0, FF_OPT_TYPE_CONST, FF_THREAD_SLICE, INT_MIN, INT_MAX, V|E|D, "thread_type"},
{"frame", NULL, 0, FF_OPT_TYPE_CONST, FF_THREAD_FRAME, INT_MIN, INT_MAX, V|E|D, "thread_type"},
{NULL},
};
......
This diff is collapsed.
/*
* Copyright (c) 2008 Alexander Strange <astrange@ithinksw.com>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* Multithreading support functions
* @author Alexander Strange <astrange@ithinksw.com>
*/
#ifndef AVCODEC_THREAD_H
#define AVCODEC_THREAD_H
#include "config.h"
#include "avcodec.h"
/**
* Waits for decoding threads to finish and resets internal
* state. Called by avcodec_flush_buffers().
*
* @param avctx The context.
*/
void ff_thread_flush(AVCodecContext *avctx);
/**
* Submits a new frame to a decoding thread.
* Returns the next available frame in picture. *got_picture_ptr
* will be 0 if none is available.
*
* Parameters are the same as avcodec_decode_video2().
*/
int ff_thread_decode_frame(AVCodecContext *avctx, AVFrame *picture,
int *got_picture_ptr, AVPacket *avpkt);
/**
* If the codec defines update_thread_context(), call this
* when they are ready for the next thread to start decoding
* the next frame. After calling it, do not change any variables
* read by the update_thread_context() method, or call ff_thread_get_buffer().
*
* @param avctx The context.
*/
void ff_thread_finish_setup(AVCodecContext *avctx);
/**
* Notifies later decoding threads when part of their reference picture
* is ready.
* Call this when some part of the picture is finished decoding.
* Later calls with lower values of progress have no effect.
*
* @param f The picture being decoded.
* @param progress Value, in arbitrary units, of how much of the picture has decoded.
* @param field The field being decoded, for field-picture codecs.
* 0 for top field or frame pictures, 1 for bottom field.
*/
void ff_thread_report_progress(AVFrame *f, int progress, int field);
/**
* Waits for earlier decoding threads to finish reference pictures
* Call this before accessing some part of a picture, with a given
* value for progress, and it will return after the responsible decoding
* thread calls ff_thread_report_progress() with the same or
* higher value for progress.
*
* @param f The picture being referenced.
* @param progress Value, in arbitrary units, to wait for.
* @param field The field being referenced, for field-picture codecs.
* 0 for top field or frame pictures, 1 for bottom field.
*/
void ff_thread_await_progress(AVFrame *f, int progress, int field);
/**
* Wrapper around get_buffer() for frame-multithreaded codecs.
* Call this function instead of avctx->get_buffer(f).
* Cannot be called after the codec has called ff_thread_finish_setup().
*
* @param avctx The current context.
* @param f The frame to write into.
*/
int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f);
/**
* Wrapper around release_buffer() frame-for multithreaded codecs.
* Call this function instead of avctx->release_buffer(f).
* The AVFrame will be copied and the actual release_buffer() call
* will be performed later. The contents of data pointed to by the
* AVFrame should not be changed until ff_thread_get_buffer() is called
* on it.
*
* @param avctx The current context.
* @param f The picture being released.
*/
void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f);
#endif /* AVCODEC_THREAD_H */
......@@ -37,6 +37,7 @@
#include "dsputil.h"
#include "libavutil/opt.h"
#include "imgconvert.h"
#include "thread.h"
#include "audioconvert.h"
#include "internal.h"
#include <stdlib.h>
......@@ -261,6 +262,11 @@ int avcodec_default_get_buffer(AVCodecContext *s, AVFrame *pic){
(*picture_number)++;
if(buf->base[0] && (buf->width != w || buf->height != h || buf->pix_fmt != s->pix_fmt)){
if(s->active_thread_type&FF_THREAD_FRAME) {
av_log_missing_feature(s, "Width/height changing with frame threads is", 0);
return -1;
}
for(i=0; i<4; i++){
av_freep(&buf->base[i]);
buf->data[i]= NULL;
......@@ -532,13 +538,21 @@ int attribute_align_arg avcodec_open(AVCodecContext *avctx, AVCodec *codec)
goto free_and_end;
}
avctx->frame_number = 0;
if (HAVE_THREADS && !avctx->thread_opaque) {
ret = avcodec_thread_init(avctx, avctx->thread_count);
if (ret < 0) {
goto free_and_end;
}
}
if (avctx->codec->max_lowres < avctx->lowres) {
av_log(avctx, AV_LOG_ERROR, "The maximum value for lowres supported by the decoder is %d\n",
avctx->codec->max_lowres);
goto free_and_end;
}
if(avctx->codec->init){
if(avctx->codec->init && !(avctx->active_thread_type&FF_THREAD_FRAME)){
ret = avctx->codec->init(avctx);
if (ret < 0) {
goto free_and_end;
......@@ -636,14 +650,18 @@ int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *pi
avctx->pkt = avpkt;
if((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size){
ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
avpkt);
if((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type&FF_THREAD_FRAME)){
if (HAVE_PTHREADS && avctx->active_thread_type&FF_THREAD_FRAME)
ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
avpkt);
else {
ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
avpkt);
picture->pkt_dts= avpkt->dts;
}
emms_c(); //needed to avoid an emms_c() call before every return;
picture->pkt_dts= avpkt->dts;
if (*got_picture_ptr)
avctx->frame_number++;
}else
......@@ -768,6 +786,7 @@ av_cold int avcodec_close(AVCodecContext *avctx)
if(avctx->codec && avctx->codec->encode)
av_freep(&avctx->extradata);
avctx->codec = NULL;
avctx->active_thread_type = 0;
entangled_thread_counter--;
/* Release any user-supplied mutex. */
......@@ -1029,6 +1048,8 @@ void avcodec_init(void)
void avcodec_flush_buffers(AVCodecContext *avctx)
{
if(HAVE_PTHREADS && avctx->active_thread_type&FF_THREAD_FRAME)
ff_thread_flush(avctx);
if(avctx->codec->flush)
avctx->codec->flush(avctx);
}
......@@ -1229,3 +1250,30 @@ unsigned int ff_toupper4(unsigned int x)
+ (toupper((x>>16)&0xFF)<<16)
+ (toupper((x>>24)&0xFF)<<24);
}
#if !HAVE_PTHREADS
int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
{
f->owner = avctx;
return avctx->get_buffer(avctx, f);
}
void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
{
f->owner->release_buffer(f->owner, f);
}
void ff_thread_finish_setup(AVCodecContext *avctx)
{
}
void ff_thread_report_progress(AVFrame *f, int progress, int field)
{
}
void ff_thread_await_progress(AVFrame *f, int progress, int field)
{
}
#endif
......@@ -129,7 +129,13 @@ int avcodec_thread_init(AVCodecContext *s, int thread_count){
ThreadContext *c;
uint32_t threadid;
if(!(s->thread_type & FF_THREAD_SLICE)){
av_log(s, AV_LOG_WARNING, "The requested thread algorithm is not supported with this thread library.\n");
return 0;
}
s->thread_count= thread_count;
s->active_thread_type= FF_THREAD_SLICE;
if (thread_count <= 1)
return 0;
......
......@@ -930,6 +930,12 @@ static void compute_pkt_fields(AVFormatContext *s, AVStream *st,
/* do we have a video B-frame ? */
delay= st->codec->has_b_frames;
presentation_delayed = 0;
// ignore delay caused by frame threading so that the mpeg2-without-dts
// warning will not trigger
if (delay && st->codec->active_thread_type&FF_THREAD_FRAME)
delay -= st->codec->thread_count-1;
/* XXX: need has_b_frame, but cannot get it if the codec is
not initialized */
if (delay &&
......
......@@ -210,4 +210,15 @@
type ff_##name args
#endif
/**
* Returns NULL if a threading library has not been enabled.
* Used to disable threading functions in AVCodec definitions
* when not needed.
*/
#if HAVE_THREADS
# define ONLY_IF_THREADS_ENABLED(x) x
#else
# define ONLY_IF_THREADS_ENABLED(x) NULL
#endif
#endif /* AVUTIL_INTERNAL_H */
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment