audio_file.go 6.7 KB

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