]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/ffmpeg.cpp
Implemented thumbnail generation for video files. Similar to 2.0, but better.
[casparcg] / modules / ffmpeg / ffmpeg.cpp
1 /*
2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>
3 *
4 * This file is part of CasparCG (www.casparcg.com).
5 *
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.
10 *
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.
15 *
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/>.
18 *
19 * Author: Robert Nagy, ronag89@gmail.com
20 */
21
22 #include "StdAfx.h"
23
24 #include "ffmpeg.h"
25
26 #include "consumer/ffmpeg_consumer.h"
27 #include "consumer/streaming_consumer.h"
28 #include "producer/ffmpeg_producer.h"
29 #include "producer/util/util.h"
30
31 #include <common/log.h>
32 #include <common/os/general_protection_fault.h>
33
34 #include <core/consumer/frame_consumer.h>
35 #include <core/producer/frame_producer.h>
36 #include <core/producer/media_info/media_info.h>
37 #include <core/producer/media_info/media_info_repository.h>
38 #include <core/system_info_provider.h>
39
40 #include <boost/property_tree/ptree.hpp>
41 #include <boost/thread/tss.hpp>
42
43 #include <tbb/recursive_mutex.h>
44
45 #if defined(_MSC_VER)
46 #pragma warning (disable : 4244)
47 #pragma warning (disable : 4603)
48 #pragma warning (disable : 4996)
49 #endif
50
51 extern "C" 
52 {
53         #define __STDC_CONSTANT_MACROS
54         #define __STDC_LIMIT_MACROS
55         #include <libavformat/avformat.h>
56         #include <libswscale/swscale.h>
57         #include <libavutil/avutil.h>
58         #include <libavfilter/avfilter.h>
59 }
60
61 namespace caspar { namespace ffmpeg {
62         
63 int ffmpeg_lock_callback(void **mutex, enum AVLockOp op) 
64
65         if(!mutex)
66                 return 0;
67
68         auto my_mutex = reinterpret_cast<tbb::recursive_mutex*>(*mutex);
69         
70         switch(op) 
71         { 
72                 case AV_LOCK_CREATE: 
73                 { 
74                         *mutex = new tbb::recursive_mutex(); 
75                         break; 
76                 } 
77                 case AV_LOCK_OBTAIN: 
78                 { 
79                         if(my_mutex)
80                                 my_mutex->lock(); 
81                         break; 
82                 } 
83                 case AV_LOCK_RELEASE: 
84                 { 
85                         if(my_mutex)
86                                 my_mutex->unlock(); 
87                         break; 
88                 } 
89                 case AV_LOCK_DESTROY: 
90                 { 
91                         delete my_mutex;
92                         *mutex = nullptr;
93                         break; 
94                 } 
95         } 
96         return 0; 
97
98
99 static void sanitize(uint8_t *line)
100 {
101     while(*line)
102         {
103         if(*line < 0x08 || (*line > 0x0D && *line < 0x20))
104             *line='?';
105         line++;
106     }
107 }
108
109 void log_callback(void* ptr, int level, const char* fmt, va_list vl)
110 {
111     static int print_prefix=1;
112     //static int count;
113     static char prev[1024];
114     char line[8192];
115     //static int is_atty;
116     AVClass* avc= ptr ? *(AVClass**)ptr : NULL;
117     if(level > av_log_get_level())
118         return;
119     line[0]=0;
120         
121 #undef fprintf
122     if(print_prefix && avc) 
123         {
124         if (avc->parent_log_context_offset) 
125                 {
126             AVClass** parent= *(AVClass***)(((uint8_t*)ptr) + avc->parent_log_context_offset);
127             if(parent && *parent)
128                 std::sprintf(line, "[%s @ %p] ", (*parent)->item_name(parent), parent);            
129         }
130         std::sprintf(line + strlen(line), "[%s @ %p] ", avc->item_name(ptr), ptr);
131     }
132
133     std::vsprintf(line + strlen(line), fmt, vl);
134
135     print_prefix = strlen(line) && line[strlen(line)-1] == '\n';
136         
137     //if(print_prefix && !strcmp(line, prev)){
138     //    count++;
139     //    if(is_atty==1)
140     //        fprintf(stderr, "    Last message repeated %d times\r", count);
141     //    return;
142     //}
143     //if(count>0){
144     //    fprintf(stderr, "    Last message repeated %d times\n", count);
145     //    count=0;
146     //}
147     strcpy(prev, line);
148     sanitize((uint8_t*)line);
149
150         auto len = strlen(line);
151         if(len > 0)
152                 line[len-1] = 0;
153         
154         if(level == AV_LOG_DEBUG)
155                 CASPAR_LOG(debug) << L"[ffmpeg] " << line;
156         else if(level == AV_LOG_INFO)
157                 CASPAR_LOG(info) << L"[ffmpeg] " << line;
158         else if(level == AV_LOG_WARNING)
159                 CASPAR_LOG(warning) << L"[ffmpeg] " << line;
160         else if(level == AV_LOG_ERROR)
161                 CASPAR_LOG(error) << L"[ffmpeg] " << line;
162         else if(level == AV_LOG_FATAL)
163                 CASPAR_LOG(fatal) << L"[ffmpeg] " << line;
164         else
165                 CASPAR_LOG(trace) << L"[ffmpeg] " << line;
166
167     //colored_fputs(av_clip(level>>3, 0, 6), line);
168 }
169
170 //static int query_yadif_formats(AVFilterContext *ctx)
171 //{
172 //    static const int pix_fmts[] = {
173 //        PIX_FMT_YUV444P,
174 //        PIX_FMT_YUV422P,
175 //        PIX_FMT_YUV420P,
176 //        PIX_FMT_YUV410P,
177 //        PIX_FMT_YUV411P,
178 //        PIX_FMT_GRAY8,
179 //        PIX_FMT_YUVJ444P,
180 //        PIX_FMT_YUVJ422P,
181 //        PIX_FMT_YUVJ420P,
182 //        AV_NE( PIX_FMT_GRAY16BE, PIX_FMT_GRAY16LE ),
183 //        PIX_FMT_YUV440P,
184 //        PIX_FMT_YUVJ440P,
185 //        AV_NE( PIX_FMT_YUV444P16BE, PIX_FMT_YUV444P16LE ),
186 //        AV_NE( PIX_FMT_YUV422P16BE, PIX_FMT_YUV422P16LE ),
187 //        AV_NE( PIX_FMT_YUV420P16BE, PIX_FMT_YUV420P16LE ),
188 //        PIX_FMT_YUVA420P,
189 //        PIX_FMT_NONE
190 //    };
191 //    avfilter_set_common_pixel_formats(ctx, avfilter_make_format_list(pix_fmts));
192 //
193 //    return 0;
194 //}
195 //
196 //#pragma warning (push)
197 //#pragma warning (disable : 4706)
198 //void fix_yadif_filter_format_query()
199 //{
200 //      AVFilter** filter = nullptr;
201 //    while((filter = av_filter_next(filter)) && *filter)
202 //      {
203 //              if(strstr((*filter)->name, "yadif") != 0)
204 //                      (*filter)->query_formats = query_yadif_formats;
205 //      }
206 //}
207 //#pragma warning (pop)
208
209 std::wstring make_version(unsigned int ver)
210 {
211         std::wstringstream str;
212         str << ((ver >> 16) & 0xFF) << L"." << ((ver >> 8) & 0xFF) << L"." << ((ver >> 0) & 0xFF);
213         return str.str();
214 }
215
216 std::wstring avcodec_version()
217 {
218         return make_version(::avcodec_version());
219 }
220
221 std::wstring avformat_version()
222 {
223         return make_version(::avformat_version());
224 }
225
226 std::wstring avutil_version()
227 {
228         return make_version(::avutil_version());
229 }
230
231 std::wstring avfilter_version()
232 {
233         return make_version(::avfilter_version());
234 }
235
236 std::wstring swscale_version()
237 {
238         return make_version(::swscale_version());
239 }
240 bool& get_quiet_logging_for_thread()
241 {
242         static boost::thread_specific_ptr<bool> quiet_logging_for_thread;
243
244         auto local = quiet_logging_for_thread.get();
245
246         if (!local)
247         {
248                 local = new bool(false);
249                 quiet_logging_for_thread.reset(local);
250         }
251
252         return *local;
253 }
254
255 bool is_logging_quiet_for_thread()
256 {
257         return get_quiet_logging_for_thread();
258 }
259
260 std::shared_ptr<void> temporary_enable_quiet_logging_for_thread(bool enable)
261 {
262         if (!enable || is_logging_quiet_for_thread())
263                 return std::shared_ptr<void>();
264
265         get_quiet_logging_for_thread() = true;
266
267         return std::shared_ptr<void>(nullptr, [](void*)
268         {
269                 get_quiet_logging_for_thread() = false; // Only works correctly if destructed in same thread as original caller.
270         });
271 }
272
273 void log_for_thread(void* ptr, int level, const char* fmt, va_list vl)
274 {
275         ensure_gpf_handler_installed_for_thread("ffmpeg-thread");
276
277         int min_level = is_logging_quiet_for_thread() ? AV_LOG_DEBUG : AV_LOG_FATAL;
278
279         log_callback(ptr, std::max(level, min_level), fmt, vl);
280 }
281
282 void init(core::module_dependencies dependencies)
283 {
284         av_lockmgr_register(ffmpeg_lock_callback);
285         av_log_set_callback(log_for_thread);
286
287     avfilter_register_all();
288         //fix_yadif_filter_format_query();
289         av_register_all();
290     avformat_network_init();
291     avcodec_register_all();
292         
293         dependencies.consumer_registry->register_consumer_factory(L"FFMpeg Consumer", create_consumer, describe_consumer);
294         dependencies.consumer_registry->register_consumer_factory(L"Streaming Consumer",  create_streaming_consumer, describe_streaming_consumer);
295         dependencies.consumer_registry->register_preconfigured_consumer_factory(L"file", create_preconfigured_consumer);
296         dependencies.consumer_registry->register_preconfigured_consumer_factory(L"stream", create_preconfigured_streaming_consumer);
297         dependencies.producer_registry->register_producer_factory(L"FFmpeg Producer", create_producer, describe_producer);
298         dependencies.producer_registry->register_thumbnail_producer_factory(create_thumbnail_producer);
299
300         dependencies.media_info_repo->register_extractor(
301                         [](const std::wstring& file, const std::wstring& extension, core::media_info& info) -> bool
302                         {
303                                 auto quiet_logging = temporary_enable_quiet_logging_for_thread(true);
304                                 if (extension == L".WAV" || extension == L".MP3")
305                                 {
306                                         info.clip_type = L"AUDIO";
307                                         return true;
308                                 }
309
310                                 if (!is_valid_file(file, true))
311                                         return false;
312
313                                 info.clip_type = L"MOVIE";
314
315                                 return try_get_duration(file, info.duration, info.time_base);
316                         });
317         dependencies.system_info_provider_repo->register_system_info_provider([](boost::property_tree::wptree& info)
318         {
319                 info.add(L"system.ffmpeg.avcodec", avcodec_version());
320                 info.add(L"system.ffmpeg.avformat", avformat_version());
321                 info.add(L"system.ffmpeg.avfilter", avfilter_version());
322                 info.add(L"system.ffmpeg.avutil", avutil_version());
323                 info.add(L"system.ffmpeg.swscale", swscale_version());
324         });
325 }
326
327 void uninit()
328 {
329         avfilter_uninit();
330     avformat_network_deinit();
331         av_lockmgr_register(nullptr);
332 }
333
334 }}