]> git.sesse.net Git - casparcg/blob - core/mixer/audio/audio_mixer.cpp
Merged OSC audio levels sending
[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/monitor/monitor.h>
29
30 #include <common/diagnostics/graph.h>
31 #include <common/linq.h>
32
33 #include <boost/range/adaptors.hpp>
34 #include <boost/range/distance.hpp>
35 #include <boost/lexical_cast.hpp>
36
37 #include <map>
38 #include <stack>
39 #include <vector>
40
41 namespace caspar { namespace core {
42
43 struct audio_item
44 {
45         const void*                     tag                     = nullptr;
46         audio_transform         transform;
47         audio_buffer            audio_data;
48
49         audio_item()
50         {
51         }
52
53         audio_item(audio_item&& other)
54                 : tag(std::move(other.tag))
55                 , transform(std::move(other.transform))
56                 , audio_data(std::move(other.audio_data))
57         {
58         }
59 };
60
61 typedef cache_aligned_vector<float> audio_buffer_ps;
62         
63 struct audio_stream
64 {
65         audio_transform         prev_transform;
66         audio_buffer_ps         audio_data;
67         bool                            is_still                = false;
68 };
69
70 struct audio_mixer::impl : boost::noncopyable
71 {
72         monitor::subject                                        monitor_subject_                { "/audio" };
73         std::stack<core::audio_transform>       transform_stack_;
74         std::map<const void*, audio_stream>     audio_streams_;
75         std::vector<audio_item>                         items_;
76         std::vector<int>                                        audio_cadence_;
77         video_format_desc                                       format_desc_;
78         float                                                           master_volume_                  = 1.0f;
79         float                                                           previous_master_volume_ = master_volume_;
80         spl::shared_ptr<diagnostics::graph>     graph_;
81 public:
82         impl(spl::shared_ptr<diagnostics::graph> graph)
83                 : graph_(std::move(graph))
84         {
85                 graph_->set_color("volume", diagnostics::color(1.0f, 0.8f, 0.1f));
86                 transform_stack_.push(core::audio_transform());
87         }
88         
89         void push(const frame_transform& transform)
90         {
91                 transform_stack_.push(transform_stack_.top()*transform.audio_transform);
92         }
93
94         void visit(const const_frame& frame)
95         {
96                 if(transform_stack_.top().volume < 0.002 || frame.audio_data().empty())
97                         return;
98
99                 audio_item item;
100                 item.tag                = frame.stream_tag();
101                 item.transform  = transform_stack_.top();
102                 item.audio_data = frame.audio_data();
103
104                 if(item.transform.is_still)
105                         item.transform.volume = 0.0;
106                 
107                 items_.push_back(std::move(item));              
108         }
109
110         void begin(const core::audio_transform& transform)
111         {
112                 transform_stack_.push(transform_stack_.top()*transform);
113         }
114                 
115         void pop()
116         {
117                 transform_stack_.pop();
118         }
119
120         void set_master_volume(float volume)
121         {
122                 master_volume_ = volume;
123         }
124
125         float get_master_volume()
126         {
127                 return master_volume_;
128         }
129
130         audio_buffer mix(const video_format_desc& format_desc)
131         {       
132                 if(format_desc_ != format_desc)
133                 {
134                         audio_streams_.clear();
135                         audio_cadence_ = format_desc.audio_cadence;
136                         format_desc_ = format_desc;
137                 }               
138                 
139                 std::map<const void*, audio_stream>     next_audio_streams;
140                 std::vector<const void*> used_tags;
141
142                 for (auto& item : items_)
143                 {                       
144                         audio_buffer_ps next_audio;
145
146                         auto next_transform = item.transform;
147                         auto prev_transform = next_transform;
148
149                         auto tag = item.tag;
150
151                         if(boost::range::find(used_tags, tag) != used_tags.end())
152                                 continue;
153                         
154                         used_tags.push_back(tag);
155
156                         const auto it = audio_streams_.find(tag);
157                         if(it != audio_streams_.end())
158                         {       
159                                 prev_transform  = it->second.prev_transform;
160                                 next_audio              = std::move(it->second.audio_data);
161                         }
162                         
163                         // Skip it if there is no existing audio stream and item has no audio-data.
164                         if(it == audio_streams_.end() && item.audio_data.empty()) 
165                                 continue;
166                                                 
167                         const float prev_volume = static_cast<float>(prev_transform.volume) * previous_master_volume_;
168                         const float next_volume = static_cast<float>(next_transform.volume) * master_volume_;
169
170                         // TODO: Move volume mixing into code below, in order to support audio sample counts not corresponding to frame audio samples.
171                         auto alpha = (next_volume-prev_volume)/static_cast<float>(item.audio_data.size()/format_desc.audio_channels);
172                         
173                         for(size_t n = 0; n < item.audio_data.size(); ++n)
174                         {
175                                 auto sample_multiplier = (prev_volume + (n/format_desc_.audio_channels) * alpha);
176                                 next_audio.push_back(item.audio_data[n] * sample_multiplier);
177                         } 
178                                                                                 
179                         next_audio_streams[tag].prev_transform  = std::move(next_transform); // Store all active tags, inactive tags will be removed at the end.
180                         next_audio_streams[tag].audio_data              = std::move(next_audio);        
181                         next_audio_streams[tag].is_still                = item.transform.is_still;
182                 }                               
183
184                 previous_master_volume_ = master_volume_;
185                 items_.clear();
186
187                 audio_streams_ = std::move(next_audio_streams);
188                 
189                 if(audio_streams_.empty())              
190                         audio_streams_[nullptr].audio_data = audio_buffer_ps(audio_size(audio_cadence_.front()), 0.0f);
191
192                 { // sanity check
193
194                         auto nb_invalid_streams = cpplinq::from(audio_streams_)
195                                 .select(values())
196                                 .where([&](const audio_stream& x) { return x.audio_data.size() < audio_size(audio_cadence_.front()); })
197                                 .count();
198
199                         if(nb_invalid_streams > 0)              
200                                 CASPAR_LOG(trace) << "[audio_mixer] Incorrect frame audio cadence detected.";                   
201                 }
202                                 
203                 std::vector<float> result_ps(audio_size(audio_cadence_.front()), 0.0f);
204                 for (auto& stream : audio_streams_ | boost::adaptors::map_values)
205                 {
206                         if(stream.audio_data.size() < result_ps.size())
207                                 stream.audio_data.resize(result_ps.size(), 0.0f);
208
209                         auto out = boost::range::transform(result_ps, stream.audio_data, std::begin(result_ps), std::plus<float>());
210                         stream.audio_data.erase(std::begin(stream.audio_data), std::begin(stream.audio_data) + std::distance(std::begin(result_ps), out));
211                 }               
212                 
213                 boost::range::rotate(audio_cadence_, std::begin(audio_cadence_)+1);
214                 
215                 audio_buffer result;
216                 result.reserve(result_ps.size());
217                 boost::range::transform(result_ps, std::back_inserter(result), [](float sample){return static_cast<int32_t>(sample);});         
218                 
219                 const int num_channels = format_desc_.audio_channels;
220                 monitor_subject_ << monitor::message("/nb_channels") % num_channels;
221
222                 auto max = std::vector<int32_t>(num_channels, std::numeric_limits<int32_t>::min());
223
224                 for (size_t n = 0; n < result.size(); n += num_channels)
225                         for (int ch = 0; ch < num_channels; ++ch)
226                                 max[ch] = std::max(max[ch], std::abs(result[n + ch]));
227
228                 // Makes the dBFS of silence => -dynamic range of 32bit LPCM => about -192 dBFS
229                 // Otherwise it would be -infinity
230                 static const auto MIN_PFS = 0.5f / static_cast<float>(std::numeric_limits<int32_t>::max());
231
232                 for (int i = 0; i < num_channels; ++i)
233                 {
234                         const auto pFS = max[i] / static_cast<float>(std::numeric_limits<int32_t>::max());
235                         const auto dBFS = 20.0f * std::log10(std::max(MIN_PFS, pFS));
236
237                         auto chan_str = boost::lexical_cast<std::string>(i + 1);
238
239                         monitor_subject_ << monitor::message("/" + chan_str + "/pFS") % pFS;
240                         monitor_subject_ << monitor::message("/" + chan_str + "/dBFS") % dBFS;
241                 }
242
243                 graph_->set_value("volume", static_cast<double>(*boost::max_element(max)) / std::numeric_limits<int32_t>::max());
244
245                 return result;
246         }
247
248         size_t audio_size(size_t num_samples) const
249         {
250                 return num_samples * format_desc_.audio_channels;
251         }
252 };
253
254 audio_mixer::audio_mixer(spl::shared_ptr<diagnostics::graph> graph) : impl_(new impl(std::move(graph))){}
255 void audio_mixer::push(const frame_transform& transform){impl_->push(transform);}
256 void audio_mixer::visit(const const_frame& frame){impl_->visit(frame);}
257 void audio_mixer::pop(){impl_->pop();}
258 void audio_mixer::set_master_volume(float volume) { impl_->set_master_volume(volume); }
259 float audio_mixer::get_master_volume() { return impl_->get_master_volume(); }
260 audio_buffer audio_mixer::operator()(const video_format_desc& format_desc){ return impl_->mix(format_desc); }
261 monitor::subject& audio_mixer::monitor_output(){ return impl_->monitor_subject_; }
262
263 }}