ebiten/audio/mp3/decode_notjs.go

112 lines
2.1 KiB
Go
Raw Normal View History

2017-06-11 11:12:12 +02:00
// Copyright 2017 The Ebiten Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// +build !js
package mp3
// #include "pdmp3.h"
import "C"
import (
"errors"
"io"
"unsafe"
)
const (
eof = 0xffffffff
)
var (
reader io.Reader
readerCache []uint8
readerPos int
readerEOF bool
writer io.Writer
)
2017-06-16 18:36:58 +02:00
func getByte() (uint8, error) {
2017-06-11 11:12:12 +02:00
for len(readerCache) == 0 && !readerEOF {
buf := make([]uint8, 4096)
n, err := reader.Read(buf)
readerCache = append(readerCache, buf[:n]...)
2017-06-11 11:12:12 +02:00
if err != nil {
if err == io.EOF {
readerEOF = true
} else {
2017-06-16 18:36:58 +02:00
return 0, err
2017-06-11 11:12:12 +02:00
}
}
}
2017-06-16 17:34:54 +02:00
if len(readerCache) == 0 {
2017-06-16 18:36:58 +02:00
return 0, io.EOF
2017-06-11 11:12:12 +02:00
}
b := readerCache[0]
readerCache = readerCache[1:]
readerPos++
2017-06-16 18:36:58 +02:00
return b, nil
2017-06-11 11:12:12 +02:00
}
2017-06-16 17:34:54 +02:00
func getBytes(buf []int) (int, error) {
for i := range buf {
2017-06-16 18:36:58 +02:00
v, err := getByte()
buf[i] = int(v)
if err == io.EOF {
2017-06-16 17:34:54 +02:00
return i, io.EOF
2017-06-12 19:49:15 +02:00
}
}
2017-06-16 17:34:54 +02:00
return len(buf), nil
2017-06-12 19:49:15 +02:00
}
2017-06-11 11:12:12 +02:00
//export Get_Filepos
func Get_Filepos() C.unsigned {
if len(readerCache) == 0 && readerEOF {
return eof
}
return C.unsigned(readerPos)
}
//export writeToWriter
func writeToWriter(data unsafe.Pointer, size C.int) C.size_t {
buf := C.GoBytes(data, size)
n, err := writer.Write(buf)
if err != nil {
panic(err)
}
return C.size_t(n)
}
2017-06-12 16:32:56 +02:00
var g_error error
2017-06-11 11:12:12 +02:00
func decode(r io.Reader, w io.Writer) error {
reader = r
writer = w
for Get_Filepos() != eof {
2017-06-16 19:43:13 +02:00
err := readFrame()
if err == nil {
2017-06-11 11:12:12 +02:00
C.Decode_L3()
continue
}
if Get_Filepos() == eof {
break
}
2017-06-16 19:43:13 +02:00
if err != nil {
return err
}
2017-06-11 11:12:12 +02:00
return errors.New("mp3: not enough maindata to decode frame")
}
2017-06-12 16:32:56 +02:00
return g_error
2017-06-11 11:12:12 +02:00
}