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