libavcodec/pthread.c
Go to the documentation of this file.
00001 /*
00002  * Copyright (c) 2004 Roman Shaposhnik
00003  * Copyright (c) 2008 Alexander Strange (astrange@ithinksw.com)
00004  *
00005  * Many thanks to Steven M. Schultz for providing clever ideas and
00006  * to Michael Niedermayer <michaelni@gmx.at> for writing initial
00007  * implementation.
00008  *
00009  * This file is part of Libav.
00010  *
00011  * Libav is free software; you can redistribute it and/or
00012  * modify it under the terms of the GNU Lesser General Public
00013  * License as published by the Free Software Foundation; either
00014  * version 2.1 of the License, or (at your option) any later version.
00015  *
00016  * Libav is distributed in the hope that it will be useful,
00017  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00018  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00019  * Lesser General Public License for more details.
00020  *
00021  * You should have received a copy of the GNU Lesser General Public
00022  * License along with Libav; if not, write to the Free Software
00023  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
00024  */
00025 
00032 #include "config.h"
00033 
00034 #if HAVE_SCHED_GETAFFINITY
00035 #define _GNU_SOURCE
00036 #include <sched.h>
00037 #endif
00038 #if HAVE_GETPROCESSAFFINITYMASK
00039 #include <windows.h>
00040 #endif
00041 #if HAVE_SYSCTL
00042 #if HAVE_SYS_PARAM_H
00043 #include <sys/param.h>
00044 #endif
00045 #include <sys/types.h>
00046 #include <sys/sysctl.h>
00047 #endif
00048 #if HAVE_SYSCONF
00049 #include <unistd.h>
00050 #endif
00051 
00052 #include "avcodec.h"
00053 #include "internal.h"
00054 #include "thread.h"
00055 
00056 #if HAVE_PTHREADS
00057 #include <pthread.h>
00058 #elif HAVE_W32THREADS
00059 #include "w32pthreads.h"
00060 #endif
00061 
00062 typedef int (action_func)(AVCodecContext *c, void *arg);
00063 typedef int (action_func2)(AVCodecContext *c, void *arg, int jobnr, int threadnr);
00064 
00065 typedef struct ThreadContext {
00066     pthread_t *workers;
00067     action_func *func;
00068     action_func2 *func2;
00069     void *args;
00070     int *rets;
00071     int rets_count;
00072     int job_count;
00073     int job_size;
00074 
00075     pthread_cond_t last_job_cond;
00076     pthread_cond_t current_job_cond;
00077     pthread_mutex_t current_job_lock;
00078     int current_job;
00079     int done;
00080 } ThreadContext;
00081 
00083 #define MAX_BUFFERS (32+1)
00084 
00088 typedef struct PerThreadContext {
00089     struct FrameThreadContext *parent;
00090 
00091     pthread_t      thread;
00092     int            thread_init;
00093     pthread_cond_t input_cond;      
00094     pthread_cond_t progress_cond;   
00095     pthread_cond_t output_cond;     
00096 
00097     pthread_mutex_t mutex;          
00098     pthread_mutex_t progress_mutex; 
00099 
00100     AVCodecContext *avctx;          
00101 
00102     AVPacket       avpkt;           
00103     int            allocated_buf_size; 
00104 
00105     AVFrame frame;                  
00106     int     got_frame;              
00107     int     result;                 
00108 
00109     enum {
00110         STATE_INPUT_READY,          
00111         STATE_SETTING_UP,           
00112         STATE_GET_BUFFER,           
00116         STATE_SETUP_FINISHED        
00117     } state;
00118 
00123     AVFrame released_buffers[MAX_BUFFERS];
00124     int     num_released_buffers;
00125 
00129     int     progress[MAX_BUFFERS][2];
00130     uint8_t progress_used[MAX_BUFFERS];
00131 
00132     AVFrame *requested_frame;       
00133 } PerThreadContext;
00134 
00138 typedef struct FrameThreadContext {
00139     PerThreadContext *threads;     
00140     PerThreadContext *prev_thread; 
00141 
00142     pthread_mutex_t buffer_mutex;  
00143 
00144     int next_decoding;             
00145     int next_finished;             
00146 
00147     int delaying;                  
00152     int die;                       
00153 } FrameThreadContext;
00154 
00155 
00156 /* H264 slice threading seems to be buggy with more than 16 threads,
00157  * limit the number of threads to 16 for automatic detection */
00158 #define MAX_AUTO_THREADS 16
00159 
00160 static int get_logical_cpus(AVCodecContext *avctx)
00161 {
00162     int ret, nb_cpus = 1;
00163 #if HAVE_SCHED_GETAFFINITY && defined(CPU_COUNT)
00164     cpu_set_t cpuset;
00165 
00166     CPU_ZERO(&cpuset);
00167 
00168     ret = sched_getaffinity(0, sizeof(cpuset), &cpuset);
00169     if (!ret) {
00170         nb_cpus = CPU_COUNT(&cpuset);
00171     }
00172 #elif HAVE_GETPROCESSAFFINITYMASK
00173     DWORD_PTR proc_aff, sys_aff;
00174     ret = GetProcessAffinityMask(GetCurrentProcess(), &proc_aff, &sys_aff);
00175     if (ret)
00176         nb_cpus = av_popcount64(proc_aff);
00177 #elif HAVE_SYSCTL && defined(HW_NCPU)
00178     int mib[2] = { CTL_HW, HW_NCPU };
00179     size_t len = sizeof(nb_cpus);
00180 
00181     ret = sysctl(mib, 2, &nb_cpus, &len, NULL, 0);
00182     if (ret == -1)
00183         nb_cpus = 0;
00184 #elif HAVE_SYSCONF && defined(_SC_NPROC_ONLN)
00185     nb_cpus = sysconf(_SC_NPROC_ONLN);
00186 #elif HAVE_SYSCONF && defined(_SC_NPROCESSORS_ONLN)
00187     nb_cpus = sysconf(_SC_NPROCESSORS_ONLN);
00188 #endif
00189     av_log(avctx, AV_LOG_DEBUG, "detected %d logical cores\n", nb_cpus);
00190     return nb_cpus;
00191 }
00192 
00193 
00194 static void* attribute_align_arg worker(void *v)
00195 {
00196     AVCodecContext *avctx = v;
00197     ThreadContext *c = avctx->thread_opaque;
00198     int our_job = c->job_count;
00199     int thread_count = avctx->thread_count;
00200     int self_id;
00201 
00202     pthread_mutex_lock(&c->current_job_lock);
00203     self_id = c->current_job++;
00204     for (;;){
00205         while (our_job >= c->job_count) {
00206             if (c->current_job == thread_count + c->job_count)
00207                 pthread_cond_signal(&c->last_job_cond);
00208 
00209             pthread_cond_wait(&c->current_job_cond, &c->current_job_lock);
00210             our_job = self_id;
00211 
00212             if (c->done) {
00213                 pthread_mutex_unlock(&c->current_job_lock);
00214                 return NULL;
00215             }
00216         }
00217         pthread_mutex_unlock(&c->current_job_lock);
00218 
00219         c->rets[our_job%c->rets_count] = c->func ? c->func(avctx, (char*)c->args + our_job*c->job_size):
00220                                                    c->func2(avctx, c->args, our_job, self_id);
00221 
00222         pthread_mutex_lock(&c->current_job_lock);
00223         our_job = c->current_job++;
00224     }
00225 }
00226 
00227 static av_always_inline void avcodec_thread_park_workers(ThreadContext *c, int thread_count)
00228 {
00229     pthread_cond_wait(&c->last_job_cond, &c->current_job_lock);
00230     pthread_mutex_unlock(&c->current_job_lock);
00231 }
00232 
00233 static void thread_free(AVCodecContext *avctx)
00234 {
00235     ThreadContext *c = avctx->thread_opaque;
00236     int i;
00237 
00238     pthread_mutex_lock(&c->current_job_lock);
00239     c->done = 1;
00240     pthread_cond_broadcast(&c->current_job_cond);
00241     pthread_mutex_unlock(&c->current_job_lock);
00242 
00243     for (i=0; i<avctx->thread_count; i++)
00244          pthread_join(c->workers[i], NULL);
00245 
00246     pthread_mutex_destroy(&c->current_job_lock);
00247     pthread_cond_destroy(&c->current_job_cond);
00248     pthread_cond_destroy(&c->last_job_cond);
00249     av_free(c->workers);
00250     av_freep(&avctx->thread_opaque);
00251 }
00252 
00253 static int avcodec_thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)
00254 {
00255     ThreadContext *c= avctx->thread_opaque;
00256     int dummy_ret;
00257 
00258     if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)
00259         return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);
00260 
00261     if (job_count <= 0)
00262         return 0;
00263 
00264     pthread_mutex_lock(&c->current_job_lock);
00265 
00266     c->current_job = avctx->thread_count;
00267     c->job_count = job_count;
00268     c->job_size = job_size;
00269     c->args = arg;
00270     c->func = func;
00271     if (ret) {
00272         c->rets = ret;
00273         c->rets_count = job_count;
00274     } else {
00275         c->rets = &dummy_ret;
00276         c->rets_count = 1;
00277     }
00278     pthread_cond_broadcast(&c->current_job_cond);
00279 
00280     avcodec_thread_park_workers(c, avctx->thread_count);
00281 
00282     return 0;
00283 }
00284 
00285 static int avcodec_thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)
00286 {
00287     ThreadContext *c= avctx->thread_opaque;
00288     c->func2 = func2;
00289     return avcodec_thread_execute(avctx, NULL, arg, ret, job_count, 0);
00290 }
00291 
00292 static int thread_init(AVCodecContext *avctx)
00293 {
00294     int i;
00295     ThreadContext *c;
00296     int thread_count = avctx->thread_count;
00297 
00298     if (!thread_count) {
00299         int nb_cpus = get_logical_cpus(avctx);
00300         // use number of cores + 1 as thread count if there is more than one
00301         if (nb_cpus > 1)
00302             thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
00303         else
00304             thread_count = avctx->thread_count = 1;
00305     }
00306 
00307     if (thread_count <= 1) {
00308         avctx->active_thread_type = 0;
00309         return 0;
00310     }
00311 
00312     c = av_mallocz(sizeof(ThreadContext));
00313     if (!c)
00314         return -1;
00315 
00316     c->workers = av_mallocz(sizeof(pthread_t)*thread_count);
00317     if (!c->workers) {
00318         av_free(c);
00319         return -1;
00320     }
00321 
00322     avctx->thread_opaque = c;
00323     c->current_job = 0;
00324     c->job_count = 0;
00325     c->job_size = 0;
00326     c->done = 0;
00327     pthread_cond_init(&c->current_job_cond, NULL);
00328     pthread_cond_init(&c->last_job_cond, NULL);
00329     pthread_mutex_init(&c->current_job_lock, NULL);
00330     pthread_mutex_lock(&c->current_job_lock);
00331     for (i=0; i<thread_count; i++) {
00332         if(pthread_create(&c->workers[i], NULL, worker, avctx)) {
00333            avctx->thread_count = i;
00334            pthread_mutex_unlock(&c->current_job_lock);
00335            ff_thread_free(avctx);
00336            return -1;
00337         }
00338     }
00339 
00340     avcodec_thread_park_workers(c, thread_count);
00341 
00342     avctx->execute = avcodec_thread_execute;
00343     avctx->execute2 = avcodec_thread_execute2;
00344     return 0;
00345 }
00346 
00354 static attribute_align_arg void *frame_worker_thread(void *arg)
00355 {
00356     PerThreadContext *p = arg;
00357     FrameThreadContext *fctx = p->parent;
00358     AVCodecContext *avctx = p->avctx;
00359     AVCodec *codec = avctx->codec;
00360 
00361     while (1) {
00362         if (p->state == STATE_INPUT_READY && !fctx->die) {
00363             pthread_mutex_lock(&p->mutex);
00364             while (p->state == STATE_INPUT_READY && !fctx->die)
00365                 pthread_cond_wait(&p->input_cond, &p->mutex);
00366             pthread_mutex_unlock(&p->mutex);
00367         }
00368 
00369         if (fctx->die) break;
00370 
00371         if (!codec->update_thread_context && avctx->thread_safe_callbacks)
00372             ff_thread_finish_setup(avctx);
00373 
00374         pthread_mutex_lock(&p->mutex);
00375         avcodec_get_frame_defaults(&p->frame);
00376         p->got_frame = 0;
00377         p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
00378 
00379         if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
00380 
00381         p->state = STATE_INPUT_READY;
00382 
00383         pthread_mutex_lock(&p->progress_mutex);
00384         pthread_cond_signal(&p->output_cond);
00385         pthread_mutex_unlock(&p->progress_mutex);
00386 
00387         pthread_mutex_unlock(&p->mutex);
00388     }
00389 
00390     return NULL;
00391 }
00392 
00400 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
00401 {
00402     int err = 0;
00403 
00404     if (dst != src) {
00405         dst->sub_id    = src->sub_id;
00406         dst->time_base = src->time_base;
00407         dst->width     = src->width;
00408         dst->height    = src->height;
00409         dst->pix_fmt   = src->pix_fmt;
00410 
00411         dst->coded_width  = src->coded_width;
00412         dst->coded_height = src->coded_height;
00413 
00414         dst->has_b_frames = src->has_b_frames;
00415         dst->idct_algo    = src->idct_algo;
00416 
00417         dst->bits_per_coded_sample = src->bits_per_coded_sample;
00418         dst->sample_aspect_ratio   = src->sample_aspect_ratio;
00419         dst->dtg_active_format     = src->dtg_active_format;
00420 
00421         dst->profile = src->profile;
00422         dst->level   = src->level;
00423 
00424         dst->bits_per_raw_sample = src->bits_per_raw_sample;
00425         dst->ticks_per_frame     = src->ticks_per_frame;
00426         dst->color_primaries     = src->color_primaries;
00427 
00428         dst->color_trc   = src->color_trc;
00429         dst->colorspace  = src->colorspace;
00430         dst->color_range = src->color_range;
00431         dst->chroma_sample_location = src->chroma_sample_location;
00432     }
00433 
00434     if (for_user) {
00435         dst->coded_frame = src->coded_frame;
00436     } else {
00437         if (dst->codec->update_thread_context)
00438             err = dst->codec->update_thread_context(dst, src);
00439     }
00440 
00441     return err;
00442 }
00443 
00451 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
00452 {
00453 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
00454     dst->flags          = src->flags;
00455 
00456     dst->draw_horiz_band= src->draw_horiz_band;
00457     dst->get_buffer     = src->get_buffer;
00458     dst->release_buffer = src->release_buffer;
00459 
00460     dst->opaque   = src->opaque;
00461     dst->dsp_mask = src->dsp_mask;
00462     dst->debug    = src->debug;
00463     dst->debug_mv = src->debug_mv;
00464 
00465     dst->slice_flags = src->slice_flags;
00466     dst->flags2      = src->flags2;
00467 
00468     copy_fields(skip_loop_filter, bidir_refine);
00469 
00470     dst->frame_number     = src->frame_number;
00471     dst->reordered_opaque = src->reordered_opaque;
00472 
00473     if (src->slice_count && src->slice_offset) {
00474         if (dst->slice_count < src->slice_count) {
00475             int *tmp = av_realloc(dst->slice_offset, src->slice_count *
00476                                   sizeof(*dst->slice_offset));
00477             if (!tmp) {
00478                 av_free(dst->slice_offset);
00479                 return AVERROR(ENOMEM);
00480             }
00481             dst->slice_offset = tmp;
00482         }
00483         memcpy(dst->slice_offset, src->slice_offset,
00484                src->slice_count * sizeof(*dst->slice_offset));
00485     }
00486     dst->slice_count = src->slice_count;
00487     return 0;
00488 #undef copy_fields
00489 }
00490 
00491 static void free_progress(AVFrame *f)
00492 {
00493     PerThreadContext *p = f->owner->thread_opaque;
00494     int *progress = f->thread_opaque;
00495 
00496     p->progress_used[(progress - p->progress[0]) / 2] = 0;
00497 }
00498 
00500 static void release_delayed_buffers(PerThreadContext *p)
00501 {
00502     FrameThreadContext *fctx = p->parent;
00503 
00504     while (p->num_released_buffers > 0) {
00505         AVFrame *f;
00506 
00507         pthread_mutex_lock(&fctx->buffer_mutex);
00508         f = &p->released_buffers[--p->num_released_buffers];
00509         free_progress(f);
00510         f->thread_opaque = NULL;
00511 
00512         f->owner->release_buffer(f->owner, f);
00513         pthread_mutex_unlock(&fctx->buffer_mutex);
00514     }
00515 }
00516 
00517 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
00518 {
00519     FrameThreadContext *fctx = p->parent;
00520     PerThreadContext *prev_thread = fctx->prev_thread;
00521     AVCodec *codec = p->avctx->codec;
00522     uint8_t *buf = p->avpkt.data;
00523 
00524     if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
00525 
00526     pthread_mutex_lock(&p->mutex);
00527 
00528     release_delayed_buffers(p);
00529 
00530     if (prev_thread) {
00531         int err;
00532         if (prev_thread->state == STATE_SETTING_UP) {
00533             pthread_mutex_lock(&prev_thread->progress_mutex);
00534             while (prev_thread->state == STATE_SETTING_UP)
00535                 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
00536             pthread_mutex_unlock(&prev_thread->progress_mutex);
00537         }
00538 
00539         err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
00540         if (err) {
00541             pthread_mutex_unlock(&p->mutex);
00542             return err;
00543         }
00544     }
00545 
00546     av_fast_malloc(&buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
00547     p->avpkt = *avpkt;
00548     p->avpkt.data = buf;
00549     memcpy(buf, avpkt->data, avpkt->size);
00550     memset(buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
00551 
00552     p->state = STATE_SETTING_UP;
00553     pthread_cond_signal(&p->input_cond);
00554     pthread_mutex_unlock(&p->mutex);
00555 
00556     /*
00557      * If the client doesn't have a thread-safe get_buffer(),
00558      * then decoding threads call back to the main thread,
00559      * and it calls back to the client here.
00560      */
00561 
00562     if (!p->avctx->thread_safe_callbacks &&
00563          p->avctx->get_buffer != avcodec_default_get_buffer) {
00564         while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
00565             pthread_mutex_lock(&p->progress_mutex);
00566             while (p->state == STATE_SETTING_UP)
00567                 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
00568 
00569             if (p->state == STATE_GET_BUFFER) {
00570                 p->result = p->avctx->get_buffer(p->avctx, p->requested_frame);
00571                 p->state  = STATE_SETTING_UP;
00572                 pthread_cond_signal(&p->progress_cond);
00573             }
00574             pthread_mutex_unlock(&p->progress_mutex);
00575         }
00576     }
00577 
00578     fctx->prev_thread = p;
00579     fctx->next_decoding++;
00580 
00581     return 0;
00582 }
00583 
00584 int ff_thread_decode_frame(AVCodecContext *avctx,
00585                            AVFrame *picture, int *got_picture_ptr,
00586                            AVPacket *avpkt)
00587 {
00588     FrameThreadContext *fctx = avctx->thread_opaque;
00589     int finished = fctx->next_finished;
00590     PerThreadContext *p;
00591     int err;
00592 
00593     /*
00594      * Submit a packet to the next decoding thread.
00595      */
00596 
00597     p = &fctx->threads[fctx->next_decoding];
00598     err = update_context_from_user(p->avctx, avctx);
00599     if (err) return err;
00600     err = submit_packet(p, avpkt);
00601     if (err) return err;
00602 
00603     /*
00604      * If we're still receiving the initial packets, don't return a frame.
00605      */
00606 
00607     if (fctx->delaying && avpkt->size) {
00608         if (fctx->next_decoding >= (avctx->thread_count-1)) fctx->delaying = 0;
00609 
00610         *got_picture_ptr=0;
00611         return avpkt->size;
00612     }
00613 
00614     /*
00615      * Return the next available frame from the oldest thread.
00616      * If we're at the end of the stream, then we have to skip threads that
00617      * didn't output a frame, because we don't want to accidentally signal
00618      * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
00619      */
00620 
00621     do {
00622         p = &fctx->threads[finished++];
00623 
00624         if (p->state != STATE_INPUT_READY) {
00625             pthread_mutex_lock(&p->progress_mutex);
00626             while (p->state != STATE_INPUT_READY)
00627                 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
00628             pthread_mutex_unlock(&p->progress_mutex);
00629         }
00630 
00631         *picture = p->frame;
00632         *got_picture_ptr = p->got_frame;
00633         picture->pkt_dts = p->avpkt.dts;
00634         picture->sample_aspect_ratio = p->avctx->sample_aspect_ratio;
00635         picture->width  = p->avctx->width;
00636         picture->height = p->avctx->height;
00637         picture->format = p->avctx->pix_fmt;
00638 
00639         /*
00640          * A later call with avkpt->size == 0 may loop over all threads,
00641          * including this one, searching for a frame to return before being
00642          * stopped by the "finished != fctx->next_finished" condition.
00643          * Make sure we don't mistakenly return the same frame again.
00644          */
00645         p->got_frame = 0;
00646 
00647         if (finished >= avctx->thread_count) finished = 0;
00648     } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
00649 
00650     update_context_from_thread(avctx, p->avctx, 1);
00651 
00652     if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
00653 
00654     fctx->next_finished = finished;
00655 
00656     /* return the size of the consumed packet if no error occurred */
00657     return (p->result >= 0) ? avpkt->size : p->result;
00658 }
00659 
00660 void ff_thread_report_progress(AVFrame *f, int n, int field)
00661 {
00662     PerThreadContext *p;
00663     int *progress = f->thread_opaque;
00664 
00665     if (!progress || progress[field] >= n) return;
00666 
00667     p = f->owner->thread_opaque;
00668 
00669     if (f->owner->debug&FF_DEBUG_THREADS)
00670         av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
00671 
00672     pthread_mutex_lock(&p->progress_mutex);
00673     progress[field] = n;
00674     pthread_cond_broadcast(&p->progress_cond);
00675     pthread_mutex_unlock(&p->progress_mutex);
00676 }
00677 
00678 void ff_thread_await_progress(AVFrame *f, int n, int field)
00679 {
00680     PerThreadContext *p;
00681     int *progress = f->thread_opaque;
00682 
00683     if (!progress || progress[field] >= n) return;
00684 
00685     p = f->owner->thread_opaque;
00686 
00687     if (f->owner->debug&FF_DEBUG_THREADS)
00688         av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
00689 
00690     pthread_mutex_lock(&p->progress_mutex);
00691     while (progress[field] < n)
00692         pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
00693     pthread_mutex_unlock(&p->progress_mutex);
00694 }
00695 
00696 void ff_thread_finish_setup(AVCodecContext *avctx) {
00697     PerThreadContext *p = avctx->thread_opaque;
00698 
00699     if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
00700 
00701     pthread_mutex_lock(&p->progress_mutex);
00702     p->state = STATE_SETUP_FINISHED;
00703     pthread_cond_broadcast(&p->progress_cond);
00704     pthread_mutex_unlock(&p->progress_mutex);
00705 }
00706 
00708 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
00709 {
00710     int i;
00711 
00712     for (i = 0; i < thread_count; i++) {
00713         PerThreadContext *p = &fctx->threads[i];
00714 
00715         if (p->state != STATE_INPUT_READY) {
00716             pthread_mutex_lock(&p->progress_mutex);
00717             while (p->state != STATE_INPUT_READY)
00718                 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
00719             pthread_mutex_unlock(&p->progress_mutex);
00720         }
00721     }
00722 }
00723 
00724 static void frame_thread_free(AVCodecContext *avctx, int thread_count)
00725 {
00726     FrameThreadContext *fctx = avctx->thread_opaque;
00727     AVCodec *codec = avctx->codec;
00728     int i;
00729 
00730     park_frame_worker_threads(fctx, thread_count);
00731 
00732     if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
00733         update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);
00734 
00735     fctx->die = 1;
00736 
00737     for (i = 0; i < thread_count; i++) {
00738         PerThreadContext *p = &fctx->threads[i];
00739 
00740         pthread_mutex_lock(&p->mutex);
00741         pthread_cond_signal(&p->input_cond);
00742         pthread_mutex_unlock(&p->mutex);
00743 
00744         if (p->thread_init)
00745             pthread_join(p->thread, NULL);
00746 
00747         if (codec->close)
00748             codec->close(p->avctx);
00749 
00750         avctx->codec = NULL;
00751 
00752         release_delayed_buffers(p);
00753     }
00754 
00755     for (i = 0; i < thread_count; i++) {
00756         PerThreadContext *p = &fctx->threads[i];
00757 
00758         avcodec_default_free_buffers(p->avctx);
00759 
00760         pthread_mutex_destroy(&p->mutex);
00761         pthread_mutex_destroy(&p->progress_mutex);
00762         pthread_cond_destroy(&p->input_cond);
00763         pthread_cond_destroy(&p->progress_cond);
00764         pthread_cond_destroy(&p->output_cond);
00765         av_freep(&p->avpkt.data);
00766 
00767         if (i) {
00768             av_freep(&p->avctx->priv_data);
00769             av_freep(&p->avctx->internal);
00770             av_freep(&p->avctx->slice_offset);
00771         }
00772 
00773         av_freep(&p->avctx);
00774     }
00775 
00776     av_freep(&fctx->threads);
00777     pthread_mutex_destroy(&fctx->buffer_mutex);
00778     av_freep(&avctx->thread_opaque);
00779 }
00780 
00781 static int frame_thread_init(AVCodecContext *avctx)
00782 {
00783     int thread_count = avctx->thread_count;
00784     AVCodec *codec = avctx->codec;
00785     AVCodecContext *src = avctx;
00786     FrameThreadContext *fctx;
00787     int i, err = 0;
00788 
00789     if (!thread_count) {
00790         int nb_cpus = get_logical_cpus(avctx);
00791         // use number of cores + 1 as thread count if there is more than one
00792         if (nb_cpus > 1)
00793             thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
00794         else
00795             thread_count = avctx->thread_count = 1;
00796     }
00797 
00798     if (thread_count <= 1) {
00799         avctx->active_thread_type = 0;
00800         return 0;
00801     }
00802 
00803     avctx->thread_opaque = fctx = av_mallocz(sizeof(FrameThreadContext));
00804 
00805     fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
00806     pthread_mutex_init(&fctx->buffer_mutex, NULL);
00807     fctx->delaying = 1;
00808 
00809     for (i = 0; i < thread_count; i++) {
00810         AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
00811         PerThreadContext *p  = &fctx->threads[i];
00812 
00813         pthread_mutex_init(&p->mutex, NULL);
00814         pthread_mutex_init(&p->progress_mutex, NULL);
00815         pthread_cond_init(&p->input_cond, NULL);
00816         pthread_cond_init(&p->progress_cond, NULL);
00817         pthread_cond_init(&p->output_cond, NULL);
00818 
00819         p->parent = fctx;
00820         p->avctx  = copy;
00821 
00822         if (!copy) {
00823             err = AVERROR(ENOMEM);
00824             goto error;
00825         }
00826 
00827         *copy = *src;
00828         copy->thread_opaque = p;
00829         copy->pkt = &p->avpkt;
00830 
00831         if (!i) {
00832             src = copy;
00833 
00834             if (codec->init)
00835                 err = codec->init(copy);
00836 
00837             update_context_from_thread(avctx, copy, 1);
00838         } else {
00839             copy->priv_data = av_malloc(codec->priv_data_size);
00840             if (!copy->priv_data) {
00841                 err = AVERROR(ENOMEM);
00842                 goto error;
00843             }
00844             memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
00845             copy->internal = av_malloc(sizeof(AVCodecInternal));
00846             if (!copy->internal) {
00847                 err = AVERROR(ENOMEM);
00848                 goto error;
00849             }
00850             *copy->internal = *src->internal;
00851             copy->internal->is_copy = 1;
00852 
00853             if (codec->init_thread_copy)
00854                 err = codec->init_thread_copy(copy);
00855         }
00856 
00857         if (err) goto error;
00858 
00859         if (!pthread_create(&p->thread, NULL, frame_worker_thread, p))
00860             p->thread_init = 1;
00861     }
00862 
00863     return 0;
00864 
00865 error:
00866     frame_thread_free(avctx, i+1);
00867 
00868     return err;
00869 }
00870 
00871 void ff_thread_flush(AVCodecContext *avctx)
00872 {
00873     FrameThreadContext *fctx = avctx->thread_opaque;
00874 
00875     if (!avctx->thread_opaque) return;
00876 
00877     park_frame_worker_threads(fctx, avctx->thread_count);
00878     if (fctx->prev_thread) {
00879         if (fctx->prev_thread != &fctx->threads[0])
00880             update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
00881         if (avctx->codec->flush)
00882             avctx->codec->flush(fctx->threads[0].avctx);
00883     }
00884 
00885     fctx->next_decoding = fctx->next_finished = 0;
00886     fctx->delaying = 1;
00887     fctx->prev_thread = NULL;
00888 }
00889 
00890 static int *allocate_progress(PerThreadContext *p)
00891 {
00892     int i;
00893 
00894     for (i = 0; i < MAX_BUFFERS; i++)
00895         if (!p->progress_used[i]) break;
00896 
00897     if (i == MAX_BUFFERS) {
00898         av_log(p->avctx, AV_LOG_ERROR, "allocate_progress() overflow\n");
00899         return NULL;
00900     }
00901 
00902     p->progress_used[i] = 1;
00903 
00904     return p->progress[i];
00905 }
00906 
00907 int ff_thread_get_buffer(AVCodecContext *avctx, AVFrame *f)
00908 {
00909     PerThreadContext *p = avctx->thread_opaque;
00910     int *progress, err;
00911 
00912     f->owner = avctx;
00913 
00914     if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
00915         f->thread_opaque = NULL;
00916         return avctx->get_buffer(avctx, f);
00917     }
00918 
00919     if (p->state != STATE_SETTING_UP &&
00920         (avctx->codec->update_thread_context || !avctx->thread_safe_callbacks)) {
00921         av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
00922         return -1;
00923     }
00924 
00925     pthread_mutex_lock(&p->parent->buffer_mutex);
00926     f->thread_opaque = progress = allocate_progress(p);
00927 
00928     if (!progress) {
00929         pthread_mutex_unlock(&p->parent->buffer_mutex);
00930         return -1;
00931     }
00932 
00933     progress[0] =
00934     progress[1] = -1;
00935 
00936     if (avctx->thread_safe_callbacks ||
00937         avctx->get_buffer == avcodec_default_get_buffer) {
00938         err = avctx->get_buffer(avctx, f);
00939     } else {
00940         p->requested_frame = f;
00941         p->state = STATE_GET_BUFFER;
00942         pthread_mutex_lock(&p->progress_mutex);
00943         pthread_cond_signal(&p->progress_cond);
00944 
00945         while (p->state != STATE_SETTING_UP)
00946             pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
00947 
00948         err = p->result;
00949 
00950         pthread_mutex_unlock(&p->progress_mutex);
00951 
00952         if (!avctx->codec->update_thread_context)
00953             ff_thread_finish_setup(avctx);
00954     }
00955 
00956     pthread_mutex_unlock(&p->parent->buffer_mutex);
00957 
00958     return err;
00959 }
00960 
00961 void ff_thread_release_buffer(AVCodecContext *avctx, AVFrame *f)
00962 {
00963     PerThreadContext *p = avctx->thread_opaque;
00964     FrameThreadContext *fctx;
00965 
00966     if (!(avctx->active_thread_type&FF_THREAD_FRAME)) {
00967         avctx->release_buffer(avctx, f);
00968         return;
00969     }
00970 
00971     if (p->num_released_buffers >= MAX_BUFFERS) {
00972         av_log(p->avctx, AV_LOG_ERROR, "too many thread_release_buffer calls!\n");
00973         return;
00974     }
00975 
00976     if(avctx->debug & FF_DEBUG_BUFFERS)
00977         av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
00978 
00979     fctx = p->parent;
00980     pthread_mutex_lock(&fctx->buffer_mutex);
00981     p->released_buffers[p->num_released_buffers++] = *f;
00982     pthread_mutex_unlock(&fctx->buffer_mutex);
00983     memset(f->data, 0, sizeof(f->data));
00984 }
00985 
00995 static void validate_thread_parameters(AVCodecContext *avctx)
00996 {
00997     int frame_threading_supported = (avctx->codec->capabilities & CODEC_CAP_FRAME_THREADS)
00998                                 && !(avctx->flags & CODEC_FLAG_TRUNCATED)
00999                                 && !(avctx->flags & CODEC_FLAG_LOW_DELAY)
01000                                 && !(avctx->flags2 & CODEC_FLAG2_CHUNKS);
01001     if (avctx->thread_count == 1) {
01002         avctx->active_thread_type = 0;
01003     } else if (frame_threading_supported && (avctx->thread_type & FF_THREAD_FRAME)) {
01004         avctx->active_thread_type = FF_THREAD_FRAME;
01005     } else if (avctx->codec->capabilities & CODEC_CAP_SLICE_THREADS &&
01006                avctx->thread_type & FF_THREAD_SLICE) {
01007         avctx->active_thread_type = FF_THREAD_SLICE;
01008     } else if (!(avctx->codec->capabilities & CODEC_CAP_AUTO_THREADS)) {
01009         avctx->thread_count       = 1;
01010         avctx->active_thread_type = 0;
01011     }
01012 }
01013 
01014 int ff_thread_init(AVCodecContext *avctx)
01015 {
01016     if (avctx->thread_opaque) {
01017         av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");
01018         return -1;
01019     }
01020 
01021 #if HAVE_W32THREADS
01022     w32thread_init();
01023 #endif
01024 
01025     if (avctx->codec) {
01026         validate_thread_parameters(avctx);
01027 
01028         if (avctx->active_thread_type&FF_THREAD_SLICE)
01029             return thread_init(avctx);
01030         else if (avctx->active_thread_type&FF_THREAD_FRAME)
01031             return frame_thread_init(avctx);
01032     }
01033 
01034     return 0;
01035 }
01036 
01037 void ff_thread_free(AVCodecContext *avctx)
01038 {
01039     if (avctx->active_thread_type&FF_THREAD_FRAME)
01040         frame_thread_free(avctx, avctx->thread_count);
01041     else
01042         thread_free(avctx);
01043 }