sound_resource.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. * Copyright (c) 2012-2017 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/taylor001/crown/blob/master/LICENSE
  4. */
  5. #include "core/filesystem/file.h"
  6. #include "core/json/json_object.h"
  7. #include "core/json/sjson.h"
  8. #include "core/memory/allocator.h"
  9. #include "core/memory/temp_allocator.h"
  10. #include "core/strings/dynamic_string.h"
  11. #include "resource/compile_options.h"
  12. #include "resource/sound_resource.h"
  13. namespace crown
  14. {
  15. namespace sound_resource_internal
  16. {
  17. struct WAVHeader
  18. {
  19. char riff[4]; // Should contain 'RIFF'
  20. s32 chunk_size; // Not Needed
  21. char wave[4]; // Should contain 'WAVE'
  22. char fmt[4]; // Should contain 'fmt '
  23. s32 fmt_size; // Size of format chunk
  24. s16 fmt_tag; // Identifies way data is stored, 1 means no compression
  25. s16 fmt_channels; // Channel, 1 means mono, 2 means stereo
  26. s32 fmt_sample_rate; // Samples per second
  27. s32 fmt_avarage; // Avarage bytes per sample
  28. s16 fmt_block_align; // Block alignment
  29. s16 fmt_bits_ps; // Number of bits per sample
  30. char data[4]; // Should contain 'data'
  31. s32 data_size; // Data dimension
  32. };
  33. void compile(CompileOptions& opts)
  34. {
  35. Buffer buf = opts.read();
  36. TempAllocator4096 ta;
  37. JsonObject object(ta);
  38. sjson::parse(buf, object);
  39. DynamicString name(ta);
  40. sjson::parse_string(object["source"], name);
  41. Buffer sound = opts.read(name.c_str());
  42. const WAVHeader* wav = (const WAVHeader*)array::begin(sound);
  43. const char* wavdata = (const char*)&wav[1];
  44. // Write
  45. SoundResource sr;
  46. sr.version = RESOURCE_VERSION_SOUND;
  47. sr.size = wav->data_size;
  48. sr.sample_rate = wav->fmt_sample_rate;
  49. sr.avg_bytes_ps = wav->fmt_avarage;
  50. sr.channels = wav->fmt_channels;
  51. sr.block_size = wav->fmt_block_align;
  52. sr.bits_ps = wav->fmt_bits_ps;
  53. sr.sound_type = SoundType::WAV;
  54. opts.write(sr.version);
  55. opts.write(sr.size);
  56. opts.write(sr.sample_rate);
  57. opts.write(sr.avg_bytes_ps);
  58. opts.write(sr.channels);
  59. opts.write(sr.block_size);
  60. opts.write(sr.bits_ps);
  61. opts.write(sr.sound_type);
  62. opts.write(wavdata, wav->data_size);
  63. }
  64. } // namespace sound_resource_internal
  65. namespace sound_resource
  66. {
  67. const char* data(const SoundResource* sr)
  68. {
  69. return (char*)&sr[1];
  70. }
  71. } // namespace sound_resource
  72. } // namespace crown