AudioBuffer.cpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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. fclose(file);
  92. buffer = new AudioBuffer(path, alBuffer);
  93. // Add the buffer to the cache.
  94. __buffers.push_back(buffer);
  95. return buffer;
  96. cleanup:
  97. if (file)
  98. fclose(file);
  99. if (alBuffer)
  100. AL_CHECK( alDeleteBuffers(1, &alBuffer) );
  101. return NULL;
  102. }
  103. bool AudioBuffer::loadWav(FILE* file, ALuint buffer)
  104. {
  105. GP_ASSERT(file);
  106. unsigned char stream[12];
  107. // Verify the wave fmt magic value meaning format.
  108. if (fread(stream, 1, 8, file) != 8 || memcmp(stream, "fmt ", 4) != 0 )
  109. {
  110. GP_ERROR("Failed to verify the magic value for the wave file format.");
  111. return false;
  112. }
  113. unsigned int section_size;
  114. section_size = stream[7]<<24;
  115. section_size |= stream[6]<<16;
  116. section_size |= stream[5]<<8;
  117. section_size |= stream[4];
  118. // Check for a valid pcm format.
  119. if (fread(stream, 1, 2, file) != 2 || stream[1] != 0 || stream[0] != 1)
  120. {
  121. GP_ERROR("Unsupported audio file format (must be a valid PCM format).");
  122. return false;
  123. }
  124. // Get the channel count (16-bit little-endian).
  125. int channels;
  126. if (fread(stream, 1, 2, file) != 2)
  127. {
  128. GP_ERROR("Failed to read the wave file's channel count.");
  129. return false;
  130. }
  131. channels = stream[1]<<8;
  132. channels |= stream[0];
  133. // Get the sample frequency (32-bit little-endian).
  134. ALuint frequency;
  135. if (fread(stream, 1, 4, file) != 4)
  136. {
  137. GP_ERROR("Failed to read the wave file's sample frequency.");
  138. return false;
  139. }
  140. frequency = stream[3]<<24;
  141. frequency |= stream[2]<<16;
  142. frequency |= stream[1]<<8;
  143. frequency |= stream[0];
  144. // The next 6 bytes hold the block size and bytes-per-second.
  145. // We don't need that info, so just read and ignore it.
  146. // We could use this later if we need to know the duration.
  147. if (fread(stream, 1, 6, file) != 6)
  148. {
  149. GP_ERROR("Failed to read past the wave file's block size and bytes-per-second.");
  150. return false;
  151. }
  152. // Get the bit depth (16-bit little-endian).
  153. int bits;
  154. if (fread(stream, 1, 2, file) != 2)
  155. {
  156. GP_ERROR("Failed to read the wave file's bit depth.");
  157. return false;
  158. }
  159. bits = stream[1]<<8;
  160. bits |= stream[0];
  161. // Now convert the given channel count and bit depth into an OpenAL format.
  162. ALuint format = 0;
  163. if (bits == 8)
  164. {
  165. if (channels == 1)
  166. format = AL_FORMAT_MONO8;
  167. else if (channels == 2)
  168. format = AL_FORMAT_STEREO8;
  169. }
  170. else if (bits == 16)
  171. {
  172. if (channels == 1)
  173. format = AL_FORMAT_MONO16;
  174. else if (channels == 2)
  175. format = AL_FORMAT_STEREO16;
  176. }
  177. else
  178. {
  179. GP_ERROR("Incompatible wave file format: (%d, %d)", channels, bits);
  180. return false;
  181. }
  182. // Check against the size of the format header as there may be more data that we need to read.
  183. if (section_size > 16)
  184. {
  185. unsigned int length = section_size - 16;
  186. // Extension size is 2 bytes.
  187. if (fread(stream, 1, length, file) != length)
  188. {
  189. GP_ERROR("Failed to read extension size from wave file.");
  190. return false;
  191. }
  192. }
  193. // Read in the rest of the file a chunk (section) at a time.
  194. while (true)
  195. {
  196. // Check if we are at the end of the file without reading the data.
  197. if (feof(file))
  198. {
  199. GP_ERROR("Failed to load wave file; file appears to have no data.");
  200. return false;
  201. }
  202. // Read in the type of the next section of the file.
  203. if (fread(stream, 1, 4, file) != 4)
  204. {
  205. GP_ERROR("Failed to read next section type from wave file.");
  206. return false;
  207. }
  208. // Data chunk.
  209. if (memcmp(stream, "data", 4) == 0)
  210. {
  211. // Read how much data is remaining and buffer it up.
  212. unsigned int dataSize;
  213. if (fread(&dataSize, sizeof(int), 1, file) != 1)
  214. {
  215. GP_ERROR("Failed to read size of data section from wave file.");
  216. return false;
  217. }
  218. char* data = new char[dataSize];
  219. if (fread(data, sizeof(char), dataSize, file) != dataSize)
  220. {
  221. GP_ERROR("Failed to load wave file; file is missing data.");
  222. SAFE_DELETE_ARRAY(data);
  223. return false;
  224. }
  225. AL_CHECK( alBufferData(buffer, format, data, dataSize, frequency) );
  226. SAFE_DELETE_ARRAY(data);
  227. // We've read the data, so return now.
  228. return true;
  229. }
  230. // Other chunk - could be any of the following:
  231. // - Fact ("fact")
  232. // - Wave List ("wavl")
  233. // - Silent ("slnt")
  234. // - Cue ("cue ")
  235. // - Playlist ("plst")
  236. // - Associated Data List ("list")
  237. // - Label ("labl")
  238. // - Note ("note")
  239. // - Labeled Text ("ltxt")
  240. // - Sampler ("smpl")
  241. // - Instrument ("inst")
  242. else
  243. {
  244. // Store the name of the chunk so we can report errors informatively.
  245. char chunk[5] = { 0 };
  246. memcpy(chunk, stream, 4);
  247. // Read the chunk size.
  248. if (fread(stream, 1, 4, file) != 4)
  249. {
  250. GP_ERROR("Failed to read size of '%s' chunk from wave file.", chunk);
  251. return false;
  252. }
  253. section_size = stream[3]<<24;
  254. section_size |= stream[2]<<16;
  255. section_size |= stream[1]<<8;
  256. section_size |= stream[0];
  257. // Seek past the chunk.
  258. if (fseek(file, section_size, SEEK_CUR) != 0)
  259. {
  260. GP_ERROR("Failed to seek past '%s' chunk in wave file.", chunk);
  261. return false;
  262. }
  263. }
  264. }
  265. }
  266. bool AudioBuffer::loadOgg(FILE* file, ALuint buffer)
  267. {
  268. GP_ASSERT(file);
  269. OggVorbis_File ogg_file;
  270. vorbis_info* info;
  271. ALenum format;
  272. int result;
  273. int section;
  274. unsigned int size = 0;
  275. rewind(file);
  276. if ((result = ov_open(file, &ogg_file, NULL, 0)) < 0)
  277. {
  278. fclose(file);
  279. GP_ERROR("Failed to open ogg file.");
  280. return false;
  281. }
  282. info = ov_info(&ogg_file, -1);
  283. GP_ASSERT(info);
  284. if (info->channels == 1)
  285. format = AL_FORMAT_MONO16;
  286. else
  287. format = AL_FORMAT_STEREO16;
  288. // size = #samples * #channels * 2 (for 16 bit).
  289. unsigned int data_size = ov_pcm_total(&ogg_file, -1) * info->channels * 2;
  290. char* data = new char[data_size];
  291. while (size < data_size)
  292. {
  293. result = ov_read(&ogg_file, data + size, data_size - size, 0, 2, 1, &section);
  294. if (result > 0)
  295. {
  296. size += result;
  297. }
  298. else if (result < 0)
  299. {
  300. SAFE_DELETE_ARRAY(data);
  301. GP_ERROR("Failed to read ogg file; file is missing data.");
  302. return false;
  303. }
  304. else
  305. {
  306. break;
  307. }
  308. }
  309. if (size == 0)
  310. {
  311. SAFE_DELETE_ARRAY(data);
  312. GP_ERROR("Filed to read ogg file; unable to read any data.");
  313. return false;
  314. }
  315. AL_CHECK( alBufferData(buffer, format, data, data_size, info->rate) );
  316. SAFE_DELETE_ARRAY(data);
  317. ov_clear(&ogg_file);
  318. // ov_clear actually closes the file pointer as well.
  319. file = 0;
  320. return true;
  321. }
  322. }