2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>
4 * This file is part of CasparCG (www.casparcg.com).
6 * CasparCG is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * CasparCG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with CasparCG. If not, see <http://www.gnu.org/licenses/>.
19 * Author: Robert Nagy, ronag89@gmail.com
22 #include "../StdAfx.h"
24 #include "tbb_avcodec.h"
26 #include <common/assert.h>
27 #include <common/except.h>
28 #include <common/log.h>
29 #include <common/env.h>
31 #include <tbb/atomic.h>
32 #include <tbb/parallel_for.h>
33 #include <tbb/tbb_thread.h>
36 #pragma warning (push)
37 #pragma warning (disable : 4244)
41 #define __STDC_CONSTANT_MACROS
42 #define __STDC_LIMIT_MACROS
43 #include <libavformat/avformat.h>
51 static const int MAX_THREADS = 16; // See mpegvideo.h
53 int thread_execute(AVCodecContext* s, int (*func)(AVCodecContext *c2, void *arg2), void* arg, int* ret, int count, int size)
55 tbb::parallel_for(0, count, 1, [&](int i)
57 int r = func(s, (char*)arg + i*size);
65 int thread_execute2(AVCodecContext* s, int (*func)(AVCodecContext* c2, void* arg2, int, int), void* arg, int* ret, int count)
67 // TODO: Micro-optimize...
69 std::array<std::vector<int>, 16> jobs;
71 for(int n = 0; n < count; ++n)
72 jobs[(n*MAX_THREADS) / count].push_back(n);
74 tbb::parallel_for(0, MAX_THREADS, [&](int n)
76 for (auto k : jobs[n])
78 int r = func(s, arg, k, n);
87 void thread_init(AVCodecContext* s)
89 static int dummy_opaque;
91 s->active_thread_type = FF_THREAD_SLICE;
92 s->opaque = &dummy_opaque;
93 s->execute = thread_execute;
94 s->execute2 = thread_execute2;
95 s->thread_count = MAX_THREADS; // We are using a task-scheduler, so use as many "threads/tasks" as possible.
98 void thread_free(AVCodecContext* s)
106 int tbb_avcodec_open(AVCodecContext* avctx, AVCodec* codec, bool single_threaded)
108 if(codec->capabilities & CODEC_CAP_EXPERIMENTAL)
109 CASPAR_THROW_EXCEPTION(invalid_argument() << msg_info("Experimental codecs are not supported."));
111 avctx->thread_count = 1;
113 if(!single_threaded && codec->capabilities & CODEC_CAP_SLICE_THREADS)
116 // ff_thread_init will not be executed since thread_opaque != nullptr || thread_count == 1.
117 return avcodec_open2(avctx, codec, nullptr);
120 int tbb_avcodec_close(AVCodecContext* avctx)
123 // ff_thread_free will not be executed since thread_opaque == nullptr.
124 return avcodec_close(avctx);