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