player.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. // Copyright 2021 The Ebiten Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package audio
  15. import (
  16. "io"
  17. "runtime"
  18. "sync"
  19. "time"
  20. "github.com/hajimehoshi/oto/v2"
  21. )
  22. type context interface {
  23. NewPlayer(io.Reader) oto.Player
  24. Suspend() error
  25. Resume() error
  26. }
  27. type playerFactory struct {
  28. context context
  29. sampleRate int
  30. m sync.Mutex
  31. }
  32. var driverForTesting context
  33. func newPlayerFactory(sampleRate int) *playerFactory {
  34. f := &playerFactory{
  35. sampleRate: sampleRate,
  36. }
  37. if driverForTesting != nil {
  38. f.context = driverForTesting
  39. }
  40. // TODO: Consider the hooks.
  41. return f
  42. }
  43. type player struct {
  44. context *Context
  45. player oto.Player
  46. src io.Reader
  47. stream *timeStream
  48. factory *playerFactory
  49. m sync.Mutex
  50. }
  51. func (f *playerFactory) newPlayer(context *Context, src io.Reader) (*player, error) {
  52. f.m.Lock()
  53. defer f.m.Unlock()
  54. p := &player{
  55. src: src,
  56. context: context,
  57. factory: f,
  58. }
  59. runtime.SetFinalizer(p, (*player).Close)
  60. return p, nil
  61. }
  62. func (f *playerFactory) suspend() error {
  63. f.m.Lock()
  64. defer f.m.Unlock()
  65. if f.context == nil {
  66. return nil
  67. }
  68. return f.context.Suspend()
  69. }
  70. func (f *playerFactory) resume() error {
  71. f.m.Lock()
  72. defer f.m.Unlock()
  73. if f.context == nil {
  74. return nil
  75. }
  76. return f.context.Resume()
  77. }
  78. func (f *playerFactory) initContextIfNeeded() (<-chan struct{}, error) {
  79. f.m.Lock()
  80. defer f.m.Unlock()
  81. if f.context != nil {
  82. return nil, nil
  83. }
  84. c, ready, err := newContext(f.sampleRate, channelNum, bitDepthInBytes)
  85. if err != nil {
  86. return nil, err
  87. }
  88. f.context = c
  89. return ready, nil
  90. }
  91. func (p *player) ensurePlayer() error {
  92. // Initialize the underlying player lazily to enable calling NewContext in an 'init' function.
  93. // Accessing the underlying player functions requires the environment to be already initialized,
  94. // but if Ebiten is used for a shared library, the timing when init functions are called
  95. // is unexpectable.
  96. // e.g. a variable for JVM on Android might not be set.
  97. ready, err := p.factory.initContextIfNeeded()
  98. if err != nil {
  99. return err
  100. }
  101. if ready != nil {
  102. go func() {
  103. <-ready
  104. p.context.setReady()
  105. }()
  106. }
  107. if p.stream == nil {
  108. s, err := newTimeStream(p.src, p.factory.sampleRate)
  109. if err != nil {
  110. return err
  111. }
  112. p.stream = s
  113. }
  114. if p.player == nil {
  115. p.player = p.factory.context.NewPlayer(p.stream)
  116. }
  117. return nil
  118. }
  119. func (p *player) Play() {
  120. p.m.Lock()
  121. defer p.m.Unlock()
  122. if err := p.ensurePlayer(); err != nil {
  123. p.context.setError(err)
  124. return
  125. }
  126. if p.player.IsPlaying() {
  127. return
  128. }
  129. p.player.Play()
  130. p.context.addPlayer(p)
  131. }
  132. func (p *player) Pause() {
  133. p.m.Lock()
  134. defer p.m.Unlock()
  135. if p.player == nil {
  136. return
  137. }
  138. if !p.player.IsPlaying() {
  139. return
  140. }
  141. p.player.Pause()
  142. p.context.removePlayer(p)
  143. }
  144. func (p *player) IsPlaying() bool {
  145. p.m.Lock()
  146. defer p.m.Unlock()
  147. if p.player == nil {
  148. return false
  149. }
  150. return p.player.IsPlaying()
  151. }
  152. func (p *player) Volume() float64 {
  153. p.m.Lock()
  154. defer p.m.Unlock()
  155. if err := p.ensurePlayer(); err != nil {
  156. p.context.setError(err)
  157. return 0
  158. }
  159. return p.player.Volume()
  160. }
  161. func (p *player) SetVolume(volume float64) {
  162. p.m.Lock()
  163. defer p.m.Unlock()
  164. if err := p.ensurePlayer(); err != nil {
  165. p.context.setError(err)
  166. return
  167. }
  168. p.player.SetVolume(volume)
  169. }
  170. func (p *player) Close() error {
  171. p.m.Lock()
  172. defer p.m.Unlock()
  173. runtime.SetFinalizer(p, nil)
  174. if p.player != nil {
  175. defer func() {
  176. p.player = nil
  177. }()
  178. p.player.Pause()
  179. return p.player.Close()
  180. }
  181. return nil
  182. }
  183. func (p *player) Current() time.Duration {
  184. p.m.Lock()
  185. defer p.m.Unlock()
  186. if err := p.ensurePlayer(); err != nil {
  187. p.context.setError(err)
  188. return 0
  189. }
  190. sample := (p.stream.Current() - int64(p.player.UnplayedBufferSize())) / bytesPerSample
  191. return time.Duration(sample) * time.Second / time.Duration(p.factory.sampleRate)
  192. }
  193. func (p *player) Rewind() error {
  194. return p.Seek(0)
  195. }
  196. func (p *player) Seek(offset time.Duration) error {
  197. p.m.Lock()
  198. defer p.m.Unlock()
  199. if err := p.ensurePlayer(); err != nil {
  200. return err
  201. }
  202. if p.player.IsPlaying() {
  203. defer func() {
  204. p.player.Play()
  205. }()
  206. }
  207. p.player.Reset()
  208. return p.stream.Seek(offset)
  209. }
  210. func (p *player) Err() error {
  211. p.m.Lock()
  212. defer p.m.Unlock()
  213. if p.player == nil {
  214. return nil
  215. }
  216. return p.player.Err()
  217. }
  218. func (p *player) source() io.Reader {
  219. return p.src
  220. }
  221. type timeStream struct {
  222. r io.Reader
  223. sampleRate int
  224. pos int64
  225. // m is a mutex for this stream.
  226. // All the exported functions are protected by this mutex as Read can be read from a different goroutine than Seek.
  227. m sync.Mutex
  228. }
  229. func newTimeStream(r io.Reader, sampleRate int) (*timeStream, error) {
  230. s := &timeStream{
  231. r: r,
  232. sampleRate: sampleRate,
  233. }
  234. if seeker, ok := s.r.(io.Seeker); ok {
  235. // Get the current position of the source.
  236. pos, err := seeker.Seek(0, io.SeekCurrent)
  237. if err != nil {
  238. return nil, err
  239. }
  240. s.pos = pos
  241. }
  242. return s, nil
  243. }
  244. func (s *timeStream) Read(buf []byte) (int, error) {
  245. s.m.Lock()
  246. defer s.m.Unlock()
  247. n, err := s.r.Read(buf)
  248. s.pos += int64(n)
  249. return n, err
  250. }
  251. func (s *timeStream) Seek(offset time.Duration) error {
  252. s.m.Lock()
  253. defer s.m.Unlock()
  254. o := int64(offset) * bytesPerSample * int64(s.sampleRate) / int64(time.Second)
  255. // Align the byte position with the samples.
  256. o -= o % bytesPerSample
  257. o += s.pos % bytesPerSample
  258. seeker, ok := s.r.(io.Seeker)
  259. if !ok {
  260. panic("audio: the source must be io.Seeker when seeking but not")
  261. }
  262. pos, err := seeker.Seek(o, io.SeekStart)
  263. if err != nil {
  264. return err
  265. }
  266. s.pos = pos
  267. return nil
  268. }
  269. func (s *timeStream) Current() int64 {
  270. s.m.Lock()
  271. defer s.m.Unlock()
  272. return s.pos
  273. }