audio_file.go 6.7 KB

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