audio_file.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. // Copyright 2016 The G3N Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package audio
  5. import (
  6. "fmt"
  7. "github.com/g3n/engine/audio/al"
  8. "github.com/g3n/engine/audio/ov"
  9. "io"
  10. "os"
  11. "unsafe"
  12. )
  13. // AudioInfo represents the information associated to an audio file
  14. type AudioInfo struct {
  15. Format int // OpenAl Format
  16. Channels int // Number of channels
  17. SampleRate int // Sample rate in hz
  18. BitsSample int // Number of bits per sample (8 or 16)
  19. DataSize int // Total data size in bytes
  20. BytesSec int // Bytes per second
  21. TotalTime float64 // Total time in seconds
  22. }
  23. // AudioFile represents an audio file
  24. type AudioFile struct {
  25. wavef *os.File // Pointer to wave file opened filed (nil for vorbis)
  26. vorbisf *ov.File // Pointer to vorbis file structure (nil for wave)
  27. info AudioInfo // Audio information structure
  28. looping bool // Looping flag
  29. }
  30. // NewAudioFile creates and returns a pointer to a new audio file object and an error
  31. func NewAudioFile(filename string) (*AudioFile, error) {
  32. // Checks if file exists
  33. _, err := os.Stat(filename)
  34. if err != nil {
  35. return nil, err
  36. }
  37. af := new(AudioFile)
  38. // Try to open as a wave file
  39. if af.openWave(filename) == nil {
  40. return af, nil
  41. }
  42. // Try to open as an ogg vorbis file
  43. if af.openVorbis(filename) == nil {
  44. return af, nil
  45. }
  46. return nil, fmt.Errorf("Unsuported file type")
  47. }
  48. // Close closes the audiofile
  49. func (af *AudioFile) Close() error {
  50. if af.wavef != nil {
  51. return af.wavef.Close()
  52. }
  53. return ov.Clear(af.vorbisf)
  54. }
  55. // Read reads decoded data from the audio file
  56. func (af *AudioFile) Read(pdata unsafe.Pointer, nbytes int) (int, error) {
  57. // Slice to access buffer
  58. bs := (*[1 << 30]byte)(pdata)[0:nbytes:nbytes]
  59. // Reads wave file directly
  60. if af.wavef != nil {
  61. n, err := af.wavef.Read(bs)
  62. if err != nil {
  63. return 0, err
  64. }
  65. if !af.looping {
  66. return n, nil
  67. }
  68. if n == nbytes {
  69. return n, nil
  70. }
  71. // EOF reached. Position file at the beginning
  72. _, err = af.wavef.Seek(int64(waveHeaderSize), 0)
  73. if err != nil {
  74. return 0, nil
  75. }
  76. // Reads next data into the remaining buffer space
  77. n2, err := af.wavef.Read(bs[n:])
  78. if err != nil {
  79. return 0, err
  80. }
  81. return n + n2, err
  82. }
  83. // Decodes Ogg vorbis
  84. decoded := 0
  85. for decoded < nbytes {
  86. n, _, err := ov.Read(af.vorbisf, unsafe.Pointer(&bs[decoded]), nbytes-decoded, false, 2, true)
  87. // Error
  88. if err != nil {
  89. return 0, err
  90. }
  91. // EOF
  92. if n == 0 {
  93. if !af.looping {
  94. break
  95. }
  96. // Position file at the beginning
  97. err = ov.PcmSeek(af.vorbisf, 0)
  98. if err != nil {
  99. return 0, err
  100. }
  101. }
  102. decoded += n
  103. }
  104. if nbytes > 0 && decoded == 0 {
  105. return 0, io.EOF
  106. }
  107. return decoded, nil
  108. }
  109. // Seek sets the file reading position relative to the origin
  110. func (af *AudioFile) Seek(pos uint) error {
  111. if af.wavef != nil {
  112. _, err := af.wavef.Seek(int64(waveHeaderSize+pos), 0)
  113. return err
  114. }
  115. return ov.PcmSeek(af.vorbisf, int64(pos))
  116. }
  117. // Info returns the audio info structure for this audio file
  118. func (af *AudioFile) Info() AudioInfo {
  119. return af.info
  120. }
  121. // CurrentTime returns the current time in seconds for the current file read position
  122. func (af *AudioFile) CurrentTime() float64 {
  123. if af.vorbisf != nil {
  124. pos, _ := ov.TimeTell(af.vorbisf)
  125. return pos
  126. }
  127. pos, err := af.wavef.Seek(0, 1)
  128. if err != nil {
  129. return 0
  130. }
  131. return float64(pos) / float64(af.info.BytesSec)
  132. }
  133. // Looping returns the current looping state of this audio file
  134. func (af *AudioFile) Looping() bool {
  135. return af.looping
  136. }
  137. // SetLooping sets the looping state of this audio file
  138. func (af *AudioFile) SetLooping(looping bool) {
  139. af.looping = looping
  140. }
  141. // openWave tries to open the specified file as a wave file
  142. // and if succesfull, sets the file pointer positioned after the header.
  143. func (af *AudioFile) openWave(filename string) error {
  144. // Open file
  145. osf, err := os.Open(filename)
  146. if err != nil {
  147. return err
  148. }
  149. // Reads header
  150. header := make([]uint8, waveHeaderSize)
  151. n, err := osf.Read(header)
  152. if err != nil {
  153. osf.Close()
  154. return err
  155. }
  156. if n < waveHeaderSize {
  157. osf.Close()
  158. return fmt.Errorf("File size less than header")
  159. }
  160. // Checks file marks
  161. if string(header[0:4]) != fileMark {
  162. osf.Close()
  163. return fmt.Errorf("'RIFF' mark not found")
  164. }
  165. if string(header[8:12]) != fileHead {
  166. osf.Close()
  167. return fmt.Errorf("'WAVE' mark not found")
  168. }
  169. // Decodes header fields
  170. af.info.Format = -1
  171. af.info.Channels = int(header[22]) + int(header[23])<<8
  172. af.info.SampleRate = int(header[24]) + int(header[25])<<8 + int(header[26])<<16 + int(header[27])<<24
  173. af.info.BitsSample = int(header[34]) + int(header[35])<<8
  174. af.info.DataSize = int(header[40]) + int(header[41])<<8 + int(header[42])<<16 + int(header[43])<<24
  175. // Sets OpenAL format field if possible
  176. if af.info.Channels == 1 {
  177. if af.info.BitsSample == 8 {
  178. af.info.Format = al.FormatMono8
  179. } else if af.info.BitsSample == 16 {
  180. af.info.Format = al.FormatMono16
  181. }
  182. } else if af.info.Channels == 2 {
  183. if af.info.BitsSample == 8 {
  184. af.info.Format = al.FormatStereo8
  185. } else if af.info.BitsSample == 16 {
  186. af.info.Format = al.FormatStereo16
  187. }
  188. }
  189. if af.info.Format == -1 {
  190. osf.Close()
  191. return fmt.Errorf("Unsupported OpenAL format")
  192. }
  193. // Calculates bytes/sec and total time
  194. var bytesChannel int
  195. if af.info.BitsSample == 8 {
  196. bytesChannel = 1
  197. } else {
  198. bytesChannel = 2
  199. }
  200. af.info.BytesSec = af.info.SampleRate * af.info.Channels * bytesChannel
  201. af.info.TotalTime = float64(af.info.DataSize) / float64(af.info.BytesSec)
  202. // Seeks after the header
  203. _, err = osf.Seek(waveHeaderSize, 0)
  204. if err != nil {
  205. osf.Close()
  206. return err
  207. }
  208. af.wavef = osf
  209. return nil
  210. }
  211. // openVorbis tries to open the specified file as an ogg vorbis file
  212. // and if succesfull, sets up the player for playing this file
  213. func (af *AudioFile) openVorbis(filename string) error {
  214. // Try to open file as ogg vorbis
  215. vf, err := ov.Fopen(filename)
  216. if err != nil {
  217. return err
  218. }
  219. // Get info for opened vorbis file
  220. var info ov.VorbisInfo
  221. err = ov.Info(vf, -1, &info)
  222. if err != nil {
  223. return err
  224. }
  225. if info.Channels == 1 {
  226. af.info.Format = al.FormatMono16
  227. } else if info.Channels == 2 {
  228. af.info.Format = al.FormatStereo16
  229. } else {
  230. return fmt.Errorf("Unsupported number of channels")
  231. }
  232. totalSamples, err := ov.PcmTotal(vf, -1)
  233. if err != nil {
  234. ov.Clear(vf)
  235. return nil
  236. }
  237. timeTotal, err := ov.TimeTotal(vf, -1)
  238. if err != nil {
  239. ov.Clear(vf)
  240. return nil
  241. }
  242. af.vorbisf = vf
  243. af.info.SampleRate = info.Rate
  244. af.info.BitsSample = 16
  245. af.info.Channels = info.Channels
  246. af.info.DataSize = int(totalSamples) * info.Channels * 2
  247. af.info.TotalTime = timeTotal
  248. return nil
  249. }