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