]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/consumer/ffmpeg_consumer.cpp
git-svn-id: https://casparcg.svn.sourceforge.net/svnroot/casparcg/server/branches...
[casparcg] / modules / ffmpeg / consumer / ffmpeg_consumer.cpp
1 /*\r
2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>\r
3 *\r
4 * This file is part of CasparCG (www.casparcg.com).\r
5 *\r
6 * CasparCG is free software: you can redistribute it and/or modify\r
7 * it under the terms of the GNU General Public License as published by\r
8 * the Free Software Foundation, either version 3 of the License, or\r
9 * (at your option) any later version.\r
10 *\r
11 * CasparCG is distributed in the hope that it will be useful,\r
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
14 * GNU General Public License for more details.\r
15 *\r
16 * You should have received a copy of the GNU General Public License\r
17 * along with CasparCG. If not, see <http://www.gnu.org/licenses/>.\r
18 *\r
19 * Author: Robert Nagy, ronag89@gmail.com\r
20 */\r
21  \r
22 #include "../StdAfx.h"\r
23 \r
24 #include "../ffmpeg_error.h"\r
25 \r
26 #include "ffmpeg_consumer.h"\r
27 \r
28 #include "../producer/tbb_avcodec.h"\r
29 \r
30 #include <core/frame/frame.h>\r
31 #include <core/mixer/audio/audio_util.h>\r
32 #include <core/consumer/frame_consumer.h>\r
33 #include <core/video_format.h>\r
34 \r
35 #include <common/array.h>\r
36 #include <common/env.h>\r
37 #include <common/except.h>\r
38 #include <common/executor.h>\r
39 #include <common/diagnostics/graph.h>\r
40 #include <common/lock.h>\r
41 #include <common/memory.h>\r
42 #include <common/param.h>\r
43 #include <common/utf.h>\r
44 #include <common/assert.h>\r
45 \r
46 #include <boost/algorithm/string.hpp>\r
47 #include <boost/timer.hpp>\r
48 #include <boost/property_tree/ptree.hpp>\r
49 #include <boost/filesystem.hpp>\r
50 #include <boost/range/algorithm.hpp>\r
51 #include <boost/range/algorithm_ext.hpp>\r
52 #include <boost/lexical_cast.hpp>\r
53 \r
54 #include <tbb/spin_mutex.h>\r
55 \r
56 #include <numeric>\r
57 \r
58 #if defined(_MSC_VER)\r
59 #pragma warning (push)\r
60 #pragma warning (disable : 4244)\r
61 #endif\r
62 extern "C" \r
63 {\r
64         #define __STDC_CONSTANT_MACROS\r
65         #define __STDC_LIMIT_MACROS\r
66         #include <libavformat/avformat.h>\r
67         #include <libswscale/swscale.h>\r
68         #include <libavutil/opt.h>\r
69         #include <libavutil/pixdesc.h>\r
70         #include <libavutil/parseutils.h>\r
71         #include <libavutil/samplefmt.h>\r
72         #include <libswresample/swresample.h>\r
73 }\r
74 #if defined(_MSC_VER)\r
75 #pragma warning (pop)\r
76 #endif\r
77 \r
78 namespace caspar { namespace ffmpeg {\r
79         \r
80 int av_opt_set(void *obj, const char *name, const char *val, int search_flags)\r
81 {\r
82         AVClass* av_class = *(AVClass**)obj;\r
83 \r
84         if((strcmp(name, "pix_fmt") == 0 || strcmp(name, "pixel_format") == 0) && strcmp(av_class->class_name, "AVCodecContext") == 0)\r
85         {\r
86                 AVCodecContext* c = (AVCodecContext*)obj;               \r
87                 auto pix_fmt = av_get_pix_fmt(val);\r
88                 if(pix_fmt == PIX_FMT_NONE)\r
89                         return -1;              \r
90                 c->pix_fmt = pix_fmt;\r
91                 return 0;\r
92         }\r
93         //if((strcmp(name, "r") == 0 || strcmp(name, "frame_rate") == 0) && strcmp(av_class->class_name, "AVCodecContext") == 0)\r
94         //{\r
95         //      AVCodecContext* c = (AVCodecContext*)obj;       \r
96 \r
97         //      if(c->codec_type != AVMEDIA_TYPE_VIDEO)\r
98         //              return -1;\r
99 \r
100         //      AVRational rate;\r
101         //      int ret = av_parse_video_rate(&rate, val);\r
102         //      if(ret < 0)\r
103         //              return ret;\r
104 \r
105         //      c->time_base.num = rate.den;\r
106         //      c->time_base.den = rate.num;\r
107         //      return 0;\r
108         //}\r
109 \r
110         return ::av_opt_set(obj, name, val, search_flags);\r
111 }\r
112 \r
113 struct option\r
114 {\r
115         std::string name;\r
116         std::string value;\r
117 \r
118         option(std::string name, std::string value)\r
119                 : name(std::move(name))\r
120                 , value(std::move(value))\r
121         {\r
122         }\r
123 };\r
124         \r
125 struct output_format\r
126 {\r
127         AVOutputFormat* format;\r
128         int                             width;\r
129         int                             height;\r
130         CodecID                 vcodec;\r
131         CodecID                 acodec;\r
132         int                             croptop;\r
133         int                             cropbot;\r
134 \r
135         output_format(const core::video_format_desc& format_desc, const std::string& filename, std::vector<option>& options)\r
136                 : format(av_guess_format(nullptr, filename.c_str(), nullptr))\r
137                 , width(format_desc.width)\r
138                 , height(format_desc.height)\r
139                 , vcodec(CODEC_ID_NONE)\r
140                 , acodec(CODEC_ID_NONE)\r
141                 , croptop(0)\r
142                 , cropbot(0)\r
143         {\r
144                 if(boost::iequals(boost::filesystem::path(filename).extension().string(), ".dv"))\r
145                         set_opt("f", "dv");\r
146 \r
147                 boost::range::remove_erase_if(options, [&](const option& o)\r
148                 {\r
149                         return set_opt(o.name, o.value);\r
150                 });\r
151                 \r
152                 if(vcodec == CODEC_ID_NONE && format)\r
153                         vcodec = format->video_codec;\r
154 \r
155                 if(acodec == CODEC_ID_NONE && format)\r
156                         acodec = format->audio_codec;\r
157                 \r
158                 if(vcodec == CODEC_ID_NONE)\r
159                         vcodec = CODEC_ID_H264;\r
160                 \r
161                 if(acodec == CODEC_ID_NONE)\r
162                         acodec = CODEC_ID_PCM_S16LE;\r
163         }\r
164         \r
165         bool set_opt(const std::string& name, const std::string& value)\r
166         {\r
167                 //if(name == "target")\r
168                 //{ \r
169                 //      enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;\r
170                 //      \r
171                 //      if(name.find("pal-") != std::string::npos)\r
172                 //              norm = PAL;\r
173                 //      else if(name.find("ntsc-") != std::string::npos)\r
174                 //              norm = NTSC;\r
175 \r
176                 //      if(norm == UNKNOWN)\r
177                 //              CASPAR_THROW_EXCEPTION(invalid_argument() << arg_name_info("target"));\r
178                 //      \r
179                 //      if (name.find("-dv") != std::string::npos) \r
180                 //      {\r
181                 //              set_opt("f", "dv");\r
182                 //              if(norm == PAL)\r
183                 //              {\r
184                 //                      set_opt("s", "720x576");\r
185                 //              }\r
186                 //              else\r
187                 //              {\r
188                 //                      set_opt("s", "720x480");\r
189                 //                      if(height == 486)\r
190                 //                      {\r
191                 //                              set_opt("croptop", "2");\r
192                 //                              set_opt("cropbot", "4");\r
193                 //                      }\r
194                 //              }\r
195                 //              set_opt("s", norm == PAL ? "720x576" : "720x480");\r
196                 //      } \r
197 \r
198                 //      return true;\r
199                 //}\r
200                 //else \r
201                 if(name == "f")\r
202                 {\r
203                         format = av_guess_format(value.c_str(), nullptr, nullptr);\r
204 \r
205                         if(format == nullptr)\r
206                                 CASPAR_THROW_EXCEPTION(invalid_argument() << arg_name_info("f"));\r
207 \r
208                         return true;\r
209                 }\r
210                 else if(name == "vcodec" || name == "v:codec")\r
211                 {\r
212                         auto c = avcodec_find_encoder_by_name(value.c_str());\r
213                         if(c == nullptr)\r
214                                 CASPAR_THROW_EXCEPTION(invalid_argument() << arg_name_info("vcodec"));\r
215 \r
216                         vcodec = avcodec_find_encoder_by_name(value.c_str())->id;\r
217                         return true;\r
218 \r
219                 }\r
220                 else if(name == "acodec" || name == "a:codec")\r
221                 {\r
222                         auto c = avcodec_find_encoder_by_name(value.c_str());\r
223                         if(c == nullptr)\r
224                                 CASPAR_THROW_EXCEPTION(invalid_argument() << arg_name_info("acodec"));\r
225 \r
226                         acodec = avcodec_find_encoder_by_name(value.c_str())->id;\r
227 \r
228                         return true;\r
229                 }\r
230                 else if(name == "s")\r
231                 {\r
232                         if(av_parse_video_size(&width, &height, value.c_str()) < 0)\r
233                                 CASPAR_THROW_EXCEPTION(invalid_argument() << arg_name_info("s"));\r
234                         \r
235                         return true;\r
236                 }\r
237                 else if(name == "croptop")\r
238                 {\r
239                         croptop = boost::lexical_cast<int>(value);\r
240 \r
241                         return true;\r
242                 }\r
243                 else if(name == "cropbot")\r
244                 {\r
245                         cropbot = boost::lexical_cast<int>(value);\r
246 \r
247                         return true;\r
248                 }\r
249                 \r
250                 return false;\r
251         }\r
252 };\r
253 \r
254 typedef std::vector<uint8_t, tbb::cache_aligned_allocator<uint8_t>>     byte_vector;\r
255 \r
256 struct ffmpeg_consumer : boost::noncopyable\r
257 {               \r
258         const spl::shared_ptr<diagnostics::graph>       graph_;\r
259         const std::string                                                       filename_;              \r
260         const std::shared_ptr<AVFormatContext>          oc_;\r
261         const core::video_format_desc                           format_desc_;   \r
262 \r
263         monitor::basic_subject                                          event_subject_;\r
264         \r
265         tbb::spin_mutex                                                         exception_mutex_;\r
266         std::exception_ptr                                                      exception_;\r
267         \r
268         std::shared_ptr<AVStream>                                       audio_st_;\r
269         std::shared_ptr<AVStream>                                       video_st_;\r
270         \r
271         byte_vector                                                                     picture_buffer_;\r
272         byte_vector                                                                     audio_buffer_;\r
273         std::shared_ptr<SwrContext>                                     swr_;\r
274         std::shared_ptr<SwsContext>                                     sws_;\r
275 \r
276         int64_t                                                                         frame_number_;\r
277 \r
278         output_format                                                           output_format_;\r
279         \r
280         executor                                                                        executor_;\r
281 public:\r
282         ffmpeg_consumer(const std::string& filename, const core::video_format_desc& format_desc, std::vector<option> options)\r
283                 : filename_(filename)\r
284                 , oc_(avformat_alloc_context(), av_free)\r
285                 , format_desc_(format_desc)\r
286                 , frame_number_(0)\r
287                 , output_format_(format_desc, filename, options)\r
288                 , executor_(print())\r
289         {\r
290                 check_space();\r
291 \r
292                 // TODO: Ask stakeholders about case where file already exists.\r
293                 boost::filesystem::remove(boost::filesystem::path(env::media_folder() + u16(filename))); // Delete the file if it exists\r
294 \r
295                 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));\r
296                 graph_->set_text(print());\r
297                 diagnostics::register_graph(graph_);\r
298 \r
299                 executor_.set_capacity(8);\r
300 \r
301                 oc_->oformat = output_format_.format;\r
302                                 \r
303                 strcpy_s(oc_->filename, filename_.c_str());\r
304                 \r
305                 //  Add the audio and video streams using the default format codecs     and initialize the codecs.\r
306                 video_st_ = add_video_stream(options);\r
307                 audio_st_ = add_audio_stream(options);\r
308                                 \r
309                 av_dump_format(oc_.get(), 0, filename_.c_str(), 1);\r
310                  \r
311                 // Open the output ffmpeg, if needed.\r
312                 if (!(oc_->oformat->flags & AVFMT_NOFILE)) \r
313                         THROW_ON_ERROR2(avio_open(&oc_->pb, filename.c_str(), AVIO_FLAG_WRITE), "[ffmpeg_consumer]");\r
314                                 \r
315                 THROW_ON_ERROR2(avformat_write_header(oc_.get(), nullptr), "[ffmpeg_consumer]");\r
316 \r
317                 if(options.size() > 0)\r
318                 {\r
319                         BOOST_FOREACH(auto& option, options)\r
320                                 CASPAR_LOG(warning) << L"Invalid option: -" << u16(option.name) << L" " << u16(option.value);\r
321                 }\r
322 \r
323                 CASPAR_LOG(info) << print() << L" Successfully Initialized.";   \r
324         }\r
325 \r
326         ~ffmpeg_consumer()\r
327         {    \r
328                 try\r
329                 {\r
330                         executor_.wait();\r
331                 }\r
332                 catch(...)\r
333                 {\r
334                         CASPAR_LOG_CURRENT_EXCEPTION();\r
335                 }\r
336 \r
337                 LOG_ON_ERROR2(av_write_trailer(oc_.get()), "[ffmpeg_consumer]");\r
338                 \r
339                 audio_st_.reset();\r
340                 video_st_.reset();\r
341                           \r
342                 if (!(oc_->oformat->flags & AVFMT_NOFILE)) \r
343                         LOG_ON_ERROR2(avio_close(oc_->pb), "[ffmpeg_consumer]");\r
344 \r
345                 CASPAR_LOG(info) << print() << L" Successfully Uninitialized."; \r
346         }\r
347         \r
348         // frame_consumer\r
349 \r
350         bool send(core::const_frame& frame)\r
351         {\r
352                 auto exception = lock(exception_mutex_, [&]\r
353                 {\r
354                         return exception_;\r
355                 });\r
356 \r
357                 if(exception != nullptr)\r
358                         std::rethrow_exception(exception);\r
359                         \r
360                 executor_.begin_invoke([=]\r
361                 {               \r
362                         encode(frame);\r
363                 });\r
364                 \r
365                 return true;\r
366         }\r
367 \r
368         std::wstring print() const\r
369         {\r
370                 return L"ffmpeg[" + u16(filename_) + L"]";\r
371         }\r
372         \r
373         void subscribe(const monitor::observable::observer_ptr& o)\r
374         {\r
375                 event_subject_.subscribe(o);\r
376         }\r
377 \r
378         void unsubscribe(const monitor::observable::observer_ptr& o)\r
379         {\r
380                 event_subject_.unsubscribe(o);\r
381         }               \r
382 \r
383 private:\r
384         std::shared_ptr<AVStream> add_video_stream(std::vector<option>& options)\r
385         { \r
386                 if(output_format_.vcodec == CODEC_ID_NONE)\r
387                         return nullptr;\r
388 \r
389                 auto st = av_new_stream(oc_.get(), 0);\r
390                 if (!st)                \r
391                         CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("Could not allocate video-stream.") << boost::errinfo_api_function("av_new_stream"));             \r
392 \r
393                 auto encoder = avcodec_find_encoder(output_format_.vcodec);\r
394                 if (!encoder)\r
395                         CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("Codec not found."));\r
396 \r
397                 auto c = st->codec;\r
398 \r
399                 avcodec_get_context_defaults3(c, encoder);\r
400                                 \r
401                 c->codec_id                     = output_format_.vcodec;\r
402                 c->codec_type           = AVMEDIA_TYPE_VIDEO;\r
403                 c->width                        = output_format_.width;\r
404                 c->height                       = output_format_.height - output_format_.croptop - output_format_.cropbot;\r
405                 c->time_base.den        = format_desc_.time_scale;\r
406                 c->time_base.num        = format_desc_.duration;\r
407                 c->gop_size                     = 25;\r
408                 c->flags                   |= format_desc_.field_mode == core::field_mode::progressive ? 0 : (CODEC_FLAG_INTERLACED_ME | CODEC_FLAG_INTERLACED_DCT);\r
409                 c->pix_fmt                      = c->pix_fmt != PIX_FMT_NONE ? c->pix_fmt : PIX_FMT_YUV420P;\r
410 \r
411                 if(c->codec_id == CODEC_ID_PRORES)\r
412                 {                       \r
413                         c->bit_rate     = output_format_.width < 1280 ? 63*1000000 : 220*1000000;\r
414                         c->pix_fmt      = PIX_FMT_YUV422P10;\r
415                 }\r
416                 else if(c->codec_id == CODEC_ID_DNXHD)\r
417                 {\r
418                         if(c->width < 1280 || c->height < 720)\r
419                                 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("Unsupported video dimensions."));\r
420 \r
421                         c->bit_rate     = 220*1000000;\r
422                         c->pix_fmt      = PIX_FMT_YUV422P;\r
423                 }\r
424                 else if(c->codec_id == CODEC_ID_DVVIDEO)\r
425                 {\r
426                         c->width = c->height == 1280 ? 960  : c->width;\r
427                         \r
428                         if(format_desc_.format == core::video_format::ntsc)\r
429                         {\r
430                                 c->pix_fmt = PIX_FMT_YUV411P;\r
431                                 output_format_.croptop = 2;\r
432                                 output_format_.cropbot = 4;\r
433                                 c->height                          = output_format_.height - output_format_.croptop - output_format_.cropbot;\r
434                         }\r
435                         else if(format_desc_.format == core::video_format::pal)\r
436                                 c->pix_fmt = PIX_FMT_YUV420P;\r
437                         else // dv50\r
438                                 c->pix_fmt = PIX_FMT_YUV422P;\r
439                         \r
440                         if(format_desc_.duration == 1001)                       \r
441                                 c->width = c->height == 1080 ? 1280 : c->width;                 \r
442                         else\r
443                                 c->width = c->height == 1080 ? 1440 : c->width;                 \r
444                 }\r
445                 else if(c->codec_id == CODEC_ID_H264)\r
446                 {                          \r
447                         c->pix_fmt = PIX_FMT_YUV420P;    \r
448                         av_opt_set(c->priv_data, "preset", "ultrafast", 0);\r
449                         av_opt_set(c->priv_data, "tune",   "fastdecode",   0);\r
450                         av_opt_set(c->priv_data, "crf",    "5",     0);\r
451                 }\r
452                 else if(c->codec_id == CODEC_ID_QTRLE)\r
453                 {\r
454                         c->pix_fmt = PIX_FMT_ARGB;\r
455                 }\r
456                                                                 \r
457                 boost::range::remove_erase_if(options, [&](const option& o)\r
458                 {\r
459                         return o.name.at(0) != 'a' && ffmpeg::av_opt_set(c, o.name.c_str(), o.value.c_str(), AV_OPT_SEARCH_CHILDREN) > -1;\r
460                 });\r
461                                 \r
462                 if(output_format_.format->flags & AVFMT_GLOBALHEADER)\r
463                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;\r
464                 \r
465                 THROW_ON_ERROR2(tbb_avcodec_open(c, encoder), "[ffmpeg_consumer]");\r
466 \r
467                 return std::shared_ptr<AVStream>(st, [](AVStream* st)\r
468                 {\r
469                         LOG_ON_ERROR2(tbb_avcodec_close(st->codec), "[ffmpeg_consumer]");\r
470                         av_freep(&st->codec);\r
471                         av_freep(&st);\r
472                 });\r
473         }\r
474                 \r
475         std::shared_ptr<AVStream> add_audio_stream(std::vector<option>& options)\r
476         {\r
477                 if(output_format_.acodec == CODEC_ID_NONE)\r
478                         return nullptr;\r
479 \r
480                 auto st = av_new_stream(oc_.get(), 1);\r
481                 if(!st)\r
482                         CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("Could not allocate audio-stream") << boost::errinfo_api_function("av_new_stream"));              \r
483                 \r
484                 auto encoder = avcodec_find_encoder(output_format_.acodec);\r
485                 if (!encoder)\r
486                         CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));\r
487                 \r
488                 auto c = st->codec;\r
489 \r
490                 avcodec_get_context_defaults3(c, encoder);\r
491 \r
492                 c->codec_id                     = output_format_.acodec;\r
493                 c->codec_type           = AVMEDIA_TYPE_AUDIO;\r
494                 c->sample_rate          = 48000;\r
495                 c->channels                     = 2;\r
496                 c->sample_fmt           = AV_SAMPLE_FMT_S16;\r
497                 c->time_base.num        = 1;\r
498                 c->time_base.den        = c->sample_rate;\r
499 \r
500                 if(output_format_.vcodec == CODEC_ID_FLV1)              \r
501                         c->sample_rate  = 44100;                \r
502 \r
503                 if(output_format_.format->flags & AVFMT_GLOBALHEADER)\r
504                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;\r
505                                 \r
506                 boost::range::remove_erase_if(options, [&](const option& o)\r
507                 {\r
508                         return ffmpeg::av_opt_set(c, o.name.c_str(), o.value.c_str(), AV_OPT_SEARCH_CHILDREN) > -1;\r
509                 });\r
510 \r
511                 THROW_ON_ERROR2(avcodec_open(c, encoder), "[ffmpeg_consumer]");\r
512 \r
513                 return std::shared_ptr<AVStream>(st, [](AVStream* st)\r
514                 {\r
515                         LOG_ON_ERROR2(avcodec_close(st->codec), "[ffmpeg_consumer]");;\r
516                         av_freep(&st->codec);\r
517                         av_freep(&st);\r
518                 });\r
519         }\r
520   \r
521         void encode_video_frame(core::const_frame frame)\r
522         { \r
523                 if(!video_st_)\r
524                         return;\r
525                 \r
526                 auto enc = video_st_->codec;\r
527          \r
528                 auto av_frame                           = convert_video(frame, enc);\r
529                 av_frame->interlaced_frame      = format_desc_.field_mode != core::field_mode::progressive;\r
530                 av_frame->top_field_first       = format_desc_.field_mode == core::field_mode::upper;\r
531                 av_frame->pts                           = frame_number_++;\r
532 \r
533                 event_subject_ << monitor::event("frame")       % static_cast<int64_t>(frame_number_)\r
534                                                                                                         % static_cast<int64_t>(std::numeric_limits<int64_t>::max());\r
535 \r
536                 AVPacket pkt;\r
537                 av_init_packet(&pkt);\r
538                 pkt.data = nullptr;\r
539                 pkt.size = 0;\r
540 \r
541                 int got_packet = 0;\r
542                 THROW_ON_ERROR2(avcodec_encode_video2(enc, &pkt, av_frame.get(), &got_packet), "[ffmpeg_consumer]");\r
543                 std::shared_ptr<AVPacket> guard(&pkt, av_free_packet);\r
544 \r
545                 if(!got_packet)\r
546                         return;\r
547                  \r
548                 if (pkt.pts != AV_NOPTS_VALUE)\r
549                         pkt.pts = av_rescale_q(pkt.pts, enc->time_base, video_st_->time_base);\r
550                 if (pkt.dts != AV_NOPTS_VALUE)\r
551                         pkt.dts = av_rescale_q(pkt.dts, enc->time_base, video_st_->time_base);\r
552                  \r
553                 pkt.stream_index = video_st_->index;\r
554                         \r
555                 THROW_ON_ERROR2(av_interleaved_write_frame(oc_.get(), &pkt), "[ffmpeg_consumer]");\r
556         }\r
557                 \r
558         uint64_t get_channel_layout(AVCodecContext* dec)\r
559         {\r
560                 auto layout = (dec->channel_layout && dec->channels == av_get_channel_layout_nb_channels(dec->channel_layout)) ? dec->channel_layout : av_get_default_channel_layout(dec->channels);\r
561                 return layout;\r
562         }\r
563                 \r
564         void encode_audio_frame(core::const_frame frame)\r
565         {               \r
566                 if(!audio_st_)\r
567                         return;\r
568                 \r
569                 auto enc = audio_st_->codec;\r
570 \r
571                 boost::push_back(audio_buffer_, convert_audio(frame, enc));\r
572                         \r
573                 auto frame_size = enc->frame_size != 0 ? enc->frame_size * enc->channels * av_get_bytes_per_sample(enc->sample_fmt) : static_cast<int>(audio_buffer_.size());\r
574                         \r
575                 while(audio_buffer_.size() >= frame_size)\r
576                 {                       \r
577                         std::shared_ptr<AVFrame> av_frame(avcodec_alloc_frame(), av_free);\r
578                         avcodec_get_frame_defaults(av_frame.get());             \r
579                         av_frame->nb_samples = frame_size / (enc->channels * av_get_bytes_per_sample(enc->sample_fmt));\r
580 \r
581                         AVPacket pkt;\r
582                         av_init_packet(&pkt);\r
583                         pkt.data = nullptr;\r
584                         pkt.size = 0;                           \r
585                         \r
586                         THROW_ON_ERROR2(avcodec_fill_audio_frame(av_frame.get(), enc->channels, enc->sample_fmt, audio_buffer_.data(), frame_size, 1), "[ffmpeg_consumer]");\r
587 \r
588                         int got_packet = 0;\r
589                         THROW_ON_ERROR2(avcodec_encode_audio2(enc, &pkt, av_frame.get(), &got_packet), "[ffmpeg_consumer]");\r
590                         std::shared_ptr<AVPacket> guard(&pkt, av_free_packet);\r
591                                 \r
592                         audio_buffer_.erase(audio_buffer_.begin(), audio_buffer_.begin() + frame_size);\r
593 \r
594                         if(!got_packet)\r
595                                 return;\r
596                 \r
597                         if (pkt.pts != AV_NOPTS_VALUE)\r
598                                 pkt.pts      = av_rescale_q(pkt.pts, enc->time_base, audio_st_->time_base);\r
599                         if (pkt.dts != AV_NOPTS_VALUE)\r
600                                 pkt.dts      = av_rescale_q(pkt.dts, enc->time_base, audio_st_->time_base);\r
601                         if (pkt.duration > 0)\r
602                                 pkt.duration = static_cast<int>(av_rescale_q(pkt.duration, enc->time_base, audio_st_->time_base));\r
603                 \r
604                         pkt.stream_index = audio_st_->index;\r
605                                                 \r
606                         THROW_ON_ERROR2(av_interleaved_write_frame(oc_.get(), &pkt), "[ffmpeg_consumer]");\r
607                 }\r
608         }                \r
609         \r
610         std::shared_ptr<AVFrame> convert_video(core::const_frame frame, AVCodecContext* c)\r
611         {\r
612                 if(!sws_) \r
613                 {\r
614                         sws_.reset(sws_getContext(format_desc_.width, \r
615                                                                           format_desc_.height - output_format_.croptop  - output_format_.cropbot, \r
616                                                                           PIX_FMT_BGRA,\r
617                                                                           c->width,\r
618                                                                           c->height, \r
619                                                                           c->pix_fmt, \r
620                                                                           SWS_BICUBIC, nullptr, nullptr, nullptr), \r
621                                                 sws_freeContext);\r
622                         if (sws_ == nullptr) \r
623                                 CASPAR_THROW_EXCEPTION(caspar_exception() << msg_info("Cannot initialize the conversion context"));\r
624                 }\r
625 \r
626                 // #in_frame\r
627 \r
628                 std::shared_ptr<AVFrame> in_frame(avcodec_alloc_frame(), av_free);\r
629 \r
630                 avpicture_fill(reinterpret_cast<AVPicture*>(in_frame.get()), \r
631                                            const_cast<uint8_t*>(frame.image_data().begin()),\r
632                                            PIX_FMT_BGRA, \r
633                                            format_desc_.width,\r
634                                            format_desc_.height - output_format_.croptop  - output_format_.cropbot);\r
635                 // crop-top\r
636 \r
637                 for(int n = 0; n < 4; ++n)              \r
638                         in_frame->data[n] += in_frame->linesize[n] * output_format_.croptop;            \r
639                 \r
640                 // #out_frame\r
641 \r
642                 std::shared_ptr<AVFrame> out_frame(avcodec_alloc_frame(), av_free);\r
643                 \r
644                 av_image_fill_linesizes(out_frame->linesize, c->pix_fmt, c->width);\r
645                 for(int n = 0; n < 4; ++n)\r
646                         out_frame->linesize[n] += 32 - (out_frame->linesize[n] % 32); // align\r
647 \r
648                 picture_buffer_.resize(av_image_fill_pointers(out_frame->data, c->pix_fmt, c->height, nullptr, out_frame->linesize));\r
649                 av_image_fill_pointers(out_frame->data, c->pix_fmt, c->height, picture_buffer_.data(), out_frame->linesize);\r
650                 \r
651                 // #scale\r
652 \r
653                 sws_scale(sws_.get(), \r
654                                   in_frame->data, \r
655                                   in_frame->linesize,\r
656                                   0, \r
657                                   format_desc_.height - output_format_.cropbot - output_format_.croptop, \r
658                                   out_frame->data, \r
659                                   out_frame->linesize);\r
660 \r
661                 return out_frame;\r
662         }\r
663         \r
664         byte_vector convert_audio(core::const_frame& frame, AVCodecContext* c)\r
665         {\r
666                 if(!swr_) \r
667                 {\r
668                         swr_ = std::shared_ptr<SwrContext>(swr_alloc_set_opts(nullptr,\r
669                                                                                 get_channel_layout(c), c->sample_fmt, c->sample_rate,\r
670                                                                                 av_get_default_channel_layout(format_desc_.audio_channels), AV_SAMPLE_FMT_S32, format_desc_.audio_sample_rate,\r
671                                                                                 0, nullptr), [](SwrContext* p){swr_free(&p);});\r
672 \r
673                         if(!swr_)\r
674                                 CASPAR_THROW_EXCEPTION(bad_alloc());\r
675 \r
676                         THROW_ON_ERROR2(swr_init(swr_.get()), "[audio_decoder]");\r
677                 }\r
678                                 \r
679                 byte_vector buffer(48000);\r
680 \r
681                 const uint8_t* in[]  = {reinterpret_cast<const uint8_t*>(frame.audio_data().data())};\r
682                 uint8_t*       out[] = {buffer.data()};\r
683 \r
684                 auto channel_samples = swr_convert(swr_.get(), \r
685                                                                                    out, static_cast<int>(buffer.size()) / c->channels / av_get_bytes_per_sample(c->sample_fmt), \r
686                                                                                    in, static_cast<int>(frame.audio_data().size()/format_desc_.audio_channels));\r
687 \r
688                 buffer.resize(channel_samples * c->channels * av_get_bytes_per_sample(c->sample_fmt));  \r
689 \r
690                 return buffer;\r
691         }\r
692 \r
693         void check_space()\r
694         {\r
695                 auto space = boost::filesystem::space(boost::filesystem::path(filename_).parent_path());\r
696                 if(space.available < 512*1000000)\r
697                         BOOST_THROW_EXCEPTION(file_write_error() << msg_info("out of space"));\r
698         }\r
699 \r
700         void encode(const core::const_frame& frame)\r
701         {\r
702                 try\r
703                 {\r
704                         if(frame_number_ % 25 == 0)\r
705                                 check_space();\r
706 \r
707                         boost::timer frame_timer;\r
708 \r
709                         encode_video_frame(frame);\r
710                         encode_audio_frame(frame);\r
711 \r
712                         graph_->set_value("frame-time", frame_timer.elapsed()*format_desc_.fps*0.5);\r
713                 }\r
714                 catch(...)\r
715                 {                       \r
716                         lock(exception_mutex_, [&]\r
717                         {\r
718                                 exception_ = std::current_exception();\r
719                         });\r
720                 }\r
721         }\r
722 };\r
723 \r
724 struct ffmpeg_consumer_proxy : public core::frame_consumer\r
725 {\r
726         const std::wstring                              filename_;\r
727         const std::vector<option>               options_;\r
728 \r
729         std::unique_ptr<ffmpeg_consumer> consumer_;\r
730 \r
731 public:\r
732 \r
733         ffmpeg_consumer_proxy(const std::wstring& filename, const std::vector<option>& options)\r
734                 : filename_(filename)\r
735                 , options_(options)\r
736         {\r
737         }\r
738         \r
739         virtual void initialize(const core::video_format_desc& format_desc, int)\r
740         {\r
741                 if(consumer_)\r
742                         BOOST_THROW_EXCEPTION(invalid_operation() << msg_info("Cannot reinitialize ffmpeg-consumer."));\r
743 \r
744                 consumer_.reset(new ffmpeg_consumer(u8(filename_), format_desc, options_));\r
745         }\r
746         \r
747         bool send(core::const_frame frame) override\r
748         {\r
749                 return consumer_->send(frame);\r
750         }\r
751         \r
752         std::wstring print() const override\r
753         {\r
754                 return consumer_ ? consumer_->print() : L"[ffmpeg_consumer]";\r
755         }\r
756 \r
757         std::wstring name() const override\r
758         {\r
759                 return L"file";\r
760         }\r
761 \r
762         boost::property_tree::wptree info() const override\r
763         {\r
764                 boost::property_tree::wptree info;\r
765                 info.add(L"type", L"file");\r
766                 info.add(L"filename", filename_);\r
767                 return info;\r
768         }\r
769                 \r
770         bool has_synchronization_clock() const override\r
771         {\r
772                 return false;\r
773         }\r
774 \r
775         int buffer_depth() const override\r
776         {\r
777                 return 1;\r
778         }\r
779 \r
780         int index() const override\r
781         {\r
782                 return 200;\r
783         }\r
784 \r
785         void subscribe(const monitor::observable::observer_ptr& o) override\r
786         {\r
787                 consumer_->subscribe(o);\r
788         }\r
789 \r
790         void unsubscribe(const monitor::observable::observer_ptr& o) override\r
791         {\r
792                 consumer_->unsubscribe(o);\r
793         }               \r
794 };      \r
795 spl::shared_ptr<core::frame_consumer> create_consumer(const std::vector<std::wstring>& params)\r
796 {\r
797         auto str = std::accumulate(params.begin(), params.end(), std::wstring(), [](const std::wstring& lhs, const std::wstring& rhs) {return lhs + L" " + rhs;});\r
798         \r
799         boost::wregex path_exp(L"\\s*FILE(\\s(?<PATH>.+\\.[^\\s]+))?.*", boost::regex::icase);\r
800 \r
801         boost::wsmatch path;\r
802         if(!boost::regex_match(str, path, path_exp))\r
803                 return core::frame_consumer::empty();\r
804         \r
805         boost::wregex opt_exp(L"-((?<NAME>[^\\s]+)\\s+(?<VALUE>[^\\s]+))");     \r
806         \r
807         std::vector<option> options;\r
808         for(boost::wsregex_iterator it(str.begin(), str.end(), opt_exp); it != boost::wsregex_iterator(); ++it)\r
809         {\r
810                 auto name  = u8(boost::trim_copy(boost::to_lower_copy((*it)["NAME"].str())));\r
811                 auto value = u8(boost::trim_copy(boost::to_lower_copy((*it)["VALUE"].str())));\r
812                 \r
813                 if(value == "h264")\r
814                         value = "libx264";\r
815                 else if(value == "dvcpro")\r
816                         value = "dvvideo";\r
817 \r
818                 options.push_back(option(name, value));\r
819         }\r
820                                 \r
821         return spl::make_shared<ffmpeg_consumer_proxy>(env::media_folder() + path["PATH"].str(), options);\r
822 }\r
823 \r
824 spl::shared_ptr<core::frame_consumer> create_consumer(const boost::property_tree::wptree& ptree)\r
825 {\r
826         auto filename   = ptree.get<std::wstring>(L"path");\r
827         auto codec              = ptree.get(L"vcodec", L"libx264");\r
828 \r
829         std::vector<option> options;\r
830         options.push_back(option("vcodec", u8(codec)));\r
831         \r
832         return spl::make_shared<ffmpeg_consumer_proxy>(env::media_folder() + filename, options);\r
833 }\r
834 \r
835 }}\r