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