]> git.sesse.net Git - casparcg/blob - modules/oal/consumer/oal_consumer.cpp
Created template alias for std::vector<T, tbb::cache_aligned_allocator<T>> to caspar...
[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
38 #include <boost/circular_buffer.hpp>
39 #include <boost/lexical_cast.hpp>
40 #include <boost/property_tree/ptree.hpp>
41 #include <boost/timer.hpp>
42 #include <boost/thread/once.hpp>
43
44 #include <tbb/concurrent_queue.h>
45
46 #include <al/alc.h>
47 #include <al/al.h>
48
49 #include <array>
50
51 namespace caspar { namespace oal {
52
53 typedef cache_aligned_vector<int16_t> audio_buffer_16;
54
55 class device
56 {
57         ALCdevice*              device_         = nullptr;
58         ALCcontext*             context_        = nullptr;
59
60 public:
61         device()
62         {
63                 device_ = alcOpenDevice(nullptr);
64
65                 if(!device_)
66                         CASPAR_THROW_EXCEPTION(invalid_operation() << msg_info("Failed to initialize audio device."));
67
68                 context_ = alcCreateContext(device_, nullptr);
69
70                 if(!context_)
71                         CASPAR_THROW_EXCEPTION(invalid_operation() << msg_info("Failed to create audio context."));
72                         
73                 if(alcMakeContextCurrent(context_) == ALC_FALSE)
74                         CASPAR_THROW_EXCEPTION(invalid_operation() << msg_info("Failed to activate audio context."));
75         }
76
77         ~device()
78         {
79                 alcMakeContextCurrent(nullptr);
80
81                 if(context_)
82                         alcDestroyContext(context_);
83
84                 if(device_)
85                         alcCloseDevice(device_);
86         }
87
88         ALCdevice* get()
89         {
90                 return device_;
91         }
92 };
93
94 void init_device()
95 {
96         static std::unique_ptr<device> instance;
97         static boost::once_flag f = BOOST_ONCE_INIT;
98         
99         boost::call_once(f, []{instance.reset(new device());});
100 }
101
102 struct oal_consumer : public core::frame_consumer
103 {
104         core::monitor::subject                          monitor_subject_;
105
106         spl::shared_ptr<diagnostics::graph>     graph_;
107         boost::timer                                            perf_timer_;
108         int                                                                     channel_index_          = -1;
109         
110         core::video_format_desc                         format_desc_;
111
112         ALuint                                                          source_                         = 0;
113         std::array<ALuint, 3>                           buffers_;
114
115         executor                                                        executor_                       = L"oal_consumer";
116
117 public:
118         oal_consumer() 
119         {
120                 buffers_.assign(0);
121
122                 init_device();
123
124                 graph_->set_color("tick-time", diagnostics::color(0.0f, 0.6f, 0.9f));   
125                 graph_->set_color("dropped-frame", diagnostics::color(0.3f, 0.6f, 0.3f));
126                 graph_->set_color("late-frame", diagnostics::color(0.6f, 0.3f, 0.3f));
127                 diagnostics::register_graph(graph_);
128         }
129
130         ~oal_consumer()
131         {
132                 executor_.begin_invoke([=]
133                 {               
134                         if(source_)
135                         {
136                                 alSourceStop(source_);
137                                 alDeleteSources(1, &source_);
138                         }
139
140                         for (auto& buffer : buffers_)
141                         {
142                                 if(buffer)
143                                         alDeleteBuffers(1, &buffer);
144                         };
145                 });
146         }
147
148         // frame consumer
149
150         void initialize(const core::video_format_desc& format_desc, int channel_index) override
151         {
152                 format_desc_    = format_desc;          
153                 channel_index_  = channel_index;
154                 graph_->set_text(print());
155                 
156                 executor_.begin_invoke([=]
157                 {               
158                         alGenBuffers(static_cast<ALsizei>(buffers_.size()), buffers_.data());
159                         alGenSources(1, &source_);
160
161                         for(std::size_t n = 0; n < buffers_.size(); ++n)
162                         {
163                                 std::vector<int16_t> audio(format_desc_.audio_cadence[n % format_desc_.audio_cadence.size()]*format_desc_.audio_channels, 0);
164                                 alBufferData(buffers_[n], AL_FORMAT_STEREO16, audio.data(), static_cast<ALsizei>(audio.size()*sizeof(int16_t)), format_desc_.audio_sample_rate);
165                                 alSourceQueueBuffers(source_, 1, &buffers_[n]);
166                         }
167                         
168                         alSourcei(source_, AL_LOOPING, AL_FALSE);
169
170                         alSourcePlay(source_);  
171                 });
172         }
173         
174         std::future<bool> send(core::const_frame frame) override
175         {
176                 // Will only block if the default executor queue capacity of 512 is
177                 // exhausted, which should not happen
178                 executor_.begin_invoke([=]
179                 {
180                         ALenum state; 
181                         alGetSourcei(source_, AL_SOURCE_STATE,&state);
182                         if(state != AL_PLAYING)
183                         {
184                                 for(int n = 0; n < buffers_.size()-1; ++n)
185                                 {                                       
186                                         ALuint buffer = 0;  
187                                         alSourceUnqueueBuffers(source_, 1, &buffer);
188                                         if(buffer)
189                                         {
190                                                 std::vector<int16_t> audio(format_desc_.audio_cadence[n % format_desc_.audio_cadence.size()] * format_desc_.audio_channels, 0);
191                                                 alBufferData(buffer, AL_FORMAT_STEREO16, audio.data(), static_cast<ALsizei>(audio.size()*sizeof(int16_t)), format_desc_.audio_sample_rate);
192                                                 alSourceQueueBuffers(source_, 1, &buffer);
193                                         }
194                                 }
195                                 alSourcePlay(source_);          
196                                 graph_->set_tag("late-frame");  
197                         }
198
199                         auto audio = core::audio_32_to_16(frame.audio_data());
200                         
201                         ALuint buffer = 0;  
202                         alSourceUnqueueBuffers(source_, 1, &buffer);
203                         if(buffer)
204                         {
205                                 alBufferData(buffer, AL_FORMAT_STEREO16, audio.data(), static_cast<ALsizei>(audio.size()*sizeof(int16_t)), format_desc_.audio_sample_rate);
206                                 alSourceQueueBuffers(source_, 1, &buffer);
207                         }
208                         else
209                                 graph_->set_tag("dropped-frame");
210
211                         graph_->set_value("tick-time", perf_timer_.elapsed()*format_desc_.fps*0.5);             
212                         perf_timer_.restart();
213                 });
214
215                 return make_ready_future(true);
216         }
217         
218         std::wstring print() const override
219         {
220                 return L"oal[" + boost::lexical_cast<std::wstring>(channel_index_) + L"|" + format_desc_.name + L"]";
221         }
222
223         std::wstring name() const override
224         {
225                 return L"system-audio";
226         }
227
228         boost::property_tree::wptree info() const override
229         {
230                 boost::property_tree::wptree info;
231                 info.add(L"type", L"system-audio");
232                 return info;
233         }
234         
235         bool has_synchronization_clock() const override
236         {
237                 return false;
238         }
239
240         int delay_millis() const
241         {
242                 return 60;
243         }
244         
245         int buffer_depth() const override
246         {
247                 int delay_in_frames = static_cast<int>(delay_millis() / (1000.0 / format_desc_.fps));
248                 
249                 return delay_in_frames;
250         }
251                 
252         int index() const override
253         {
254                 return 500;
255         }
256
257         core::monitor::subject& monitor_output()
258         {
259                 return monitor_subject_;
260         }
261 };
262
263 spl::shared_ptr<core::frame_consumer> create_consumer(const std::vector<std::wstring>& params)
264 {
265         if(params.size() < 1 || params[0] != L"AUDIO")
266                 return core::frame_consumer::empty();
267
268         return spl::make_shared<oal_consumer>();
269 }
270
271 spl::shared_ptr<core::frame_consumer> create_consumer()
272 {
273         return spl::make_shared<oal_consumer>();
274 }
275
276 }}