AudioBuffer.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. #include "Base.h"
  2. #include "AudioBuffer.h"
  3. #include "FileSystem.h"
  4. namespace gameplay
  5. {
  6. // Audio buffer cache
  7. static std::vector<AudioBuffer*> __buffers;
  8. AudioBuffer::AudioBuffer(const char* path, ALuint buffer)
  9. : _filePath(path), _alBuffer(buffer)
  10. {
  11. }
  12. AudioBuffer::~AudioBuffer()
  13. {
  14. // Remove the buffer from the cache.
  15. unsigned int bufferCount = (unsigned int)__buffers.size();
  16. for (unsigned int i = 0; i < bufferCount; i++)
  17. {
  18. if (this == __buffers[i])
  19. {
  20. __buffers.erase(__buffers.begin() + i);
  21. break;
  22. }
  23. }
  24. if (_alBuffer)
  25. {
  26. AL_CHECK( alDeleteBuffers(1, &_alBuffer) );
  27. _alBuffer = 0;
  28. }
  29. }
  30. AudioBuffer* AudioBuffer::create(const char* path)
  31. {
  32. GP_ASSERT(path);
  33. // Search the cache for a stream from this file.
  34. unsigned int bufferCount = (unsigned int)__buffers.size();
  35. AudioBuffer* buffer = NULL;
  36. for (unsigned int i = 0; i < bufferCount; i++)
  37. {
  38. buffer = __buffers[i];
  39. GP_ASSERT(buffer);
  40. if (buffer->_filePath.compare(path) == 0)
  41. {
  42. buffer->addRef();
  43. return buffer;
  44. }
  45. }
  46. ALuint alBuffer;
  47. // Load audio data into a buffer.
  48. AL_CHECK( alGenBuffers(1, &alBuffer) );
  49. if (AL_LAST_ERROR())
  50. {
  51. GP_ERROR("Failed to create OpenAL buffer; alGenBuffers error: %d", AL_LAST_ERROR());
  52. AL_CHECK( alDeleteBuffers(1, &alBuffer) );
  53. return NULL;
  54. }
  55. // Load sound file.
  56. FILE* file = FileSystem::openFile(path, "rb");
  57. if (!file)
  58. {
  59. GP_ERROR("Failed to load audio file %s.", path);
  60. goto cleanup;
  61. }
  62. // Read the file header
  63. char header[12];
  64. if (fread(header, 1, 12, file) != 12)
  65. {
  66. GP_ERROR("Invalid header for audio file %s.", path);
  67. goto cleanup;
  68. }
  69. // Check the file format
  70. if (memcmp(header, "RIFF", 4) == 0)
  71. {
  72. if (!AudioBuffer::loadWav(file, alBuffer))
  73. {
  74. GP_ERROR("Invalid wave file: %s", path);
  75. goto cleanup;
  76. }
  77. }
  78. else if (memcmp(header, "OggS", 4) == 0)
  79. {
  80. if (!AudioBuffer::loadOgg(file, alBuffer))
  81. {
  82. GP_ERROR("Invalid ogg file: %s", path);
  83. goto cleanup;
  84. }
  85. }
  86. else
  87. {
  88. GP_ERROR("Unsupported audio file: %s", path);
  89. goto cleanup;
  90. }
  91. if (file)
  92. fclose(file);
  93. buffer = new AudioBuffer(path, alBuffer);
  94. // Add the buffer to the cache.
  95. __buffers.push_back(buffer);
  96. return buffer;
  97. cleanup:
  98. if (file)
  99. fclose(file);
  100. if (alBuffer)
  101. AL_CHECK( alDeleteBuffers(1, &alBuffer) );
  102. return NULL;
  103. }
  104. bool AudioBuffer::loadWav(FILE* file, ALuint buffer)
  105. {
  106. GP_ASSERT(file);
  107. unsigned char stream[12];
  108. // Verify the wave fmt magic value meaning format.
  109. if (fread(stream, 1, 8, file) != 8 || memcmp(stream, "fmt ", 4) != 0 )
  110. {
  111. GP_ERROR("Failed to verify the magic value for the wave file format.");
  112. return false;
  113. }
  114. unsigned int section_size;
  115. section_size = stream[7]<<24;
  116. section_size |= stream[6]<<16;
  117. section_size |= stream[5]<<8;
  118. section_size |= stream[4];
  119. // Check for a valid pcm format.
  120. if (fread(stream, 1, 2, file) != 2 || stream[1] != 0 || stream[0] != 1)
  121. {
  122. GP_ERROR("Unsupported audio file format (must be a valid PCM format).");
  123. return false;
  124. }
  125. // Get the channel count (16-bit little-endian).
  126. int channels;
  127. if (fread(stream, 1, 2, file) != 2)
  128. {
  129. GP_ERROR("Failed to read the wave file's channel count.");
  130. return false;
  131. }
  132. channels = stream[1]<<8;
  133. channels |= stream[0];
  134. // Get the sample frequency (32-bit little-endian).
  135. ALuint frequency;
  136. if (fread(stream, 1, 4, file) != 4)
  137. {
  138. GP_ERROR("Failed to read the wave file's sample frequency.");
  139. return false;
  140. }
  141. frequency = stream[3]<<24;
  142. frequency |= stream[2]<<16;
  143. frequency |= stream[1]<<8;
  144. frequency |= stream[0];
  145. // The next 6 bytes hold the block size and bytes-per-second.
  146. // We don't need that info, so just read and ignore it.
  147. // We could use this later if we need to know the duration.
  148. if (fread(stream, 1, 6, file) != 6)
  149. {
  150. GP_ERROR("Failed to read past the wave file's block size and bytes-per-second.");
  151. return false;
  152. }
  153. // Get the bit depth (16-bit little-endian).
  154. int bits;
  155. if (fread(stream, 1, 2, file) != 2)
  156. {
  157. GP_ERROR("Failed to read the wave file's bit depth.");
  158. return false;
  159. }
  160. bits = stream[1]<<8;
  161. bits |= stream[0];
  162. // Now convert the given channel count and bit depth into an OpenAL format.
  163. ALuint format = 0;
  164. if (bits == 8)
  165. {
  166. if (channels == 1)
  167. format = AL_FORMAT_MONO8;
  168. else if (channels == 2)
  169. format = AL_FORMAT_STEREO8;
  170. }
  171. else if (bits == 16)
  172. {
  173. if (channels == 1)
  174. format = AL_FORMAT_MONO16;
  175. else if (channels == 2)
  176. format = AL_FORMAT_STEREO16;
  177. }
  178. else
  179. {
  180. GP_ERROR("Incompatible wave file format: (%d, %d)", channels, bits);
  181. return false;
  182. }
  183. // Check against the size of the format header as there may be more data that we need to read.
  184. if (section_size > 16)
  185. {
  186. unsigned int length = section_size - 16;
  187. // Extension size is 2 bytes.
  188. if (fread(stream, 1, length, file) != length)
  189. {
  190. GP_ERROR("Failed to read extension size from wave file.");
  191. return false;
  192. }
  193. }
  194. // Read in the rest of the file a chunk (section) at a time.
  195. while (true)
  196. {
  197. // Check if we are at the end of the file without reading the data.
  198. if (feof(file))
  199. {
  200. GP_ERROR("Failed to load wave file; file appears to have no data.");
  201. return false;
  202. }
  203. // Read in the type of the next section of the file.
  204. if (fread(stream, 1, 4, file) != 4)
  205. {
  206. GP_ERROR("Failed to read next section type from wave file.");
  207. return false;
  208. }
  209. // Data chunk.
  210. if (memcmp(stream, "data", 4) == 0)
  211. {
  212. // Read how much data is remaining and buffer it up.
  213. unsigned int dataSize;
  214. if (fread(&dataSize, sizeof(int), 1, file) != 1)
  215. {
  216. GP_ERROR("Failed to read size of data section from wave file.");
  217. return false;
  218. }
  219. char* data = new char[dataSize];
  220. if (fread(data, sizeof(char), dataSize, file) != dataSize)
  221. {
  222. GP_ERROR("Failed to load wave file; file is missing data.");
  223. SAFE_DELETE_ARRAY(data);
  224. return false;
  225. }
  226. AL_CHECK( alBufferData(buffer, format, data, dataSize, frequency) );
  227. SAFE_DELETE_ARRAY(data);
  228. // We've read the data, so return now.
  229. return true;
  230. }
  231. // Other chunk - could be any of the following:
  232. // - Fact ("fact")
  233. // - Wave List ("wavl")
  234. // - Silent ("slnt")
  235. // - Cue ("cue ")
  236. // - Playlist ("plst")
  237. // - Associated Data List ("list")
  238. // - Label ("labl")
  239. // - Note ("note")
  240. // - Labeled Text ("ltxt")
  241. // - Sampler ("smpl")
  242. // - Instrument ("inst")
  243. else
  244. {
  245. // Store the name of the chunk so we can report errors informatively.
  246. char chunk[5] = { 0 };
  247. memcpy(chunk, stream, 4);
  248. // Read the chunk size.
  249. if (fread(stream, 1, 4, file) != 4)
  250. {
  251. GP_ERROR("Failed to read size of '%s' chunk from wave file.", chunk);
  252. return false;
  253. }
  254. section_size = stream[3]<<24;
  255. section_size |= stream[2]<<16;
  256. section_size |= stream[1]<<8;
  257. section_size |= stream[0];
  258. // Seek past the chunk.
  259. if (fseek(file, section_size, SEEK_CUR) != 0)
  260. {
  261. GP_ERROR("Failed to seek past '%s' chunk in wave file.", chunk);
  262. return false;
  263. }
  264. }
  265. }
  266. }
  267. bool AudioBuffer::loadOgg(FILE* file, ALuint buffer)
  268. {
  269. GP_ASSERT(file);
  270. OggVorbis_File ogg_file;
  271. vorbis_info* info;
  272. ALenum format;
  273. long result;
  274. int section;
  275. long size = 0;
  276. rewind(file);
  277. if ((result = ov_open(file, &ogg_file, NULL, 0)) < 0)
  278. {
  279. fclose(file);
  280. GP_ERROR("Failed to open ogg file.");
  281. return false;
  282. }
  283. info = ov_info(&ogg_file, -1);
  284. GP_ASSERT(info);
  285. if (info->channels == 1)
  286. format = AL_FORMAT_MONO16;
  287. else
  288. format = AL_FORMAT_STEREO16;
  289. // size = #samples * #channels * 2 (for 16 bit).
  290. ogg_int64_t data_size = ov_pcm_total(&ogg_file, -1) * info->channels * 2;
  291. char* data = new char[data_size];
  292. while (size < data_size)
  293. {
  294. result = ov_read(&ogg_file, data + size, data_size - size, 0, 2, 1, &section);
  295. if (result > 0)
  296. {
  297. size += result;
  298. }
  299. else if (result < 0)
  300. {
  301. SAFE_DELETE_ARRAY(data);
  302. GP_ERROR("Failed to read ogg file; file is missing data.");
  303. return false;
  304. }
  305. else
  306. {
  307. break;
  308. }
  309. }
  310. if (size == 0)
  311. {
  312. SAFE_DELETE_ARRAY(data);
  313. GP_ERROR("Filed to read ogg file; unable to read any data.");
  314. return false;
  315. }
  316. AL_CHECK( alBufferData(buffer, format, data, data_size, info->rate) );
  317. SAFE_DELETE_ARRAY(data);
  318. ov_clear(&ogg_file);
  319. // ov_clear actually closes the file pointer as well.
  320. file = 0;
  321. return true;
  322. }
  323. }