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