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