/*\r
-* copyright (c) 2010 Sveriges Television AB <info@casparcg.com>\r
+* Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>\r
*\r
-* This ffmpeg is part of CasparCG.\r
+* This file is part of CasparCG (www.casparcg.com).\r
*\r
-* CasparCG is free software: you can redistribute it and/or modify\r
-* it under the terms of the GNU General Public License as published by\r
-* the Free Software Foundation, either version 3 of the License, or\r
-* (at your option) any later version.\r
+* CasparCG is free software: you can redistribute it and/or modify\r
+* it under the terms of the GNU General Public License as published by\r
+* the Free Software Foundation, either version 3 of the License, or\r
+* (at your option) any later version.\r
*\r
-* CasparCG is distributed in the hope that it will be useful,\r
-* but WITHOUT ANY WARRANTY; without even the implied warranty of\r
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
-* GNU General Public License for more details.\r
-\r
-* You should have received a copy of the GNU General Public License\r
-* along with CasparCG. If not, see <http://www.gnu.org/licenses/>.\r
+* CasparCG is distributed in the hope that it will be useful,\r
+* but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r
+* GNU General Public License for more details.\r
+*\r
+* You should have received a copy of the GNU General Public License\r
+* along with CasparCG. If not, see <http://www.gnu.org/licenses/>.\r
*\r
+* Author: Robert Nagy, ronag89@gmail.com\r
*/\r
\r
#include "../StdAfx.h"\r
\r
+#include "../ffmpeg_error.h"\r
+\r
#include "ffmpeg_consumer.h"\r
\r
-#include <core/consumer/frame/read_frame.h>\r
+#include <core/mixer/read_frame.h>\r
+#include <core/mixer/audio/audio_util.h>\r
+#include <core/consumer/frame_consumer.h>\r
+#include <core/video_format.h>\r
\r
#include <common/concurrency/executor.h>\r
-#include <common/utility/string.h>\r
+#include <common/diagnostics/graph.h>\r
#include <common/env.h>\r
+#include <common/utility/string.h>\r
+#include <common/utility/param.h>\r
\r
-#include <boost/thread/once.hpp>\r
+#include <boost/algorithm/string.hpp>\r
+#include <boost/timer.hpp>\r
+#include <boost/property_tree/ptree.hpp>\r
\r
#include <tbb/cache_aligned_allocator.h>\r
#include <tbb/parallel_invoke.h>\r
\r
-#include <cstdio>\r
-\r
#if defined(_MSC_VER)\r
#pragma warning (push)\r
#pragma warning (disable : 4244)\r
#define __STDC_LIMIT_MACROS\r
#include <libavformat/avformat.h>\r
#include <libswscale/swscale.h>\r
+ #include <libavutil/opt.h>\r
}\r
#if defined(_MSC_VER)\r
#pragma warning (pop)\r
#endif\r
\r
-namespace caspar { \r
+namespace caspar { namespace ffmpeg {\r
\r
-struct ffmpeg_consumer::implementation : boost::noncopyable\r
+struct ffmpeg_consumer : boost::noncopyable\r
{ \r
- printer parent_printer_;\r
- std::string filename_;\r
-\r
- // Audio\r
- AVStream* audio_st_;\r
- std::vector<unsigned char, tbb::cache_aligned_allocator<unsigned char>> audio_outbuf_;\r
+ const std::string filename_;\r
+ \r
+ const std::shared_ptr<AVFormatContext> oc_;\r
+ const core::video_format_desc format_desc_;\r
+ \r
+ const safe_ptr<diagnostics::graph> graph_;\r
+ boost::timer frame_timer_;\r
+ boost::timer write_timer_;\r
\r
- // Video\r
- AVStream* video_st_;\r
- std::vector<uint8_t, tbb::cache_aligned_allocator<unsigned char>> picture_buf_;\r
+ executor executor_;\r
+ executor file_write_executor_;\r
\r
- std::vector<unsigned char, tbb::cache_aligned_allocator<unsigned char>> video_outbuf_;\r
- SwsContext* img_convert_ctx_;\r
+ // Audio\r
+ std::shared_ptr<AVStream> audio_st_;\r
\r
- AVOutputFormat* fmt_;\r
- std::shared_ptr<AVFormatContext> oc_;\r
- core::video_format_desc format_desc_;\r
-\r
- std::vector<short, tbb::cache_aligned_allocator<short>> audio_input_buffer_;\r
+ // Video\r
+ std::shared_ptr<AVStream> video_st_;\r
\r
- boost::unique_future<void> active_;\r
+ std::vector<uint8_t> video_outbuf_;\r
+ std::vector<uint8_t> picture_buf_;\r
+ std::shared_ptr<SwsContext> sws_;\r
\r
- executor executor_;\r
+ int64_t frame_number_;\r
+ \r
public:\r
- implementation(const std::string& filename)\r
+ ffmpeg_consumer(const std::string& filename, const core::video_format_desc& format_desc, const std::string& codec, const std::string& options)\r
: filename_(filename)\r
- , audio_st_(nullptr)\r
- , video_st_(nullptr)\r
- , fmt_(nullptr)\r
- , img_convert_ctx_(nullptr)\r
- , video_outbuf_(1920*1080*4)\r
- , audio_outbuf_(48000)\r
- {}\r
-\r
- ~implementation()\r
- { \r
- executor_.invoke([]{});\r
- executor_.stop();\r
+ , video_outbuf_(1920*1080*8)\r
+ , oc_(avformat_alloc_context(), av_free)\r
+ , format_desc_(format_desc)\r
+ , executor_(print())\r
+ , file_write_executor_(print() + L"/output")\r
+ , frame_number_(0)\r
+ {\r
+ // TODO: Ask stakeholders about case where file already exists.\r
+ boost::filesystem2::remove(boost::filesystem2::wpath(env::media_folder() + widen(filename))); // Delete the file if it exists\r
+\r
+ graph_->add_guide("frame-time", 0.5);\r
+ graph_->set_color("frame-time", diagnostics::color(0.1f, 1.0f, 0.1f));\r
+ graph_->set_color("write-time", diagnostics::color(0.5f, 0.5f, 0.1f));\r
+ graph_->set_text(print());\r
+ diagnostics::register_graph(graph_);\r
\r
- av_write_trailer(oc_.get());\r
+ executor_.set_capacity(8);\r
+ file_write_executor_.set_capacity(8);\r
\r
- // Close each codec.\r
- if (video_st_) \r
- avcodec_close(video_st_->codec);\r
+ oc_->oformat = av_guess_format(nullptr, filename_.c_str(), nullptr);\r
+ if (!oc_->oformat)\r
+ BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not find suitable output format."));\r
\r
- if (audio_st_)\r
- avcodec_close(audio_st_->codec);\r
+ THROW_ON_ERROR2(av_set_parameters(oc_.get(), nullptr), "[ffmpeg_consumer]");\r
+\r
+ strcpy_s(oc_->filename, filename_.c_str());\r
+ \r
+ auto video_codec = avcodec_find_encoder_by_name(codec.c_str());\r
+ if(video_codec == nullptr)\r
+ BOOST_THROW_EXCEPTION(invalid_argument() << arg_name_info(codec));\r
+\r
+ // Add the audio and video streams using the default format codecs and initialize the codecs .\r
+ video_st_ = add_video_stream(video_codec->id, options);\r
+ audio_st_ = add_audio_stream();\r
\r
- // Free the streams.\r
- for(size_t i = 0; i < oc_->nb_streams; ++i) \r
- {\r
- av_freep(&oc_->streams[i]->codec);\r
- av_freep(&oc_->streams[i]);\r
- }\r
+ dump_format(oc_.get(), 0, filename_.c_str(), 1);\r
+ \r
+ // Open the output ffmpeg, if needed.\r
+ if (!(oc_->oformat->flags & AVFMT_NOFILE)) \r
+ THROW_ON_ERROR2(avio_open(&oc_->pb, filename_.c_str(), URL_WRONLY), "[ffmpeg_consumer]");\r
+ \r
+ THROW_ON_ERROR2(av_write_header(oc_.get()), "[ffmpeg_consumer]");\r
\r
- if (!(fmt_->flags & AVFMT_NOFILE)) \r
- url_fclose(oc_->pb); // Close the output ffmpeg.\r
+ CASPAR_LOG(info) << print() << L" Successfully Initialized."; \r
}\r
\r
- void initialize(const core::video_format_desc& format_desc, const printer& parent_printer)\r
- {\r
- format_desc_ = format_desc;\r
- parent_printer_ = parent_printer;\r
- executor_.start();\r
- active_ = executor_.begin_invoke([]{});\r
+ ~ffmpeg_consumer()\r
+ { \r
+ executor_.stop();\r
+ executor_.join();\r
\r
- fmt_ = av_guess_format(nullptr, filename_.c_str(), nullptr);\r
- if (!fmt_) \r
- {\r
- CASPAR_LOG(warning) << "Could not deduce output format from ffmpeg extension: using MPEG.";\r
- fmt_ = av_guess_format("mpeg", nullptr, nullptr);\r
- filename_ = filename_ + ".avi"; \r
- }\r
- if (!fmt_)\r
- BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not find suitable output format"));\r
+ file_write_executor_.stop();\r
+ file_write_executor_.join();\r
\r
- oc_.reset(avformat_alloc_context(), av_free);\r
- if (!oc_)\r
- BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Memory error"));\r
- std::copy_n(filename_.c_str(), filename_.size(), oc_->filename);\r
-\r
- oc_->oformat = fmt_;\r
- // To avoid mpeg buffer underflow (http://www.mail-archive.com/libav-user@mplayerhq.hu/msg00194.html)\r
- oc_->preload = static_cast<int>(0.5*AV_TIME_BASE);\r
- oc_->max_delay = static_cast<int>(0.7*AV_TIME_BASE);\r
- \r
- // Add the audio and video streams using the default format codecs and initialize the codecs .\r
- if (fmt_->video_codec != CODEC_ID_NONE) \r
- video_st_ = add_video_stream(fmt_->video_codec);\r
- \r
- if (fmt_->audio_codec != CODEC_ID_NONE) \r
- audio_st_ = add_audio_stream(fmt_->audio_codec); \r
-\r
- // Set the output parameters (must be done even if no parameters). \r
- int errn = 0;\r
- if ((errn = -av_set_parameters(oc_.get(), nullptr)) > 0)\r
- BOOST_THROW_EXCEPTION(\r
- file_read_error() << \r
- msg_info("Invalid output format parameters") <<\r
- boost::errinfo_api_function("avcodec_open") <<\r
- boost::errinfo_errno(errn) <<\r
- boost::errinfo_file_name(filename_));\r
+ LOG_ON_ERROR2(av_write_trailer(oc_.get()), "[ffmpeg_consumer]");\r
\r
- dump_format(oc_.get(), 0, filename_.c_str(), 1);\r
+ audio_st_.reset();\r
+ video_st_.reset();\r
+ \r
+ if (!(oc_->oformat->flags & AVFMT_NOFILE)) \r
+ LOG_ON_ERROR2(avio_close(oc_->pb), "[ffmpeg_consumer]"); // Close the output ffmpeg.\r
\r
- // Now that all the parameters are set, we can open the audio and\r
- // video codecs and allocate the necessary encode buffers.\r
- if (video_st_)\r
- open_video(video_st_);\r
- \r
- try\r
+ CASPAR_LOG(info) << print() << L" Successfully Uninitialized."; \r
+ }\r
+ \r
+ std::wstring print() const\r
+ {\r
+ return L"ffmpeg[" + widen(filename_) + L"]";\r
+ }\r
+\r
+ std::shared_ptr<AVStream> add_video_stream(enum CodecID codec_id, const std::string& options)\r
+ { \r
+ auto st = av_new_stream(oc_.get(), 0);\r
+ if (!st) \r
+ BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not allocate video-stream") << boost::errinfo_api_function("av_new_stream")); \r
+\r
+ auto encoder = avcodec_find_encoder(codec_id);\r
+ if (!encoder)\r
+ BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));\r
+\r
+ auto c = st->codec;\r
+\r
+ avcodec_get_context_defaults3(c, encoder);\r
+ \r
+ c->codec_id = codec_id;\r
+ c->codec_type = AVMEDIA_TYPE_VIDEO;\r
+ c->width = format_desc_.width;\r
+ c->height = format_desc_.height;\r
+ c->time_base.den = format_desc_.time_scale;\r
+ c->time_base.num = format_desc_.duration;\r
+ c->gop_size = 25;\r
+ c->flags |= format_desc_.field_mode == core::field_mode::progressive ? 0 : (CODEC_FLAG_INTERLACED_ME | CODEC_FLAG_INTERLACED_DCT);\r
+\r
+ if(c->codec_id == CODEC_ID_PRORES)\r
+ { \r
+ c->bit_rate = format_desc_.width < 1280 ? 63*1000000 : 220*1000000;\r
+ c->pix_fmt = PIX_FMT_YUV422P10;\r
+ THROW_ON_ERROR2(av_set_options_string(c->priv_data, options.c_str(), "=", ":"), "[ffmpeg_consumer]");\r
+ }\r
+ else if(c->codec_id == CODEC_ID_DNXHD)\r
{\r
- if (audio_st_)\r
- open_audio(audio_st_);\r
+ if(format_desc_.width < 1280 || format_desc_.height < 720)\r
+ BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("unsupported dimension"));\r
+\r
+ c->bit_rate = 220*1000000;\r
+ c->pix_fmt = PIX_FMT_YUV422P;\r
+ \r
+ THROW_ON_ERROR2(av_set_options_string(c->priv_data, options.c_str(), "=", ":"), "[ffmpeg_consumer]");\r
}\r
- catch(...)\r
+ else if(c->codec_id == CODEC_ID_DVVIDEO)\r
{\r
- CASPAR_LOG_CURRENT_EXCEPTION();\r
- audio_st_ = nullptr;\r
+ c->bit_rate = format_desc_.width < 1280 ? 50*1000000 : 100*1000000;\r
+ c->pix_fmt = PIX_FMT_YUV422P;\r
+ \r
+ c->width = format_desc_.height == 1280 ? 960 : c->width;\r
+\r
+ if(format_desc_.duration == 1001) \r
+ c->width = format_desc_.height == 1080 ? 1280 : c->width; \r
+ else\r
+ c->width = format_desc_.height == 1080 ? 1440 : c->width;\r
+ \r
+ THROW_ON_ERROR2(av_set_options_string(c->priv_data, options.c_str(), "=", ":"), "[ffmpeg_consumer]");\r
}\r
- \r
- // Open the output ffmpeg, if needed.\r
- if (!(fmt_->flags & AVFMT_NOFILE)) \r
+ else if(c->codec_id == CODEC_ID_H264)\r
+ { \r
+ c->pix_fmt = PIX_FMT_YUV420P; \r
+ av_opt_set(c->priv_data, "preset", "ultrafast", 0);\r
+ av_opt_set(c->priv_data, "tune", "film", 0);\r
+ av_opt_set(c->priv_data, "crf", "5", 0);\r
+ \r
+ THROW_ON_ERROR2(av_set_options_string(c->priv_data, options.c_str(), "=", ":"), "[ffmpeg_consumer]");\r
+ }\r
+ else\r
{\r
- int errn = 0;\r
- if ((errn = -url_fopen(&oc_->pb, filename_.c_str(), URL_WRONLY)) > 0) \r
- BOOST_THROW_EXCEPTION(\r
- file_not_found() << \r
- msg_info("Could not open file") <<\r
- boost::errinfo_api_function("url_fopen") <<\r
- boost::errinfo_errno(errn) <<\r
- boost::errinfo_file_name(filename_));\r
+ THROW_ON_ERROR2(av_set_options_string(c->priv_data, options.c_str(), "=", ":"), "[ffmpeg_consumer]");\r
+ CASPAR_LOG(warning) << " Potentially unsupported output parameters.";\r
}\r
\r
- av_write_header(oc_.get()); // write the stream header, if any \r
+ c->max_b_frames = 0; // b-franes not supported.\r
+\r
+ if(oc_->oformat->flags & AVFMT_GLOBALHEADER)\r
+ c->flags |= CODEC_FLAG_GLOBAL_HEADER;\r
+ \r
+ c->thread_count = boost::thread::hardware_concurrency();\r
+ THROW_ON_ERROR2(avcodec_open(c, encoder), "[ffmpeg_consumer]");\r
\r
- CASPAR_LOG(info) << print() << L" Successfully initialized.";\r
+ return std::shared_ptr<AVStream>(st, [](AVStream* st)\r
+ {\r
+ LOG_ON_ERROR2(avcodec_close(st->codec), "[ffmpeg_consumer]");\r
+ av_freep(&st->codec);\r
+ av_freep(&st);\r
+ });\r
}\r
\r
- std::wstring print() const\r
+ std::shared_ptr<AVStream> add_audio_stream()\r
{\r
- return (parent_printer_ ? parent_printer_() + L"/" : L"") + L"ffmpeg[" + widen(filename_) + L"]";\r
- }\r
-\r
- AVStream* add_video_stream(enum CodecID codec_id)\r
- { \r
- auto st = av_new_stream(oc_.get(), 0);\r
- if (!st) \r
- BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not alloc stream"));\r
- \r
- auto c = st->codec;\r
- c->codec_id = codec_id;\r
- c->codec_type = AVMEDIA_TYPE_VIDEO;\r
- \r
- // Put sample parameters.\r
- c->bit_rate = static_cast<int>(static_cast<double>(format_desc_.size)*format_desc_.fps*0.1326);\r
- c->width = format_desc_.width;\r
- c->height = format_desc_.height;\r
- c->time_base.den = static_cast<int>(format_desc_.fps);\r
- c->time_base.num = 1;\r
- c->pix_fmt = c->pix_fmt == -1 ? PIX_FMT_YUV420P : c->pix_fmt;\r
-\r
- // Some formats want stream headers to be separate.\r
+ auto st = av_new_stream(oc_.get(), 1);\r
+ if(!st)\r
+ BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not allocate audio-stream") << boost::errinfo_api_function("av_new_stream")); \r
+\r
+ st->codec->codec_id = CODEC_ID_PCM_S16LE;\r
+ st->codec->codec_type = AVMEDIA_TYPE_AUDIO;\r
+ st->codec->sample_rate = 48000;\r
+ st->codec->channels = 2;\r
+ st->codec->sample_fmt = SAMPLE_FMT_S16;\r
+ \r
if(oc_->oformat->flags & AVFMT_GLOBALHEADER)\r
- c->flags |= CODEC_FLAG_GLOBAL_HEADER;\r
- \r
- return st;\r
- }\r
- \r
- void open_video(AVStream* st)\r
- { \r
- auto c = st->codec;\r
- \r
- auto codec = avcodec_find_encoder(c->codec_id);\r
+ st->codec->flags |= CODEC_FLAG_GLOBAL_HEADER;\r
+ \r
+ auto codec = avcodec_find_encoder(st->codec->codec_id);\r
if (!codec)\r
BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));\r
- \r
- int errn = 0;\r
- if ((errn = -avcodec_open(c, codec)) > 0)\r
- BOOST_THROW_EXCEPTION(\r
- file_read_error() << \r
- msg_info("Could not open video codec.") <<\r
- boost::errinfo_api_function("avcodec_open") <<\r
- boost::errinfo_errno(errn) <<\r
- boost::errinfo_file_name(filename_)); \r
+\r
+ THROW_ON_ERROR2(avcodec_open(st->codec, codec), "[ffmpeg_consumer]");\r
+\r
+ return std::shared_ptr<AVStream>(st, [](AVStream* st)\r
+ {\r
+ LOG_ON_ERROR2(avcodec_close(st->codec), "[ffmpeg_consumer]");;\r
+ av_freep(&st->codec);\r
+ av_freep(&st);\r
+ });\r
}\r
- \r
- void encode_video_frame(const safe_ptr<const core::read_frame>& frame)\r
- { \r
- AVCodecContext* c = video_st_->codec;\r
- \r
- if (img_convert_ctx_ == nullptr) \r
+\r
+ std::shared_ptr<AVFrame> convert_video_frame(const safe_ptr<core::read_frame>& frame, AVCodecContext* c)\r
+ {\r
+ if(!sws_) \r
{\r
- img_convert_ctx_ = sws_getContext(format_desc_.width, format_desc_.height, PIX_FMT_BGRA, c->width, c->height, c->pix_fmt, SWS_BICUBIC, nullptr, nullptr, nullptr);\r
- if (img_convert_ctx_ == nullptr) \r
+ sws_.reset(sws_getContext(format_desc_.width, format_desc_.height, PIX_FMT_BGRA, c->width, c->height, c->pix_fmt, SWS_BICUBIC, nullptr, nullptr, nullptr), sws_freeContext);\r
+ if (sws_ == nullptr) \r
BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Cannot initialize the conversion context"));\r
}\r
\r
picture_buf_.resize(avpicture_get_size(c->pix_fmt, format_desc_.width, format_desc_.height));\r
avpicture_fill(reinterpret_cast<AVPicture*>(local_av_frame.get()), picture_buf_.data(), c->pix_fmt, format_desc_.width, format_desc_.height);\r
\r
- sws_scale(img_convert_ctx_, av_frame->data, av_frame->linesize, 0, c->height, local_av_frame->data, local_av_frame->linesize);\r
- \r
- int ret = avcodec_encode_video(c, video_outbuf_.data(), video_outbuf_.size(), local_av_frame.get());\r
- \r
- int errn = -ret;\r
- if (errn > 0) \r
- BOOST_THROW_EXCEPTION(\r
- invalid_operation() << \r
- msg_info("Could not encode video frame.") <<\r
- boost::errinfo_api_function("avcodec_encode_video") <<\r
- boost::errinfo_errno(errn) <<\r
- boost::errinfo_file_name(filename_));\r
-\r
- auto out_size = ret;\r
- AVPacket pkt;\r
- av_init_packet(&pkt);\r
- pkt.size = out_size;\r
-\r
- // If zero size, it means the image was buffered.\r
- if (out_size > 0) \r
- { \r
- if (c->coded_frame->pts != AV_NOPTS_VALUE)\r
- pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_st_->time_base);\r
- if(c->coded_frame->key_frame)\r
- pkt.flags |= AV_PKT_FLAG_KEY;\r
+ sws_scale(sws_.get(), av_frame->data, av_frame->linesize, 0, c->height, local_av_frame->data, local_av_frame->linesize);\r
\r
- pkt.stream_index = video_st_->index;\r
- pkt.data = video_outbuf_.data();\r
-\r
- if (av_interleaved_write_frame(oc_.get(), &pkt) != 0)\r
- BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Error while writing video frame"));\r
- } \r
+ return local_av_frame;\r
}\r
+ \r
+ std::shared_ptr<AVPacket> encode_video_frame(const safe_ptr<core::read_frame>& frame)\r
+ { \r
+ auto c = video_st_->codec;\r
+ \r
+ auto av_frame = convert_video_frame(frame, c);\r
+ av_frame->interlaced_frame = format_desc_.field_mode != core::field_mode::progressive;\r
+ av_frame->top_field_first = format_desc_.field_mode == core::field_mode::upper;\r
+ av_frame->pts = frame_number_++;\r
\r
- AVStream* add_audio_stream(enum CodecID codec_id)\r
- {\r
- audio_st_ = av_new_stream(oc_.get(), 1);\r
- if (!audio_st_)\r
- BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Could not alloc stream"));\r
-\r
- auto c = audio_st_->codec;\r
- c->codec_id = codec_id;\r
- c->codec_type = AVMEDIA_TYPE_AUDIO;\r
-\r
- // Put sample parameters.\r
- c->bit_rate = 192000;\r
- c->sample_rate = 48000;\r
- c->channels = 2;\r
+ int out_size = THROW_ON_ERROR2(avcodec_encode_video(c, video_outbuf_.data(), video_outbuf_.size(), av_frame.get()), "[ffmpeg_consumer]");\r
+ if(out_size > 0)\r
+ {\r
+ safe_ptr<AVPacket> pkt(new AVPacket, [](AVPacket* p)\r
+ {\r
+ av_free_packet(p);\r
+ delete p;\r
+ });\r
+ av_init_packet(pkt.get());\r
+ \r
+ if (c->coded_frame->pts != AV_NOPTS_VALUE)\r
+ pkt->pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_st_->time_base);\r
\r
- // Some formats want stream headers to be separate.\r
- if(oc_->oformat->flags & AVFMT_GLOBALHEADER)\r
- c->flags |= CODEC_FLAG_GLOBAL_HEADER;\r
+ if(c->coded_frame->key_frame)\r
+ pkt->flags |= AV_PKT_FLAG_KEY;\r
\r
- return audio_st_;\r
+ pkt->stream_index = video_st_->index;\r
+ pkt->data = video_outbuf_.data();\r
+ pkt->size = out_size;\r
+ \r
+ av_dup_packet(pkt.get());\r
+ return pkt;\r
+ } \r
+ return nullptr;\r
}\r
+ \r
+ std::shared_ptr<AVPacket> encode_audio_frame(const safe_ptr<core::read_frame>& frame)\r
+ { \r
+ auto c = audio_st_->codec;\r
\r
- void open_audio(AVStream* st)\r
- {\r
- auto c = st->codec;\r
+ auto audio_data = core::audio_32_to_16(frame->audio_data());\r
+ \r
+ safe_ptr<AVPacket> pkt(new AVPacket, [](AVPacket* p)\r
+ {\r
+ av_free_packet(p);\r
+ delete p;\r
+ });\r
+ av_init_packet(pkt.get());\r
+ \r
+ if (c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE)\r
+ pkt->pts = av_rescale_q(c->coded_frame->pts, c->time_base, audio_st_->time_base);\r
\r
- // Find the audio encoder.\r
- auto codec = avcodec_find_encoder(c->codec_id);\r
- if (!codec) \r
- BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("codec not found"));\r
+ pkt->flags |= AV_PKT_FLAG_KEY;\r
+ pkt->stream_index = audio_st_->index;\r
+ pkt->size = audio_data.size()*2;\r
+ pkt->data = reinterpret_cast<uint8_t*>(audio_data.data());\r
\r
- // Open it.\r
- int errn = 0;\r
- if ((errn = -avcodec_open(c, codec)) > 0)\r
- BOOST_THROW_EXCEPTION(\r
- file_read_error() << \r
- msg_info("Could not open audio codec") <<\r
- boost::errinfo_api_function("avcodec_open") <<\r
- boost::errinfo_errno(errn) <<\r
- boost::errinfo_file_name(filename_));\r
+ av_dup_packet(pkt.get());\r
+ return pkt;\r
}\r
- \r
- void encode_audio_frame(const safe_ptr<const core::read_frame>& frame)\r
- { \r
- if(!frame->audio_data().empty())\r
- audio_input_buffer_.insert(audio_input_buffer_.end(), frame->audio_data().begin(), frame->audio_data().end());\r
- else\r
- audio_input_buffer_.insert(audio_input_buffer_.end(), 3840, 0);\r
+ \r
+ void send(const safe_ptr<core::read_frame>& frame)\r
+ {\r
+ executor_.begin_invoke([=]\r
+ { \r
+ frame_timer_.restart();\r
\r
- while(encode_audio_packet()){}\r
- }\r
+ auto video = encode_video_frame(frame);\r
+ auto audio = encode_audio_frame(frame);\r
\r
- bool encode_audio_packet()\r
- { \r
- auto c = audio_st_->codec;\r
+ graph_->update_value("frame-time", frame_timer_.elapsed()*format_desc_.fps*0.5);\r
+ \r
+ file_write_executor_.begin_invoke([=]\r
+ {\r
+ write_timer_.restart();\r
\r
- auto frame_bytes = c->frame_size * 2 * 2; // samples per frame * 2 channels * 2 bytes per sample\r
- if(static_cast<int>(audio_input_buffer_.size()) < frame_bytes/2)\r
- return false;\r
+ if(video)\r
+ av_write_frame(oc_.get(), video.get());\r
+ if(audio)\r
+ av_write_frame(oc_.get(), audio.get());\r
\r
- AVPacket pkt;\r
- av_init_packet(&pkt);\r
- \r
- int ret = avcodec_encode_audio(c, audio_outbuf_.data(), audio_outbuf_.size(), audio_input_buffer_.data());\r
- \r
- int errn = -ret;\r
- if (errn > 0) \r
- BOOST_THROW_EXCEPTION(\r
- invalid_operation() << \r
- msg_info("Could not encode audio samples.") <<\r
- boost::errinfo_api_function("avcodec_encode_audio") <<\r
- boost::errinfo_errno(errn) <<\r
- boost::errinfo_file_name(filename_));\r
-\r
- pkt.size = ret;\r
- audio_input_buffer_ = std::vector<short, tbb::cache_aligned_allocator<short>>(audio_input_buffer_.begin() + frame_bytes/2, audio_input_buffer_.end());\r
+ graph_->update_value("write-time", write_timer_.elapsed()*format_desc_.fps*0.5);\r
+ });\r
+ });\r
+ }\r
+};\r
\r
- if (c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE)\r
- pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, audio_st_->time_base);\r
- pkt.flags |= AV_PKT_FLAG_KEY;\r
- pkt.stream_index = audio_st_->index;\r
- pkt.data = audio_outbuf_.data();\r
- \r
- if (av_interleaved_write_frame(oc_.get(), &pkt) != 0)\r
- BOOST_THROW_EXCEPTION(caspar_exception() << msg_info("Error while writing audio frame"));\r
+struct ffmpeg_consumer_proxy : public core::frame_consumer\r
+{\r
+ const std::wstring filename_;\r
+ const bool key_only_;\r
+ const std::wstring codec_;\r
+ const std::wstring options_;\r
\r
+ std::unique_ptr<ffmpeg_consumer> consumer_;\r
+\r
+public:\r
+\r
+ ffmpeg_consumer_proxy(const std::wstring& filename, bool key_only, const std::wstring codec, const std::wstring& options)\r
+ : filename_(filename)\r
+ , key_only_(key_only)\r
+ , codec_(boost::to_lower_copy(codec))\r
+ , options_(options)\r
+ {\r
+ }\r
+ \r
+ virtual void initialize(const core::video_format_desc& format_desc, int)\r
+ {\r
+ consumer_.reset();\r
+ consumer_.reset(new ffmpeg_consumer(narrow(filename_), format_desc, narrow(codec_), narrow(options_)));\r
+ }\r
+ \r
+ virtual bool send(const safe_ptr<core::read_frame>& frame) override\r
+ {\r
+ consumer_->send(frame);\r
return true;\r
}\r
- \r
- void send(const safe_ptr<const core::read_frame>& frame)\r
+ \r
+ virtual std::wstring print() const override\r
{\r
- active_.get();\r
- active_ = executor_.begin_invoke([=]\r
- { \r
- auto my_frame = frame;\r
- encode_video_frame(my_frame);\r
- encode_audio_frame(my_frame);\r
- });\r
+ return consumer_ ? consumer_->print() : L"[ffmpeg_consumer]";\r
}\r
\r
- size_t buffer_depth() const { return 1; }\r
-};\r
+ virtual boost::property_tree::wptree info() const override\r
+ {\r
+ boost::property_tree::wptree info;\r
+ info.add(L"type", L"ffmpeg-consumer");\r
+ info.add(L"key-only", key_only_);\r
+ info.add(L"filename", filename_);\r
+ info.add(L"codec", codec_);\r
+ info.add(L"options", options_);\r
+ return info;\r
+ }\r
+ \r
+ virtual bool has_synchronization_clock() const override\r
+ {\r
+ return false;\r
+ }\r
\r
-ffmpeg_consumer::ffmpeg_consumer(const std::wstring& filename) : impl_(new implementation(narrow(filename))){}\r
-ffmpeg_consumer::ffmpeg_consumer(ffmpeg_consumer&& other) : impl_(std::move(other.impl_)){}\r
-void ffmpeg_consumer::send(const safe_ptr<const core::read_frame>& frame){impl_->send(frame);}\r
-size_t ffmpeg_consumer::buffer_depth() const{return impl_->buffer_depth();}\r
-void ffmpeg_consumer::initialize(const core::video_format_desc& format_desc, const printer& parent_printer) {impl_->initialize(format_desc, parent_printer);}\r
-std::wstring ffmpeg_consumer::print() const {return impl_->print();}\r
+ virtual size_t buffer_depth() const override\r
+ {\r
+ return 1;\r
+ }\r
\r
-safe_ptr<core::frame_consumer> create_ffmpeg_consumer(const std::vector<std::wstring>& params)\r
+ virtual int index() const override\r
+ {\r
+ return 200;\r
+ }\r
+}; \r
+\r
+safe_ptr<core::frame_consumer> create_consumer(const std::vector<std::wstring>& params)\r
{\r
- if(params.size() < 2 || params[0] != L"FILE")\r
+ if(params.size() < 1 || params[0] != L"FILE")\r
return core::frame_consumer::empty();\r
\r
- // TODO: Ask stakeholders about case where file already exists.\r
- boost::filesystem::remove(boost::filesystem::wpath(env::media_folder() + params[1])); // Delete the file if it exists\r
- return make_safe<ffmpeg_consumer>(env::media_folder() + params[1]);\r
+ auto filename = (params.size() > 1 ? params[1] : L"");\r
+ bool key_only = get_param(L"KEY_ONLY", params, false);\r
+ auto codec = get_param(L"CODEC", params, L"libx264");\r
+ auto options = get_param(L"OPTIONS", params);\r
+ \r
+ if(codec == L"H264")\r
+ codec = L"libx264";\r
+\r
+ if(codec == L"DVCPRO")\r
+ codec = L"dvvideo";\r
+\r
+ boost::to_lower(options);\r
+\r
+ return make_safe<ffmpeg_consumer_proxy>(env::media_folder() + filename, key_only, codec, options);\r
}\r
\r
+safe_ptr<core::frame_consumer> create_consumer(const boost::property_tree::ptree& ptree)\r
+{\r
+ std::string filename = ptree.get<std::string>("path");\r
+ auto key_only = ptree.get("key-only", false);\r
+ auto codec = ptree.get("codec", "libx264");\r
+ auto options = ptree.get("options", "");\r
+ \r
+ return make_safe<ffmpeg_consumer_proxy>(env::media_folder() + widen(filename), key_only, widen(codec), widen(options));\r
}\r
+\r
+}}\r