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