]> git.sesse.net Git - casparcg/blob - core/mixer/audio/audio_mixer.cpp
29a89c7609c9283c639737e41c77424fdcddc4a3
[casparcg] / core / mixer / audio / audio_mixer.cpp
1 /*
2 * Copyright (c) 2011 Sveriges Television AB <info@casparcg.com>
3 *
4 * This file is part of CasparCG (www.casparcg.com).
5 *
6 * CasparCG is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * CasparCG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with CasparCG. If not, see <http://www.gnu.org/licenses/>.
18 *
19 * Author: Robert Nagy, ronag89@gmail.com
20 */
21
22 #include "../../StdAfx.h"
23
24 #include "audio_mixer.h"
25
26 #include <core/frame/frame.h>
27 #include <core/frame/frame_transform.h>
28 #include <core/frame/audio_channel_layout.h>
29 #include <core/monitor/monitor.h>
30
31 #include <common/diagnostics/graph.h>
32 #include <common/linq.h>
33
34 #include <boost/range/adaptors.hpp>
35 #include <boost/range/distance.hpp>
36 #include <boost/lexical_cast.hpp>
37
38 #include <map>
39 #include <stack>
40 #include <vector>
41
42 namespace caspar { namespace core {
43
44 struct audio_item
45 {
46         const void*                             tag                             = nullptr;
47         audio_transform                 transform;
48         audio_buffer                    audio_data;
49         audio_channel_layout    channel_layout  = audio_channel_layout::invalid();
50
51         audio_item()
52         {
53         }
54
55         audio_item(audio_item&& other)
56                 : tag(std::move(other.tag))
57                 , transform(std::move(other.transform))
58                 , audio_data(std::move(other.audio_data))
59                 , channel_layout(std::move(other.channel_layout))
60         {
61         }
62 };
63
64 typedef cache_aligned_vector<double> audio_buffer_ps;
65
66 struct audio_stream
67 {
68         audio_transform                                                 prev_transform;
69         audio_buffer_ps                                                 audio_data;
70         std::unique_ptr<audio_channel_remapper> channel_remapper;
71         bool                                                                    remapping_failed        = false;
72         bool                                                                    is_still                        = false;
73 };
74
75 struct audio_mixer::impl : boost::noncopyable
76 {
77         monitor::subject                                        monitor_subject_                { "/audio" };
78         std::stack<core::audio_transform>       transform_stack_;
79         std::map<const void*, audio_stream>     audio_streams_;
80         std::vector<audio_item>                         items_;
81         std::vector<int>                                        audio_cadence_;
82         video_format_desc                                       format_desc_;
83         audio_channel_layout                            channel_layout_                 = audio_channel_layout::invalid();
84         float                                                           master_volume_                  = 1.0f;
85         float                                                           previous_master_volume_ = master_volume_;
86         spl::shared_ptr<diagnostics::graph>     graph_;
87 public:
88         impl(spl::shared_ptr<diagnostics::graph> graph)
89                 : graph_(std::move(graph))
90         {
91                 graph_->set_color("volume", diagnostics::color(1.0f, 0.8f, 0.1f));
92                 graph_->set_color("audio-clipping", diagnostics::color(0.3f, 0.6f, 0.3f));
93                 transform_stack_.push(core::audio_transform());
94         }
95
96         void push(const frame_transform& transform)
97         {
98                 transform_stack_.push(transform_stack_.top()*transform.audio_transform);
99         }
100
101         void visit(const const_frame& frame)
102         {
103                 if(transform_stack_.top().volume < 0.002 || frame.audio_data().empty())
104                         return;
105
106                 audio_item item;
107                 item.tag                        = frame.stream_tag();
108                 item.transform          = transform_stack_.top();
109                 item.audio_data         = frame.audio_data();
110                 item.channel_layout = frame.audio_channel_layout();
111
112                 if(item.transform.is_still)
113                         item.transform.volume = 0.0;
114
115                 items_.push_back(std::move(item));
116         }
117
118         void pop()
119         {
120                 transform_stack_.pop();
121         }
122
123         void set_master_volume(float volume)
124         {
125                 master_volume_ = volume;
126         }
127
128         float get_master_volume()
129         {
130                 return master_volume_;
131         }
132
133         audio_buffer mix(const video_format_desc& format_desc, const audio_channel_layout& channel_layout)
134         {
135                 if(format_desc_ != format_desc || channel_layout_ != channel_layout)
136                 {
137                         audio_streams_.clear();
138                         audio_cadence_ = format_desc.audio_cadence;
139                         format_desc_ = format_desc;
140                         channel_layout_ = channel_layout;
141                 }
142
143                 std::map<const void*, audio_stream>     next_audio_streams;
144
145                 for (auto& item : items_)
146                 {
147                         audio_buffer_ps next_audio;
148                         std::unique_ptr<audio_channel_remapper> channel_remapper;
149                         bool remapping_failed = false;
150
151                         auto next_transform = item.transform;
152                         auto prev_transform = next_transform;
153
154                         auto tag = item.tag;
155
156                         auto it = next_audio_streams.find(tag);
157                         bool found = it != next_audio_streams.end();
158
159                         if (!found)
160                         {
161                                 it = audio_streams_.find(tag);
162                                 found = it != audio_streams_.end();
163                         }
164
165                         if (found)
166                         {
167                                 prev_transform = it->second.prev_transform;
168                                 next_audio = std::move(it->second.audio_data);
169                                 channel_remapper = std::move(it->second.channel_remapper);
170                                 remapping_failed = it->second.remapping_failed;
171                         }
172
173                         if (remapping_failed)
174                         {
175                                 CASPAR_LOG(trace) << "[audio_mixer] audio channel remapping already failed for stream.";
176                                 next_audio_streams[tag].remapping_failed = true;
177                                 continue;
178                         }
179
180                         // Skip it if there is no existing audio stream and item has no audio-data.
181                         if(!found && item.audio_data.empty())
182                                 continue;
183
184                         if (item.channel_layout == audio_channel_layout::invalid())
185                         {
186                                 CASPAR_LOG(warning) << "[audio_mixer] invalid audio channel layout for item";
187                                 next_audio_streams[tag].remapping_failed = true;
188                                 continue;
189                         }
190
191                         if (!channel_remapper)
192                         {
193                                 try
194                                 {
195                                         channel_remapper.reset(new audio_channel_remapper(item.channel_layout, channel_layout_));
196                                 }
197                                 catch (...)
198                                 {
199                                         CASPAR_LOG_CURRENT_EXCEPTION();
200                                         CASPAR_LOG(error) << "[audio_mixer] audio channel remapping failed for stream.";
201                                         next_audio_streams[tag].remapping_failed = true;
202                                         continue;
203                                 }
204                         }
205
206                         item.audio_data = channel_remapper->mix_and_rearrange(item.audio_data);
207
208                         const double prev_volume = prev_transform.volume * previous_master_volume_;
209                         const double next_volume = next_transform.volume * master_volume_;
210
211                         // TODO: Move volume mixing into code below, in order to support audio sample counts not corresponding to frame audio samples.
212                         auto alpha = (next_volume-prev_volume)/static_cast<double>(item.audio_data.size()/channel_layout_.num_channels);
213
214                         for(size_t n = 0; n < item.audio_data.size(); ++n)
215                         {
216                                 auto sample_multiplier = (prev_volume + (n / channel_layout_.num_channels) * alpha);
217                                 next_audio.push_back(item.audio_data.data()[n] * sample_multiplier);
218                         }
219
220                         next_audio_streams[tag].prev_transform          = std::move(next_transform); // Store all active tags, inactive tags will be removed at the end.
221                         next_audio_streams[tag].audio_data                      = std::move(next_audio);
222                         next_audio_streams[tag].channel_remapper        = std::move(channel_remapper);
223                         next_audio_streams[tag].remapping_failed        = remapping_failed;
224                         next_audio_streams[tag].is_still                        = item.transform.is_still;
225                 }
226
227                 previous_master_volume_ = master_volume_;
228                 items_.clear();
229
230                 audio_streams_ = std::move(next_audio_streams);
231
232                 if(audio_streams_.empty())
233                         audio_streams_[nullptr].audio_data = audio_buffer_ps(audio_size(audio_cadence_.front()), 0.0);
234
235                 { // sanity check
236
237                         auto nb_invalid_streams = cpplinq::from(audio_streams_)
238                                 .select(values())
239                                 .where([&](const audio_stream& x)
240                                 {
241                                         return !x.remapping_failed && x.audio_data.size() < audio_size(audio_cadence_.front());
242                                 })
243                                 .count();
244
245                         if(nb_invalid_streams > 0)
246                                 CASPAR_LOG(trace) << "[audio_mixer] Incorrect frame audio cadence detected.";
247                 }
248
249                 audio_buffer_ps result_ps(audio_size(audio_cadence_.front()), 0.0);
250                 for (auto& stream : audio_streams_ | boost::adaptors::map_values)
251                 {
252                         if (stream.audio_data.size() < result_ps.size())
253                         {
254                                 auto samples = (result_ps.size() - stream.audio_data.size()) / channel_layout_.num_channels;
255                                 CASPAR_LOG(trace) << L"[audio_mixer] Appended " << samples << L" zero samples";
256                                 CASPAR_LOG(trace) << L"[audio_mixer] Actual number of samples " << stream.audio_data.size() / channel_layout_.num_channels;
257                                 CASPAR_LOG(trace) << L"[audio_mixer] Wanted number of samples " << result_ps.size() / channel_layout_.num_channels;
258                                 stream.audio_data.resize(result_ps.size(), 0.0);
259                         }
260
261                         auto out = boost::range::transform(result_ps, stream.audio_data, std::begin(result_ps), std::plus<double>());
262                         stream.audio_data.erase(std::begin(stream.audio_data), std::begin(stream.audio_data) + std::distance(std::begin(result_ps), out));
263                 }
264
265                 boost::range::rotate(audio_cadence_, std::begin(audio_cadence_)+1);
266
267                 auto result_owner = spl::make_shared<mutable_audio_buffer>();
268                 auto& result = *result_owner;
269                 result.reserve(result_ps.size());
270                 const int32_t min_amplitude = std::numeric_limits<int32_t>::min();
271                 const int32_t max_amplitude = std::numeric_limits<int32_t>::max();
272                 bool clipping = false;
273                 boost::range::transform(result_ps, std::back_inserter(result), [&](double sample)
274                 {
275                         if (sample > max_amplitude)
276                         {
277                                 clipping = true;
278                                 return max_amplitude;
279                         }
280                         else if (sample < min_amplitude)
281                         {
282                                 clipping = true;
283                                 return min_amplitude;
284                         }
285                         else
286                                 return static_cast<int32_t>(sample);
287                 });
288
289                 if (clipping)
290                         graph_->set_tag(diagnostics::tag_severity::WARNING, "audio-clipping");
291
292                 const int num_channels = channel_layout_.num_channels;
293                 monitor_subject_ << monitor::message("/nb_channels") % num_channels;
294
295                 auto max = std::vector<int32_t>(num_channels, std::numeric_limits<int32_t>::min());
296
297                 for (size_t n = 0; n < result.size(); n += num_channels)
298                         for (int ch = 0; ch < num_channels; ++ch)
299                                 max[ch] = std::max(max[ch], std::abs(result[n + ch]));
300
301                 // Makes the dBFS of silence => -dynamic range of 32bit LPCM => about -192 dBFS
302                 // Otherwise it would be -infinity
303                 static const auto MIN_PFS = 0.5f / static_cast<float>(std::numeric_limits<int32_t>::max());
304
305                 for (int i = 0; i < num_channels; ++i)
306                 {
307                         const auto pFS = max[i] / static_cast<float>(std::numeric_limits<int32_t>::max());
308                         const auto dBFS = 20.0f * std::log10(std::max(MIN_PFS, pFS));
309
310                         auto chan_str = boost::lexical_cast<std::string>(i + 1);
311
312                         monitor_subject_ << monitor::message("/" + chan_str + "/pFS") % pFS;
313                         monitor_subject_ << monitor::message("/" + chan_str + "/dBFS") % dBFS;
314                 }
315
316                 graph_->set_value("volume", static_cast<double>(*boost::max_element(max)) / std::numeric_limits<int32_t>::max());
317
318                 return caspar::array<int32_t>(result.data(), result.size(), true, std::move(result_owner));
319         }
320
321         size_t audio_size(size_t num_samples) const
322         {
323                 return num_samples * channel_layout_.num_channels;
324         }
325 };
326
327 audio_mixer::audio_mixer(spl::shared_ptr<diagnostics::graph> graph) : impl_(new impl(std::move(graph))){}
328 void audio_mixer::push(const frame_transform& transform){impl_->push(transform);}
329 void audio_mixer::visit(const const_frame& frame){impl_->visit(frame);}
330 void audio_mixer::pop(){impl_->pop();}
331 void audio_mixer::set_master_volume(float volume) { impl_->set_master_volume(volume); }
332 float audio_mixer::get_master_volume() { return impl_->get_master_volume(); }
333 audio_buffer audio_mixer::operator()(const video_format_desc& format_desc, const audio_channel_layout& channel_layout){ return impl_->mix(format_desc, channel_layout); }
334 monitor::subject& audio_mixer::monitor_output(){ return impl_->monitor_subject_; }
335
336 }}