@@ -175,7 +175,7 @@ type playerImpl struct {
175
175
volume float64
176
176
err error
177
177
state playerState
178
- tmpbuf [] byte
178
+ bufPool * sync. Pool
179
179
buf []byte
180
180
eof bool
181
181
bufferSize int
@@ -246,15 +246,32 @@ func (p *playerImpl) setBufferSize(bufferSize int) {
246
246
p .bufferSize = p .mux .defaultBufferSize ()
247
247
}
248
248
if orig != p .bufferSize {
249
- p .tmpbuf = nil
249
+ p .bufPool = & sync.Pool {
250
+ New : func () interface {} {
251
+ buf := make ([]byte , p .bufferSize )
252
+ return & buf
253
+ },
254
+ }
250
255
}
251
256
}
252
257
253
- func (p * playerImpl ) ensureTmpBuf () []byte {
254
- if p .tmpbuf == nil {
255
- p .tmpbuf = make ([]byte , p .bufferSize )
258
+ func (p * playerImpl ) getTmpBuf () ([]byte , func ()) {
259
+ // The returned buffer could be accessed regardless of the mutex m (#254).
260
+ // In order to oavoid races, use a sync.Pool.
261
+ // On the other hand, the calls of getTmpBuf itself should be protected by the mutex m,
262
+ // then accessing p.bufPool doesn't cause races.
263
+ if p .bufPool == nil {
264
+ p .bufPool = & sync.Pool {
265
+ New : func () interface {} {
266
+ buf := make ([]byte , p .bufferSize )
267
+ return & buf
268
+ },
269
+ }
270
+ }
271
+ buf := p .bufPool .Get ().(* []byte )
272
+ return * buf , func () {
273
+ p .bufPool .Put (buf )
256
274
}
257
- return p .tmpbuf
258
275
}
259
276
260
277
// read reads the source to buf.
@@ -296,7 +313,8 @@ func (p *playerImpl) playImpl() {
296
313
p .state = playerPlay
297
314
298
315
if ! p .eof {
299
- buf := p .ensureTmpBuf ()
316
+ buf , free := p .getTmpBuf ()
317
+ defer free ()
300
318
for len (p .buf ) < p .bufferSize {
301
319
n , err := p .read (buf )
302
320
if err != nil && err != io .EOF {
@@ -525,7 +543,8 @@ func (p *playerImpl) readSourceToBuffer() int {
525
543
return 0
526
544
}
527
545
528
- buf := p .ensureTmpBuf ()
546
+ buf , free := p .getTmpBuf ()
547
+ defer free ()
529
548
n , err := p .read (buf )
530
549
531
550
if err != nil && err != io .EOF {
0 commit comments