audio_file.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. type AudioInfo struct {
  14. Format int // OpenAl Format
  15. Channels int // Number of channels
  16. SampleRate int // Sample rate in hz
  17. BitsSample int // Number of bits per sample (8 or 16)
  18. DataSize int // Total data size in bytes
  19. BytesSec int // Bytes per second
  20. TotalTime float64 // Total time in seconds
  21. }
  22. type AudioFile struct {
  23. wavef *os.File // Pointer to wave file opened filed (nil for vorbis)
  24. vorbisf *ov.File // Pointer to vorbis file structure (nil for wave)
  25. info AudioInfo // Audio information structure
  26. looping bool // Looping flag
  27. }
  28. // NewAudioFile creates and returns a pointer to a new audio file object and an error
  29. func NewAudioFile(filename string) (*AudioFile, error) {
  30. // Checks if file exists
  31. _, err := os.Stat(filename)
  32. if err != nil {
  33. return nil, err
  34. }
  35. af := new(AudioFile)
  36. // Try to open as a wave file
  37. if af.openWave(filename) == nil {
  38. return af, nil
  39. }
  40. // Try to open as an ogg vorbis file
  41. if af.openVorbis(filename) == nil {
  42. return af, nil
  43. }
  44. return nil, fmt.Errorf("Unsuported file type")
  45. }
  46. // Close closes the audiofile
  47. func (af *AudioFile) Close() error {
  48. if af.wavef != nil {
  49. return af.wavef.Close()
  50. }
  51. return ov.Clear(af.vorbisf)
  52. }
  53. // Read reads decoded data from the audio file
  54. func (af *AudioFile) Read(pdata unsafe.Pointer, nbytes int) (int, error) {
  55. // Slice to access buffer
  56. bs := (*[1 << 30]byte)(pdata)[0:nbytes:nbytes]
  57. // Reads wave file directly
  58. if af.wavef != nil {
  59. n, err := af.wavef.Read(bs)
  60. if err != nil {
  61. return 0, err
  62. }
  63. if !af.looping {
  64. return n, nil
  65. }
  66. if n == nbytes {
  67. return n, nil
  68. }
  69. // EOF reached. Position file at the beginning
  70. _, err = af.wavef.Seek(int64(waveHeaderSize), 0)
  71. if err != nil {
  72. return 0, nil
  73. }
  74. // Reads next data into the remaining buffer space
  75. n2, err := af.wavef.Read(bs[n:])
  76. if err != nil {
  77. return 0, err
  78. }
  79. return n + n2, err
  80. }
  81. // Decodes Ogg vorbis
  82. decoded := 0
  83. for decoded < nbytes {
  84. n, _, err := ov.Read(af.vorbisf, unsafe.Pointer(&bs[decoded]), nbytes-decoded, false, 2, true)
  85. // Error
  86. if err != nil {
  87. return 0, err
  88. }
  89. // EOF
  90. if n == 0 {
  91. if !af.looping {
  92. break
  93. }
  94. // Position file at the beginning
  95. err = ov.PcmSeek(af.vorbisf, 0)
  96. if err != nil {
  97. return 0, err
  98. }
  99. }
  100. decoded += n
  101. }
  102. if nbytes > 0 && decoded == 0 {
  103. return 0, io.EOF
  104. }
  105. return decoded, nil
  106. }
  107. // Seek sets the file reading position relative to the origin
  108. func (af *AudioFile) Seek(pos uint) error {
  109. if af.wavef != nil {
  110. _, err := af.wavef.Seek(int64(waveHeaderSize+pos), 0)
  111. return err
  112. }
  113. return ov.PcmSeek(af.vorbisf, int64(pos))
  114. }
  115. // AudioInfo returns the audio info structure for this audio file
  116. func (af *AudioFile) Info() AudioInfo {
  117. return af.info
  118. }
  119. // CurrenTime returns the current time in seconds for the current
  120. // file read position
  121. func (af *AudioFile) CurrentTime() float64 {
  122. if af.vorbisf != nil {
  123. pos, _ := ov.TimeTell(af.vorbisf)
  124. return pos
  125. } else {
  126. pos, err := af.wavef.Seek(0, 1)
  127. if err != nil {
  128. return 0
  129. }
  130. return float64(pos) / float64(af.info.BytesSec)
  131. }
  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. // Checks for Ogg Vorbis support
  215. if !ov.IsLoaded() {
  216. return fmt.Errorf("Unsupported file type")
  217. }
  218. // Try to open file as ogg vorbis
  219. vf, err := ov.Fopen(filename)
  220. if err != nil {
  221. return err
  222. }
  223. // Get info for opened vorbis file
  224. var info ov.VorbisInfo
  225. err = ov.Info(vf, -1, &info)
  226. if err != nil {
  227. return err
  228. }
  229. if info.Channels == 1 {
  230. af.info.Format = al.FormatMono16
  231. } else if info.Channels == 2 {
  232. af.info.Format = al.FormatStereo16
  233. } else {
  234. return fmt.Errorf("Unsupported number of channels")
  235. }
  236. totalSamples, err := ov.PcmTotal(vf, -1)
  237. if err != nil {
  238. ov.Clear(vf)
  239. return nil
  240. }
  241. timeTotal, err := ov.TimeTotal(vf, -1)
  242. if err != nil {
  243. ov.Clear(vf)
  244. return nil
  245. }
  246. af.vorbisf = vf
  247. af.info.SampleRate = info.Rate
  248. af.info.BitsSample = 16
  249. af.info.Channels = info.Channels
  250. af.info.DataSize = int(totalSamples) * info.Channels * 2
  251. af.info.TotalTime = timeTotal
  252. return nil
  253. }