audio_file.go 6.6 KB

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