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