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