]> git.sesse.net Git - casparcg/blob - modules/ffmpeg/producer/audio/audio_decoder.cpp
2.0.0.2: Simplified audio-chunk handling.
[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 <tbb/task_group.h>\r
25 \r
26 #if defined(_MSC_VER)\r
27 #pragma warning (push)\r
28 #pragma warning (disable : 4244)\r
29 #endif\r
30 extern "C" \r
31 {\r
32         #define __STDC_CONSTANT_MACROS\r
33         #define __STDC_LIMIT_MACROS\r
34         #include <libavformat/avformat.h>\r
35         #include <libavcodec/avcodec.h>\r
36 }\r
37 #if defined(_MSC_VER)\r
38 #pragma warning (pop)\r
39 #endif\r
40 \r
41 namespace caspar {\r
42         \r
43 struct audio_decoder::implementation : boost::noncopyable\r
44 {       \r
45         std::shared_ptr<AVCodecContext>                                                         codec_context_;         \r
46         const core::video_format_desc                                                           format_desc_;\r
47         int                                                                                                                     index_;\r
48         std::shared_ptr<ReSampleContext>                                                        resampler_;\r
49 \r
50         std::vector<int8_t,  tbb::cache_aligned_allocator<int8_t>>      buffer1_;\r
51         std::vector<int8_t,  tbb::cache_aligned_allocator<int8_t>>      buffer2_;\r
52         std::queue<std::shared_ptr<AVPacket>>                                           packets_;\r
53         size_t                                                                                                          sample_count_;\r
54 public:\r
55         explicit implementation(const std::shared_ptr<AVFormatContext>& context, const core::video_format_desc& format_desc) \r
56                 : format_desc_(format_desc)     \r
57                 , sample_count_(0)\r
58         {                          \r
59                 AVCodec* dec;\r
60                 index_ = av_find_best_stream(context.get(), AVMEDIA_TYPE_AUDIO, -1, -1, &dec, 0);\r
61 \r
62                 int errn = avcodec_open(context->streams[index_]->codec, dec);\r
63                 if(errn < 0)\r
64                         return;\r
65                                 \r
66                 codec_context_.reset(context->streams[index_]->codec, avcodec_close);\r
67 \r
68                 if(codec_context_ &&\r
69                    (codec_context_->sample_rate != static_cast<int>(format_desc_.audio_sample_rate) || \r
70                     codec_context_->channels    != static_cast<int>(format_desc_.audio_channels)) ||\r
71                         codec_context_->sample_fmt      != AV_SAMPLE_FMT_S16)\r
72                 {       \r
73                         auto resampler = av_audio_resample_init(format_desc_.audio_channels,    codec_context_->channels,\r
74                                                                                                         format_desc_.audio_sample_rate, codec_context_->sample_rate,\r
75                                                                                                         AV_SAMPLE_FMT_S16,                              codec_context_->sample_fmt,\r
76                                                                                                         16, 10, 0, 0.8);\r
77 \r
78                         CASPAR_LOG(warning) << L" Invalid audio format.";\r
79 \r
80                         if(resampler)\r
81                                 resampler_.reset(resampler, audio_resample_close);\r
82                         else\r
83                                 codec_context_ = nullptr;\r
84                 }               \r
85         }\r
86 \r
87         void push(const std::shared_ptr<AVPacket>& packet)\r
88         {                       \r
89                 if(!codec_context_)\r
90                         return;\r
91 \r
92                 if(packet && packet->stream_index != index_)\r
93                         return;\r
94 \r
95                 packets_.push(packet);\r
96         }       \r
97         \r
98         std::vector<std::vector<int16_t>> poll()\r
99         {\r
100                 std::vector<std::vector<int16_t>> result;\r
101 \r
102                 if(!codec_context_)\r
103                         result.push_back(std::vector<int16_t>(format_desc_.audio_samples_per_frame, 0));\r
104                 else if(!packets_.empty())\r
105                 {                       \r
106                         if(packets_.front())            \r
107                         {\r
108                                 AVPacket pkt;\r
109                                 av_init_packet(&pkt);\r
110                                 pkt.data = packets_.front()->data;\r
111                                 pkt.size = packets_.front()->size;\r
112 \r
113                                 for(int n = 0; n < 64 && pkt.size > 0; ++n)\r
114                                         decode(pkt, result);\r
115                         }\r
116                         else\r
117                                 avcodec_flush_buffers(codec_context_.get());\r
118 \r
119                         packets_.pop();\r
120                 }\r
121 \r
122                 return result;\r
123         }\r
124 \r
125         void decode(AVPacket& pkt, std::vector<std::vector<int16_t>>& audio_chunks)\r
126         {               \r
127                 buffer1_.resize(AVCODEC_MAX_AUDIO_FRAME_SIZE*2, 0);\r
128                 int written_bytes = buffer1_.size() - FF_INPUT_BUFFER_PADDING_SIZE;\r
129 \r
130                 const int ret = avcodec_decode_audio3(codec_context_.get(), reinterpret_cast<int16_t*>(buffer1_.data()), &written_bytes, &pkt);\r
131                 if(ret < 0)\r
132                 {       \r
133                         BOOST_THROW_EXCEPTION(\r
134                                 invalid_operation() <<\r
135                                 boost::errinfo_api_function("avcodec_decode_audio2") <<\r
136                                 boost::errinfo_errno(AVUNERROR(ret)));\r
137                 }\r
138 \r
139                 // There might be several frames in one packet.\r
140                 pkt.size -= ret;\r
141                 pkt.data += ret;\r
142                         \r
143                 buffer1_.resize(written_bytes);\r
144 \r
145                 if(resampler_)\r
146                 {\r
147                         buffer2_.resize(AVCODEC_MAX_AUDIO_FRAME_SIZE*2, 0);\r
148                         auto ret = audio_resample(resampler_.get(),\r
149                                                                                 reinterpret_cast<short*>(buffer2_.data()), \r
150                                                                                 reinterpret_cast<short*>(buffer1_.data()), \r
151                                                                                 buffer1_.size() / (av_get_bytes_per_sample(codec_context_->sample_fmt) * codec_context_->channels)); \r
152                         buffer2_.resize(ret * av_get_bytes_per_sample(AV_SAMPLE_FMT_S16) * format_desc_.audio_channels);\r
153                         std::swap(buffer1_, buffer2_);\r
154                 }\r
155 \r
156                 const auto n_samples = buffer1_.size() / av_get_bytes_per_sample(AV_SAMPLE_FMT_S16);\r
157                 const auto samples = reinterpret_cast<int16_t*>(buffer1_.data());\r
158 \r
159                 sample_count_ = std::max(sample_count_, n_samples);\r
160 \r
161                 if(sample_count_ == 0 || n_samples == sample_count_)\r
162                         audio_chunks.push_back(std::vector<int16_t>(samples, samples + n_samples));\r
163                 else\r
164                         CASPAR_LOG(warning) << L" audio_decoder: Discarding " << n_samples << L" samples.";\r
165         }\r
166 \r
167         bool ready() const\r
168         {\r
169                 return !codec_context_ || !packets_.empty();\r
170         }\r
171 };\r
172 \r
173 audio_decoder::audio_decoder(const std::shared_ptr<AVFormatContext>& context, const core::video_format_desc& format_desc) : impl_(new implementation(context, format_desc)){}\r
174 void audio_decoder::push(const std::shared_ptr<AVPacket>& packet){impl_->push(packet);}\r
175 bool audio_decoder::ready() const{return impl_->ready();}\r
176 std::vector<std::vector<int16_t>> audio_decoder::poll(){return impl_->poll();}\r
177 }