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