2 * This file is part of FFmpeg.
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.
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.
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
21 * Libavfilter multithreading support
26 #include "libavutil/common.h"
27 #include "libavutil/cpu.h"
28 #include "libavutil/mem.h"
29 #include "libavutil/thread.h"
30 #include "libavutil/slicethread.h"
36 typedef struct ThreadContext {
38 AVSliceThread *thread;
39 avfilter_action_func *func;
41 /* per-execute parameters */
47 static void worker_func(void *priv, int jobnr, int threadnr, int nb_jobs, int nb_threads)
49 ThreadContext *c = priv;
50 int ret = c->func(c->ctx, c->arg, jobnr, nb_jobs);
55 static void slice_thread_uninit(ThreadContext *c)
57 avpriv_slicethread_free(&c->thread);
60 static int thread_execute(AVFilterContext *ctx, avfilter_action_func *func,
61 void *arg, int *ret, int nb_jobs)
63 ThreadContext *c = ctx->graph->internal->thread;
72 avpriv_slicethread_execute(c->thread, nb_jobs, 0);
76 static int thread_init_internal(ThreadContext *c, int nb_threads)
78 nb_threads = avpriv_slicethread_create(&c->thread, c, worker_func, NULL, nb_threads);
80 avpriv_slicethread_free(&c->thread);
81 return FFMAX(nb_threads, 1);
84 int ff_graph_thread_init(AVFilterGraph *graph)
88 if (graph->nb_threads == 1) {
89 graph->thread_type = 0;
93 graph->internal->thread = av_mallocz(sizeof(ThreadContext));
94 if (!graph->internal->thread)
95 return AVERROR(ENOMEM);
97 ret = thread_init_internal(graph->internal->thread, graph->nb_threads);
99 av_freep(&graph->internal->thread);
100 graph->thread_type = 0;
101 graph->nb_threads = 1;
102 return (ret < 0) ? ret : 0;
104 graph->nb_threads = ret;
106 graph->internal->thread_execute = thread_execute;
111 void ff_graph_thread_free(AVFilterGraph *graph)
113 if (graph->internal->thread)
114 slice_thread_uninit(graph->internal->thread);
115 av_freep(&graph->internal->thread);