]> git.sesse.net Git - casparcg/blob - modules/oal/consumer/oal_consumer.cpp
Merged INFO DELAY from 2.0
[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
32 #include <core/consumer/frame_consumer.h>
33 #include <core/frame/frame.h>
34 #include <core/mixer/audio/audio_util.h>
35 #include <core/mixer/audio/audio_mixer.h>
36 #include <core/video_format.h>
37 #include <core/help/help_sink.h>
38 #include <core/help/help_repository.h>
39
40 #include <boost/circular_buffer.hpp>
41 #include <boost/lexical_cast.hpp>
42 #include <boost/property_tree/ptree.hpp>
43 #include <boost/timer.hpp>
44 #include <boost/thread/once.hpp>
45 #include <boost/algorithm/string.hpp>
46
47 #include <tbb/concurrent_queue.h>
48
49 #include <AL/alc.h>
50 #include <AL/al.h>
51
52 #include <array>
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
116         ALuint                                                          source_                         = 0;
117         std::array<ALuint, 3>                           buffers_;
118
119         executor                                                        executor_                       { L"oal_consumer" };
120
121 public:
122         oal_consumer() 
123         {
124                 buffers_.fill(0);
125                 presentation_age_ = 0;
126
127                 init_device();
128
129                 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));   
130                 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));
131                 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.3f));
132                 diagnostics::register_graph(graph_);
133         }
134
135         ~oal_consumer()
136         {
137                 executor_.begin_invoke([=]
138                 {               
139                         if(source_)
140                         {
141                                 alSourceStop(source_);
142                                 alDeleteSources(1, &source_);
143                         }
144
145                         for (auto& buffer : buffers_)
146                         {
147                                 if(buffer)
148                                         alDeleteBuffers(1, &buffer);
149                         };
150                 });
151         }
152
153         // frame consumer
154
155         void initialize(const core::video_format_desc& format_desc, int channel_index) override
156         {
157                 format_desc_    = format_desc;          
158                 channel_index_  = channel_index;
159                 graph_->set_text(print());
160                 
161                 executor_.begin_invoke([=]
162                 {               
163                         alGenBuffers(static_cast<ALsizei>(buffers_.size()), buffers_.data());
164                         alGenSources(1, &source_);
165
166                         for(std::size_t n = 0; n < buffers_.size(); ++n)
167                         {
168                                 std::vector<int16_t> audio(format_desc_.audio_cadence[n % format_desc_.audio_cadence.size()]*format_desc_.audio_channels, 0);
169                                 alBufferData(buffers_[n], AL_FORMAT_STEREO16, audio.data(), static_cast<ALsizei>(audio.size()*sizeof(int16_t)), format_desc_.audio_sample_rate);
170                                 alSourceQueueBuffers(source_, 1, &buffers_[n]);
171                         }
172                         
173                         alSourcei(source_, AL_LOOPING, AL_FALSE);
174
175                         alSourcePlay(source_);  
176                 });
177         }
178
179         int64_t presentation_frame_age_millis() const override
180         {
181                 return presentation_age_;
182         }
183
184         std::future<bool> send(core::const_frame frame) override
185         {
186                 // Will only block if the default executor queue capacity of 512 is
187                 // exhausted, which should not happen
188                 executor_.begin_invoke([=]
189                 {
190                         ALenum state; 
191                         alGetSourcei(source_, AL_SOURCE_STATE,&state);
192                         if(state != AL_PLAYING)
193                         {
194                                 for(int n = 0; n < buffers_.size()-1; ++n)
195                                 {                                       
196                                         ALuint buffer = 0;  
197                                         alSourceUnqueueBuffers(source_, 1, &buffer);
198                                         if(buffer)
199                                         {
200                                                 std::vector<int16_t> audio(format_desc_.audio_cadence[n % format_desc_.audio_cadence.size()] * format_desc_.audio_channels, 0);
201                                                 alBufferData(buffer, AL_FORMAT_STEREO16, audio.data(), static_cast<ALsizei>(audio.size()*sizeof(int16_t)), format_desc_.audio_sample_rate);
202                                                 alSourceQueueBuffers(source_, 1, &buffer);
203                                         }
204                                 }
205                                 alSourcePlay(source_);          
206                                 graph_->set_tag("late-frame");  
207                         }
208
209                         auto audio = core::audio_32_to_16(frame.audio_data());
210                         
211                         ALuint buffer = 0;  
212                         alSourceUnqueueBuffers(source_, 1, &buffer);
213                         if(buffer)
214                         {
215                                 alBufferData(buffer, AL_FORMAT_STEREO16, audio.data(), static_cast<ALsizei>(audio.size()*sizeof(int16_t)), format_desc_.audio_sample_rate);
216                                 alSourceQueueBuffers(source_, 1, &buffer);
217                         }
218                         else
219                                 graph_->set_tag("dropped-frame");
220
221                         graph_->set_value("tick-time", perf_timer_.elapsed()*format_desc_.fps*0.5);             
222                         perf_timer_.restart();
223                         presentation_age_ = frame.get_age_millis() + delay_millis();
224                 });
225
226                 return make_ready_future(true);
227         }
228         
229         std::wstring print() const override
230         {
231                 return L"oal[" + boost::lexical_cast<std::wstring>(channel_index_) + L"|" + format_desc_.name + L"]";
232         }
233
234         std::wstring name() const override
235         {
236                 return L"system-audio";
237         }
238
239         boost::property_tree::wptree info() const override
240         {
241                 boost::property_tree::wptree info;
242                 info.add(L"type", L"system-audio");
243                 return info;
244         }
245         
246         bool has_synchronization_clock() const override
247         {
248                 return false;
249         }
250
251         int delay_millis() const
252         {
253                 return 160;
254         }
255         
256         int buffer_depth() const override
257         {
258                 int delay_in_frames = static_cast<int>(delay_millis() / (1000.0 / format_desc_.fps));
259                 
260                 return delay_in_frames;
261         }
262                 
263         int index() const override
264         {
265                 return 500;
266         }
267
268         core::monitor::subject& monitor_output()
269         {
270                 return monitor_subject_;
271         }
272 };
273
274 void describe_consumer(core::help_sink& sink, const core::help_repository& repo)
275 {
276         sink.short_description(L"A system audio consumer.");
277         sink.syntax(L"AUDIO");
278         sink.para()->text(L"Uses the system's default audio playback device.");
279         sink.para()->text(L"Examples:");
280         sink.example(L">> ADD 1 AUDIO");
281 }
282
283 spl::shared_ptr<core::frame_consumer> create_consumer(const std::vector<std::wstring>& params, core::interaction_sink*)
284 {
285         if(params.size() < 1 || !boost::iequals(params.at(0), L"AUDIO"))
286                 return core::frame_consumer::empty();
287
288         return spl::make_shared<oal_consumer>();
289 }
290
291 spl::shared_ptr<core::frame_consumer> create_preconfigured_consumer(const boost::property_tree::wptree&, core::interaction_sink*)
292 {
293         return spl::make_shared<oal_consumer>();
294 }
295
296 }}