]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/producer/audio/audio_decoder.cpp
2.0. Refactoring
[casparcg] / modules / ffmpeg / producer / audio / audio_decoder.cpp
1 /*\r
2 * copyright (c) 2010 Sveriges Television AB <info@casparcg.com>\r
3 *\r
4 *  This file is part of CasparCG.\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 */\r
20 #include "../../stdafx.h"\r
21 \r
22 #include "audio_decoder.h"\r
23 \r
24 #include "../../ffmpeg_error.h"\r
25 \r
26 #include <tbb/task_group.h>\r
27 \r
28 #if defined(_MSC_VER)\r
29 #pragma warning (push)\r
30 #pragma warning (disable : 4244)\r
31 #endif\r
32 extern "C" \r
33 {\r
34         #define __STDC_CONSTANT_MACROS\r
35         #define __STDC_LIMIT_MACROS\r
36         #include <libavformat/avformat.h>\r
37         #include <libavcodec/avcodec.h>\r
38 }\r
39 #if defined(_MSC_VER)\r
40 #pragma warning (pop)\r
41 #endif\r
42 \r
43 namespace caspar {\r
44         \r
45 struct audio_decoder::implementation : boost::noncopyable\r
46 {       \r
47         std::shared_ptr<AVCodecContext>                                                         codec_context_;         \r
48         const core::video_format_desc                                                           format_desc_;\r
49         int                                                                                                                     index_;\r
50         std::shared_ptr<ReSampleContext>                                                        resampler_;\r
51 \r
52         std::vector<int8_t,  tbb::cache_aligned_allocator<int8_t>>      buffer1_;\r
53         std::vector<int8_t,  tbb::cache_aligned_allocator<int8_t>>      buffer2_;\r
54         std::vector<int16_t, tbb::cache_aligned_allocator<int16_t>>     audio_samples_; \r
55         std::queue<std::shared_ptr<AVPacket>>                                           packets_;\r
56 \r
57         int64_t                                                                                                         nb_frames_;\r
58 public:\r
59         explicit implementation(const std::shared_ptr<AVFormatContext>& context, const core::video_format_desc& format_desc) \r
60                 : format_desc_(format_desc)     \r
61                 , nb_frames_(0)\r
62         {                                       \r
63                 try\r
64                 {\r
65                         AVCodec* dec;\r
66                         index_ = av_find_best_stream(context.get(), AVMEDIA_TYPE_AUDIO, -1, -1, &dec, 0);\r
67 \r
68                         if(index_ < 0)\r
69                         {\r
70                                 BOOST_THROW_EXCEPTION(\r
71                                         file_read_error() <<\r
72                                         msg_info(av_error_str(index_)) <<\r
73                                         boost::errinfo_api_function("av_find_best_stream") <<\r
74                                         boost::errinfo_errno(AVUNERROR(index_)));\r
75                         }\r
76 \r
77                         const int ret = avcodec_open(context->streams[index_]->codec, dec);\r
78                         if(ret < 0)\r
79                         {                               \r
80                                 BOOST_THROW_EXCEPTION(\r
81                                         file_read_error() <<\r
82                                         msg_info(av_error_str(ret)) <<\r
83                                         boost::errinfo_api_function("avcodec_open") <<\r
84                                         boost::errinfo_errno(AVUNERROR(ret)));\r
85                         }\r
86                 }\r
87                 catch(...)\r
88                 {\r
89                         CASPAR_LOG_CURRENT_EXCEPTION();\r
90                         CASPAR_LOG(warning) << "[audio_decoder] Failed to open audio. Running without audio.";\r
91                         return;\r
92                 }\r
93 \r
94                 codec_context_.reset(context->streams[index_]->codec, avcodec_close);\r
95 \r
96                 //nb_frames_ = context->streams[index_]->nb_frames;\r
97                 //if(nb_frames_ == 0)\r
98                 //      nb_frames_ = context->streams[index_]->duration * context->streams[index_]->time_base.den;\r
99 \r
100                 if(codec_context_ &&\r
101                    (codec_context_->sample_rate != static_cast<int>(format_desc_.audio_sample_rate) || \r
102                     codec_context_->channels    != static_cast<int>(format_desc_.audio_channels)) ||\r
103                         codec_context_->sample_fmt      != AV_SAMPLE_FMT_S16)\r
104                 {       \r
105                         auto resampler = av_audio_resample_init(format_desc_.audio_channels,    codec_context_->channels,\r
106                                                                                                         format_desc_.audio_sample_rate, codec_context_->sample_rate,\r
107                                                                                                         AV_SAMPLE_FMT_S16,                              codec_context_->sample_fmt,\r
108                                                                                                         16, 10, 0, 0.8);\r
109 \r
110                         CASPAR_LOG(warning) << L" Invalid audio format. Resampling.";\r
111 \r
112                         if(resampler)\r
113                                 resampler_.reset(resampler, audio_resample_close);\r
114                         else\r
115                                 codec_context_ = nullptr;\r
116                 }               \r
117         }\r
118 \r
119         void push(const std::shared_ptr<AVPacket>& packet)\r
120         {                       \r
121                 if(!codec_context_)\r
122                         return;\r
123 \r
124                 if(packet && packet->stream_index != index_)\r
125                         return;\r
126 \r
127                 packets_.push(packet);\r
128         }       \r
129         \r
130         std::vector<std::shared_ptr<std::vector<int16_t>>> poll()\r
131         {\r
132                 std::vector<std::shared_ptr<std::vector<int16_t>>> result;\r
133 \r
134                 if(!codec_context_)\r
135                         result.push_back(std::make_shared<std::vector<int16_t>>(format_desc_.audio_samples_per_frame, 0));\r
136                 else if(!packets_.empty())\r
137                 {               \r
138                         auto packet = packets_.front();\r
139 \r
140                         if(packet)              \r
141                         {\r
142                                 result.push_back(decode(*packet));\r
143                                 if(packet->size == 0)                                   \r
144                                         packets_.pop();\r
145                         }\r
146                         else                    \r
147                         {       \r
148                                 avcodec_flush_buffers(codec_context_.get());\r
149                                 result.push_back(nullptr);\r
150                                 packets_.pop();\r
151                         }\r
152                 }\r
153 \r
154                 return result;\r
155         }\r
156 \r
157         std::shared_ptr<std::vector<int16_t>> decode(AVPacket& pkt)\r
158         {               \r
159                 buffer1_.resize(AVCODEC_MAX_AUDIO_FRAME_SIZE*2, 0);\r
160                 int written_bytes = buffer1_.size() - FF_INPUT_BUFFER_PADDING_SIZE;\r
161 \r
162                 const int ret = avcodec_decode_audio3(codec_context_.get(), reinterpret_cast<int16_t*>(buffer1_.data()), &written_bytes, &pkt);\r
163                 if(ret < 0)\r
164                 {       \r
165                         BOOST_THROW_EXCEPTION(\r
166                                 invalid_operation() <<\r
167                                 msg_info(av_error_str(ret)) <<\r
168                                 boost::errinfo_api_function("avcodec_decode_audio2") <<\r
169                                 boost::errinfo_errno(AVUNERROR(ret)));\r
170                 }\r
171 \r
172                 // There might be several frames in one packet.\r
173                 pkt.size -= ret;\r
174                 pkt.data += ret;\r
175                         \r
176                 buffer1_.resize(written_bytes);\r
177 \r
178                 if(resampler_)\r
179                 {\r
180                         buffer2_.resize(AVCODEC_MAX_AUDIO_FRAME_SIZE*2, 0);\r
181                         auto ret = audio_resample(resampler_.get(),\r
182                                                                                 reinterpret_cast<short*>(buffer2_.data()), \r
183                                                                                 reinterpret_cast<short*>(buffer1_.data()), \r
184                                                                                 buffer1_.size() / (av_get_bytes_per_sample(codec_context_->sample_fmt) * codec_context_->channels)); \r
185                         buffer2_.resize(ret * av_get_bytes_per_sample(AV_SAMPLE_FMT_S16) * format_desc_.audio_channels);\r
186                         std::swap(buffer1_, buffer2_);\r
187                 }\r
188 \r
189                 const auto n_samples = buffer1_.size() / av_get_bytes_per_sample(AV_SAMPLE_FMT_S16);\r
190                 const auto samples = reinterpret_cast<int16_t*>(buffer1_.data());\r
191 \r
192                 return std::make_shared<std::vector<int16_t>>(samples, samples + n_samples);\r
193         }\r
194 \r
195         bool ready() const\r
196         {\r
197                 return !codec_context_ || !packets_.empty();\r
198         }\r
199 };\r
200 \r
201 audio_decoder::audio_decoder(const std::shared_ptr<AVFormatContext>& context, const core::video_format_desc& format_desc) : impl_(new implementation(context, format_desc)){}\r
202 void audio_decoder::push(const std::shared_ptr<AVPacket>& packet){impl_->push(packet);}\r
203 bool audio_decoder::ready() const{return impl_->ready();}\r
204 std::vector<std::shared_ptr<std::vector<int16_t>>> audio_decoder::poll(){return impl_->poll();}\r
205 int64_t audio_decoder::nb_frames() const{return impl_->nb_frames_;}\r
206 }