audio/mp3: refactoring

This commit is contained in:
Hajime Hoshi 2024-07-21 17:00:46 +09:00
parent a6a6709163
commit 1d7c350967

View File

@ -33,33 +33,24 @@ const (
// Stream is a decoded stream. // Stream is a decoded stream.
type Stream struct { type Stream struct {
orig *mp3.Decoder readSeeker io.ReadSeeker
resampling *convert.Resampling length int64
sampleRate int sampleRate int
} }
// Read is implementation of io.Reader's Read. // Read is implementation of io.Reader's Read.
func (s *Stream) Read(buf []byte) (int, error) { func (s *Stream) Read(buf []byte) (int, error) {
if s.resampling != nil { return s.readSeeker.Read(buf)
return s.resampling.Read(buf)
}
return s.orig.Read(buf)
} }
// Seek is implementation of io.Seeker's Seek. // Seek is implementation of io.Seeker's Seek.
func (s *Stream) Seek(offset int64, whence int) (int64, error) { func (s *Stream) Seek(offset int64, whence int) (int64, error) {
if s.resampling != nil { return s.readSeeker.Seek(offset, whence)
return s.resampling.Seek(offset, whence)
}
return s.orig.Seek(offset, whence)
} }
// Length returns the size of decoded stream in bytes. // Length returns the size of decoded stream in bytes.
func (s *Stream) Length() int64 { func (s *Stream) Length() int64 {
if s.resampling != nil { return s.length
return s.resampling.Length()
}
return s.orig.Length()
} }
// SampleRate returns the sample rate of the decoded stream. // SampleRate returns the sample rate of the decoded stream.
@ -81,8 +72,8 @@ func DecodeWithoutResampling(src io.Reader) (*Stream, error) {
return nil, err return nil, err
} }
s := &Stream{ s := &Stream{
orig: d, readSeeker: d,
resampling: nil, length: d.Length(),
sampleRate: d.SampleRate(), sampleRate: d.SampleRate(),
} }
return s, nil return s, nil
@ -107,13 +98,16 @@ func DecodeWithSampleRate(sampleRate int, src io.Reader) (*Stream, error) {
return nil, err return nil, err
} }
var r *convert.Resampling var r io.ReadSeeker = d
length := d.Length()
if d.SampleRate() != sampleRate { if d.SampleRate() != sampleRate {
r = convert.NewResampling(d, d.Length(), d.SampleRate(), sampleRate, bitDepthInBytesInt16) r2 := convert.NewResampling(d, d.Length(), d.SampleRate(), sampleRate, bitDepthInBytesInt16)
r = r2
length = r2.Length()
} }
s := &Stream{ s := &Stream{
orig: d, readSeeker: r,
resampling: r, length: length,
sampleRate: sampleRate, sampleRate: sampleRate,
} }
return s, nil return s, nil