• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *
3  * Copyright (C) 2018 The Android Open Source Project
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 
18 #include "sdl_wrapper.h"
19 
20 #include "glog/logging.h"
21 #include <SDL2/SDL.h>
22 
23 #include <cstdint>
24 
25 using cfp::SDLAudioDevice;
26 using cfp::SDLLib;
27 
SDLAudioDevice(SDLAudioDevice && other)28 SDLAudioDevice::SDLAudioDevice(SDLAudioDevice&& other)
29     : device_id_{other.device_id_} {
30   other.device_id_ = 0;
31 }
operator =(SDLAudioDevice && other)32 SDLAudioDevice& SDLAudioDevice::operator=(SDLAudioDevice&& other) {
33   close();
34   device_id_ = other.device_id_;
35   other.device_id_ = 0;
36   return *this;
37 }
38 
~SDLAudioDevice()39 SDLAudioDevice::~SDLAudioDevice() { close(); }
40 
QueueAudio(const void * data,std::uint32_t len)41 int SDLAudioDevice::QueueAudio(const void* data, std::uint32_t len) {
42   return SDL_QueueAudio(device_id_, data, len);
43 }
44 
SDLAudioDevice(SDL_AudioDeviceID device_id)45 SDLAudioDevice::SDLAudioDevice(SDL_AudioDeviceID device_id)
46     : device_id_{device_id} {}
47 
close()48 void SDLAudioDevice::close() {
49   if (device_id_ != 0) {
50     SDL_CloseAudioDevice(device_id_);
51   }
52 }
53 
SDLLib()54 SDLLib::SDLLib() { SDL_Init(SDL_INIT_AUDIO); }
~SDLLib()55 SDLLib::~SDLLib() { SDL_Quit(); }
56 
OpenAudioDevice(int freq,std::uint8_t num_channels)57 SDLAudioDevice SDLLib::OpenAudioDevice(int freq, std::uint8_t num_channels) {
58   SDL_AudioSpec wav_spec{};
59   wav_spec.freq = freq;
60   wav_spec.format = AUDIO_S16LSB;
61   wav_spec.channels = num_channels;
62   wav_spec.silence = 0;
63   // .samples seems to work as low as 256,
64   // docs say this is 4096 when used with SDL_LoadWAV so I'm sticking with
65   // that
66   wav_spec.samples = 4096;
67   wav_spec.size = 0;
68 
69   auto audio_device_id = SDL_OpenAudioDevice(nullptr, 0, &wav_spec, nullptr, 0);
70   if (audio_device_id == 0) {
71     LOG(FATAL) << "failed to open audio device: " << SDL_GetError() << '\n';
72   }
73   SDL_PauseAudioDevice(audio_device_id, false);
74   return SDLAudioDevice{audio_device_id};
75 }
76