]> git.sesse.net Git - casparcg/blob - modules/oal/consumer/oal_consumer.cpp
* Reenabled unit-test project after move to CMake.
[casparcg] / modules / oal / consumer / oal_consumer.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 "oal_consumer.h"
23
24 #include <common/except.h>
25 #include <common/executor.h>
26 #include <common/diagnostics/graph.h>
27 #include <common/log.h>
28 #include <common/utf.h>
29 #include <common/env.h>
30 #include <common/future.h>
31 #include <common/param.h>
32
33 #include <core/consumer/frame_consumer.h>
34 #include <core/frame/frame.h>
35 #include <core/frame/audio_channel_layout.h>
36 #include <core/mixer/audio/audio_util.h>
37 #include <core/mixer/audio/audio_mixer.h>
38 #include <core/video_format.h>
39 #include <core/help/help_sink.h>
40 #include <core/help/help_repository.h>
41
42 #include <boost/circular_buffer.hpp>
43 #include <boost/lexical_cast.hpp>
44 #include <boost/property_tree/ptree.hpp>
45 #include <boost/timer.hpp>
46 #include <boost/thread/once.hpp>
47 #include <boost/algorithm/string.hpp>
48
49 #include <tbb/concurrent_queue.h>
50
51 #include <AL/alc.h>
52 #include <AL/al.h>
53
54 namespace caspar { namespace oal {
55
56 typedef cache_aligned_vector<int16_t> audio_buffer_16;
57
58 class device
59 {
60         ALCdevice*              device_         = nullptr;
61         ALCcontext*             context_        = nullptr;
62
63 public:
64         device()
65         {
66                 device_ = alcOpenDevice(nullptr);
67
68                 if(!device_)
69                         CASPAR_THROW_EXCEPTION(invalid_operation() << msg_info("Failed to initialize audio device."));
70
71                 context_ = alcCreateContext(device_, nullptr);
72
73                 if(!context_)
74                         CASPAR_THROW_EXCEPTION(invalid_operation() << msg_info("Failed to create audio context."));
75                         
76                 if(alcMakeContextCurrent(context_) == ALC_FALSE)
77                         CASPAR_THROW_EXCEPTION(invalid_operation() << msg_info("Failed to activate audio context."));
78         }
79
80         ~device()
81         {
82                 alcMakeContextCurrent(nullptr);
83
84                 if(context_)
85                         alcDestroyContext(context_);
86
87                 if(device_)
88                         alcCloseDevice(device_);
89         }
90
91         ALCdevice* get()
92         {
93                 return device_;
94         }
95 };
96
97 void init_device()
98 {
99         static std::unique_ptr<device> instance;
100         static boost::once_flag f = BOOST_ONCE_INIT;
101         
102         boost::call_once(f, []{instance.reset(new device());});
103 }
104
105 struct oal_consumer : public core::frame_consumer
106 {
107         core::monitor::subject                                                  monitor_subject_;
108
109         spl::shared_ptr<diagnostics::graph>                             graph_;
110         boost::timer                                                                    perf_timer_;
111         tbb::atomic<int64_t>                                                    presentation_age_;
112         int                                                                                             channel_index_          = -1;
113         
114         core::video_format_desc                                                 format_desc_;
115         core::audio_channel_layout                                              out_channel_layout_;
116         std::unique_ptr<core::audio_channel_remapper>   channel_remapper_;
117
118         ALuint                                                                                  source_                         = 0;
119         std::vector<ALuint>                                                             buffers_;
120
121         executor                                                                                executor_                       { L"oal_consumer" };
122
123 public:
124         oal_consumer(const core::audio_channel_layout& out_channel_layout)
125                 : out_channel_layout_(out_channel_layout)
126         {
127                 presentation_age_ = 0;
128
129                 init_device();
130
131                 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));   
132                 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));
133                 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.3f));
134                 diagnostics::register_graph(graph_);
135         }
136
137         ~oal_consumer()
138         {
139                 executor_.invoke([=]
140                 {               
141                         if(source_)
142                         {
143                                 alSourceStop(source_);
144                                 alDeleteSources(1, &source_);
145                         }
146
147                         for (auto& buffer : buffers_)
148                         {
149                                 if(buffer)
150                                         alDeleteBuffers(1, &buffer);
151                         };
152                 });
153         }
154
155         // frame consumer
156
157         void initialize(const core::video_format_desc& format_desc, const core::audio_channel_layout& channel_layout, int channel_index) override
158         {
159                 format_desc_    = format_desc;          
160                 channel_index_  = channel_index;
161                 if (out_channel_layout_ == core::audio_channel_layout::invalid())
162                         out_channel_layout_ = channel_layout.num_channels == 2 ? channel_layout : *core::audio_channel_layout_repository::get_default()->get_layout(L"stereo");
163
164                 out_channel_layout_.num_channels = 2;
165
166                 channel_remapper_.reset(new core::audio_channel_remapper(channel_layout, out_channel_layout_));
167                 graph_->set_text(print());
168
169                 executor_.begin_invoke([=]
170                 {               
171                         buffers_.resize(format_desc_.fps > 30 ? 8 : 4);
172                         alGenBuffers(static_cast<ALsizei>(buffers_.size()), buffers_.data());
173                         alGenSources(1, &source_);
174
175                         for(std::size_t n = 0; n < buffers_.size(); ++n)
176                         {
177                                 audio_buffer_16 audio(format_desc_.audio_cadence[n % format_desc_.audio_cadence.size()]*2, 0);
178                                 alBufferData(buffers_[n], AL_FORMAT_STEREO16, audio.data(), static_cast<ALsizei>(audio.size()*sizeof(int16_t)), format_desc_.audio_sample_rate);
179                                 alSourceQueueBuffers(source_, 1, &buffers_[n]);
180                         }
181                         
182                         alSourcei(source_, AL_LOOPING, AL_FALSE);
183
184                         alSourcePlay(source_);  
185                 });
186         }
187
188         int64_t presentation_frame_age_millis() const override
189         {
190                 return presentation_age_;
191         }
192
193         std::future<bool> send(core::const_frame frame) override
194         {
195                 // Will only block if the default executor queue capacity of 512 is
196                 // exhausted, which should not happen
197                 executor_.begin_invoke([=]
198                 {
199                         ALenum state; 
200                         alGetSourcei(source_, AL_SOURCE_STATE,&state);
201                         if(state != AL_PLAYING)
202                         {
203                                 for(int n = 0; n < buffers_.size()-1; ++n)
204                                 {                                       
205                                         ALuint buffer = 0;  
206                                         alSourceUnqueueBuffers(source_, 1, &buffer);
207                                         if(buffer)
208                                         {
209                                                 std::vector<int16_t> audio(format_desc_.audio_cadence[n % format_desc_.audio_cadence.size()] * 2, 0);
210                                                 alBufferData(buffer, AL_FORMAT_STEREO16, audio.data(), static_cast<ALsizei>(audio.size()*sizeof(int16_t)), format_desc_.audio_sample_rate);
211                                                 alSourceQueueBuffers(source_, 1, &buffer);
212                                         }
213                                 }
214                                 alSourcePlay(source_);          
215                                 graph_->set_tag("late-frame");  
216                         }
217
218                         auto audio = core::audio_32_to_16(channel_remapper_->mix_and_rearrange(frame.audio_data()));
219                         
220                         ALuint buffer = 0;  
221                         alSourceUnqueueBuffers(source_, 1, &buffer);
222                         if(buffer)
223                         {
224                                 alBufferData(buffer, AL_FORMAT_STEREO16, audio.data(), static_cast<ALsizei>(audio.size()*sizeof(int16_t)), format_desc_.audio_sample_rate);
225                                 alSourceQueueBuffers(source_, 1, &buffer);
226                         }
227                         else
228                                 graph_->set_tag("dropped-frame");
229
230                         graph_->set_value("tick-time", perf_timer_.elapsed()*format_desc_.fps*0.5);             
231                         perf_timer_.restart();
232                         presentation_age_ = frame.get_age_millis() + delay_millis();
233                 });
234
235                 return make_ready_future(true);
236         }
237         
238         std::wstring print() const override
239         {
240                 return L"oal[" + boost::lexical_cast<std::wstring>(channel_index_) + L"|" + format_desc_.name + L"]";
241         }
242
243         std::wstring name() const override
244         {
245                 return L"system-audio";
246         }
247
248         boost::property_tree::wptree info() const override
249         {
250                 boost::property_tree::wptree info;
251                 info.add(L"type", L"system-audio");
252                 return info;
253         }
254         
255         bool has_synchronization_clock() const override
256         {
257                 return false;
258         }
259
260         int delay_millis() const
261         {
262                 return 213;
263         }
264         
265         int buffer_depth() const override
266         {
267                 int delay_in_frames = static_cast<int>(delay_millis() / (1000.0 / format_desc_.fps));
268                 
269                 return delay_in_frames;
270         }
271                 
272         int index() const override
273         {
274                 return 500;
275         }
276
277         core::monitor::subject& monitor_output()
278         {
279                 return monitor_subject_;
280         }
281 };
282
283 void describe_consumer(core::help_sink& sink, const core::help_repository& repo)
284 {
285         sink.short_description(L"A system audio consumer.");
286         sink.syntax(L"AUDIO {CHANNEL_LAYOUT [channel_layout:string]}");
287         sink.para()->text(L"Uses the system's default audio playback device.");
288         sink.para()->text(L"Examples:");
289         sink.example(L">> ADD 1 AUDIO");
290         sink.example(L">> ADD 1 AUDIO CHANNEL_LAYOUT matrix", L"Uses the matrix channel layout");
291 }
292
293 spl::shared_ptr<core::frame_consumer> create_consumer(const std::vector<std::wstring>& params, core::interaction_sink*)
294 {
295         if(params.size() < 1 || !boost::iequals(params.at(0), L"AUDIO"))
296                 return core::frame_consumer::empty();
297
298         auto channel_layout                     = core::audio_channel_layout::invalid();
299         auto channel_layout_spec        = get_param(L"CHANNEL_LAYOUT", params);
300         
301         if (!channel_layout_spec.empty())
302         {
303                 auto found_layout = core::audio_channel_layout_repository::get_default()->get_layout(channel_layout_spec);
304
305                 if (!found_layout)
306                         CASPAR_THROW_EXCEPTION(file_not_found() << msg_info(L"Channel layout " + channel_layout_spec + L" not found."));
307
308                 channel_layout = *found_layout;
309         }
310
311         return spl::make_shared<oal_consumer>(channel_layout);
312 }
313
314 spl::shared_ptr<core::frame_consumer> create_preconfigured_consumer(const boost::property_tree::wptree& ptree, core::interaction_sink*)
315 {
316         auto channel_layout                     = core::audio_channel_layout::invalid();
317         auto channel_layout_spec        = ptree.get_optional<std::wstring>(L"channel-layout");
318
319         if (channel_layout_spec)
320         {
321                 auto found_layout = core::audio_channel_layout_repository::get_default()->get_layout(*channel_layout_spec);
322
323                 if (!found_layout)
324                         CASPAR_THROW_EXCEPTION(file_not_found() << msg_info(L"Channel layout " + *channel_layout_spec + L" not found."));
325
326                 channel_layout = *found_layout;
327         }
328
329         return spl::make_shared<oal_consumer>(channel_layout);
330 }
331
332 }}