]> git.sesse.net Git - ffmpeg/blob - libavcodec/pthread_frame.c
avcodec/webp: use av_packet_alloc() to allocate packets
[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 <stdatomic.h>
28 #include <stdint.h>
29
30 #include "avcodec.h"
31 #include "hwconfig.h"
32 #include "internal.h"
33 #include "pthread_internal.h"
34 #include "thread.h"
35 #include "version.h"
36
37 #include "libavutil/avassert.h"
38 #include "libavutil/buffer.h"
39 #include "libavutil/common.h"
40 #include "libavutil/cpu.h"
41 #include "libavutil/frame.h"
42 #include "libavutil/internal.h"
43 #include "libavutil/log.h"
44 #include "libavutil/mem.h"
45 #include "libavutil/opt.h"
46 #include "libavutil/thread.h"
47
48 enum {
49     ///< Set when the thread is awaiting a packet.
50     STATE_INPUT_READY,
51     ///< Set before the codec has called ff_thread_finish_setup().
52     STATE_SETTING_UP,
53     /**
54      * Set when the codec calls get_buffer().
55      * State is returned to STATE_SETTING_UP afterwards.
56      */
57     STATE_GET_BUFFER,
58      /**
59       * Set when the codec calls get_format().
60       * State is returned to STATE_SETTING_UP afterwards.
61       */
62     STATE_GET_FORMAT,
63     ///< Set after the codec has called ff_thread_finish_setup().
64     STATE_SETUP_FINISHED,
65 };
66
67 /**
68  * Context used by codec threads and stored in their AVCodecInternal thread_ctx.
69  */
70 typedef struct PerThreadContext {
71     struct FrameThreadContext *parent;
72
73     pthread_t      thread;
74     int            thread_init;
75     pthread_cond_t input_cond;      ///< Used to wait for a new packet from the main thread.
76     pthread_cond_t progress_cond;   ///< Used by child threads to wait for progress to change.
77     pthread_cond_t output_cond;     ///< Used by the main thread to wait for frames to finish.
78
79     pthread_mutex_t mutex;          ///< Mutex used to protect the contents of the PerThreadContext.
80     pthread_mutex_t progress_mutex; ///< Mutex used to protect frame progress values and progress_cond.
81
82     AVCodecContext *avctx;          ///< Context used to decode packets passed to this thread.
83
84     AVPacket       *avpkt;          ///< Input packet (for decoding) or output (for encoding).
85
86     AVFrame *frame;                 ///< Output frame (for decoding) or input (for encoding).
87     int     got_frame;              ///< The output of got_picture_ptr from the last avcodec_decode_video() call.
88     int     result;                 ///< The result of the last codec decode/encode() call.
89
90     atomic_int state;
91
92 #if FF_API_THREAD_SAFE_CALLBACKS
93     /**
94      * Array of frames passed to ff_thread_release_buffer().
95      * Frames are released after all threads referencing them are finished.
96      */
97     AVFrame **released_buffers;
98     int   num_released_buffers;
99     int       released_buffers_allocated;
100
101     AVFrame *requested_frame;       ///< AVFrame the codec passed to get_buffer()
102     int      requested_flags;       ///< flags passed to get_buffer() for requested_frame
103
104     const enum AVPixelFormat *available_formats; ///< Format array for get_format()
105     enum AVPixelFormat result_format;            ///< get_format() result
106 #endif
107
108     int die;                        ///< Set when the thread should exit.
109
110     int hwaccel_serializing;
111     int async_serializing;
112
113     atomic_int debug_threads;       ///< Set if the FF_DEBUG_THREADS option is set.
114 } PerThreadContext;
115
116 /**
117  * Context stored in the client AVCodecInternal thread_ctx.
118  */
119 typedef struct FrameThreadContext {
120     PerThreadContext *threads;     ///< The contexts for each thread.
121     PerThreadContext *prev_thread; ///< The last thread submit_packet() was called on.
122
123     pthread_mutex_t buffer_mutex;  ///< Mutex used to protect get/release_buffer().
124     /**
125      * This lock is used for ensuring threads run in serial when hwaccel
126      * is used.
127      */
128     pthread_mutex_t hwaccel_mutex;
129     pthread_mutex_t async_mutex;
130     pthread_cond_t async_cond;
131     int async_lock;
132
133     int next_decoding;             ///< The next context to submit a packet to.
134     int next_finished;             ///< The next context to return output from.
135
136     int delaying;                  /**<
137                                     * Set for the first N packets, where N is the number of threads.
138                                     * While it is set, ff_thread_en/decode_frame won't return any results.
139                                     */
140 } FrameThreadContext;
141
142 #if FF_API_THREAD_SAFE_CALLBACKS
143 #define THREAD_SAFE_CALLBACKS(avctx) \
144 ((avctx)->thread_safe_callbacks || (avctx)->get_buffer2 == avcodec_default_get_buffer2)
145 #endif
146
147 static void async_lock(FrameThreadContext *fctx)
148 {
149     pthread_mutex_lock(&fctx->async_mutex);
150     while (fctx->async_lock)
151         pthread_cond_wait(&fctx->async_cond, &fctx->async_mutex);
152     fctx->async_lock = 1;
153     pthread_mutex_unlock(&fctx->async_mutex);
154 }
155
156 static void async_unlock(FrameThreadContext *fctx)
157 {
158     pthread_mutex_lock(&fctx->async_mutex);
159     av_assert0(fctx->async_lock);
160     fctx->async_lock = 0;
161     pthread_cond_broadcast(&fctx->async_cond);
162     pthread_mutex_unlock(&fctx->async_mutex);
163 }
164
165 /**
166  * Codec worker thread.
167  *
168  * Automatically calls ff_thread_finish_setup() if the codec does
169  * not provide an update_thread_context method, or if the codec returns
170  * before calling it.
171  */
172 static attribute_align_arg void *frame_worker_thread(void *arg)
173 {
174     PerThreadContext *p = arg;
175     AVCodecContext *avctx = p->avctx;
176     const AVCodec *codec = avctx->codec;
177
178     pthread_mutex_lock(&p->mutex);
179     while (1) {
180         while (atomic_load(&p->state) == STATE_INPUT_READY && !p->die)
181             pthread_cond_wait(&p->input_cond, &p->mutex);
182
183         if (p->die) break;
184
185 FF_DISABLE_DEPRECATION_WARNINGS
186         if (!codec->update_thread_context
187 #if FF_API_THREAD_SAFE_CALLBACKS
188             && THREAD_SAFE_CALLBACKS(avctx)
189 #endif
190             )
191             ff_thread_finish_setup(avctx);
192 FF_ENABLE_DEPRECATION_WARNINGS
193
194         /* If a decoder supports hwaccel, then it must call ff_get_format().
195          * Since that call must happen before ff_thread_finish_setup(), the
196          * decoder is required to implement update_thread_context() and call
197          * ff_thread_finish_setup() manually. Therefore the above
198          * ff_thread_finish_setup() call did not happen and hwaccel_serializing
199          * cannot be true here. */
200         av_assert0(!p->hwaccel_serializing);
201
202         /* if the previous thread uses hwaccel then we take the lock to ensure
203          * the threads don't run concurrently */
204         if (avctx->hwaccel) {
205             pthread_mutex_lock(&p->parent->hwaccel_mutex);
206             p->hwaccel_serializing = 1;
207         }
208
209         av_frame_unref(p->frame);
210         p->got_frame = 0;
211         p->result = codec->decode(avctx, p->frame, &p->got_frame, p->avpkt);
212
213         if ((p->result < 0 || !p->got_frame) && p->frame->buf[0]) {
214             if (avctx->codec->caps_internal & FF_CODEC_CAP_ALLOCATE_PROGRESS)
215                 av_log(avctx, AV_LOG_ERROR, "A frame threaded decoder did not "
216                        "free the frame on failure. This is a bug, please report it.\n");
217             av_frame_unref(p->frame);
218         }
219
220         if (atomic_load(&p->state) == STATE_SETTING_UP)
221             ff_thread_finish_setup(avctx);
222
223         if (p->hwaccel_serializing) {
224             p->hwaccel_serializing = 0;
225             pthread_mutex_unlock(&p->parent->hwaccel_mutex);
226         }
227
228         if (p->async_serializing) {
229             p->async_serializing = 0;
230
231             async_unlock(p->parent);
232         }
233
234         pthread_mutex_lock(&p->progress_mutex);
235
236         atomic_store(&p->state, STATE_INPUT_READY);
237
238         pthread_cond_broadcast(&p->progress_cond);
239         pthread_cond_signal(&p->output_cond);
240         pthread_mutex_unlock(&p->progress_mutex);
241     }
242     pthread_mutex_unlock(&p->mutex);
243
244     return NULL;
245 }
246
247 /**
248  * Update the next thread's AVCodecContext with values from the reference thread's context.
249  *
250  * @param dst The destination context.
251  * @param src The source context.
252  * @param for_user 0 if the destination is a codec thread, 1 if the destination is the user's thread
253  * @return 0 on success, negative error code on failure
254  */
255 static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)
256 {
257     int err = 0;
258
259     if (dst != src && (for_user || src->codec->update_thread_context)) {
260         dst->time_base = src->time_base;
261         dst->framerate = src->framerate;
262         dst->width     = src->width;
263         dst->height    = src->height;
264         dst->pix_fmt   = src->pix_fmt;
265         dst->sw_pix_fmt = src->sw_pix_fmt;
266
267         dst->coded_width  = src->coded_width;
268         dst->coded_height = src->coded_height;
269
270         dst->has_b_frames = src->has_b_frames;
271         dst->idct_algo    = src->idct_algo;
272
273         dst->bits_per_coded_sample = src->bits_per_coded_sample;
274         dst->sample_aspect_ratio   = src->sample_aspect_ratio;
275
276         dst->profile = src->profile;
277         dst->level   = src->level;
278
279         dst->bits_per_raw_sample = src->bits_per_raw_sample;
280         dst->ticks_per_frame     = src->ticks_per_frame;
281         dst->color_primaries     = src->color_primaries;
282
283         dst->color_trc   = src->color_trc;
284         dst->colorspace  = src->colorspace;
285         dst->color_range = src->color_range;
286         dst->chroma_sample_location = src->chroma_sample_location;
287
288         dst->hwaccel = src->hwaccel;
289         dst->hwaccel_context = src->hwaccel_context;
290
291         dst->channels       = src->channels;
292         dst->sample_rate    = src->sample_rate;
293         dst->sample_fmt     = src->sample_fmt;
294         dst->channel_layout = src->channel_layout;
295         dst->internal->hwaccel_priv_data = src->internal->hwaccel_priv_data;
296
297         if (!!dst->hw_frames_ctx != !!src->hw_frames_ctx ||
298             (dst->hw_frames_ctx && dst->hw_frames_ctx->data != src->hw_frames_ctx->data)) {
299             av_buffer_unref(&dst->hw_frames_ctx);
300
301             if (src->hw_frames_ctx) {
302                 dst->hw_frames_ctx = av_buffer_ref(src->hw_frames_ctx);
303                 if (!dst->hw_frames_ctx)
304                     return AVERROR(ENOMEM);
305             }
306         }
307
308         dst->hwaccel_flags = src->hwaccel_flags;
309
310         err = av_buffer_replace(&dst->internal->pool, src->internal->pool);
311         if (err < 0)
312             return err;
313     }
314
315     if (for_user) {
316 #if FF_API_CODED_FRAME
317 FF_DISABLE_DEPRECATION_WARNINGS
318         dst->coded_frame = src->coded_frame;
319 FF_ENABLE_DEPRECATION_WARNINGS
320 #endif
321     } else {
322         if (dst->codec->update_thread_context)
323             err = dst->codec->update_thread_context(dst, src);
324     }
325
326     return err;
327 }
328
329 /**
330  * Update the next thread's AVCodecContext with values set by the user.
331  *
332  * @param dst The destination context.
333  * @param src The source context.
334  * @return 0 on success, negative error code on failure
335  */
336 static int update_context_from_user(AVCodecContext *dst, AVCodecContext *src)
337 {
338     dst->flags          = src->flags;
339
340     dst->draw_horiz_band= src->draw_horiz_band;
341     dst->get_buffer2    = src->get_buffer2;
342
343     dst->opaque   = src->opaque;
344     dst->debug    = src->debug;
345
346     dst->slice_flags = src->slice_flags;
347     dst->flags2      = src->flags2;
348     dst->export_side_data = src->export_side_data;
349
350     dst->skip_loop_filter = src->skip_loop_filter;
351     dst->skip_idct        = src->skip_idct;
352     dst->skip_frame       = src->skip_frame;
353
354     dst->frame_number     = src->frame_number;
355     dst->reordered_opaque = src->reordered_opaque;
356 #if FF_API_THREAD_SAFE_CALLBACKS
357 FF_DISABLE_DEPRECATION_WARNINGS
358     dst->thread_safe_callbacks = src->thread_safe_callbacks;
359 FF_ENABLE_DEPRECATION_WARNINGS
360 #endif
361
362     if (src->slice_count && src->slice_offset) {
363         if (dst->slice_count < src->slice_count) {
364             int err = av_reallocp_array(&dst->slice_offset, src->slice_count,
365                                         sizeof(*dst->slice_offset));
366             if (err < 0)
367                 return err;
368         }
369         memcpy(dst->slice_offset, src->slice_offset,
370                src->slice_count * sizeof(*dst->slice_offset));
371     }
372     dst->slice_count = src->slice_count;
373     return 0;
374 }
375
376 #if FF_API_THREAD_SAFE_CALLBACKS
377 /// Releases the buffers that this decoding thread was the last user of.
378 static void release_delayed_buffers(PerThreadContext *p)
379 {
380     FrameThreadContext *fctx = p->parent;
381
382     while (p->num_released_buffers > 0) {
383         AVFrame *f;
384
385         pthread_mutex_lock(&fctx->buffer_mutex);
386
387         // fix extended data in case the caller screwed it up
388         av_assert0(p->avctx->codec_type == AVMEDIA_TYPE_VIDEO ||
389                    p->avctx->codec_type == AVMEDIA_TYPE_AUDIO);
390         f = p->released_buffers[--p->num_released_buffers];
391         f->extended_data = f->data;
392         av_frame_unref(f);
393
394         pthread_mutex_unlock(&fctx->buffer_mutex);
395     }
396 }
397 #endif
398
399 static int submit_packet(PerThreadContext *p, AVCodecContext *user_avctx,
400                          AVPacket *avpkt)
401 {
402     FrameThreadContext *fctx = p->parent;
403     PerThreadContext *prev_thread = fctx->prev_thread;
404     const AVCodec *codec = p->avctx->codec;
405     int ret;
406
407     if (!avpkt->size && !(codec->capabilities & AV_CODEC_CAP_DELAY))
408         return 0;
409
410     pthread_mutex_lock(&p->mutex);
411
412     ret = update_context_from_user(p->avctx, user_avctx);
413     if (ret) {
414         pthread_mutex_unlock(&p->mutex);
415         return ret;
416     }
417     atomic_store_explicit(&p->debug_threads,
418                           (p->avctx->debug & FF_DEBUG_THREADS) != 0,
419                           memory_order_relaxed);
420
421 #if FF_API_THREAD_SAFE_CALLBACKS
422     release_delayed_buffers(p);
423 #endif
424
425     if (prev_thread) {
426         int err;
427         if (atomic_load(&prev_thread->state) == STATE_SETTING_UP) {
428             pthread_mutex_lock(&prev_thread->progress_mutex);
429             while (atomic_load(&prev_thread->state) == STATE_SETTING_UP)
430                 pthread_cond_wait(&prev_thread->progress_cond, &prev_thread->progress_mutex);
431             pthread_mutex_unlock(&prev_thread->progress_mutex);
432         }
433
434         err = update_context_from_thread(p->avctx, prev_thread->avctx, 0);
435         if (err) {
436             pthread_mutex_unlock(&p->mutex);
437             return err;
438         }
439     }
440
441     av_packet_unref(p->avpkt);
442     ret = av_packet_ref(p->avpkt, avpkt);
443     if (ret < 0) {
444         pthread_mutex_unlock(&p->mutex);
445         av_log(p->avctx, AV_LOG_ERROR, "av_packet_ref() failed in submit_packet()\n");
446         return ret;
447     }
448
449     atomic_store(&p->state, STATE_SETTING_UP);
450     pthread_cond_signal(&p->input_cond);
451     pthread_mutex_unlock(&p->mutex);
452
453 #if FF_API_THREAD_SAFE_CALLBACKS
454 FF_DISABLE_DEPRECATION_WARNINGS
455     /*
456      * If the client doesn't have a thread-safe get_buffer(),
457      * then decoding threads call back to the main thread,
458      * and it calls back to the client here.
459      */
460
461     if (!p->avctx->thread_safe_callbacks && (
462          p->avctx->get_format != avcodec_default_get_format ||
463          p->avctx->get_buffer2 != avcodec_default_get_buffer2)) {
464         while (atomic_load(&p->state) != STATE_SETUP_FINISHED && atomic_load(&p->state) != STATE_INPUT_READY) {
465             int call_done = 1;
466             pthread_mutex_lock(&p->progress_mutex);
467             while (atomic_load(&p->state) == STATE_SETTING_UP)
468                 pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
469
470             switch (atomic_load_explicit(&p->state, memory_order_acquire)) {
471             case STATE_GET_BUFFER:
472                 p->result = ff_get_buffer(p->avctx, p->requested_frame, p->requested_flags);
473                 break;
474             case STATE_GET_FORMAT:
475                 p->result_format = ff_get_format(p->avctx, p->available_formats);
476                 break;
477             default:
478                 call_done = 0;
479                 break;
480             }
481             if (call_done) {
482                 atomic_store(&p->state, STATE_SETTING_UP);
483                 pthread_cond_signal(&p->progress_cond);
484             }
485             pthread_mutex_unlock(&p->progress_mutex);
486         }
487     }
488 FF_ENABLE_DEPRECATION_WARNINGS
489 #endif
490
491     fctx->prev_thread = p;
492     fctx->next_decoding++;
493
494     return 0;
495 }
496
497 int ff_thread_decode_frame(AVCodecContext *avctx,
498                            AVFrame *picture, int *got_picture_ptr,
499                            AVPacket *avpkt)
500 {
501     FrameThreadContext *fctx = avctx->internal->thread_ctx;
502     int finished = fctx->next_finished;
503     PerThreadContext *p;
504     int err;
505
506     /* release the async lock, permitting blocked hwaccel threads to
507      * go forward while we are in this function */
508     async_unlock(fctx);
509
510     /*
511      * Submit a packet to the next decoding thread.
512      */
513
514     p = &fctx->threads[fctx->next_decoding];
515     err = submit_packet(p, avctx, avpkt);
516     if (err)
517         goto finish;
518
519     /*
520      * If we're still receiving the initial packets, don't return a frame.
521      */
522
523     if (fctx->next_decoding > (avctx->thread_count-1-(avctx->codec_id == AV_CODEC_ID_FFV1)))
524         fctx->delaying = 0;
525
526     if (fctx->delaying) {
527         *got_picture_ptr=0;
528         if (avpkt->size) {
529             err = avpkt->size;
530             goto finish;
531         }
532     }
533
534     /*
535      * Return the next available frame from the oldest thread.
536      * If we're at the end of the stream, then we have to skip threads that
537      * didn't output a frame/error, because we don't want to accidentally signal
538      * EOF (avpkt->size == 0 && *got_picture_ptr == 0 && err >= 0).
539      */
540
541     do {
542         p = &fctx->threads[finished++];
543
544         if (atomic_load(&p->state) != STATE_INPUT_READY) {
545             pthread_mutex_lock(&p->progress_mutex);
546             while (atomic_load_explicit(&p->state, memory_order_relaxed) != STATE_INPUT_READY)
547                 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
548             pthread_mutex_unlock(&p->progress_mutex);
549         }
550
551         av_frame_move_ref(picture, p->frame);
552         *got_picture_ptr = p->got_frame;
553         picture->pkt_dts = p->avpkt->dts;
554         err = p->result;
555
556         /*
557          * A later call with avkpt->size == 0 may loop over all threads,
558          * including this one, searching for a frame/error to return before being
559          * stopped by the "finished != fctx->next_finished" condition.
560          * Make sure we don't mistakenly return the same frame/error again.
561          */
562         p->got_frame = 0;
563         p->result = 0;
564
565         if (finished >= avctx->thread_count) finished = 0;
566     } while (!avpkt->size && !*got_picture_ptr && err >= 0 && finished != fctx->next_finished);
567
568     update_context_from_thread(avctx, p->avctx, 1);
569
570     if (fctx->next_decoding >= avctx->thread_count) fctx->next_decoding = 0;
571
572     fctx->next_finished = finished;
573
574     /* return the size of the consumed packet if no error occurred */
575     if (err >= 0)
576         err = avpkt->size;
577 finish:
578     async_lock(fctx);
579     return err;
580 }
581
582 void ff_thread_report_progress(ThreadFrame *f, int n, int field)
583 {
584     PerThreadContext *p;
585     atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
586
587     if (!progress ||
588         atomic_load_explicit(&progress[field], memory_order_relaxed) >= n)
589         return;
590
591     p = f->owner[field]->internal->thread_ctx;
592
593     if (atomic_load_explicit(&p->debug_threads, memory_order_relaxed))
594         av_log(f->owner[field], AV_LOG_DEBUG,
595                "%p finished %d field %d\n", progress, n, field);
596
597     pthread_mutex_lock(&p->progress_mutex);
598
599     atomic_store_explicit(&progress[field], n, memory_order_release);
600
601     pthread_cond_broadcast(&p->progress_cond);
602     pthread_mutex_unlock(&p->progress_mutex);
603 }
604
605 void ff_thread_await_progress(ThreadFrame *f, int n, int field)
606 {
607     PerThreadContext *p;
608     atomic_int *progress = f->progress ? (atomic_int*)f->progress->data : NULL;
609
610     if (!progress ||
611         atomic_load_explicit(&progress[field], memory_order_acquire) >= n)
612         return;
613
614     p = f->owner[field]->internal->thread_ctx;
615
616     if (atomic_load_explicit(&p->debug_threads, memory_order_relaxed))
617         av_log(f->owner[field], AV_LOG_DEBUG,
618                "thread awaiting %d field %d from %p\n", n, field, progress);
619
620     pthread_mutex_lock(&p->progress_mutex);
621     while (atomic_load_explicit(&progress[field], memory_order_relaxed) < n)
622         pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
623     pthread_mutex_unlock(&p->progress_mutex);
624 }
625
626 void ff_thread_finish_setup(AVCodecContext *avctx) {
627     PerThreadContext *p = avctx->internal->thread_ctx;
628
629     if (!(avctx->active_thread_type&FF_THREAD_FRAME)) return;
630
631     if (avctx->hwaccel && !p->hwaccel_serializing) {
632         pthread_mutex_lock(&p->parent->hwaccel_mutex);
633         p->hwaccel_serializing = 1;
634     }
635
636     /* this assumes that no hwaccel calls happen before ff_thread_finish_setup() */
637     if (avctx->hwaccel &&
638         !(avctx->hwaccel->caps_internal & HWACCEL_CAP_ASYNC_SAFE)) {
639         p->async_serializing = 1;
640
641         async_lock(p->parent);
642     }
643
644     pthread_mutex_lock(&p->progress_mutex);
645     if(atomic_load(&p->state) == STATE_SETUP_FINISHED){
646         av_log(avctx, AV_LOG_WARNING, "Multiple ff_thread_finish_setup() calls\n");
647     }
648
649     atomic_store(&p->state, STATE_SETUP_FINISHED);
650
651     pthread_cond_broadcast(&p->progress_cond);
652     pthread_mutex_unlock(&p->progress_mutex);
653 }
654
655 /// Waits for all threads to finish.
656 static void park_frame_worker_threads(FrameThreadContext *fctx, int thread_count)
657 {
658     int i;
659
660     async_unlock(fctx);
661
662     for (i = 0; i < thread_count; i++) {
663         PerThreadContext *p = &fctx->threads[i];
664
665         if (atomic_load(&p->state) != STATE_INPUT_READY) {
666             pthread_mutex_lock(&p->progress_mutex);
667             while (atomic_load(&p->state) != STATE_INPUT_READY)
668                 pthread_cond_wait(&p->output_cond, &p->progress_mutex);
669             pthread_mutex_unlock(&p->progress_mutex);
670         }
671         p->got_frame = 0;
672     }
673
674     async_lock(fctx);
675 }
676
677 void ff_frame_thread_free(AVCodecContext *avctx, int thread_count)
678 {
679     FrameThreadContext *fctx = avctx->internal->thread_ctx;
680     const AVCodec *codec = avctx->codec;
681     int i;
682
683     park_frame_worker_threads(fctx, thread_count);
684
685     if (fctx->prev_thread && avctx->internal->hwaccel_priv_data !=
686                              fctx->prev_thread->avctx->internal->hwaccel_priv_data) {
687         if (update_context_from_thread(avctx, fctx->prev_thread->avctx, 1) < 0) {
688             av_log(avctx, AV_LOG_ERROR, "Failed to update user thread.\n");
689         }
690     }
691
692     if (fctx->prev_thread && fctx->prev_thread != fctx->threads)
693         if (update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0) < 0) {
694             av_log(avctx, AV_LOG_ERROR, "Final thread update failed\n");
695             fctx->prev_thread->avctx->internal->is_copy = fctx->threads->avctx->internal->is_copy;
696             fctx->threads->avctx->internal->is_copy = 1;
697         }
698
699     for (i = 0; i < thread_count; i++) {
700         PerThreadContext *p = &fctx->threads[i];
701
702         pthread_mutex_lock(&p->mutex);
703         p->die = 1;
704         pthread_cond_signal(&p->input_cond);
705         pthread_mutex_unlock(&p->mutex);
706
707         if (p->thread_init)
708             pthread_join(p->thread, NULL);
709         p->thread_init=0;
710
711         if (codec->close && p->avctx)
712             codec->close(p->avctx);
713
714 #if FF_API_THREAD_SAFE_CALLBACKS
715         release_delayed_buffers(p);
716 #endif
717         av_frame_free(&p->frame);
718     }
719
720     for (i = 0; i < thread_count; i++) {
721         PerThreadContext *p = &fctx->threads[i];
722
723         pthread_mutex_destroy(&p->mutex);
724         pthread_mutex_destroy(&p->progress_mutex);
725         pthread_cond_destroy(&p->input_cond);
726         pthread_cond_destroy(&p->progress_cond);
727         pthread_cond_destroy(&p->output_cond);
728         av_packet_free(&p->avpkt);
729
730 #if FF_API_THREAD_SAFE_CALLBACKS
731         for (int j = 0; j < p->released_buffers_allocated; j++)
732             av_frame_free(&p->released_buffers[j]);
733         av_freep(&p->released_buffers);
734 #endif
735
736         if (p->avctx) {
737             if (codec->priv_class)
738                 av_opt_free(p->avctx->priv_data);
739             av_freep(&p->avctx->priv_data);
740
741             av_freep(&p->avctx->slice_offset);
742         }
743
744         if (p->avctx) {
745             av_buffer_unref(&p->avctx->internal->pool);
746             av_freep(&p->avctx->internal);
747             av_buffer_unref(&p->avctx->hw_frames_ctx);
748         }
749
750         av_freep(&p->avctx);
751     }
752
753     av_freep(&fctx->threads);
754     pthread_mutex_destroy(&fctx->buffer_mutex);
755     pthread_mutex_destroy(&fctx->hwaccel_mutex);
756     pthread_mutex_destroy(&fctx->async_mutex);
757     pthread_cond_destroy(&fctx->async_cond);
758
759     av_freep(&avctx->internal->thread_ctx);
760
761     if (avctx->priv_data && avctx->codec && avctx->codec->priv_class)
762         av_opt_free(avctx->priv_data);
763     avctx->codec = NULL;
764 }
765
766 int ff_frame_thread_init(AVCodecContext *avctx)
767 {
768     int thread_count = avctx->thread_count;
769     const AVCodec *codec = avctx->codec;
770     AVCodecContext *src = avctx;
771     FrameThreadContext *fctx;
772     int i, err = 0;
773
774     if (!thread_count) {
775         int nb_cpus = av_cpu_count();
776         // use number of cores + 1 as thread count if there is more than one
777         if (nb_cpus > 1)
778             thread_count = avctx->thread_count = FFMIN(nb_cpus + 1, MAX_AUTO_THREADS);
779         else
780             thread_count = avctx->thread_count = 1;
781     }
782
783     if (thread_count <= 1) {
784         avctx->active_thread_type = 0;
785         return 0;
786     }
787
788     avctx->internal->thread_ctx = fctx = av_mallocz(sizeof(FrameThreadContext));
789     if (!fctx)
790         return AVERROR(ENOMEM);
791
792     fctx->threads = av_mallocz_array(thread_count, sizeof(PerThreadContext));
793     if (!fctx->threads) {
794         av_freep(&avctx->internal->thread_ctx);
795         return AVERROR(ENOMEM);
796     }
797
798     pthread_mutex_init(&fctx->buffer_mutex, NULL);
799     pthread_mutex_init(&fctx->hwaccel_mutex, NULL);
800     pthread_mutex_init(&fctx->async_mutex, NULL);
801     pthread_cond_init(&fctx->async_cond, NULL);
802
803     fctx->async_lock = 1;
804     fctx->delaying = 1;
805
806     if (codec->type == AVMEDIA_TYPE_VIDEO)
807         avctx->delay = src->thread_count - 1;
808
809     for (i = 0; i < thread_count; i++) {
810         AVCodecContext *copy = av_malloc(sizeof(AVCodecContext));
811         PerThreadContext *p  = &fctx->threads[i];
812
813         pthread_mutex_init(&p->mutex, NULL);
814         pthread_mutex_init(&p->progress_mutex, NULL);
815         pthread_cond_init(&p->input_cond, NULL);
816         pthread_cond_init(&p->progress_cond, NULL);
817         pthread_cond_init(&p->output_cond, NULL);
818
819         p->frame = av_frame_alloc();
820         if (!p->frame) {
821             av_freep(&copy);
822             err = AVERROR(ENOMEM);
823             goto error;
824         }
825         p->avpkt = av_packet_alloc();
826         if (!p->avpkt) {
827             av_freep(&copy);
828             err = AVERROR(ENOMEM);
829             goto error;
830         }
831
832         p->parent = fctx;
833         p->avctx  = copy;
834
835         if (!copy) {
836             err = AVERROR(ENOMEM);
837             goto error;
838         }
839
840         *copy = *src;
841
842         copy->internal = av_malloc(sizeof(AVCodecInternal));
843         if (!copy->internal) {
844             copy->priv_data = NULL;
845             err = AVERROR(ENOMEM);
846             goto error;
847         }
848         *copy->internal = *src->internal;
849         copy->internal->thread_ctx = p;
850         copy->internal->last_pkt_props = p->avpkt;
851
852         copy->delay = avctx->delay;
853
854         if (codec->priv_data_size) {
855             copy->priv_data = av_mallocz(codec->priv_data_size);
856             if (!copy->priv_data) {
857                 err = AVERROR(ENOMEM);
858                 goto error;
859             }
860
861             if (codec->priv_class) {
862                 *(const AVClass **)copy->priv_data = codec->priv_class;
863                 err = av_opt_copy(copy->priv_data, src->priv_data);
864                 if (err < 0)
865                     goto error;
866             }
867         }
868
869         if (i)
870             copy->internal->is_copy = 1;
871
872         if (codec->init)
873             err = codec->init(copy);
874
875         if (err) goto error;
876
877         if (!i)
878             update_context_from_thread(avctx, copy, 1);
879
880         atomic_init(&p->debug_threads, (copy->debug & FF_DEBUG_THREADS) != 0);
881
882         err = AVERROR(pthread_create(&p->thread, NULL, frame_worker_thread, p));
883         p->thread_init= !err;
884         if(!p->thread_init)
885             goto error;
886     }
887
888     return 0;
889
890 error:
891     ff_frame_thread_free(avctx, i+1);
892
893     return err;
894 }
895
896 void ff_thread_flush(AVCodecContext *avctx)
897 {
898     int i;
899     FrameThreadContext *fctx = avctx->internal->thread_ctx;
900
901     if (!fctx) return;
902
903     park_frame_worker_threads(fctx, avctx->thread_count);
904     if (fctx->prev_thread) {
905         if (fctx->prev_thread != &fctx->threads[0])
906             update_context_from_thread(fctx->threads[0].avctx, fctx->prev_thread->avctx, 0);
907     }
908
909     fctx->next_decoding = fctx->next_finished = 0;
910     fctx->delaying = 1;
911     fctx->prev_thread = NULL;
912     for (i = 0; i < avctx->thread_count; i++) {
913         PerThreadContext *p = &fctx->threads[i];
914         // Make sure decode flush calls with size=0 won't return old frames
915         p->got_frame = 0;
916         av_frame_unref(p->frame);
917         p->result = 0;
918
919 #if FF_API_THREAD_SAFE_CALLBACKS
920         release_delayed_buffers(p);
921 #endif
922
923         if (avctx->codec->flush)
924             avctx->codec->flush(p->avctx);
925     }
926 }
927
928 int ff_thread_can_start_frame(AVCodecContext *avctx)
929 {
930     PerThreadContext *p = avctx->internal->thread_ctx;
931 FF_DISABLE_DEPRECATION_WARNINGS
932     if ((avctx->active_thread_type&FF_THREAD_FRAME) && atomic_load(&p->state) != STATE_SETTING_UP &&
933         (avctx->codec->update_thread_context
934 #if FF_API_THREAD_SAFE_CALLBACKS
935          || !THREAD_SAFE_CALLBACKS(avctx)
936 #endif
937          )) {
938         return 0;
939     }
940 FF_ENABLE_DEPRECATION_WARNINGS
941     return 1;
942 }
943
944 static int thread_get_buffer_internal(AVCodecContext *avctx, ThreadFrame *f, int flags)
945 {
946     PerThreadContext *p = avctx->internal->thread_ctx;
947     int err;
948
949     f->owner[0] = f->owner[1] = avctx;
950
951     if (!(avctx->active_thread_type & FF_THREAD_FRAME))
952         return ff_get_buffer(avctx, f->f, flags);
953
954 FF_DISABLE_DEPRECATION_WARNINGS
955     if (atomic_load(&p->state) != STATE_SETTING_UP &&
956         (avctx->codec->update_thread_context
957 #if FF_API_THREAD_SAFE_CALLBACKS
958          || !THREAD_SAFE_CALLBACKS(avctx)
959 #endif
960          )) {
961 FF_ENABLE_DEPRECATION_WARNINGS
962         av_log(avctx, AV_LOG_ERROR, "get_buffer() cannot be called after ff_thread_finish_setup()\n");
963         return -1;
964     }
965
966     if (avctx->codec->caps_internal & FF_CODEC_CAP_ALLOCATE_PROGRESS) {
967         atomic_int *progress;
968         f->progress = av_buffer_alloc(2 * sizeof(*progress));
969         if (!f->progress) {
970             return AVERROR(ENOMEM);
971         }
972         progress = (atomic_int*)f->progress->data;
973
974         atomic_init(&progress[0], -1);
975         atomic_init(&progress[1], -1);
976     }
977
978     pthread_mutex_lock(&p->parent->buffer_mutex);
979 #if !FF_API_THREAD_SAFE_CALLBACKS
980     err = ff_get_buffer(avctx, f->f, flags);
981 #else
982 FF_DISABLE_DEPRECATION_WARNINGS
983     if (THREAD_SAFE_CALLBACKS(avctx)) {
984         err = ff_get_buffer(avctx, f->f, flags);
985     } else {
986         pthread_mutex_lock(&p->progress_mutex);
987         p->requested_frame = f->f;
988         p->requested_flags = flags;
989         atomic_store_explicit(&p->state, STATE_GET_BUFFER, memory_order_release);
990         pthread_cond_broadcast(&p->progress_cond);
991
992         while (atomic_load(&p->state) != STATE_SETTING_UP)
993             pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
994
995         err = p->result;
996
997         pthread_mutex_unlock(&p->progress_mutex);
998
999     }
1000     if (!THREAD_SAFE_CALLBACKS(avctx) && !avctx->codec->update_thread_context)
1001         ff_thread_finish_setup(avctx);
1002 FF_ENABLE_DEPRECATION_WARNINGS
1003 #endif
1004     if (err)
1005         av_buffer_unref(&f->progress);
1006
1007     pthread_mutex_unlock(&p->parent->buffer_mutex);
1008
1009     return err;
1010 }
1011
1012 #if FF_API_THREAD_SAFE_CALLBACKS
1013 FF_DISABLE_DEPRECATION_WARNINGS
1014 enum AVPixelFormat ff_thread_get_format(AVCodecContext *avctx, const enum AVPixelFormat *fmt)
1015 {
1016     enum AVPixelFormat res;
1017     PerThreadContext *p = avctx->internal->thread_ctx;
1018     if (!(avctx->active_thread_type & FF_THREAD_FRAME) || avctx->thread_safe_callbacks ||
1019         avctx->get_format == avcodec_default_get_format)
1020         return ff_get_format(avctx, fmt);
1021     if (atomic_load(&p->state) != STATE_SETTING_UP) {
1022         av_log(avctx, AV_LOG_ERROR, "get_format() cannot be called after ff_thread_finish_setup()\n");
1023         return -1;
1024     }
1025     pthread_mutex_lock(&p->progress_mutex);
1026     p->available_formats = fmt;
1027     atomic_store(&p->state, STATE_GET_FORMAT);
1028     pthread_cond_broadcast(&p->progress_cond);
1029
1030     while (atomic_load(&p->state) != STATE_SETTING_UP)
1031         pthread_cond_wait(&p->progress_cond, &p->progress_mutex);
1032
1033     res = p->result_format;
1034
1035     pthread_mutex_unlock(&p->progress_mutex);
1036
1037     return res;
1038 }
1039 FF_ENABLE_DEPRECATION_WARNINGS
1040 #endif
1041
1042 int ff_thread_get_buffer(AVCodecContext *avctx, ThreadFrame *f, int flags)
1043 {
1044     int ret = thread_get_buffer_internal(avctx, f, flags);
1045     if (ret < 0)
1046         av_log(avctx, AV_LOG_ERROR, "thread_get_buffer() failed\n");
1047     return ret;
1048 }
1049
1050 void ff_thread_release_buffer(AVCodecContext *avctx, ThreadFrame *f)
1051 {
1052 #if FF_API_THREAD_SAFE_CALLBACKS
1053 FF_DISABLE_DEPRECATION_WARNINGS
1054     PerThreadContext *p = avctx->internal->thread_ctx;
1055     FrameThreadContext *fctx;
1056     AVFrame *dst;
1057     int ret = 0;
1058     int can_direct_free = !(avctx->active_thread_type & FF_THREAD_FRAME) ||
1059                           THREAD_SAFE_CALLBACKS(avctx);
1060 FF_ENABLE_DEPRECATION_WARNINGS
1061 #endif
1062
1063     if (!f->f)
1064         return;
1065
1066     if (avctx->debug & FF_DEBUG_BUFFERS)
1067         av_log(avctx, AV_LOG_DEBUG, "thread_release_buffer called on pic %p\n", f);
1068
1069     av_buffer_unref(&f->progress);
1070     f->owner[0] = f->owner[1] = NULL;
1071
1072 #if !FF_API_THREAD_SAFE_CALLBACKS
1073     av_frame_unref(f->f);
1074 #else
1075     // when the frame buffers are not allocated, just reset it to clean state
1076     if (can_direct_free || !f->f->buf[0]) {
1077         av_frame_unref(f->f);
1078         return;
1079     }
1080
1081     fctx = p->parent;
1082     pthread_mutex_lock(&fctx->buffer_mutex);
1083
1084     if (p->num_released_buffers == p->released_buffers_allocated) {
1085         AVFrame **tmp = av_realloc_array(p->released_buffers, p->released_buffers_allocated + 1,
1086                                          sizeof(*p->released_buffers));
1087         if (tmp) {
1088             tmp[p->released_buffers_allocated] = av_frame_alloc();
1089             p->released_buffers = tmp;
1090         }
1091
1092         if (!tmp || !tmp[p->released_buffers_allocated]) {
1093             ret = AVERROR(ENOMEM);
1094             goto fail;
1095         }
1096         p->released_buffers_allocated++;
1097     }
1098
1099     dst = p->released_buffers[p->num_released_buffers];
1100     av_frame_move_ref(dst, f->f);
1101
1102     p->num_released_buffers++;
1103
1104 fail:
1105     pthread_mutex_unlock(&fctx->buffer_mutex);
1106
1107     // make sure the frame is clean even if we fail to free it
1108     // this leaks, but it is better than crashing
1109     if (ret < 0) {
1110         av_log(avctx, AV_LOG_ERROR, "Could not queue a frame for freeing, this will leak\n");
1111         memset(f->f->buf, 0, sizeof(f->f->buf));
1112         if (f->f->extended_buf)
1113             memset(f->f->extended_buf, 0, f->f->nb_extended_buf * sizeof(*f->f->extended_buf));
1114         av_frame_unref(f->f);
1115     }
1116 #endif
1117 }