]> git.sesse.net Git - ffmpeg/blob - libavcodec/pthread_frame.c
Merge commit 'cffecc0e7ebd642afaa1fb9f56fab1fcc283293c'
[ffmpeg] / libavcodec / pthread_frame.c
1 /*
2  * This file is part of FFmpeg.
3  *
4  * FFmpeg is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * FFmpeg is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with FFmpeg; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18
19 /**
20  * @file
21  * Frame multithreading support functions
22  * @see doc/multithreading.txt
23  */
24
25 #include "config.h"
26
27 #include <stdint.h>
28
29 #if HAVE_PTHREADS
30 #include <pthread.h>
31 #elif HAVE_W32THREADS
32 #include "compat/w32pthreads.h"
33 #elif HAVE_OS2THREADS
34 #include "compat/os2threads.h"
35 #endif
36
37 #include "avcodec.h"
38 #include "internal.h"
39 #include "pthread_internal.h"
40 #include "thread.h"
41
42 #include "libavutil/avassert.h"
43 #include "libavutil/buffer.h"
44 #include "libavutil/common.h"
45 #include "libavutil/cpu.h"
46 #include "libavutil/frame.h"
47 #include "libavutil/log.h"
48 #include "libavutil/mem.h"
49
50 /**
51  * Context used by codec threads and stored in their AVCodecInternal thread_ctx.
52  */
53 typedef struct PerThreadContext {
54     struct FrameThreadContext *parent;
55
56     pthread_t      thread;
57     int            thread_init;
58     pthread_cond_t input_cond;      ///< Used to wait for a new packet from the main thread.
59     pthread_cond_t progress_cond;   ///< Used by child threads to wait for progress to change.
60     pthread_cond_t output_cond;     ///< Used by the main thread to wait for frames to finish.
61
62     pthread_mutex_t mutex;          ///< Mutex used to protect the contents of the PerThreadContext.
63     pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
64
65     AVCodecContext *avctx;          ///< Context used to decode packets passed to this thread.
66
67     AVPacket       avpkt;           ///< Input packet (for decoding) or output (for encoding).
68     uint8_t       *buf;             ///< backup storage for packet data when the input packet is not refcounted
69     int            allocated_buf_size; ///< Size allocated for buf
70
71     AVFrame frame;                  ///< Output frame (for decoding) or input (for encoding).
72     int     got_frame;              ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
73     int     result;                 ///< The result of the last codec decode/encode() call.
74
75     enum {
76         STATE_INPUT_READY,          ///< Set when the thread is awaiting a packet.
77         STATE_SETTING_UP,           ///< Set before the codec has called ff_thread_finish_setup().
78         STATE_GET_BUFFER,           /**<
79                                      * Set when the codec calls get_buffer().
80                                      * State is returned to STATE_SETTING_UP afterwards.
81                                      */
82         STATE_GET_FORMAT,           /**<
83                                      * Set when the codec calls get_format().
84                                      * State is returned to STATE_SETTING_UP afterwards.
85                                      */
86         STATE_SETUP_FINISHED        ///< Set after the codec has called ff_thread_finish_setup().
87     } state;
88
89     /**
90      * Array of frames passed to ff_thread_release_buffer().
91      * Frames are released after all threads referencing them are finished.
92      */
93     AVFrame *released_buffers;
94     int  num_released_buffers;
95     int      released_buffers_allocated;
96
97     AVFrame *requested_frame;       ///< AVFrame the codec passed to get_buffer()
98     int      requested_flags;       ///< flags passed to get_buffer() for requested_frame
99
100     const enum AVPixelFormat *available_formats; ///< Format array for get_format()
101     enum AVPixelFormat result_format;            ///< get_format() result
102 } PerThreadContext;
103
104 /**
105  * Context stored in the client AVCodecInternal thread_ctx.
106  */
107 typedef struct FrameThreadContext {
108     PerThreadContext *threads;     ///< The contexts for each thread.
109     PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
110
111     pthread_mutex_t buffer_mutex;  ///< Mutex used to protect get/release_buffer().
112
113     int next_decoding;             ///< The next context to submit a packet to.
114     int next_finished;             ///< The next context to return output from.
115
116     int delaying;                  /**<
117                                     * Set for the first N packets, where N is the number of threads.
118                                     * While it is set, ff_thread_en/decode_frame won't return any results.
119                                     */
120
121     int die;                       ///< Set when threads should exit.
122 } FrameThreadContext;
123
124 #define THREAD_SAFE_CALLBACKS(avctx) \
125 ((avctx)->thread_safe_callbacks || (!(avctx)->get_buffer && (avctx)->get_buffer2 == avcodec_default_get_buffer2))
126
127 /**
128  * Codec worker thread.
129  *
130  * Automatically calls ff_thread_finish_setup() if the codec does
131  * not provide an update_thread_context method, or if the codec returns
132  * before calling it.
133  */
134 static attribute_align_arg void *frame_worker_thread(void *arg)
135 {
136     PerThreadContext *p = arg;
137     FrameThreadContext *fctx = p->parent;
138     AVCodecContext *avctx = p->avctx;
139     const AVCodec *codec = avctx->codec;
140
141     pthread_mutex_lock(&p->mutex);
142     while (1) {
143             while (p->state == STATE_INPUT_READY && !fctx->die)
144                 pthread_cond_wait(&p->input_cond, &p->mutex);
145
146         if (fctx->die) break;
147
148         if (!codec->update_thread_context && THREAD_SAFE_CALLBACKS(avctx))
149             ff_thread_finish_setup(avctx);
150
151         avcodec_get_frame_defaults(&p->frame);
152         p->got_frame = 0;
153         p->result = codec->decode(avctx, &p->frame, &p->got_frame, &p->avpkt);
154
155         /* many decoders assign whole AVFrames, thus overwriting extended_data;
156          * make sure it's set correctly */
157         p->frame.extended_data = p->frame.data;
158
159         if (p->state == STATE_SETTING_UP) ff_thread_finish_setup(avctx);
160
161         pthread_mutex_lock(&p->progress_mutex);
162 #if 0 //BUFREF-FIXME
163         for (i = 0; i < MAX_BUFFERS; i++)
164             if (p->progress_used[i] && (p->got_frame || p->result<0 || avctx->codec_id != AV_CODEC_ID_H264)) {
165                 p->progress[i][0] = INT_MAX;
166                 p->progress[i][1] = INT_MAX;
167             }
168 #endif
169         p->state = STATE_INPUT_READY;
170
171         pthread_cond_broadcast(&p->progress_cond);
172         pthread_cond_signal(&p->output_cond);
173         pthread_mutex_unlock(&p->progress_mutex);
174     }
175     pthread_mutex_unlock(&p->mutex);
176
177     return NULL;
178 }
179
180 /**
181  * Update the next thread's AVCodecContext with values from the reference thread's context.
182  *
183  * @param dst The destination context.
184  * @param src The source context.
185  * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
186  */
187 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
188 {
189     int err = 0;
190
191     if (dst != src) {
192         dst->time_base = src->time_base;
193         dst->width     = src->width;
194         dst->height    = src->height;
195         dst->pix_fmt   = src->pix_fmt;
196
197         dst->coded_width  = src->coded_width;
198         dst->coded_height = src->coded_height;
199
200         dst->has_b_frames = src->has_b_frames;
201         dst->idct_algo    = src->idct_algo;
202
203         dst->bits_per_coded_sample = src->bits_per_coded_sample;
204         dst->sample_aspect_ratio   = src->sample_aspect_ratio;
205         dst->dtg_active_format     = src->dtg_active_format;
206
207         dst->profile = src->profile;
208         dst->level   = src->level;
209
210         dst->bits_per_raw_sample = src->bits_per_raw_sample;
211         dst->ticks_per_frame     = src->ticks_per_frame;
212         dst->color_primaries     = src->color_primaries;
213
214         dst->color_trc   = src->color_trc;
215         dst->colorspace  = src->colorspace;
216         dst->color_range = src->color_range;
217         dst->chroma_sample_location = src->chroma_sample_location;
218
219         dst->hwaccel = src->hwaccel;
220         dst->hwaccel_context = src->hwaccel_context;
221
222         dst->channels       = src->channels;
223         dst->sample_rate    = src->sample_rate;
224         dst->sample_fmt     = src->sample_fmt;
225         dst->channel_layout = src->channel_layout;
226     }
227
228     if (for_user) {
229         dst->delay       = src->thread_count - 1;
230         dst->coded_frame = src->coded_frame;
231     } else {
232         if (dst->codec->update_thread_context)
233             err = dst->codec->update_thread_context(dst, src);
234     }
235
236     return err;
237 }
238
239 /**
240  * Update the next thread's AVCodecContext with values set by the user.
241  *
242  * @param dst The destination context.
243  * @param src The source context.
244  * @return 0 on success, negative error code on failure
245  */
246 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
247 {
248 #define copy_fields(s, e) memcpy(&dst->s, &src->s, (char*)&dst->e - (char*)&dst->s);
249     dst->flags          = src->flags;
250
251     dst->draw_horiz_band= src->draw_horiz_band;
252     dst->get_buffer2    = src->get_buffer2;
253 #if FF_API_GET_BUFFER
254 FF_DISABLE_DEPRECATION_WARNINGS
255     dst->get_buffer     = src->get_buffer;
256     dst->release_buffer = src->release_buffer;
257 FF_ENABLE_DEPRECATION_WARNINGS
258 #endif
259
260     dst->opaque   = src->opaque;
261     dst->debug    = src->debug;
262     dst->debug_mv = src->debug_mv;
263
264     dst->slice_flags = src->slice_flags;
265     dst->flags2      = src->flags2;
266
267     copy_fields(skip_loop_filter, subtitle_header);
268
269     dst->frame_number     = src->frame_number;
270     dst->reordered_opaque = src->reordered_opaque;
271     dst->thread_safe_callbacks = src->thread_safe_callbacks;
272
273     if (src->slice_count && src->slice_offset) {
274         if (dst->slice_count < src->slice_count) {
275             int *tmp = av_realloc(dst->slice_offset, src->slice_count *
276                                   sizeof(*dst->slice_offset));
277             if (!tmp) {
278                 av_free(dst->slice_offset);
279                 return AVERROR(ENOMEM);
280             }
281             dst->slice_offset = tmp;
282         }
283         memcpy(dst->slice_offset, src->slice_offset,
284                src->slice_count * sizeof(*dst->slice_offset));
285     }
286     dst->slice_count = src->slice_count;
287     return 0;
288 #undef copy_fields
289 }
290
291 /// Releases the buffers that this decoding thread was the last user of.
292 static void release_delayed_buffers(PerThreadContext *p)
293 {
294     FrameThreadContext *fctx = p->parent;
295
296     while (p->num_released_buffers > 0) {
297         AVFrame *f;
298
299         pthread_mutex_lock(&fctx->buffer_mutex);
300
301         // fix extended data in case the caller screwed it up
302         av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
303                    p->avctx->codec_type == AVMEDIA_TYPE_AUDIO);
304         f = &p->released_buffers[--p->num_released_buffers];
305         f->extended_data = f->data;
306         av_frame_unref(f);
307
308         pthread_mutex_unlock(&fctx->buffer_mutex);
309     }
310 }
311
312 static int submit_packet(PerThreadContext *p, AVPacket *avpkt)
313 {
314     FrameThreadContext *fctx = p->parent;
315     PerThreadContext *prev_thread = fctx->prev_thread;
316     const AVCodec *codec = p->avctx->codec;
317
318     if (!avpkt->size && !(codec->capabilities & CODEC_CAP_DELAY)) return 0;
319
320     pthread_mutex_lock(&p->mutex);
321
322     release_delayed_buffers(p);
323
324     if (prev_thread) {
325         int err;
326         if (prev_thread->state == STATE_SETTING_UP) {
327             pthread_mutex_lock(&prev_thread->progress_mutex);
328             while (prev_thread->state == STATE_SETTING_UP)
329                 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
330             pthread_mutex_unlock(&prev_thread->progress_mutex);
331         }
332
333         err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
334         if (err) {
335             pthread_mutex_unlock(&p->mutex);
336             return err;
337         }
338     }
339
340     av_buffer_unref(&p->avpkt.buf);
341     p->avpkt = *avpkt;
342     if (avpkt->buf)
343         p->avpkt.buf = av_buffer_ref(avpkt->buf);
344     else {
345         av_fast_malloc(&p->buf, &p->allocated_buf_size, avpkt->size + FF_INPUT_BUFFER_PADDING_SIZE);
346         p->avpkt.data = p->buf;
347         memcpy(p->buf, avpkt->data, avpkt->size);
348         memset(p->buf + avpkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
349     }
350
351     p->state = STATE_SETTING_UP;
352     pthread_cond_signal(&p->input_cond);
353     pthread_mutex_unlock(&p->mutex);
354
355     /*
356      * If the client doesn't have a thread-safe get_buffer(),
357      * then decoding threads call back to the main thread,
358      * and it calls back to the client here.
359      */
360
361 FF_DISABLE_DEPRECATION_WARNINGS
362     if (!p->avctx->thread_safe_callbacks && (
363          p->avctx->get_format != avcodec_default_get_format ||
364 #if FF_API_GET_BUFFER
365          p->avctx->get_buffer ||
366 #endif
367          p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
368 FF_ENABLE_DEPRECATION_WARNINGS
369         while (p->state != STATE_SETUP_FINISHED && p->state != STATE_INPUT_READY) {
370             int call_done = 1;
371             pthread_mutex_lock(&p->progress_mutex);
372             while (p->state == STATE_SETTING_UP)
373                 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
374
375             switch (p->state) {
376             case STATE_GET_BUFFER:
377                 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
378                 break;
379             case STATE_GET_FORMAT:
380                 p->result_format = p->avctx->get_format(p->avctx, p->available_formats);
381                 break;
382             default:
383                 call_done = 0;
384                 break;
385             }
386             if (call_done) {
387                 p->state  = STATE_SETTING_UP;
388                 pthread_cond_signal(&p->progress_cond);
389             }
390             pthread_mutex_unlock(&p->progress_mutex);
391         }
392     }
393
394     fctx->prev_thread = p;
395     fctx->next_decoding++;
396
397     return 0;
398 }
399
400 int ff_thread_decode_frame(AVCodecContext *avctx,
401                            AVFrame *picture, int *got_picture_ptr,
402                            AVPacket *avpkt)
403 {
404     FrameThreadContext *fctx = avctx->internal->thread_ctx;
405     int finished = fctx->next_finished;
406     PerThreadContext *p;
407     int err;
408
409     /*
410      * Submit a packet to the next decoding thread.
411      */
412
413     p = &fctx->threads[fctx->next_decoding];
414     err = update_context_from_user(p->avctx, avctx);
415     if (err) return err;
416     err = submit_packet(p, avpkt);
417     if (err) return err;
418
419     /*
420      * If we're still receiving the initial packets, don't return a frame.
421      */
422
423     if (fctx->next_decoding > (avctx->thread_count-1-(avctx->codec_id == AV_CODEC_ID_FFV1)))
424         fctx->delaying = 0;
425
426     if (fctx->delaying) {
427         *got_picture_ptr=0;
428         if (avpkt->size)
429             return avpkt->size;
430     }
431
432     /*
433      * Return the next available frame from the oldest thread.
434      * If we're at the end of the stream, then we have to skip threads that
435      * didn't output a frame, because we don't want to accidentally signal
436      * EOF (avpkt->size == 0 && *got_picture_ptr == 0).
437      */
438
439     do {
440         p = &fctx->threads[finished++];
441
442         if (p->state != STATE_INPUT_READY) {
443             pthread_mutex_lock(&p->progress_mutex);
444             while (p->state != STATE_INPUT_READY)
445                 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
446             pthread_mutex_unlock(&p->progress_mutex);
447         }
448
449         av_frame_move_ref(picture, &p->frame);
450         *got_picture_ptr = p->got_frame;
451         picture->pkt_dts = p->avpkt.dts;
452
453         /*
454          * A later call with avkpt->size == 0 may loop over all threads,
455          * including this one, searching for a frame to return before being
456          * stopped by the "finished != fctx->next_finished" condition.
457          * Make sure we don't mistakenly return the same frame again.
458          */
459         p->got_frame = 0;
460
461         if (finished >= avctx->thread_count) finished = 0;
462     } while (!avpkt->size && !*got_picture_ptr && finished != fctx->next_finished);
463
464     update_context_from_thread(avctx, p->avctx, 1);
465
466     if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
467
468     fctx->next_finished = finished;
469
470     /* return the size of the consumed packet if no error occurred */
471     return (p->result >= 0) ? avpkt->size : p->result;
472 }
473
474 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
475 {
476     PerThreadContext *p;
477     volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
478
479     if (!progress || progress[field] >= n) return;
480
481     p = f->owner->internal->thread_ctx;
482
483     if (f->owner->debug&FF_DEBUG_THREADS)
484         av_log(f->owner, AV_LOG_DEBUG, "%p finished %d field %d\n", progress, n, field);
485
486     pthread_mutex_lock(&p->progress_mutex);
487     progress[field] = n;
488     pthread_cond_broadcast(&p->progress_cond);
489     pthread_mutex_unlock(&p->progress_mutex);
490 }
491
492 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
493 {
494     PerThreadContext *p;
495     volatile int *progress = f->progress ? (int*)f->progress->data : NULL;
496
497     if (!progress || progress[field] >= n) return;
498
499     p = f->owner->internal->thread_ctx;
500
501     if (f->owner->debug&FF_DEBUG_THREADS)
502         av_log(f->owner, AV_LOG_DEBUG, "thread awaiting %d field %d from %p\n", n, field, progress);
503
504     pthread_mutex_lock(&p->progress_mutex);
505     while (progress[field] < n)
506         pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
507     pthread_mutex_unlock(&p->progress_mutex);
508 }
509
510 void ff_thread_finish_setup(AVCodecContext *avctx) {
511     PerThreadContext *p = avctx->internal->thread_ctx;
512
513     if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
514
515     if(p->state == STATE_SETUP_FINISHED){
516         av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
517     }
518
519     pthread_mutex_lock(&p->progress_mutex);
520     p->state = STATE_SETUP_FINISHED;
521     pthread_cond_broadcast(&p->progress_cond);
522     pthread_mutex_unlock(&p->progress_mutex);
523 }
524
525 /// Waits for all threads to finish.
526 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
527 {
528     int i;
529
530     for (i = 0; i < thread_count; i++) {
531         PerThreadContext *p = &fctx->threads[i];
532
533         if (p->state != STATE_INPUT_READY) {
534             pthread_mutex_lock(&p->progress_mutex);
535             while (p->state != STATE_INPUT_READY)
536                 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
537             pthread_mutex_unlock(&p->progress_mutex);
538         }
539         p->got_frame = 0;
540     }
541 }
542
543 void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
544 {
545     FrameThreadContext *fctx = avctx->internal->thread_ctx;
546     const AVCodec *codec = avctx->codec;
547     int i;
548
549     park_frame_worker_threads(fctx, thread_count);
550
551     if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
552         if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
553             av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
554             fctx->prev_thread->avctx->internal->is_copy = fctx->threads->avctx->internal->is_copy;
555             fctx->threads->avctx->internal->is_copy = 1;
556         }
557
558     fctx->die = 1;
559
560     for (i = 0; i < thread_count; i++) {
561         PerThreadContext *p = &fctx->threads[i];
562
563         pthread_mutex_lock(&p->mutex);
564         pthread_cond_signal(&p->input_cond);
565         pthread_mutex_unlock(&p->mutex);
566
567         if (p->thread_init)
568             pthread_join(p->thread, NULL);
569         p->thread_init=0;
570
571         if (codec->close)
572             codec->close(p->avctx);
573
574         avctx->codec = NULL;
575
576         release_delayed_buffers(p);
577         av_frame_unref(&p->frame);
578     }
579
580     for (i = 0; i < thread_count; i++) {
581         PerThreadContext *p = &fctx->threads[i];
582
583         pthread_mutex_destroy(&p->mutex);
584         pthread_mutex_destroy(&p->progress_mutex);
585         pthread_cond_destroy(&p->input_cond);
586         pthread_cond_destroy(&p->progress_cond);
587         pthread_cond_destroy(&p->output_cond);
588         av_buffer_unref(&p->avpkt.buf);
589         av_freep(&p->buf);
590         av_freep(&p->released_buffers);
591
592         if (i) {
593             av_freep(&p->avctx->priv_data);
594             av_freep(&p->avctx->slice_offset);
595         }
596
597         av_freep(&p->avctx->internal);
598         av_freep(&p->avctx);
599     }
600
601     av_freep(&fctx->threads);
602     pthread_mutex_destroy(&fctx->buffer_mutex);
603     av_freep(&avctx->internal->thread_ctx);
604 }
605
606 int ff_frame_thread_init(AVCodecContext *avctx)
607 {
608     int thread_count = avctx->thread_count;
609     const AVCodec *codec = avctx->codec;
610     AVCodecContext *src = avctx;
611     FrameThreadContext *fctx;
612     int i, err = 0;
613
614 #if HAVE_W32THREADS
615     w32thread_init();
616 #endif
617
618     if (!thread_count) {
619         int nb_cpus = av_cpu_count();
620         if ((avctx->debug & (FF_DEBUG_VIS_QP | FF_DEBUG_VIS_MB_TYPE)) || avctx->debug_mv)
621             nb_cpus = 1;
622         // use number of cores + 1 as thread count if there is more than one
623         if (nb_cpus > 1)
624             thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
625         else
626             thread_count = avctx->thread_count = 1;
627     }
628
629     if (thread_count <= 1) {
630         avctx->active_thread_type = 0;
631         return 0;
632     }
633
634     avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
635
636     fctx->threads = av_mallocz(sizeof(PerThreadContext) * thread_count);
637     pthread_mutex_init(&fctx->buffer_mutex, NULL);
638     fctx->delaying = 1;
639
640     for (i = 0; i < thread_count; i++) {
641         AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
642         PerThreadContext *p  = &fctx->threads[i];
643
644         pthread_mutex_init(&p->mutex, NULL);
645         pthread_mutex_init(&p->progress_mutex, NULL);
646         pthread_cond_init(&p->input_cond, NULL);
647         pthread_cond_init(&p->progress_cond, NULL);
648         pthread_cond_init(&p->output_cond, NULL);
649
650         p->parent = fctx;
651         p->avctx  = copy;
652
653         if (!copy) {
654             err = AVERROR(ENOMEM);
655             goto error;
656         }
657
658         *copy = *src;
659
660         copy->internal = av_malloc(sizeof(AVCodecInternal));
661         if (!copy->internal) {
662             err = AVERROR(ENOMEM);
663             goto error;
664         }
665         *copy->internal = *src->internal;
666         copy->internal->thread_ctx = p;
667         copy->internal->pkt = &p->avpkt;
668
669         if (!i) {
670             src = copy;
671
672             if (codec->init)
673                 err = codec->init(copy);
674
675             update_context_from_thread(avctx, copy, 1);
676         } else {
677             copy->priv_data = av_malloc(codec->priv_data_size);
678             if (!copy->priv_data) {
679                 err = AVERROR(ENOMEM);
680                 goto error;
681             }
682             memcpy(copy->priv_data, src->priv_data, codec->priv_data_size);
683             copy->internal->is_copy = 1;
684
685             if (codec->init_thread_copy)
686                 err = codec->init_thread_copy(copy);
687         }
688
689         if (err) goto error;
690
691         err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
692         p->thread_init= !err;
693         if(!p->thread_init)
694             goto error;
695     }
696
697     return 0;
698
699 error:
700     ff_frame_thread_free(avctx, i+1);
701
702     return err;
703 }
704
705 void ff_thread_flush(AVCodecContext *avctx)
706 {
707     int i;
708     FrameThreadContext *fctx = avctx->internal->thread_ctx;
709
710     if (!fctx) return;
711
712     park_frame_worker_threads(fctx, avctx->thread_count);
713     if (fctx->prev_thread) {
714         if (fctx->prev_thread != &fctx->threads[0])
715             update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
716         if (avctx->codec->flush)
717             avctx->codec->flush(fctx->threads[0].avctx);
718     }
719
720     fctx->next_decoding = fctx->next_finished = 0;
721     fctx->delaying = 1;
722     fctx->prev_thread = NULL;
723     for (i = 0; i < avctx->thread_count; i++) {
724         PerThreadContext *p = &fctx->threads[i];
725         // Make sure decode flush calls with size=0 won't return old frames
726         p->got_frame = 0;
727         av_frame_unref(&p->frame);
728
729         release_delayed_buffers(p);
730     }
731 }
732
733 int ff_thread_can_start_frame(AVCodecContext *avctx)
734 {
735     PerThreadContext *p = avctx->internal->thread_ctx;
736     if ((avctx->active_thread_type&FF_THREAD_FRAME) && p->state != STATE_SETTING_UP &&
737         (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
738         return 0;
739     }
740     return 1;
741 }
742
743 static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
744 {
745     PerThreadContext *p = avctx->internal->thread_ctx;
746     int err;
747
748     f->owner = avctx;
749
750     ff_init_buffer_info(avctx, f->f);
751
752     if (!(avctx->active_thread_type & FF_THREAD_FRAME))
753         return ff_get_buffer(avctx, f->f, flags);
754
755     if (p->state != STATE_SETTING_UP &&
756         (avctx->codec->update_thread_context || !THREAD_SAFE_CALLBACKS(avctx))) {
757         av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
758         return -1;
759     }
760
761     if (avctx->internal->allocate_progress) {
762         int *progress;
763         f->progress = av_buffer_alloc(2 * sizeof(int));
764         if (!f->progress) {
765             return AVERROR(ENOMEM);
766         }
767         progress = (int*)f->progress->data;
768
769         progress[0] = progress[1] = -1;
770     }
771
772     pthread_mutex_lock(&p->parent->buffer_mutex);
773 FF_DISABLE_DEPRECATION_WARNINGS
774     if (avctx->thread_safe_callbacks || (
775 #if FF_API_GET_BUFFER
776         !avctx->get_buffer &&
777 #endif
778         avctx->get_buffer2 == avcodec_default_get_buffer2)) {
779 FF_ENABLE_DEPRECATION_WARNINGS
780         err = ff_get_buffer(avctx, f->f, flags);
781     } else {
782         pthread_mutex_lock(&p->progress_mutex);
783         p->requested_frame = f->f;
784         p->requested_flags = flags;
785         p->state = STATE_GET_BUFFER;
786         pthread_cond_broadcast(&p->progress_cond);
787
788         while (p->state != STATE_SETTING_UP)
789             pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
790
791         err = p->result;
792
793         pthread_mutex_unlock(&p->progress_mutex);
794
795     }
796     if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
797         ff_thread_finish_setup(avctx);
798
799     if (err)
800         av_buffer_unref(&f->progress);
801
802     pthread_mutex_unlock(&p->parent->buffer_mutex);
803
804     return err;
805 }
806
807 enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
808 {
809     enum AVPixelFormat res;
810     PerThreadContext *p = avctx->internal->thread_ctx;
811     if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
812         avctx->get_format == avcodec_default_get_format)
813         return avctx->get_format(avctx, fmt);
814     if (p->state != STATE_SETTING_UP) {
815         av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
816         return -1;
817     }
818     pthread_mutex_lock(&p->progress_mutex);
819     p->available_formats = fmt;
820     p->state = STATE_GET_FORMAT;
821     pthread_cond_broadcast(&p->progress_cond);
822
823     while (p->state != STATE_SETTING_UP)
824         pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
825
826     res = p->result_format;
827
828     pthread_mutex_unlock(&p->progress_mutex);
829
830     return res;
831 }
832
833 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
834 {
835     int ret = thread_get_buffer_internal(avctx, f, flags);
836     if (ret < 0)
837         av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
838     return ret;
839 }
840
841 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
842 {
843     PerThreadContext *p = avctx->internal->thread_ctx;
844     FrameThreadContext *fctx;
845     AVFrame *dst, *tmp;
846 FF_DISABLE_DEPRECATION_WARNINGS
847     int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
848                           avctx->thread_safe_callbacks                   ||
849                           (
850 #if FF_API_GET_BUFFER
851                            !avctx->get_buffer &&
852 #endif
853                            avctx->get_buffer2 == avcodec_default_get_buffer2);
854 FF_ENABLE_DEPRECATION_WARNINGS
855
856     if (!f->f->data[0])
857         return;
858
859     if (avctx->debug & FF_DEBUG_BUFFERS)
860         av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
861
862     av_buffer_unref(&f->progress);
863     f->owner    = NULL;
864
865     if (can_direct_free) {
866         av_frame_unref(f->f);
867         return;
868     }
869
870     fctx = p->parent;
871     pthread_mutex_lock(&fctx->buffer_mutex);
872
873     if (p->num_released_buffers + 1 >= INT_MAX / sizeof(*p->released_buffers))
874         goto fail;
875     tmp = av_fast_realloc(p->released_buffers, &p->released_buffers_allocated,
876                           (p->num_released_buffers + 1) *
877                           sizeof(*p->released_buffers));
878     if (!tmp)
879         goto fail;
880     p->released_buffers = tmp;
881
882     dst = &p->released_buffers[p->num_released_buffers];
883     av_frame_move_ref(dst, f->f);
884
885     p->num_released_buffers++;
886
887 fail:
888     pthread_mutex_unlock(&fctx->buffer_mutex);
889 }