]> 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/audio/audio_resampler.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/env.h>\r
36 #include <common/utf.h>\r
37 #include <common/param.h>\r
38 #include <common/executor.h>\r
39 #include <common/diagnostics/graph.h>\r
40 #include <common/array.h>\r
41 #include <common/memory.h>\r
42 \r
43 #include <boost/algorithm/string.hpp>\r
44 #include <boost/timer.hpp>\r
45 #include <boost/property_tree/ptree.hpp>\r
46 #include <boost/filesystem.hpp>\r
47 #include <boost/range/algorithm.hpp>\r
48 #include <boost/range/algorithm_ext.hpp>\r
49 #include <boost/lexical_cast.hpp>\r
50 \r
51 #if defined(_MSC_VER)\r
52 #pragma warning (push)\r
53 #pragma warning (disable : 4244)\r
54 #endif\r
55 extern "C" \r
56 {\r
57         #define __STDC_CONSTANT_MACROS\r
58         #define __STDC_LIMIT_MACROS\r
59         #include <libavformat/avformat.h>\r
60         #include <libswscale/swscale.h>\r
61         #include <libavutil/opt.h>\r
62         #include <libavutil/pixdesc.h>\r
63         #include <libavutil/parseutils.h>\r
64 }\r
65 #if defined(_MSC_VER)\r
66 #pragma warning (pop)\r
67 #endif\r
68 \r
69 namespace caspar { namespace ffmpeg {\r
70         \r
71 int av_opt_set(void *obj, const char *name, const char *val, int search_flags)\r
72 {\r
73         AVClass* av_class = *(AVClass**)obj;\r
74 \r
75         if((strcmp(name, "pix_fmt") == 0 || strcmp(name, "pixel_format") == 0) && strcmp(av_class->class_name, "AVCodecContext") == 0)\r
76         {\r
77                 AVCodecContext* c = (AVCodecContext*)obj;               \r
78                 auto pix_fmt = av_get_pix_fmt(val);\r
79                 if(pix_fmt == PIX_FMT_NONE)\r
80                         return -1;              \r
81                 c->pix_fmt = pix_fmt;\r
82                 return 0;\r
83         }\r
84         if((strcmp(name, "r") == 0 || strcmp(name, "frame_rate") == 0) && strcmp(av_class->class_name, "AVCodecContext") == 0)\r
85         {\r
86                 AVCodecContext* c = (AVCodecContext*)obj;       \r
87 \r
88                 if(c->codec_type != AVMEDIA_TYPE_VIDEO)\r
89                         return -1;\r
90 \r
91                 AVRational rate;\r
92                 int ret = av_parse_video_rate(&rate, val);\r
93                 if(ret < 0)\r
94                         return ret;\r
95 \r
96                 c->time_base.num = rate.den;\r
97                 c->time_base.den = rate.num;\r
98                 return 0;\r
99         }\r
100 \r
101         return ::av_opt_set(obj, name, val, search_flags);\r
102 }\r
103 \r
104 struct option\r
105 {\r
106         std::string name;\r
107         std::string value;\r
108 \r
109         option(std::string name, std::string value)\r
110                 : name(std::move(name))\r
111                 , value(std::move(value))\r
112         {\r
113         }\r
114 };\r
115         \r
116 struct output_format\r
117 {\r
118         AVOutputFormat* format;\r
119         int                             width;\r
120         int                             height;\r
121         CodecID                 vcodec;\r
122         CodecID                 acodec;\r
123         int                             croptop;\r
124         int                             cropbot;\r
125 \r
126         output_format(const core::video_format_desc& format_desc, const std::string& filename, std::vector<option>& options)\r
127                 : format(av_guess_format(nullptr, filename.c_str(), nullptr))\r
128                 , width(format_desc.width)\r
129                 , height(format_desc.height)\r
130                 , vcodec(CODEC_ID_NONE)\r
131                 , acodec(CODEC_ID_NONE)\r
132                 , croptop(0)\r
133                 , cropbot(0)\r
134         {\r
135                 boost::range::remove_erase_if(options, [&](const option& o)\r
136                 {\r
137                         return set_opt(o.name, o.value);\r
138                 });\r
139                 \r
140                 if(vcodec == CODEC_ID_NONE)\r
141                         vcodec = format->video_codec;\r
142 \r
143                 if(acodec == CODEC_ID_NONE)\r
144                         acodec = format->audio_codec;\r
145                 \r
146                 if(vcodec == CODEC_ID_NONE)\r
147                         vcodec = CODEC_ID_H264;\r
148                 \r
149                 if(acodec == CODEC_ID_NONE)\r
150                         acodec = CODEC_ID_PCM_S16LE;\r
151         }\r
152         \r
153         bool set_opt(const std::string& name, const std::string& value)\r
154         {\r
155                 //if(name == "target")\r
156                 //{ \r
157                 //      enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;\r
158                 //      \r
159                 //      if(name.find("pal-") != std::string::npos)\r
160                 //              norm = PAL;\r
161                 //      else if(name.find("ntsc-") != std::string::npos)\r
162                 //              norm = NTSC;\r
163 \r
164                 //      if(norm == UNKNOWN)\r
165                 //              BOOST_THROW_EXCEPTION(invalid_argument() << arg_name_info("target"));\r
166                 //      \r
167                 //      if (name.find("-dv") != std::string::npos) \r
168                 //      {\r
169                 //              set_opt("f", "dv");\r
170                 //              set_opt("s", norm == PAL ? "720x576" : "720x480");\r
171                 //              //set_opt("pix_fmt", name.find("-dv50") != std::string::npos ? "yuv422p" : norm == PAL ? "yuv420p" : "yuv411p");\r
172                 //              //set_opt("ar", "48000");\r
173                 //              //set_opt("ac", "2");\r
174                 //      } \r
175                 //}\r
176                 if(name == "f")\r
177                 {\r
178                         format = av_guess_format(value.c_str(), nullptr, nullptr);\r
179 \r
180                         if(format == nullptr)\r
181                                 BOOST_THROW_EXCEPTION(invalid_argument() << arg_name_info("f"));\r
182 \r
183                         return true;\r
184                 }\r
185                 else if(name == "vcodec")\r
186                 {\r
187                         auto c = avcodec_find_encoder_by_name(value.c_str());\r
188                         if(c == nullptr)\r
189                                 BOOST_THROW_EXCEPTION(invalid_argument() << arg_name_info("vcodec"));\r
190 \r
191                         vcodec = avcodec_find_encoder_by_name(value.c_str())->id;\r
192                         return true;\r
193 \r
194                 }\r
195                 else if(name == "acodec")\r
196                 {\r
197                         auto c = avcodec_find_encoder_by_name(value.c_str());\r
198                         if(c == nullptr)\r
199                                 BOOST_THROW_EXCEPTION(invalid_argument() << arg_name_info("acodec"));\r
200 \r
201                         acodec = avcodec_find_encoder_by_name(value.c_str())->id;\r
202 \r
203                         return true;\r
204                 }\r
205                 else if(name == "s")\r
206                 {\r
207                         if(av_parse_video_size(&width, &height, value.c_str()) < 0)\r
208                                 BOOST_THROW_EXCEPTION(invalid_argument() << arg_name_info("s"));\r
209                         \r
210                         return true;\r
211                 }\r
212                 else if(name == "croptop")\r
213                 {\r
214                         croptop = boost::lexical_cast<int>(value);\r
215 \r
216                         return true;\r
217                 }\r
218                 else if(name == "cropbot")\r
219                 {\r
220                         cropbot = boost::lexical_cast<int>(value);\r
221 \r
222                         return true;\r
223                 }\r
224                 \r
225                 return false;\r
226         }\r
227 };\r
228 \r
229 typedef std::vector<uint8_t, tbb::cache_aligned_allocator<uint8_t>>     byte_vector;\r
230 \r
231 struct ffmpeg_consumer : boost::noncopyable\r
232 {               \r
233         const std::string                                               filename_;\r
234                 \r
235         const std::shared_ptr<AVFormatContext>  oc_;\r
236         const core::video_format_desc                   format_desc_;\r
237         \r
238         const spl::shared_ptr<diagnostics::graph>               graph_;\r
239 \r
240         executor                                                                encode_executor_;\r
241         executor                                                                write_executor_;\r
242         \r
243         std::shared_ptr<AVStream>                               audio_st_;\r
244         std::shared_ptr<AVStream>                               video_st_;\r
245         \r
246         byte_vector                                                             audio_outbuf_;\r
247         byte_vector                                                             audio_buf_;\r
248         byte_vector                                                             video_outbuf_;\r
249         byte_vector                                                             picture_buf_;\r
250         std::shared_ptr<audio_resampler>                swr_;\r
251         std::shared_ptr<SwsContext>                             sws_;\r
252 \r
253         int64_t                                                                 in_frame_number_;\r
254         int64_t                                                                 out_frame_number_;\r
255 \r
256         output_format                                                   output_format_;\r
257         \r
258 public:\r
259         ffmpeg_consumer(const std::string& filename, const core::video_format_desc& format_desc, std::vector<option> options)\r
260                 : filename_(filename)\r
261                 , video_outbuf_(1920*1080*8)\r
262                 , audio_outbuf_(10000)\r
263                 , oc_(avformat_alloc_context(), av_free)\r
264                 , format_desc_(format_desc)\r
265                 , encode_executor_(print())\r
266                 , write_executor_(print() + L"/output")\r
267                 , in_frame_number_(0)\r
268                 , out_frame_number_(0)\r
269                 , output_format_(format_desc, filename, options)\r
270         {\r
271                 // TODO: Ask stakeholders about case where file already exists.\r
272                 boost::filesystem::remove(boost::filesystem::path(env::media_folder() + u16(filename))); // Delete the file if it exists\r
273 \r
274                 graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));\r
275                 graph_->set_text(print());\r
276                 diagnostics::register_graph(graph_);\r
277 \r
278                 encode_executor_.set_capacity(8);\r
279                 write_executor_.set_capacity(8);\r
280 \r
281                 oc_->oformat = output_format_.format;\r
282                                 \r
283                 THROW_ON_ERROR2(av_set_parameters(oc_.get(), nullptr), "[ffmpeg_consumer]");\r
284 \r
285                 strcpy_s(oc_->filename, filename_.c_str());\r
286                 \r
287                 //  Add the audio and video streams using the default format codecs     and initialize the codecs.\r
288                 auto options2 = options;\r
289                 video_st_ = add_video_stream(options2);\r
290                 audio_st_ = add_audio_stream(options);\r
291                                 \r
292                 dump_format(oc_.get(), 0, filename_.c_str(), 1);\r
293                  \r
294                 // Open the output ffmpeg, if needed.\r
295                 if (!(oc_->oformat->flags & AVFMT_NOFILE)) \r
296                         THROW_ON_ERROR2(avio_open(&oc_->pb, filename_.c_str(), URL_WRONLY), "[ffmpeg_consumer]");\r
297                                 \r
298                 THROW_ON_ERROR2(av_write_header(oc_.get()), "[ffmpeg_consumer]");\r
299 \r
300                 if(options.size() > 0)\r
301                 {\r
302                         BOOST_FOREACH(auto& option, options)\r
303                                 CASPAR_LOG(warning) << L"Invalid option: -" << u16(option.name) << L" " << u16(option.value);\r
304                 }\r
305 \r
306                 CASPAR_LOG(info) << print() << L" Successfully Initialized.";   \r
307         }\r
308 \r
309         ~ffmpeg_consumer()\r
310         {    \r
311                 encode_executor_.wait();\r
312                 write_executor_.wait();\r
313                 \r
314                 LOG_ON_ERROR2(av_write_trailer(oc_.get()), "[ffmpeg_consumer]");\r
315                 \r
316                 audio_st_.reset();\r
317                 video_st_.reset();\r
318                           \r
319                 if (!(oc_->oformat->flags & AVFMT_NOFILE)) \r
320                         LOG_ON_ERROR2(avio_close(oc_->pb), "[ffmpeg_consumer]"); // Close the output ffmpeg.\r
321 \r
322                 CASPAR_LOG(info) << print() << L" Successfully Uninitialized."; \r
323         }\r
324                         \r
325         std::wstring print() const\r
326         {\r
327                 return L"ffmpeg[" + u16(filename_) + L"]";\r
328         }\r
329 \r
330         std::shared_ptr<AVStream> add_video_stream(std::vector<option>& options)\r
331         { \r
332                 if(output_format_.vcodec == CODEC_ID_NONE)\r
333                         return nullptr;\r
334 \r
335                 auto st = av_new_stream(oc_.get(), 0);\r
336                 if (!st)                \r
337                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not allocate video-stream.") << boost::errinfo_api_function("av_new_stream"));              \r
338 \r
339                 auto encoder = avcodec_find_encoder(output_format_.vcodec);\r
340                 if (!encoder)\r
341                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Codec not found."));\r
342 \r
343                 auto c = st->codec;\r
344 \r
345                 avcodec_get_context_defaults3(c, encoder);\r
346                                 \r
347                 c->codec_id                     = output_format_.vcodec;\r
348                 c->codec_type           = AVMEDIA_TYPE_VIDEO;\r
349                 c->width                        = output_format_.width;\r
350                 c->height                       = output_format_.height - output_format_.croptop - output_format_.cropbot;\r
351                 c->time_base.den        = format_desc_.time_scale;\r
352                 c->time_base.num        = format_desc_.duration;\r
353                 c->gop_size                     = 25;\r
354                 c->flags                   |= format_desc_.field_mode == core::field_mode::progressive ? 0 : (CODEC_FLAG_INTERLACED_ME | CODEC_FLAG_INTERLACED_DCT);\r
355                 if(c->pix_fmt == PIX_FMT_NONE)\r
356                         c->pix_fmt = PIX_FMT_YUV420P;\r
357 \r
358                 if(c->codec_id == CODEC_ID_PRORES)\r
359                 {                       \r
360                         c->bit_rate     = c->width < 1280 ? 63*1000000 : 220*1000000;\r
361                         c->pix_fmt      = PIX_FMT_YUV422P10;\r
362                 }\r
363                 else if(c->codec_id == CODEC_ID_DNXHD)\r
364                 {\r
365                         if(c->width < 1280 || c->height < 720)\r
366                                 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Unsupported video dimensions."));\r
367 \r
368                         c->bit_rate     = 220*1000000;\r
369                         c->pix_fmt      = PIX_FMT_YUV422P;\r
370                 }\r
371                 else if(c->codec_id == CODEC_ID_DVVIDEO)\r
372                 {\r
373                         c->width = c->height == 1280 ? 960  : c->width;\r
374                         \r
375                         if(format_desc_.format == core::video_format::ntsc)\r
376                                 c->pix_fmt = PIX_FMT_YUV411P;\r
377                         else if(format_desc_.format == core::video_format::pal)\r
378                                 c->pix_fmt = PIX_FMT_YUV420P;\r
379                         else // dv50\r
380                                 c->pix_fmt = PIX_FMT_YUV422P;\r
381                         \r
382                         if(format_desc_.duration == 1001)                       \r
383                                 c->width = c->height == 1080 ? 1280 : c->width;                 \r
384                         else\r
385                                 c->width = c->height == 1080 ? 1440 : c->width;                 \r
386                 }\r
387                 else if(c->codec_id == CODEC_ID_H264)\r
388                 {                          \r
389                         c->pix_fmt = PIX_FMT_YUV420P;    \r
390                         if(options.empty())\r
391                         {\r
392                                 av_opt_set(c->priv_data, "preset", "ultrafast", 0);\r
393                                 av_opt_set(c->priv_data, "tune",   "fastdecode",   0);\r
394                                 av_opt_set(c->priv_data, "crf",    "5",     0);\r
395                         }\r
396                 }\r
397                 else if(c->codec_id == CODEC_ID_QTRLE)\r
398                 {\r
399                         c->pix_fmt = PIX_FMT_ARGB;\r
400                 }\r
401                                 \r
402                 c->max_b_frames = 0; // b-frames not supported.\r
403                                 \r
404                 boost::range::remove_erase_if(options, [&](const option& o)\r
405                 {\r
406                         return ffmpeg::av_opt_set(c, o.name.c_str(), o.value.c_str(), AV_OPT_SEARCH_CHILDREN) > -1;\r
407                 });\r
408                                 \r
409                 if(output_format_.format->flags & AVFMT_GLOBALHEADER)\r
410                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;\r
411                 \r
412                 c->thread_count = boost::thread::hardware_concurrency();\r
413                 if(avcodec_open(c, encoder) < 0)\r
414                 {\r
415                         c->thread_count = 1;\r
416                         THROW_ON_ERROR2(avcodec_open(c, encoder), "[ffmpeg_consumer]");\r
417                 }\r
418 \r
419                 return std::shared_ptr<AVStream>(st, [](AVStream* st)\r
420                 {\r
421                         LOG_ON_ERROR2(avcodec_close(st->codec), "[ffmpeg_consumer]");\r
422                         av_freep(&st->codec);\r
423                         av_freep(&st);\r
424                 });\r
425         }\r
426                 \r
427         std::shared_ptr<AVStream> add_audio_stream(std::vector<option>& options)\r
428         {\r
429                 if(output_format_.acodec == CODEC_ID_NONE)\r
430                         return nullptr;\r
431 \r
432                 auto st = av_new_stream(oc_.get(), 1);\r
433                 if(!st)\r
434                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not allocate audio-stream") << boost::errinfo_api_function("av_new_stream"));               \r
435                 \r
436                 auto encoder = avcodec_find_encoder(output_format_.acodec);\r
437                 if (!encoder)\r
438                         BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));\r
439                 \r
440                 auto c = st->codec;\r
441 \r
442                 avcodec_get_context_defaults3(c, encoder);\r
443 \r
444                 c->codec_id                     = output_format_.acodec;\r
445                 c->codec_type           = AVMEDIA_TYPE_AUDIO;\r
446                 c->sample_rate          = 48000;\r
447                 c->channels                     = 2;\r
448                 c->sample_fmt           = SAMPLE_FMT_S16;\r
449 \r
450                 if(output_format_.vcodec == CODEC_ID_FLV1)              \r
451                         c->sample_rate  = 44100;                \r
452 \r
453                 if(output_format_.format->flags & AVFMT_GLOBALHEADER)\r
454                         c->flags |= CODEC_FLAG_GLOBAL_HEADER;\r
455                                 \r
456                 boost::range::remove_erase_if(options, [&](const option& o)\r
457                 {\r
458                         return ffmpeg::av_opt_set(c, o.name.c_str(), o.value.c_str(), AV_OPT_SEARCH_CHILDREN) > -1;\r
459                 });\r
460 \r
461                 THROW_ON_ERROR2(avcodec_open(c, encoder), "[ffmpeg_consumer]");\r
462 \r
463                 return std::shared_ptr<AVStream>(st, [](AVStream* st)\r
464                 {\r
465                         LOG_ON_ERROR2(avcodec_close(st->codec), "[ffmpeg_consumer]");;\r
466                         av_freep(&st->codec);\r
467                         av_freep(&st);\r
468                 });\r
469         }\r
470         \r
471         std::shared_ptr<AVFrame> convert_video(core::const_frame frame, AVCodecContext* c)\r
472         {\r
473                 if(!sws_) \r
474                 {\r
475                         sws_.reset(sws_getContext(format_desc_.width, \r
476                                                                           format_desc_.height - output_format_.croptop  - output_format_.cropbot, \r
477                                                                           PIX_FMT_BGRA,\r
478                                                                           c->width,\r
479                                                                           c->height, \r
480                                                                           c->pix_fmt, \r
481                                                                           SWS_BICUBIC, nullptr, nullptr, nullptr), \r
482                                                 sws_freeContext);\r
483                         if (sws_ == nullptr) \r
484                                 BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Cannot initialize the conversion context"));\r
485                 }\r
486 \r
487                 std::shared_ptr<AVFrame> in_frame(avcodec_alloc_frame(), av_free);\r
488 \r
489                 avpicture_fill(reinterpret_cast<AVPicture*>(in_frame.get()), \r
490                                            const_cast<uint8_t*>(frame.image_data().begin()),\r
491                                            PIX_FMT_BGRA, \r
492                                            format_desc_.width,\r
493                                            format_desc_.height - output_format_.croptop  - output_format_.cropbot);\r
494 \r
495                 for(int n = 0; n < 4; ++n)              \r
496                         in_frame->data[n] += in_frame->linesize[n] * output_format_.croptop;            \r
497                                                                 \r
498                 std::shared_ptr<AVFrame> out_frame(avcodec_alloc_frame(), av_free);\r
499 \r
500                 picture_buf_.resize(avpicture_get_size(c->pix_fmt, \r
501                                                                                            c->width,\r
502                                                                                            c->height));\r
503 \r
504                 avpicture_fill(reinterpret_cast<AVPicture*>(out_frame.get()),\r
505                                            picture_buf_.data(), \r
506                                            c->pix_fmt, \r
507                                            c->width, \r
508                                            c->height);\r
509 \r
510                 sws_scale(sws_.get(), \r
511                                   in_frame->data, \r
512                                   in_frame->linesize,\r
513                                   0, \r
514                                   format_desc_.height - output_format_.cropbot - output_format_.croptop, \r
515                                   out_frame->data, \r
516                                   out_frame->linesize);\r
517 \r
518                 return out_frame;\r
519         }\r
520   \r
521         std::shared_ptr<AVPacket> encode_video_frame(core::const_frame frame)\r
522         { \r
523                 auto c = video_st_->codec;\r
524                 \r
525                 auto in_time  = static_cast<double>(in_frame_number_) / format_desc_.fps;\r
526                 auto out_time = static_cast<double>(out_frame_number_) / (static_cast<double>(c->time_base.den) / static_cast<double>(c->time_base.num));\r
527                 \r
528                 in_frame_number_++;\r
529 \r
530                 if(out_time - in_time > 0.01)\r
531                         return nullptr;\r
532  \r
533                 auto av_frame = convert_video(frame, c);\r
534                 av_frame->interlaced_frame      = format_desc_.field_mode != core::field_mode::progressive;\r
535                 av_frame->top_field_first       = format_desc_.field_mode == core::field_mode::upper;\r
536                 av_frame->pts                           = out_frame_number_++;\r
537 \r
538                 int out_size = THROW_ON_ERROR2(avcodec_encode_video(c, video_outbuf_.data(), static_cast<int>(video_outbuf_.size()), av_frame.get()), "[ffmpeg_consumer]");\r
539                 if(out_size > 0)\r
540                 {\r
541                         spl::shared_ptr<AVPacket> pkt(new AVPacket, [](AVPacket* p)\r
542                         {\r
543                                 av_free_packet(p);\r
544                                 delete p;\r
545                         });\r
546                         av_init_packet(pkt.get());\r
547  \r
548                         if (c->coded_frame->pts != AV_NOPTS_VALUE)\r
549                                 pkt->pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_st_->time_base);\r
550 \r
551                         if(c->coded_frame->key_frame)\r
552                                 pkt->flags |= AV_PKT_FLAG_KEY;\r
553 \r
554                         pkt->stream_index       = video_st_->index;\r
555                         pkt->data                       = video_outbuf_.data();\r
556                         pkt->size                       = out_size;\r
557  \r
558                         av_dup_packet(pkt.get());\r
559                         return pkt;\r
560                 }       \r
561                 return nullptr;\r
562         }\r
563                 \r
564         byte_vector convert_audio(core::const_frame& frame, AVCodecContext* c)\r
565         {\r
566                 if(!swr_)               \r
567                         swr_.reset(new audio_resampler(c->channels, format_desc_.audio_channels, \r
568                                                                                    c->sample_rate, format_desc_.audio_sample_rate,\r
569                                                                                    c->sample_fmt, AV_SAMPLE_FMT_S32));\r
570                 \r
571 \r
572                 auto audio_data = frame.audio_data();\r
573 \r
574                 std::vector<int8_t,  tbb::cache_aligned_allocator<int8_t>> audio_resample_buffer;\r
575                 std::copy(reinterpret_cast<const uint8_t*>(audio_data.data()), \r
576                                   reinterpret_cast<const uint8_t*>(audio_data.data()) + audio_data.size()*4, \r
577                                   std::back_inserter(audio_resample_buffer));\r
578                 \r
579                 audio_resample_buffer = swr_->resample(std::move(audio_resample_buffer));\r
580                 \r
581                 return byte_vector(audio_resample_buffer.begin(), audio_resample_buffer.end());\r
582         }\r
583         \r
584         std::shared_ptr<AVPacket> encode_audio_frame(core::const_frame frame)\r
585         {                       \r
586                 auto c = audio_st_->codec;\r
587 \r
588                 boost::range::push_back(audio_buf_, convert_audio(frame, c));\r
589                 \r
590                 std::size_t frame_size = c->frame_size;\r
591                 \r
592                 spl::shared_ptr<AVPacket> pkt(new AVPacket, [](AVPacket* p)\r
593                 {\r
594                         av_free_packet(p);\r
595                         delete p;\r
596                 });\r
597                 av_init_packet(pkt.get());\r
598 \r
599                 if(frame_size > 1)\r
600                 {                       \r
601                         auto input_audio_size = frame_size * av_get_bytes_per_sample(c->sample_fmt) * c->channels;\r
602                    \r
603                         if(audio_buf_.size() < input_audio_size)\r
604                                 return nullptr;\r
605                                         \r
606                         pkt->size = avcodec_encode_audio(c, audio_outbuf_.data(), static_cast<int>(audio_outbuf_.size()), reinterpret_cast<short*>(audio_buf_.data()));\r
607                         audio_buf_.erase(audio_buf_.begin(), audio_buf_.begin() + input_audio_size);\r
608                 }\r
609                 else\r
610                 {\r
611                         audio_outbuf_ = std::move(audio_buf_);          \r
612                         audio_buf_.clear();\r
613                         pkt->size = static_cast<int>(audio_outbuf_.size());\r
614                         pkt->data = audio_outbuf_.data();\r
615                 }\r
616                 \r
617                 if(pkt->size == 0)\r
618                         return nullptr;\r
619 \r
620                 if (c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE)\r
621                         pkt->pts = av_rescale_q(c->coded_frame->pts, c->time_base, audio_st_->time_base);\r
622 \r
623                 pkt->flags               |= AV_PKT_FLAG_KEY;\r
624                 pkt->stream_index = audio_st_->index;\r
625                 pkt->data                 = reinterpret_cast<uint8_t*>(audio_outbuf_.data());\r
626                 \r
627                 av_dup_packet(pkt.get());\r
628                 return pkt;\r
629         }\r
630                  \r
631         void send(core::const_frame& frame)\r
632         {\r
633                 encode_executor_.begin_invoke([=]\r
634                 {               \r
635                         boost::timer frame_timer;\r
636 \r
637                         auto video = encode_video_frame(frame);\r
638                         auto audio = encode_audio_frame(frame);\r
639 \r
640                         graph_->set_value("frame-time", frame_timer.elapsed()*format_desc_.fps*0.5);\r
641                         \r
642                         write_executor_.begin_invoke([=]\r
643                         {\r
644                                 if(video)\r
645                                         av_interleaved_write_frame(oc_.get(), video.get());\r
646                                 if(audio)\r
647                                         av_interleaved_write_frame(oc_.get(), audio.get());\r
648                         });\r
649                 });\r
650         }\r
651 };\r
652 \r
653 struct ffmpeg_consumer_proxy : public core::frame_consumer\r
654 {\r
655         const std::wstring                              filename_;\r
656         const std::vector<option>               options_;\r
657 \r
658         std::unique_ptr<ffmpeg_consumer> consumer_;\r
659 \r
660 public:\r
661 \r
662         ffmpeg_consumer_proxy(const std::wstring& filename, const std::vector<option>& options)\r
663                 : filename_(filename)\r
664                 , options_(options)\r
665         {\r
666         }\r
667         \r
668         virtual void initialize(const core::video_format_desc& format_desc, int)\r
669         {\r
670                 consumer_.reset();\r
671                 consumer_.reset(new ffmpeg_consumer(u8(filename_), format_desc, options_));\r
672         }\r
673         \r
674         virtual bool send(core::const_frame frame) override\r
675         {\r
676                 consumer_->send(frame);\r
677                 return true;\r
678         }\r
679         \r
680         virtual std::wstring print() const override\r
681         {\r
682                 return consumer_ ? consumer_->print() : L"[ffmpeg_consumer]";\r
683         }\r
684 \r
685         virtual std::wstring name() const override\r
686         {\r
687                 return L"file";\r
688         }\r
689 \r
690         virtual boost::property_tree::wptree info() const override\r
691         {\r
692                 boost::property_tree::wptree info;\r
693                 info.add(L"type", L"file");\r
694                 info.add(L"filename", filename_);\r
695                 return info;\r
696         }\r
697                 \r
698         virtual bool has_synchronization_clock() const override\r
699         {\r
700                 return false;\r
701         }\r
702 \r
703         virtual int buffer_depth() const override\r
704         {\r
705                 return 1;\r
706         }\r
707 \r
708         virtual int index() const override\r
709         {\r
710                 return 200;\r
711         }\r
712 };      \r
713 spl::shared_ptr<core::frame_consumer> create_consumer(const std::vector<std::wstring>& params)\r
714 {\r
715         if(params.size() < 1 || params[0] != L"FILE")\r
716                 return core::frame_consumer::empty();\r
717         \r
718         auto filename   = (params.size() > 1 ? params[1] : L"");\r
719                         \r
720         std::vector<option> options;\r
721         \r
722         if(params.size() >= 3)\r
723         {\r
724                 for(auto opt_it = params.begin()+2; opt_it != params.end();)\r
725                 {\r
726                         auto name  = u8(boost::trim_copy(boost::to_lower_copy(*opt_it++))).substr(1);\r
727                         auto value = u8(boost::trim_copy(boost::to_lower_copy(*opt_it++)));\r
728                                 \r
729                         if(value == "h264")\r
730                                 value = "libx264";\r
731                         else if(value == "dvcpro")\r
732                                 value = "dvvideo";\r
733 \r
734                         options.push_back(option(name, value));\r
735                 }\r
736         }\r
737                 \r
738         return spl::make_shared<ffmpeg_consumer_proxy>(env::media_folder() + filename, options);\r
739 }\r
740 \r
741 spl::shared_ptr<core::frame_consumer> create_consumer(const boost::property_tree::wptree& ptree)\r
742 {\r
743         auto filename   = ptree.get<std::wstring>(L"path");\r
744         auto codec              = ptree.get(L"vcodec", L"libx264");\r
745 \r
746         std::vector<option> options;\r
747         options.push_back(option("vcodec", u8(codec)));\r
748         \r
749         return spl::make_shared<ffmpeg_consumer_proxy>(env::media_folder() + filename, options);\r
750 }\r
751 \r
752 }}\r