loop.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. // Copyright 2017 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. "fmt"
  17. "io"
  18. "math"
  19. )
  20. // InfiniteLoop represents a looped stream which never ends.
  21. type InfiniteLoop struct {
  22. src io.ReadSeeker
  23. lstart int64
  24. llength int64
  25. pos int64
  26. bitDepthInBytes int
  27. bytesPerSample int
  28. // extra is the remainder in the case when the read byte sizes are not multiple of the bit depth.
  29. extra []byte
  30. // afterLoop is data after the loop.
  31. afterLoop []byte
  32. // blending represents whether the loop start and afterLoop are blended or not.
  33. blending bool
  34. noBlendForTesting bool
  35. }
  36. // NewInfiniteLoop creates a new infinite loop stream with a source stream and length in bytes.
  37. //
  38. // src is a signed 16bit integer little endian stream, 2 channels (stereo).
  39. //
  40. // If the loop's total length is exactly the same as src's length, you might hear noises around the loop joint.
  41. // This noise can be heard especially when src is decoded from a lossy compression format like Ogg/Vorbis and MP3.
  42. // In this case, try to add more (about 0.1[s]) data to src after the loop end.
  43. // If src has data after the loop end, an InfiniteLoop uses part of the data to blend with the loop start
  44. // to make the loop joint smooth.
  45. func NewInfiniteLoop(src io.ReadSeeker, length int64) *InfiniteLoop {
  46. return newInfiniteLoopWithIntro(src, 0, length, bitDepthInBytesInt16)
  47. }
  48. // NewInfiniteLoopF32 creates a new infinite loop stream with a source stream and length in bytes.
  49. //
  50. // src is a 32bit float little endian stream, 2 channels (stereo).
  51. //
  52. // If the loop's total length is exactly the same as src's length, you might hear noises around the loop joint.
  53. // This noise can be heard especially when src is decoded from a lossy compression format like Ogg/Vorbis and MP3.
  54. // In this case, try to add more (about 0.1[s]) data to src after the loop end.
  55. // If src has data after the loop end, an InfiniteLoop uses part of the data to blend with the loop start
  56. // to make the loop joint smooth.
  57. func NewInfiniteLoopF32(src io.ReadSeeker, length int64) *InfiniteLoop {
  58. return newInfiniteLoopWithIntro(src, 0, length, bitDepthInBytesFloat32)
  59. }
  60. // NewInfiniteLoopWithIntro creates a new infinite loop stream with an intro part.
  61. // NewInfiniteLoopWithIntro accepts a source stream src, introLength in bytes and loopLength in bytes.
  62. //
  63. // src is a signed 16bit integer little endian stream, 2 channels (stereo).
  64. //
  65. // If the loop's total length is exactly the same as src's length, you might hear noises around the loop joint.
  66. // This noise can be heard especially when src is decoded from a lossy compression format like Ogg/Vorbis and MP3.
  67. // In this case, try to add more (about 0.1[s]) data to src after the loop end.
  68. // If src has data after the loop end, an InfiniteLoop uses part of the data to blend with the loop start
  69. // to make the loop joint smooth.
  70. func NewInfiniteLoopWithIntro(src io.ReadSeeker, introLength int64, loopLength int64) *InfiniteLoop {
  71. return newInfiniteLoopWithIntro(src, introLength, loopLength, bitDepthInBytesInt16)
  72. }
  73. // NewInfiniteLoopWithIntroF32 creates a new infinite loop stream with an intro part.
  74. // NewInfiniteLoopWithIntroF32 accepts a source stream src, introLength in bytes and loopLength in bytes.
  75. //
  76. // src is a 32bit float little endian stream, 2 channels (stereo).
  77. //
  78. // If the loop's total length is exactly the same as src's length, you might hear noises around the loop joint.
  79. // This noise can be heard especially when src is decoded from a lossy compression format like Ogg/Vorbis and MP3.
  80. // In this case, try to add more (about 0.1[s]) data to src after the loop end.
  81. // If src has data after the loop end, an InfiniteLoop uses part of the data to blend with the loop start
  82. // to make the loop joint smooth.
  83. func NewInfiniteLoopWithIntroF32(src io.ReadSeeker, introLength int64, loopLength int64) *InfiniteLoop {
  84. return newInfiniteLoopWithIntro(src, introLength, loopLength, bitDepthInBytesFloat32)
  85. }
  86. func newInfiniteLoopWithIntro(src io.ReadSeeker, introLength int64, loopLength int64, bitDepthInBytes int) *InfiniteLoop {
  87. bytesPerSample := bitDepthInBytes * channelCount
  88. return &InfiniteLoop{
  89. src: src,
  90. lstart: introLength / int64(bytesPerSample) * int64(bytesPerSample),
  91. llength: loopLength / int64(bytesPerSample) * int64(bytesPerSample),
  92. pos: -1,
  93. bitDepthInBytes: bitDepthInBytes,
  94. bytesPerSample: bytesPerSample,
  95. }
  96. }
  97. func (i *InfiniteLoop) length() int64 {
  98. return i.lstart + i.llength
  99. }
  100. func (i *InfiniteLoop) ensurePos() error {
  101. if i.pos >= 0 {
  102. return nil
  103. }
  104. pos, err := i.src.Seek(0, io.SeekCurrent)
  105. if err != nil {
  106. return err
  107. }
  108. if pos >= i.length() {
  109. return fmt.Errorf("audio: stream position must be less than the specified length")
  110. }
  111. i.pos = pos
  112. return nil
  113. }
  114. func (i *InfiniteLoop) blendRate(pos int64) float32 {
  115. if pos < i.lstart {
  116. return 0
  117. }
  118. if pos >= i.lstart+int64(len(i.afterLoop)) {
  119. return 0
  120. }
  121. p := (pos - i.lstart) / int64(i.bytesPerSample)
  122. l := len(i.afterLoop) / i.bytesPerSample
  123. return 1 - float32(p)/float32(l)
  124. }
  125. // Read is implementation of ReadSeeker's Read.
  126. func (i *InfiniteLoop) Read(b []byte) (int, error) {
  127. if err := i.ensurePos(); err != nil {
  128. return 0, err
  129. }
  130. if i.pos+int64(len(b)) > i.length() {
  131. b = b[:i.length()-i.pos]
  132. }
  133. extralen := len(i.extra)
  134. copy(b, i.extra)
  135. i.extra = i.extra[:0]
  136. n, err := i.src.Read(b[extralen:])
  137. n += extralen
  138. i.pos += int64(n)
  139. if i.pos > i.length() {
  140. panic(fmt.Sprintf("audio: position must be <= length but not at (*InfiniteLoop).Read: pos: %d, length: %d", i.pos, i.length()))
  141. }
  142. // Save the remainder part to extra. This will be used at the next Read.
  143. if rem := n % i.bitDepthInBytes; rem != 0 {
  144. i.extra = append(i.extra, b[n-rem:n]...)
  145. b = b[:n-rem]
  146. n = n - rem
  147. }
  148. // Blend afterLoop and the loop start to reduce noises (#1888).
  149. // Ideally, afterLoop and the loop start should be identical, but they can have very slight differences.
  150. if !i.noBlendForTesting && i.blending && i.pos >= i.lstart && i.pos-int64(n) < i.lstart+int64(len(i.afterLoop)) {
  151. if n%i.bitDepthInBytes != 0 {
  152. panic(fmt.Sprintf("audio: n must be a multiple of bit depth %d [bytes] but not: %d", i.bitDepthInBytes, n))
  153. }
  154. for idx := 0; idx < n/i.bitDepthInBytes; idx++ {
  155. abspos := i.pos - int64(n) + int64(idx)*int64(i.bitDepthInBytes)
  156. rate := i.blendRate(abspos)
  157. if rate == 0 {
  158. continue
  159. }
  160. relpos := abspos - i.lstart
  161. switch i.bitDepthInBytes {
  162. case 2:
  163. afterLoop := int16(i.afterLoop[relpos]) | (int16(i.afterLoop[relpos+1]) << 8)
  164. orig := int16(b[2*idx]) | (int16(b[2*idx+1]) << 8)
  165. newVal := int16(float32(afterLoop)*rate + float32(orig)*(1-rate))
  166. b[2*idx] = byte(newVal)
  167. b[2*idx+1] = byte(newVal >> 8)
  168. case 4:
  169. afterLoop := math.Float32frombits(uint32(i.afterLoop[relpos]) | (uint32(i.afterLoop[relpos+1]) << 8) | (uint32(i.afterLoop[relpos+2]) << 16) | (uint32(i.afterLoop[relpos+3]) << 24))
  170. orig := math.Float32frombits(uint32(b[4*idx]) | (uint32(b[4*idx+1]) << 8) | (uint32(b[4*idx+2]) << 16) | (uint32(b[4*idx+3]) << 24))
  171. newVal := float32(afterLoop*rate + orig*(1-rate))
  172. newValBits := math.Float32bits(newVal)
  173. b[4*idx] = byte(newValBits)
  174. b[4*idx+1] = byte(newValBits >> 8)
  175. b[4*idx+2] = byte(newValBits >> 16)
  176. b[4*idx+3] = byte(newValBits >> 24)
  177. default:
  178. panic("not reached")
  179. }
  180. }
  181. }
  182. if err != nil && err != io.EOF {
  183. return 0, err
  184. }
  185. // Read the afterLoop part if necessary.
  186. if i.pos == i.length() && err == nil {
  187. if i.afterLoop == nil {
  188. buflen := int64(256 * i.bytesPerSample)
  189. if buflen > i.length() {
  190. buflen = i.length()
  191. }
  192. buf := make([]byte, buflen)
  193. pos := 0
  194. for pos < len(buf) {
  195. n, err := i.src.Read(buf[pos:])
  196. if err != nil && err != io.EOF {
  197. return 0, err
  198. }
  199. pos += n
  200. if err == io.EOF {
  201. break
  202. }
  203. }
  204. i.afterLoop = buf[:pos]
  205. }
  206. if len(i.afterLoop) > 0 {
  207. i.blending = true
  208. }
  209. }
  210. if i.pos == i.length() || err == io.EOF {
  211. // Ignore the new position returned by Seek since the source position might not be match with the position
  212. // managed by this.
  213. if _, err := i.src.Seek(i.lstart, io.SeekStart); err != nil {
  214. return 0, err
  215. }
  216. i.pos = i.lstart
  217. }
  218. return n, nil
  219. }
  220. // Seek is implementation of ReadSeeker's Seek.
  221. func (i *InfiniteLoop) Seek(offset int64, whence int) (int64, error) {
  222. i.blending = false
  223. if err := i.ensurePos(); err != nil {
  224. return 0, err
  225. }
  226. next := int64(0)
  227. switch whence {
  228. case io.SeekStart:
  229. next = offset
  230. case io.SeekCurrent:
  231. next = i.pos + offset
  232. case io.SeekEnd:
  233. return 0, fmt.Errorf("audio: whence must be io.SeekStart or io.SeekCurrent for InfiniteLoop")
  234. }
  235. if next < 0 {
  236. return 0, fmt.Errorf("audio: position must >= 0")
  237. }
  238. if next > i.lstart {
  239. next = ((next - i.lstart) % i.llength) + i.lstart
  240. }
  241. // Ignore the new position returned by Seek since the source position might not be match with the position
  242. // managed by this.
  243. if _, err := i.src.Seek(next, io.SeekStart); err != nil {
  244. return 0, err
  245. }
  246. i.pos = next
  247. return i.pos, nil
  248. }