feat: port the client to MyGo native UI (0.3.0)
Switch from Asuka to MyGo, keeping the API client and the feature set: - servers: saved servers, passwordless and password login, proxy, self-signed certificates, per-server device tokens (Keystore), connect form, instance list sheet with switch/disconnect - sessions: virtualized list, search, new session, rename/archive/delete, running indicator, event stream keeps it live - chat: pushed window with system back bar, streaming Markdown via ui/markdown, reasoning and tool rows with image previews, footer menu (read aloud via a Kotlin TTS plugin, copy, fork), user message menu (copy, revert, fork), context usage ring and detail sheet, attachments (photos/files via the document picker), permissions - release builds allow plain http:// LAN servers (Go's net/http dials directly, no cleartext manifest needed) - a local fork of MyGo (third_party/mygo) lowers the Android host's minSdk to 24 (Android 7.0); Go 1.27.4 via mise Version 0.3.0.
This commit is contained in:
1 parent
2fb4a8ea79
commit
6c0ee61750
2538 files changed
+675779
-4792
No files matched your search
Vendored
+538
@@ -0,0 +1,538 @@
|
||||
package mp4
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"math/bits"
|
||||
)
|
||||
|
||||
// An ALAC decoder decodes Apple Lossless packets, as an MP4 holds them, after
|
||||
// Apple's own decoder (https://github.com/macosforge/alac, under the Apache
|
||||
// License 2.0): each packet a frame of up to frameLength
|
||||
// samples a channel, adaptively Golomb coded, then predicted from the samples
|
||||
// before it. It gives stereo, of a mono file in both ears.
|
||||
type alacDecoder struct {
|
||||
frameLength uint32
|
||||
bitDepth uint8
|
||||
pb, mb, kb uint8
|
||||
channels uint8
|
||||
rate uint32
|
||||
predictor []int32
|
||||
u, v []int32 // a channel pair's, mixed
|
||||
shift []uint16
|
||||
left, right []int32 // the channels kept: the front pair
|
||||
leftCh, rightCh int
|
||||
bitsPerSample float32
|
||||
coefsU, coefsV [32]int16
|
||||
packet []byte // the last, with zeros after it
|
||||
}
|
||||
|
||||
// ALAC elements, as AAC's.
|
||||
const (
|
||||
alacSCE = 0 // a single channel
|
||||
alacCPE = 1 // a channel pair
|
||||
alacCCE = 2
|
||||
alacLFE = 3
|
||||
alacDSE = 4
|
||||
alacPCE = 5
|
||||
alacFIL = 6
|
||||
alacEND = 7
|
||||
)
|
||||
|
||||
// newALACDecoder reads the stream's magic cookie: its ALACSpecificConfig, in
|
||||
// an MP4 within an 'alac' atom of its own, and in QuickTime's after a 'frma'.
|
||||
func newALACDecoder(cookie []byte) (*alacDecoder, error) {
|
||||
for len(cookie) >= 12 {
|
||||
switch string(cookie[4:8]) {
|
||||
case "frma":
|
||||
cookie = cookie[12:]
|
||||
continue
|
||||
case "alac":
|
||||
cookie = cookie[12:]
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
if len(cookie) < 24 {
|
||||
return nil, errors.New("alac: short magic cookie")
|
||||
}
|
||||
d := &alacDecoder{
|
||||
frameLength: binary.BigEndian.Uint32(cookie),
|
||||
bitDepth: cookie[5],
|
||||
pb: cookie[6],
|
||||
mb: cookie[7],
|
||||
kb: cookie[8],
|
||||
channels: cookie[9],
|
||||
rate: binary.BigEndian.Uint32(cookie[20:]),
|
||||
}
|
||||
switch {
|
||||
case cookie[4] != 0:
|
||||
return nil, errors.New("alac: unknown version")
|
||||
case d.frameLength == 0 || d.frameLength > 1<<16:
|
||||
return nil, errors.New("alac: bad frame length")
|
||||
case d.bitDepth != 16 && d.bitDepth != 20 && d.bitDepth != 24 && d.bitDepth != 32:
|
||||
return nil, errors.New("alac: bad bit depth")
|
||||
case d.channels == 0 || d.channels > 8:
|
||||
return nil, errors.New("alac: bad channel count")
|
||||
case d.kb == 0 || d.kb > 30:
|
||||
return nil, errors.New("alac: bad parameters")
|
||||
}
|
||||
n := int(d.frameLength)
|
||||
d.predictor = make([]int32, n)
|
||||
d.u, d.v = make([]int32, n), make([]int32, n)
|
||||
d.shift = make([]uint16, 2*n)
|
||||
d.left, d.right = make([]int32, n), make([]int32, n)
|
||||
// The front left and right, of ALAC's channel layouts: C L R first from
|
||||
// three channels, and C Lc Rc L R from eight.
|
||||
switch d.channels {
|
||||
case 1:
|
||||
d.leftCh, d.rightCh = 0, 0
|
||||
case 2:
|
||||
d.leftCh, d.rightCh = 0, 1
|
||||
case 8:
|
||||
d.leftCh, d.rightCh = 3, 4
|
||||
default:
|
||||
d.leftCh, d.rightCh = 1, 2
|
||||
}
|
||||
d.bitsPerSample = 1 / float32(int64(1)<<(d.bitDepth-1))
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// alacBits reads a packet's bits, most significant first. Reads past its end
|
||||
// read zeros, and mark it overrun.
|
||||
type alacBits struct {
|
||||
b []byte // with 8 bytes of zeros after it
|
||||
n uint // its bits, but the zeros
|
||||
pos uint
|
||||
}
|
||||
|
||||
func (r *alacBits) at(pos, n uint) uint32 {
|
||||
if n == 0 {
|
||||
return 0
|
||||
}
|
||||
i := pos >> 3
|
||||
if i+8 > uint(len(r.b)) {
|
||||
return 0
|
||||
}
|
||||
return uint32(binary.BigEndian.Uint64(r.b[i:]) << (pos & 7) >> (64 - n))
|
||||
}
|
||||
|
||||
func (r *alacBits) read(n uint) uint32 {
|
||||
v := r.at(r.pos, n)
|
||||
r.pos += n
|
||||
return v
|
||||
}
|
||||
|
||||
func (r *alacBits) over() bool { return r.pos > r.n }
|
||||
|
||||
var errALACData = errors.New("alac: bad packet")
|
||||
|
||||
// Decode decodes a packet into dst, as stereo, and returns it.
|
||||
func (d *alacDecoder) Decode(dst []float32, packet []byte) ([]float32, error) {
|
||||
// With zeros after it, for reads of 8 bytes at a time near its end.
|
||||
d.packet = append(append(d.packet[:0], packet...), make([]byte, 8)...)
|
||||
r := &alacBits{b: d.packet, n: uint(len(packet)) * 8}
|
||||
ch := 0
|
||||
samples := -1
|
||||
for {
|
||||
if r.over() {
|
||||
return dst, errALACData
|
||||
}
|
||||
tag := r.read(3)
|
||||
switch tag {
|
||||
case alacSCE, alacLFE, alacCPE:
|
||||
if ch >= int(d.channels) {
|
||||
return dst, errALACData
|
||||
}
|
||||
pair := tag == alacCPE
|
||||
n, err := d.element(r, pair, ch)
|
||||
if err != nil {
|
||||
return dst, err
|
||||
}
|
||||
if samples >= 0 && n != samples {
|
||||
return dst, errALACData
|
||||
}
|
||||
samples = n
|
||||
if pair {
|
||||
ch += 2
|
||||
} else {
|
||||
ch++
|
||||
}
|
||||
case alacDSE:
|
||||
r.read(4) // its instance
|
||||
align := r.read(1)
|
||||
count := r.read(8)
|
||||
if count == 255 {
|
||||
count += r.read(8)
|
||||
}
|
||||
if align != 0 {
|
||||
r.pos = (r.pos + 7) &^ 7
|
||||
}
|
||||
r.pos += uint(count) * 8
|
||||
case alacFIL:
|
||||
count := r.read(4)
|
||||
if count == 15 {
|
||||
count += r.read(8) - 1
|
||||
}
|
||||
r.pos += uint(count) * 8
|
||||
case alacEND:
|
||||
if samples < 0 {
|
||||
return dst, errALACData
|
||||
}
|
||||
for i := range samples {
|
||||
dst = append(dst, float32(d.left[i])*d.bitsPerSample, float32(d.right[i])*d.bitsPerSample)
|
||||
}
|
||||
return dst, nil
|
||||
default:
|
||||
return dst, errors.New("alac: unsupported element")
|
||||
}
|
||||
if ch >= int(d.channels) {
|
||||
// Done with the channels: an END element should follow, but
|
||||
// some encoders leave it out.
|
||||
if r.over() || samples < 0 {
|
||||
return dst, errALACData
|
||||
}
|
||||
for i := range samples {
|
||||
dst = append(dst, float32(d.left[i])*d.bitsPerSample, float32(d.right[i])*d.bitsPerSample)
|
||||
}
|
||||
return dst, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// element decodes a single channel, or a pair, as channel ch on, and keeps
|
||||
// what of it plays. It returns its samples a channel.
|
||||
func (d *alacDecoder) element(r *alacBits, pair bool, ch int) (int, error) {
|
||||
r.read(4) // its instance
|
||||
if r.read(12) != 0 {
|
||||
return 0, errALACData
|
||||
}
|
||||
header := r.read(4)
|
||||
partial := header>>3 != 0
|
||||
shifted := uint(header >> 1 & 3)
|
||||
escape := header&1 != 0
|
||||
if shifted == 3 {
|
||||
return 0, errALACData
|
||||
}
|
||||
n := d.frameLength
|
||||
if partial {
|
||||
n = r.read(32)
|
||||
if n == 0 || n > d.frameLength {
|
||||
return 0, errALACData
|
||||
}
|
||||
}
|
||||
chanBits := uint(d.bitDepth) - shifted*8
|
||||
if pair {
|
||||
chanBits++
|
||||
}
|
||||
if chanBits > 32 {
|
||||
return 0, errALACData
|
||||
}
|
||||
u, v := d.u[:n], d.v[:n]
|
||||
var mixBits uint32
|
||||
var mixRes int32
|
||||
if !escape {
|
||||
mixBits = r.read(8)
|
||||
mixRes = int32(int8(r.read(8)))
|
||||
modeU, denU, pbU, coefsU := d.predictorHeader(r, &d.coefsU)
|
||||
var modeV, denV, pbV uint32
|
||||
var coefsV []int16
|
||||
if pair {
|
||||
modeV, denV, pbV, coefsV = d.predictorHeader(r, &d.coefsV)
|
||||
}
|
||||
var shiftBits alacBits
|
||||
if shifted != 0 {
|
||||
shiftBits = *r
|
||||
ways := uint(1)
|
||||
if pair {
|
||||
ways = 2
|
||||
}
|
||||
r.pos += shifted * 8 * ways * uint(n)
|
||||
}
|
||||
if err := d.channel(r, u, modeU, denU, pbU, coefsU, chanBits); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if pair {
|
||||
if err := d.channel(r, v, modeV, denV, pbV, coefsV, chanBits); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
if shifted != 0 {
|
||||
bits := shifted * 8
|
||||
if pair {
|
||||
for i := range n {
|
||||
d.shift[2*i] = uint16(shiftBits.read(bits))
|
||||
d.shift[2*i+1] = uint16(shiftBits.read(bits))
|
||||
}
|
||||
} else {
|
||||
for i := range n {
|
||||
d.shift[i] = uint16(shiftBits.read(bits))
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Uncompressed, and never shifted.
|
||||
shifted = 0
|
||||
chanBits = uint(d.bitDepth)
|
||||
ext := 32 - chanBits
|
||||
for i := range n {
|
||||
u[i] = int32(r.read(chanBits)<<ext) >> ext
|
||||
if pair {
|
||||
v[i] = int32(r.read(chanBits)<<ext) >> ext
|
||||
}
|
||||
}
|
||||
}
|
||||
if r.over() {
|
||||
return 0, errALACData
|
||||
}
|
||||
keep := func(c int, out []int32) {
|
||||
switch c {
|
||||
case d.leftCh:
|
||||
copy(d.left, out)
|
||||
if d.rightCh == c {
|
||||
copy(d.right, out)
|
||||
}
|
||||
case d.rightCh:
|
||||
copy(d.right, out)
|
||||
}
|
||||
}
|
||||
bits := shifted * 8
|
||||
if !pair {
|
||||
if shifted != 0 {
|
||||
for i := range n {
|
||||
u[i] = u[i]<<bits | int32(d.shift[i])
|
||||
}
|
||||
}
|
||||
keep(ch, u)
|
||||
return int(n), nil
|
||||
}
|
||||
for i := range n {
|
||||
l, rr := u[i], v[i]
|
||||
if mixRes != 0 {
|
||||
l = u[i] + v[i] - (mixRes*v[i])>>mixBits
|
||||
rr = l - v[i]
|
||||
}
|
||||
if shifted != 0 {
|
||||
l = l<<bits | int32(d.shift[2*i])
|
||||
rr = rr<<bits | int32(d.shift[2*i+1])
|
||||
}
|
||||
u[i], v[i] = l, rr
|
||||
}
|
||||
keep(ch, u)
|
||||
keep(ch+1, v)
|
||||
return int(n), nil
|
||||
}
|
||||
|
||||
// predictorHeader reads a channel's predictor: its mode, its shift, its
|
||||
// rice parameter's factor and its coefficients.
|
||||
func (d *alacDecoder) predictorHeader(r *alacBits, coefs *[32]int16) (mode, den, pbFactor uint32, c []int16) {
|
||||
h := r.read(8)
|
||||
mode, den = h>>4, h&15
|
||||
h = r.read(8)
|
||||
pbFactor = h >> 5
|
||||
num := h & 31
|
||||
for i := range num {
|
||||
coefs[i] = int16(r.read(16))
|
||||
}
|
||||
return mode, den, pbFactor, coefs[:num]
|
||||
}
|
||||
|
||||
// channel entropy-decodes a channel's residues, and predicts its samples
|
||||
// from them, into out.
|
||||
func (d *alacDecoder) channel(r *alacBits, out []int32, mode, den, pbFactor uint32, coefs []int16, chanBits uint) error {
|
||||
pc := d.predictor[:len(out)]
|
||||
pb := uint32(d.pb) * pbFactor / 4
|
||||
if err := d.residues(r, pc, pb, chanBits); err != nil {
|
||||
return err
|
||||
}
|
||||
if mode != 0 {
|
||||
unpredict(pc, pc, nil, 31, uint32(chanBits), 0)
|
||||
}
|
||||
unpredict(pc, out, coefs, len(coefs), uint32(chanBits), den)
|
||||
return nil
|
||||
}
|
||||
|
||||
// The adaptive Golomb coder's constants.
|
||||
const (
|
||||
alacQBShift = 9
|
||||
alacQB = 1 << alacQBShift
|
||||
alacMMulShift = 2
|
||||
alacMDenShift = alacQBShift - alacMMulShift - 1
|
||||
alacMOff = 1 << (alacMDenShift - 2)
|
||||
alacBitOff = 24
|
||||
alacMaxPrefix = 9
|
||||
)
|
||||
|
||||
// residues decodes len(out) residues, adapting the code to their mean as it
|
||||
// goes, with runs of zeros coded apart where it's small.
|
||||
func (d *alacDecoder) residues(r *alacBits, out []int32, pb uint32, maxBits uint) error {
|
||||
mb := uint32(d.mb)
|
||||
kb := uint32(d.kb)
|
||||
wb := uint32(1)<<kb - 1
|
||||
zmode := uint32(0)
|
||||
for c := 0; c < len(out); {
|
||||
if r.pos >= r.n {
|
||||
return errALACData
|
||||
}
|
||||
m := mb >> alacQBShift
|
||||
k := min(uint32(31-bits.LeadingZeros32(m+3)), kb)
|
||||
m = 1<<k - 1
|
||||
n := r.golomb32(m, k, maxBits)
|
||||
nd := n + zmode
|
||||
del := int32((nd + 1) >> 1)
|
||||
if nd&1 != 0 {
|
||||
del = -del
|
||||
}
|
||||
out[c] = del
|
||||
c++
|
||||
mb = pb*(n+zmode) + mb - (pb*mb)>>alacQBShift
|
||||
if n > 0xffff {
|
||||
mb = 0xffff
|
||||
}
|
||||
zmode = 0
|
||||
if mb<<alacMMulShift < alacQB && c < len(out) {
|
||||
zmode = 1
|
||||
k := uint32(bits.LeadingZeros32(mb)) - alacBitOff + (mb+alacMOff)>>alacMDenShift
|
||||
mz := (uint32(1)<<k - 1) & wb
|
||||
run := r.golomb16(mz, k)
|
||||
if c+int(run) > len(out) {
|
||||
return errALACData
|
||||
}
|
||||
for range run {
|
||||
out[c] = 0
|
||||
c++
|
||||
}
|
||||
if run >= 0xffff {
|
||||
zmode = 0
|
||||
}
|
||||
mb = 0
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// golomb32 reads a residue: a unary prefix, then k bits, or else, after
|
||||
// alacMaxPrefix ones, the residue in maxBits.
|
||||
func (r *alacBits) golomb32(m, k uint32, maxBits uint) uint32 {
|
||||
word := r.at(r.pos, 32)
|
||||
pre := uint32(bits.LeadingZeros32(^word))
|
||||
if pre >= alacMaxPrefix {
|
||||
v := r.at(r.pos+alacMaxPrefix, maxBits)
|
||||
r.pos += alacMaxPrefix + maxBits
|
||||
return v
|
||||
}
|
||||
r.pos += uint(pre) + 1
|
||||
if k == 1 {
|
||||
return pre
|
||||
}
|
||||
v := word << (pre + 1) >> (32 - k)
|
||||
r.pos += uint(k) - 1
|
||||
res := pre * m
|
||||
if v >= 2 {
|
||||
res += v - 1
|
||||
r.pos++
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// golomb16 reads the length of a run of zeros, as golomb32 does a residue
|
||||
// but escaping to 16 bits.
|
||||
func (r *alacBits) golomb16(m, k uint32) uint32 {
|
||||
word := r.at(r.pos, 32)
|
||||
pre := uint32(bits.LeadingZeros32(^word))
|
||||
if pre >= alacMaxPrefix {
|
||||
v := r.at(r.pos+alacMaxPrefix, 16)
|
||||
r.pos += alacMaxPrefix + 16
|
||||
return v
|
||||
}
|
||||
v := word << (pre + 1) >> (32 - k)
|
||||
r.pos += uint(pre) + 1 + uint(k)
|
||||
res := pre*m + v - 1
|
||||
if v < 2 {
|
||||
res = pre * m
|
||||
r.pos--
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func signOf(i int32) int32 {
|
||||
switch {
|
||||
case i > 0:
|
||||
return 1
|
||||
case i < 0:
|
||||
return -1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// unpredict undoes the adaptive linear prediction of numActive coefficients
|
||||
// on pc into out, which may be the same. With 31 it's the first-order one.
|
||||
func unpredict(pc, out []int32, coefs []int16, numActive int, chanBits, denShift uint32) {
|
||||
num := len(out)
|
||||
if num == 0 {
|
||||
return
|
||||
}
|
||||
shift := 32 - chanBits
|
||||
out[0] = pc[0]
|
||||
if numActive == 0 {
|
||||
copy(out[1:], pc[1:num])
|
||||
return
|
||||
}
|
||||
if numActive == 31 {
|
||||
prev := out[0]
|
||||
for j := 1; j < num; j++ {
|
||||
del := pc[j] + prev
|
||||
prev = del << shift >> shift
|
||||
out[j] = prev
|
||||
}
|
||||
return
|
||||
}
|
||||
for j := 1; j <= numActive && j < num; j++ {
|
||||
del := pc[j] + out[j-1]
|
||||
out[j] = del << shift >> shift
|
||||
}
|
||||
var half int32
|
||||
if denShift > 0 {
|
||||
half = 1 << (denShift - 1)
|
||||
}
|
||||
lim := numActive + 1
|
||||
for j := lim; j < num; j++ {
|
||||
top := out[j-lim]
|
||||
var sum int32
|
||||
for k := range numActive {
|
||||
sum += int32(coefs[k]) * (out[j-1-k] - top)
|
||||
}
|
||||
del := pc[j]
|
||||
del0 := del
|
||||
sg := signOf(del)
|
||||
del += top + (sum+half)>>denShift
|
||||
out[j] = del << shift >> shift
|
||||
switch {
|
||||
case sg > 0:
|
||||
for k := numActive - 1; k >= 0; k-- {
|
||||
dd := top - out[j-1-k]
|
||||
sgn := signOf(dd)
|
||||
coefs[k] -= int16(sgn)
|
||||
del0 -= int32(numActive-k) * ((sgn * dd) >> denShift)
|
||||
if del0 <= 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
case sg < 0:
|
||||
for k := numActive - 1; k >= 0; k-- {
|
||||
dd := top - out[j-1-k]
|
||||
sgn := signOf(dd)
|
||||
coefs[k] += int16(sgn)
|
||||
del0 -= int32(numActive-k) * ((-sgn * dd) >> denShift)
|
||||
if del0 >= 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (d *alacDecoder) SampleRate() int { return int(d.rate) }
|
||||
func (d *alacDecoder) Reset() {}
|
||||
func (d *alacDecoder) Preroll() int { return 0 }
|
||||
func (d *alacDecoder) PacketFrames() int { return 0 }
|
||||
Vendored
+633
@@ -0,0 +1,633 @@
|
||||
package mp4
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"iter"
|
||||
)
|
||||
|
||||
// A track is an MP4's first sound track.
|
||||
type track struct {
|
||||
// Codec is the type of its sample entry: "mp4a", "alac", "fLaC", ...
|
||||
Codec string
|
||||
// Config is AAC's AudioSpecificConfig, ALAC's magic cookie, FLAC's
|
||||
// metadata blocks, or another codec's boxes within the sample entry.
|
||||
Config []byte
|
||||
Timescale int64 // the units of its times, a second's
|
||||
// Duration is how long it is, in the timescale, as its header says.
|
||||
Duration int64
|
||||
// Prime is where the edit list starts it: the encoder's priming, in
|
||||
// the timescale, to drop.
|
||||
Prime int64
|
||||
// Where each packet is, and where it ends, in the timescale. Only
|
||||
// read with the tables.
|
||||
Offsets []int64
|
||||
Sizes []uint32
|
||||
Ends []int64
|
||||
|
||||
// Fragmented says the packets aren't in the movie header's tables but
|
||||
// in fragments after it, as a stream cut up for DASH has them: the
|
||||
// tables fill in as fragment reads each. Next is where the boxes after
|
||||
// the movie header start.
|
||||
Fragmented bool
|
||||
Next int64
|
||||
id uint32 // the track's ID, which its fragments name
|
||||
defaults fragmentDefaults
|
||||
}
|
||||
|
||||
// fragmentDefaults are what a fragment's packets are unless it says.
|
||||
type fragmentDefaults struct {
|
||||
duration, size uint32
|
||||
}
|
||||
|
||||
// ErrNoMovie says an MP4 has no movie header: no tracks to play.
|
||||
var ErrNoMovie = errors.New("mp4: no movie header")
|
||||
|
||||
// readTrack reads the sound track of the MP4 r holds, of size bytes. With tables,
|
||||
// it reads where each packet is too. The movie header is often after the
|
||||
// media data: r may wait for the bytes asked of it, as a file coming in.
|
||||
func readTrack(r io.ReaderAt, size int64, tables bool) (*track, error) {
|
||||
var h [16]byte
|
||||
for off := int64(0); off+8 <= size; {
|
||||
if _, err := r.ReadAt(h[:8], off); err != nil {
|
||||
return nil, ErrNoMovie
|
||||
}
|
||||
n, head := int64(binary.BigEndian.Uint32(h[:])), int64(8)
|
||||
switch n {
|
||||
case 0: // to the end
|
||||
n = size - off
|
||||
case 1:
|
||||
if _, err := r.ReadAt(h[8:], off+8); err != nil {
|
||||
return nil, ErrNoMovie
|
||||
}
|
||||
n, head = int64(binary.BigEndian.Uint64(h[8:])), 16
|
||||
}
|
||||
if n < head || n > size-off {
|
||||
return nil, errors.New("mp4: bad box")
|
||||
}
|
||||
if string(h[4:8]) == "moov" {
|
||||
if n > 256<<20 {
|
||||
return nil, errors.New("mp4: movie header too big")
|
||||
}
|
||||
moov := make([]byte, n-head)
|
||||
if _, err := r.ReadAt(moov, off+head); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a, err := parseMoov(moov, tables)
|
||||
if err != nil || !a.Fragmented {
|
||||
return a, err
|
||||
}
|
||||
a.Next = off + n
|
||||
a.readIndex(r, size)
|
||||
return a, nil
|
||||
}
|
||||
off += n
|
||||
}
|
||||
return nil, ErrNoMovie
|
||||
}
|
||||
|
||||
// boxes walks the boxes in b, giving each one's type and body.
|
||||
func boxes(b []byte) iter.Seq2[string, []byte] {
|
||||
return func(yield func(string, []byte) bool) {
|
||||
for len(b) >= 8 {
|
||||
size, head := uint64(binary.BigEndian.Uint32(b)), uint64(8)
|
||||
typ := string(b[4:8])
|
||||
switch size {
|
||||
case 0:
|
||||
size = uint64(len(b))
|
||||
case 1:
|
||||
if len(b) < 16 {
|
||||
return
|
||||
}
|
||||
size, head = binary.BigEndian.Uint64(b[8:]), 16
|
||||
}
|
||||
if size < head || size > uint64(len(b)) {
|
||||
return
|
||||
}
|
||||
if !yield(typ, b[head:size]) {
|
||||
return
|
||||
}
|
||||
b = b[size:]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// child returns the body of the box of type typ in b, following the path of
|
||||
// types after it into the boxes within.
|
||||
func child(b []byte, path ...string) []byte {
|
||||
for _, typ := range path {
|
||||
var found []byte
|
||||
for t, body := range boxes(b) {
|
||||
if t == typ {
|
||||
found = body
|
||||
break
|
||||
}
|
||||
}
|
||||
if found == nil {
|
||||
return nil
|
||||
}
|
||||
b = found
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// parseMoov finds the first sound track in a movie header.
|
||||
func parseMoov(moov []byte, tables bool) (*track, error) {
|
||||
mvex := child(moov, "mvex")
|
||||
for typ, trak := range boxes(moov) {
|
||||
if typ != "trak" {
|
||||
continue
|
||||
}
|
||||
mdia := child(trak, "mdia")
|
||||
if hdlr := child(mdia, "hdlr"); len(hdlr) < 12 || string(hdlr[8:12]) != "soun" {
|
||||
continue
|
||||
}
|
||||
a, err := parseTrack(trak, mdia, mvex, tables)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
return nil, errors.New("mp4: no sound track")
|
||||
}
|
||||
|
||||
var errMP4Table = errors.New("mp4: bad sample table")
|
||||
|
||||
func parseTrack(trak, mdia, mvex []byte, tables bool) (*track, error) {
|
||||
a := &track{}
|
||||
mdhd := child(mdia, "mdhd")
|
||||
switch {
|
||||
case len(mdhd) >= 32 && mdhd[0] == 1:
|
||||
a.Timescale = int64(binary.BigEndian.Uint32(mdhd[20:]))
|
||||
a.Duration = int64(binary.BigEndian.Uint64(mdhd[24:]))
|
||||
case len(mdhd) >= 20:
|
||||
a.Timescale = int64(binary.BigEndian.Uint32(mdhd[12:]))
|
||||
a.Duration = int64(binary.BigEndian.Uint32(mdhd[16:]))
|
||||
}
|
||||
if a.Timescale <= 0 || a.Duration < 0 {
|
||||
return nil, errors.New("mp4: no timescale")
|
||||
}
|
||||
stbl := child(mdia, "minf", "stbl")
|
||||
if err := a.parseEntry(child(stbl, "stsd")); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if mvex != nil && !hasSamples(stbl) {
|
||||
a.Fragmented = true
|
||||
if tkhd := child(trak, "tkhd"); len(tkhd) >= 16 {
|
||||
at := 12
|
||||
if tkhd[0] == 1 {
|
||||
at = 20
|
||||
}
|
||||
a.id = binary.BigEndian.Uint32(tkhd[at:])
|
||||
}
|
||||
for typ, trex := range boxes(mvex) {
|
||||
if typ == "trex" && len(trex) >= 24 && binary.BigEndian.Uint32(trex[4:]) == a.id {
|
||||
a.defaults = fragmentDefaults{binary.BigEndian.Uint32(trex[12:]), binary.BigEndian.Uint32(trex[16:])}
|
||||
}
|
||||
}
|
||||
} else if tables {
|
||||
if err := a.parseTables(stbl); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.Duration = a.Ends[len(a.Ends)-1]
|
||||
}
|
||||
if elst := child(trak, "edts", "elst"); len(elst) >= 8 {
|
||||
n := binary.BigEndian.Uint32(elst[4:])
|
||||
b := elst[8:]
|
||||
for range n {
|
||||
var t int64
|
||||
if elst[0] == 1 {
|
||||
if len(b) < 20 {
|
||||
break
|
||||
}
|
||||
t, b = int64(binary.BigEndian.Uint64(b[8:])), b[20:]
|
||||
} else {
|
||||
if len(b) < 12 {
|
||||
break
|
||||
}
|
||||
t, b = int64(int32(binary.BigEndian.Uint32(b[4:]))), b[12:]
|
||||
}
|
||||
if t >= 0 { // past an empty edit, which plays nothing
|
||||
a.Prime = t
|
||||
if a.Duration > 0 {
|
||||
a.Prime = min(t, a.Duration)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
// parseEntry reads the track's sample description: its codec and its
|
||||
// configuration, in a box within the entry, or within a 'wave' box there in
|
||||
// QuickTime's own kind.
|
||||
func (a *track) parseEntry(stsd []byte) error {
|
||||
if len(stsd) < 8+36 {
|
||||
return errors.New("mp4: no sample description")
|
||||
}
|
||||
entry := stsd[8:]
|
||||
size := int(binary.BigEndian.Uint32(entry))
|
||||
if size < 36 || size > len(entry) {
|
||||
return errors.New("mp4: bad sample description")
|
||||
}
|
||||
a.Codec = string(entry[4:8])
|
||||
inner := entry[36:size]
|
||||
switch binary.BigEndian.Uint16(entry[16:]) { // the version of the sound description
|
||||
case 1:
|
||||
inner = inner[min(16, len(inner)):]
|
||||
case 2:
|
||||
inner = inner[min(36, len(inner)):]
|
||||
}
|
||||
if wave := child(inner, "wave"); wave != nil {
|
||||
inner = wave
|
||||
}
|
||||
switch a.Codec {
|
||||
case "alac":
|
||||
cookie := child(inner, "alac")
|
||||
if len(cookie) < 4 {
|
||||
return errors.New("mp4: no ALAC configuration")
|
||||
}
|
||||
a.Config = cookie[4:]
|
||||
case "fLaC":
|
||||
dfla := child(inner, "dfLa")
|
||||
if len(dfla) < 4+4+34 {
|
||||
return errors.New("mp4: no FLAC configuration")
|
||||
}
|
||||
a.Config = dfla[4:]
|
||||
case "mp4a":
|
||||
esds := child(inner, "esds")
|
||||
if len(esds) < 4 {
|
||||
return errors.New("mp4: no AAC configuration")
|
||||
}
|
||||
asc, ok := decoderConfig(esds[4:])
|
||||
if !ok {
|
||||
return errors.New("mp4: not AAC")
|
||||
}
|
||||
a.Config = asc
|
||||
default:
|
||||
a.Config = inner
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// decoderConfig finds the DecoderSpecificInfo in an elementary stream's
|
||||
// descriptors: AAC's AudioSpecificConfig. A stream not of AAC has none it
|
||||
// takes, as an MP3's in an MP4.
|
||||
func decoderConfig(b []byte) ([]byte, bool) {
|
||||
descriptor := func(b []byte) (tag byte, body, rest []byte, ok bool) {
|
||||
if len(b) < 2 {
|
||||
return 0, nil, nil, false
|
||||
}
|
||||
tag, b = b[0], b[1:]
|
||||
n := 0
|
||||
for i := 0; i < 4 && len(b) > 0; i++ {
|
||||
c := b[0]
|
||||
b = b[1:]
|
||||
n = n<<7 | int(c&0x7f)
|
||||
if c&0x80 == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if n > len(b) {
|
||||
return 0, nil, nil, false
|
||||
}
|
||||
return tag, b[:n], b[n:], true
|
||||
}
|
||||
tag, es, _, ok := descriptor(b)
|
||||
if !ok || tag != 3 || len(es) < 3 {
|
||||
return nil, false
|
||||
}
|
||||
flags := es[2]
|
||||
es = es[3:]
|
||||
if flags&0x80 != 0 { // depends on a stream
|
||||
es = es[min(2, len(es)):]
|
||||
}
|
||||
if flags&0x40 != 0 && len(es) > 0 { // a URL
|
||||
es = es[min(1+int(es[0]), len(es)):]
|
||||
}
|
||||
if flags&0x20 != 0 { // an OCR stream
|
||||
es = es[min(2, len(es)):]
|
||||
}
|
||||
tag, dc, _, ok := descriptor(es)
|
||||
if !ok || tag != 4 || len(dc) < 13 {
|
||||
return nil, false
|
||||
}
|
||||
switch dc[0] { // MPEG-4 audio, or MPEG-2 AAC's profiles
|
||||
case 0x40, 0x66, 0x67, 0x68:
|
||||
default:
|
||||
return nil, false
|
||||
}
|
||||
tag, asc, _, ok := descriptor(dc[13:])
|
||||
if !ok || tag != 5 || len(asc) < 2 {
|
||||
return nil, false
|
||||
}
|
||||
return asc, true
|
||||
}
|
||||
|
||||
// maxSamples bounds the tables read, against a file that claims more than it
|
||||
// could hold: a day of AAC at 48 kHz.
|
||||
const maxSamples = 1 << 22
|
||||
|
||||
// parseTables reads the sample table: each packet's size, which chunk holds
|
||||
// it, where that chunk is, and how long each packet lasts.
|
||||
func (a *track) parseTables(stbl []byte) error {
|
||||
// Sizes.
|
||||
if stsz := child(stbl, "stsz"); len(stsz) >= 12 {
|
||||
fixed := binary.BigEndian.Uint32(stsz[4:])
|
||||
n := int(binary.BigEndian.Uint32(stsz[8:]))
|
||||
if n > maxSamples || fixed == 0 && len(stsz) < 12+4*n {
|
||||
return errMP4Table
|
||||
}
|
||||
a.Sizes = make([]uint32, n)
|
||||
for i := range a.Sizes {
|
||||
if fixed != 0 {
|
||||
a.Sizes[i] = fixed
|
||||
} else {
|
||||
a.Sizes[i] = binary.BigEndian.Uint32(stsz[12+4*i:])
|
||||
}
|
||||
}
|
||||
} else if stz2 := child(stbl, "stz2"); len(stz2) >= 12 {
|
||||
field := int(stz2[7])
|
||||
n := int(binary.BigEndian.Uint32(stz2[8:]))
|
||||
if n > maxSamples || field != 4 && field != 8 && field != 16 || len(stz2) < 12+(n*field+7)/8 {
|
||||
return errMP4Table
|
||||
}
|
||||
a.Sizes = make([]uint32, n)
|
||||
b := stz2[12:]
|
||||
for i := range a.Sizes {
|
||||
switch field {
|
||||
case 4:
|
||||
a.Sizes[i] = uint32(b[i/2]>>(4*(1-i%2))) & 15
|
||||
case 8:
|
||||
a.Sizes[i] = uint32(b[i])
|
||||
case 16:
|
||||
a.Sizes[i] = uint32(binary.BigEndian.Uint16(b[2*i:]))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return errMP4Table
|
||||
}
|
||||
if len(a.Sizes) == 0 {
|
||||
return errMP4Table
|
||||
}
|
||||
|
||||
// Where the chunks are.
|
||||
var chunks []int64
|
||||
if stco := child(stbl, "stco"); len(stco) >= 8 {
|
||||
n := int(binary.BigEndian.Uint32(stco[4:]))
|
||||
if n > maxSamples || len(stco) < 8+4*n {
|
||||
return errMP4Table
|
||||
}
|
||||
chunks = make([]int64, n)
|
||||
for i := range chunks {
|
||||
chunks[i] = int64(binary.BigEndian.Uint32(stco[8+4*i:]))
|
||||
}
|
||||
} else if co64 := child(stbl, "co64"); len(co64) >= 8 {
|
||||
n := int(binary.BigEndian.Uint32(co64[4:]))
|
||||
if n > maxSamples || len(co64) < 8+8*n {
|
||||
return errMP4Table
|
||||
}
|
||||
chunks = make([]int64, n)
|
||||
for i := range chunks {
|
||||
chunks[i] = int64(binary.BigEndian.Uint64(co64[8+8*i:]))
|
||||
}
|
||||
} else {
|
||||
return errMP4Table
|
||||
}
|
||||
|
||||
// Which packets each chunk holds, in runs of chunks alike.
|
||||
stsc := child(stbl, "stsc")
|
||||
if len(stsc) < 8 {
|
||||
return errMP4Table
|
||||
}
|
||||
runs := int(binary.BigEndian.Uint32(stsc[4:]))
|
||||
if runs > maxSamples || len(stsc) < 8+12*runs || runs == 0 {
|
||||
return errMP4Table
|
||||
}
|
||||
a.Offsets = make([]int64, len(a.Sizes))
|
||||
s := 0
|
||||
for r := 0; r < runs && s < len(a.Sizes); r++ {
|
||||
e := stsc[8+12*r:]
|
||||
first := int(binary.BigEndian.Uint32(e)) - 1
|
||||
per := int(binary.BigEndian.Uint32(e[4:]))
|
||||
last := len(chunks)
|
||||
if r+1 < runs {
|
||||
last = int(binary.BigEndian.Uint32(stsc[8+12*(r+1):])) - 1
|
||||
}
|
||||
if first < 0 || last > len(chunks) || per <= 0 {
|
||||
return errMP4Table
|
||||
}
|
||||
for c := first; c < last && s < len(a.Sizes); c++ {
|
||||
off := chunks[c]
|
||||
for range per {
|
||||
if s == len(a.Sizes) {
|
||||
break
|
||||
}
|
||||
a.Offsets[s] = off
|
||||
off += int64(a.Sizes[s])
|
||||
s++
|
||||
}
|
||||
}
|
||||
}
|
||||
if s < len(a.Sizes) {
|
||||
a.Sizes, a.Offsets = a.Sizes[:s], a.Offsets[:s]
|
||||
}
|
||||
|
||||
// How long each lasts.
|
||||
stts := child(stbl, "stts")
|
||||
if len(stts) < 8 {
|
||||
return errMP4Table
|
||||
}
|
||||
n := int(binary.BigEndian.Uint32(stts[4:]))
|
||||
if len(stts) < 8+8*n {
|
||||
return errMP4Table
|
||||
}
|
||||
a.Ends = make([]int64, 0, len(a.Sizes))
|
||||
var t int64
|
||||
for i := 0; i < n && len(a.Ends) < len(a.Sizes); i++ {
|
||||
count := int(binary.BigEndian.Uint32(stts[8+8*i:]))
|
||||
delta := int64(binary.BigEndian.Uint32(stts[12+8*i:]))
|
||||
for range min(count, len(a.Sizes)-len(a.Ends)) {
|
||||
t += delta
|
||||
a.Ends = append(a.Ends, t)
|
||||
}
|
||||
}
|
||||
if len(a.Ends) == 0 {
|
||||
return errMP4Table
|
||||
}
|
||||
a.Sizes, a.Offsets = a.Sizes[:len(a.Ends)], a.Offsets[:len(a.Ends)]
|
||||
return nil
|
||||
}
|
||||
|
||||
// hasSamples says whether a sample table lists any packets: a fragmented
|
||||
// file's lists none, its packets being in the fragments.
|
||||
func hasSamples(stbl []byte) bool {
|
||||
if stsz := child(stbl, "stsz"); len(stsz) >= 12 {
|
||||
return binary.BigEndian.Uint32(stsz[8:]) > 0
|
||||
}
|
||||
if stz2 := child(stbl, "stz2"); len(stz2) >= 12 {
|
||||
return binary.BigEndian.Uint32(stz2[8:]) > 0
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// readIndex reads how long a fragmented track is from the segment index
|
||||
// that comes before its first fragment, if there's one: the movie header
|
||||
// of such a file says nothing of it.
|
||||
func (a *track) readIndex(r io.ReaderAt, size int64) {
|
||||
var h [8]byte
|
||||
for off := a.Next; off+8 <= size; {
|
||||
if _, err := r.ReadAt(h[:], off); err != nil {
|
||||
return
|
||||
}
|
||||
n := int64(binary.BigEndian.Uint32(h[:]))
|
||||
switch string(h[4:]) {
|
||||
case "sidx":
|
||||
if n < 8+24 || n > 1<<20 || n > size-off {
|
||||
return
|
||||
}
|
||||
sidx := make([]byte, n-8)
|
||||
if _, err := r.ReadAt(sidx, off+8); err != nil {
|
||||
return
|
||||
}
|
||||
if d, ok := indexDuration(sidx); ok && a.Timescale > 0 {
|
||||
a.Duration = d * a.Timescale / int64(binary.BigEndian.Uint32(sidx[8:]))
|
||||
}
|
||||
return
|
||||
case "moof", "mdat":
|
||||
return
|
||||
}
|
||||
if n < 8 {
|
||||
return
|
||||
}
|
||||
off += n
|
||||
}
|
||||
}
|
||||
|
||||
// indexDuration adds up the durations of the segments a segment index lists.
|
||||
func indexDuration(sidx []byte) (int64, bool) {
|
||||
at := 20
|
||||
if len(sidx) > 0 && sidx[0] == 1 {
|
||||
at = 28
|
||||
}
|
||||
if len(sidx) < at+4 || binary.BigEndian.Uint32(sidx[8:]) == 0 {
|
||||
return 0, false
|
||||
}
|
||||
b := sidx[at:]
|
||||
n := int(binary.BigEndian.Uint16(b[2:]))
|
||||
b = b[4:]
|
||||
if len(b) < 12*n {
|
||||
return 0, false
|
||||
}
|
||||
var d int64
|
||||
for i := range n {
|
||||
d += int64(binary.BigEndian.Uint32(b[12*i+4:]))
|
||||
}
|
||||
return d, d > 0
|
||||
}
|
||||
|
||||
// fragment reads a fragment's movie header, the body of the moof box at off
|
||||
// in the file, adding where the track's packets are in it to the tables.
|
||||
func (a *track) fragment(moof []byte, off int64) error {
|
||||
for typ, traf := range boxes(moof) {
|
||||
if typ != "traf" {
|
||||
continue
|
||||
}
|
||||
tfhd := child(traf, "tfhd")
|
||||
if len(tfhd) < 8 || binary.BigEndian.Uint32(tfhd[4:]) != a.id {
|
||||
continue
|
||||
}
|
||||
flags := binary.BigEndian.Uint32(tfhd) & 0xffffff
|
||||
base := off // where the moof starts, unless it says
|
||||
d := a.defaults
|
||||
b := tfhd[8:]
|
||||
field := func(flag uint32, n int) ([]byte, bool) {
|
||||
if flags&flag == 0 {
|
||||
return nil, false
|
||||
}
|
||||
if len(b) < n {
|
||||
return nil, false
|
||||
}
|
||||
v := b[:n]
|
||||
b = b[n:]
|
||||
return v, true
|
||||
}
|
||||
if v, ok := field(0x01, 8); ok {
|
||||
base = int64(binary.BigEndian.Uint64(v))
|
||||
}
|
||||
field(0x02, 4) // the sample description: there's one
|
||||
if v, ok := field(0x08, 4); ok {
|
||||
d.duration = binary.BigEndian.Uint32(v)
|
||||
}
|
||||
if v, ok := field(0x10, 4); ok {
|
||||
d.size = binary.BigEndian.Uint32(v)
|
||||
}
|
||||
at := base
|
||||
for typ, trun := range boxes(traf) {
|
||||
if typ != "trun" {
|
||||
continue
|
||||
}
|
||||
var err error
|
||||
if at, err = a.run(trun, base, at, d); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// run reads a track run: packets one after another, from at unless it says
|
||||
// where from base. It returns where the next run starts, unless it says.
|
||||
func (a *track) run(trun []byte, base, at int64, d fragmentDefaults) (int64, error) {
|
||||
if len(trun) < 8 {
|
||||
return 0, errMP4Table
|
||||
}
|
||||
flags := binary.BigEndian.Uint32(trun) & 0xffffff
|
||||
n := int(binary.BigEndian.Uint32(trun[4:]))
|
||||
b := trun[8:]
|
||||
if flags&0x01 != 0 {
|
||||
if len(b) < 4 {
|
||||
return 0, errMP4Table
|
||||
}
|
||||
at = base + int64(int32(binary.BigEndian.Uint32(b)))
|
||||
b = b[4:]
|
||||
}
|
||||
if flags&0x04 != 0 { // the first packet's flags
|
||||
if len(b) < 4 {
|
||||
return 0, errMP4Table
|
||||
}
|
||||
b = b[4:]
|
||||
}
|
||||
per := 0
|
||||
for _, f := range []uint32{0x100, 0x200, 0x400, 0x800} {
|
||||
if flags&f != 0 {
|
||||
per += 4
|
||||
}
|
||||
}
|
||||
if n > maxSamples || len(b) < n*per || len(a.Sizes)+n > maxSamples {
|
||||
return 0, errMP4Table
|
||||
}
|
||||
var t int64
|
||||
if len(a.Ends) > 0 {
|
||||
t = a.Ends[len(a.Ends)-1]
|
||||
}
|
||||
for range n {
|
||||
duration, size := d.duration, d.size
|
||||
e := b
|
||||
if flags&0x100 != 0 {
|
||||
duration, e = binary.BigEndian.Uint32(e), e[4:]
|
||||
}
|
||||
if flags&0x200 != 0 {
|
||||
size = binary.BigEndian.Uint32(e)
|
||||
}
|
||||
b = b[per:]
|
||||
t += int64(duration)
|
||||
a.Offsets = append(a.Offsets, at)
|
||||
a.Sizes = append(a.Sizes, size)
|
||||
a.Ends = append(a.Ends, t)
|
||||
at += int64(size)
|
||||
}
|
||||
return at, nil
|
||||
}
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
package mp4
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// A decoder decodes a track's packets, whose places it knows from the
|
||||
// movie header's sample table or, of a fragmented file, from each
|
||||
// fragment's header as it reaches it. A seek goes to the packet holding the
|
||||
// frame asked for.
|
||||
type decoder struct {
|
||||
r io.ReaderAt
|
||||
codec Codec
|
||||
rate int
|
||||
offs []int64
|
||||
sizes []int
|
||||
ends []int64 // where each packet ends, in frames
|
||||
// last is where the last packet found ends, in frames, as the file
|
||||
// says, when ends places packets by the codec's PacketFrames instead;
|
||||
// 0 when ends is as the file says.
|
||||
last int64
|
||||
// more finds the next fragment's packets, and says if there were
|
||||
// any. Nil once all are found.
|
||||
more func() bool
|
||||
prime int64 // the encoder's priming, in frames, to drop
|
||||
frames int64 // the length, or -1 if unknown
|
||||
exact bool // whether it is: then what's past it is padding, dropped
|
||||
next int // the packet decoded next
|
||||
pos int64 // the frame Read returns next
|
||||
skip int64 // frames to drop before it
|
||||
packet []byte
|
||||
out []float32
|
||||
pend []float32
|
||||
}
|
||||
|
||||
func newDecoder(r io.ReaderAt, size int64) (*decoder, error) {
|
||||
t, err := readTrack(r, size, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c, err := openCodec(t)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d := &decoder{r: r, codec: c, rate: c.SampleRate(), frames: -1}
|
||||
if d.rate <= 0 {
|
||||
return nil, errors.New("mp4: no sample rate")
|
||||
}
|
||||
// In frames, from the track's timescale: most often the same.
|
||||
frames := func(v int64) int64 { return v * int64(d.rate) / t.Timescale }
|
||||
d.prime = frames(t.Prime)
|
||||
d.skip = d.prime
|
||||
if !t.Fragmented {
|
||||
for i := range t.Sizes {
|
||||
d.add(t.Offsets[i], int(t.Sizes[i]), frames(t.Ends[i]))
|
||||
}
|
||||
if len(d.ends) == 0 {
|
||||
return nil, errors.New("mp4: no packets")
|
||||
}
|
||||
d.frames, d.exact = d.length()-d.prime, true
|
||||
return d, nil
|
||||
}
|
||||
d.fragments(t, size, frames)
|
||||
if t.Duration > 0 {
|
||||
// From the segment index: the fragments are found as they play.
|
||||
d.frames = frames(t.Duration) - d.prime
|
||||
} else {
|
||||
for d.findMore() {
|
||||
}
|
||||
}
|
||||
if !d.have(0) {
|
||||
return nil, errors.New("mp4: no fragments")
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func (d *decoder) SampleRate() int { return d.rate }
|
||||
func (d *decoder) Channels() int { return 2 }
|
||||
func (d *decoder) Len() int64 { return d.frames }
|
||||
|
||||
// add adds a packet of size bytes at off, ending at end frames as the file
|
||||
// says.
|
||||
func (d *decoder) add(off int64, size int, end int64) {
|
||||
d.offs = append(d.offs, off)
|
||||
d.sizes = append(d.sizes, size)
|
||||
if n := d.codec.PacketFrames(); n > 0 {
|
||||
d.last = end
|
||||
end = int64(len(d.ends)+1) * int64(n)
|
||||
}
|
||||
d.ends = append(d.ends, end)
|
||||
}
|
||||
|
||||
// length is where the packets found end, in frames, as the file says.
|
||||
func (d *decoder) length() int64 {
|
||||
if d.last > 0 {
|
||||
return d.last
|
||||
}
|
||||
return d.ends[len(d.ends)-1]
|
||||
}
|
||||
|
||||
// packetStart is the frame packet i starts at.
|
||||
func (d *decoder) packetStart(i int) int64 {
|
||||
if i == 0 {
|
||||
return 0
|
||||
}
|
||||
return d.ends[i-1]
|
||||
}
|
||||
|
||||
// have says whether packet i is known, finding more if need be.
|
||||
func (d *decoder) have(i int) bool {
|
||||
for i >= len(d.offs) {
|
||||
if !d.findMore() {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// findMore finds the next fragment's packets, if there are any left to
|
||||
// find. Once all are found, the length is known.
|
||||
func (d *decoder) findMore() bool {
|
||||
if d.more == nil {
|
||||
return false
|
||||
}
|
||||
if d.more() {
|
||||
return true
|
||||
}
|
||||
d.more = nil
|
||||
if len(d.ends) > 0 {
|
||||
d.frames, d.exact = d.length()-d.prime, true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (d *decoder) Read(dst []float32) (int, error) {
|
||||
for len(d.pend) == 0 {
|
||||
if !d.have(d.next) {
|
||||
return 0, io.EOF
|
||||
}
|
||||
if !d.exact {
|
||||
// Whether this is the last packet, whose padding is dropped:
|
||||
// the next fragment's are found, if any.
|
||||
d.have(d.next + 1)
|
||||
}
|
||||
size := d.sizes[d.next]
|
||||
if cap(d.packet) < size {
|
||||
d.packet = make([]byte, size)
|
||||
}
|
||||
d.packet = d.packet[:size]
|
||||
if _, err := d.r.ReadAt(d.packet, d.offs[d.next]); err != nil {
|
||||
if err == io.ErrUnexpectedEOF {
|
||||
err = io.EOF // cut short
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
d.next++
|
||||
out, err := d.codec.Decode(d.out[:0], d.packet)
|
||||
d.out = out
|
||||
if err != nil {
|
||||
continue // a packet gone bad: on to the next
|
||||
}
|
||||
drop := min(d.skip, int64(len(out)/2))
|
||||
d.skip -= drop
|
||||
d.pend = out[drop*2:]
|
||||
}
|
||||
n := copy(dst[:len(dst)/2*2], d.pend)
|
||||
if d.exact {
|
||||
// What the encoder padded the last packet with.
|
||||
n = int(min(int64(n), (d.frames-d.pos)*2))
|
||||
if n <= 0 {
|
||||
d.pend = nil
|
||||
return 0, io.EOF
|
||||
}
|
||||
}
|
||||
d.pend = d.pend[n:]
|
||||
d.pos += int64(n / 2)
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// SetPosition goes to the packet holding frame, from those before it its
|
||||
// sound overlaps, and drops what comes before frame.
|
||||
func (d *decoder) SetPosition(frame int64) error {
|
||||
frame = max(frame, 0)
|
||||
if d.frames >= 0 {
|
||||
frame = min(frame, d.frames)
|
||||
}
|
||||
at := frame + d.prime
|
||||
for (len(d.ends) == 0 || d.ends[len(d.ends)-1] <= at) && d.findMore() {
|
||||
}
|
||||
i := sort.Search(len(d.ends), func(i int) bool { return d.ends[i] > at })
|
||||
start := max(0, i-d.codec.Preroll())
|
||||
d.codec.Reset()
|
||||
d.next, d.pos = start, frame
|
||||
d.skip = at - d.packetStart(start)
|
||||
d.pend = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
// fragments has the decoder find a fragmented file's packets as it needs
|
||||
// them, a fragment at a time, walking the boxes after the movie header.
|
||||
func (d *decoder) fragments(t *track, size int64, frames func(int64) int64) {
|
||||
off := t.Next
|
||||
var h [16]byte
|
||||
d.more = func() bool {
|
||||
for off+8 <= size {
|
||||
if _, err := d.r.ReadAt(h[:8], off); err != nil {
|
||||
return false
|
||||
}
|
||||
n, head := int64(binary.BigEndian.Uint32(h[:])), int64(8)
|
||||
if n == 1 {
|
||||
if _, err := d.r.ReadAt(h[8:], off+8); err != nil {
|
||||
return false
|
||||
}
|
||||
n, head = int64(binary.BigEndian.Uint64(h[8:])), 16
|
||||
}
|
||||
if n < head {
|
||||
return false // to the end, or broken: no more fragments
|
||||
}
|
||||
at := off
|
||||
off += n
|
||||
if string(h[4:8]) != "moof" {
|
||||
continue
|
||||
}
|
||||
if n > 16<<20 {
|
||||
return false
|
||||
}
|
||||
moof := make([]byte, n-head)
|
||||
if _, err := d.r.ReadAt(moof, at+head); err != nil {
|
||||
return false
|
||||
}
|
||||
found := len(t.Sizes)
|
||||
if err := t.fragment(moof, at); err != nil {
|
||||
return false
|
||||
}
|
||||
for i := found; i < len(t.Sizes); i++ {
|
||||
d.add(t.Offsets[i], int(t.Sizes[i]), frames(t.Ends[i]))
|
||||
}
|
||||
if len(t.Sizes) > found {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
Vendored
+147
@@ -0,0 +1,147 @@
|
||||
// Package mp4 decodes the sound of MP4 files for package audio: .m4a and
|
||||
// .mp4, whole or cut into fragments as a stream for DASH is (.m4s). It
|
||||
// reads the container, and a codec registered with RegisterCodec decodes
|
||||
// its packets. Apple Lossless (ALAC) is built in; import package
|
||||
// audio/aac for AAC, and audio/flac for FLAC in MP4:
|
||||
//
|
||||
// import (
|
||||
// _ "github.com/egoist/mygo/audio/aac" // AAC, in MP4 too
|
||||
// _ "github.com/egoist/mygo/audio/flac" // FLAC, in MP4 too
|
||||
// )
|
||||
//
|
||||
// Each imports this package, which registers the format with package
|
||||
// audio.
|
||||
package mp4
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/audio"
|
||||
)
|
||||
|
||||
func init() {
|
||||
audio.RegisterFormat("mp4", "????ftyp", func(r io.ReadSeeker) (audio.Decoder, error) { return NewDecoder(r) })
|
||||
RegisterCodec("alac", func(config []byte) (Codec, error) { return newALACDecoder(config) })
|
||||
}
|
||||
|
||||
// A Codec decodes the packets of a track, one at a time, to stereo.
|
||||
type Codec interface {
|
||||
// SampleRate returns the frames per second it decodes to.
|
||||
SampleRate() int
|
||||
// Decode appends the sound of a packet to dst, as interleaved left
|
||||
// and right samples in [-1, 1], and returns it. A mono track plays in
|
||||
// both; of more channels, the front left and right play.
|
||||
Decode(dst []float32, packet []byte) ([]float32, error)
|
||||
// Reset forgets the packets decoded before, as after a seek.
|
||||
Reset()
|
||||
// Preroll returns how many packets before the one holding a frame
|
||||
// sought to are decoded first, for codecs whose packets overlap the
|
||||
// sound of the one before, as AAC's (1); 0 when packets stand alone.
|
||||
Preroll() int
|
||||
// PacketFrames returns how many frames every packet decodes to, when
|
||||
// all do, as AAC's 1024: packets are then placed in time by counting
|
||||
// them, whatever the file says they last. 0 places them as the file
|
||||
// says, for codecs whose packets differ.
|
||||
PacketFrames() int
|
||||
}
|
||||
|
||||
var (
|
||||
codecsMu sync.Mutex
|
||||
codecs = map[string]func([]byte) (Codec, error){}
|
||||
)
|
||||
|
||||
// RegisterCodec registers the codec of tracks whose sample entry is of
|
||||
// type fourcc, as "mp4a": open returns a decoder of its packets from the
|
||||
// track's configuration (see Track's Config). A package for a codec calls
|
||||
// it in its init function.
|
||||
func RegisterCodec(fourcc string, open func(config []byte) (Codec, error)) {
|
||||
codecsMu.Lock()
|
||||
defer codecsMu.Unlock()
|
||||
codecs[fourcc] = open
|
||||
}
|
||||
|
||||
func openCodec(t *track) (Codec, error) {
|
||||
codecsMu.Lock()
|
||||
open := codecs[t.Codec]
|
||||
codecsMu.Unlock()
|
||||
if open == nil {
|
||||
return nil, errors.New("mp4: no codec registered for " + t.Codec)
|
||||
}
|
||||
return open(t.Config)
|
||||
}
|
||||
|
||||
// Track describes an MP4's sound track, as its movie header says, for an
|
||||
// app to know of a file without decoding it, as a music library scanning
|
||||
// files does.
|
||||
type Track struct {
|
||||
// Codec is the type of the track's sample entry: "mp4a" (AAC),
|
||||
// "alac", "fLaC", "Opus", ...
|
||||
Codec string
|
||||
// Config configures the codec: AAC's AudioSpecificConfig, ALAC's
|
||||
// magic cookie, FLAC's metadata blocks, or another codec's boxes
|
||||
// within the sample entry.
|
||||
Config []byte
|
||||
// Duration is how long it plays, without the encoder's priming, or 0
|
||||
// for a fragmented file whose length its header doesn't say.
|
||||
Duration time.Duration
|
||||
// Fragmented says its packets are in fragments after the movie header.
|
||||
Fragmented bool
|
||||
}
|
||||
|
||||
// ReadTrack reads the first sound track of the MP4 file r holds, of size
|
||||
// bytes, from its movie header.
|
||||
func ReadTrack(r io.ReaderAt, size int64) (*Track, error) {
|
||||
t, err := readTrack(r, size, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Track{
|
||||
Codec: t.Codec,
|
||||
Config: t.Config,
|
||||
Duration: time.Duration(max(t.Duration-t.Prime, 0) * int64(time.Second) / t.Timescale),
|
||||
Fragmented: t.Fragmented,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Decodable says whether a codec registered decodes the track: HE-AAC, for
|
||||
// one, package aac does not.
|
||||
func (t *Track) Decodable() bool {
|
||||
_, err := openCodec(&track{Codec: t.Codec, Config: t.Config})
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// NewDecoder returns a decoder of the first sound track of the MP4 file r
|
||||
// holds, which decodes to stereo. It reads the movie header, and the
|
||||
// packets as they are played, so a file still coming in plays as it comes
|
||||
// when r waits for the bytes asked of it: a fragmented one, a fragment at
|
||||
// a time, with its length from its segment index. One with no index is
|
||||
// read through for its length.
|
||||
func NewDecoder(r io.ReadSeeker) (audio.Decoder, error) {
|
||||
size, err := r.Seek(0, io.SeekEnd)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ra, ok := r.(io.ReaderAt)
|
||||
if !ok {
|
||||
ra = &readerAt{r: r}
|
||||
}
|
||||
return newDecoder(ra, size)
|
||||
}
|
||||
|
||||
// readerAt reads at offsets of a ReadSeeker, seeking.
|
||||
type readerAt struct {
|
||||
mu sync.Mutex
|
||||
r io.ReadSeeker
|
||||
}
|
||||
|
||||
func (r *readerAt) ReadAt(b []byte, off int64) (int, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if _, err := r.r.Seek(off, io.SeekStart); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return io.ReadFull(r.r, b)
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
package mp4_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
_ "github.com/egoist/mygo/audio/flac"
|
||||
"github.com/egoist/mygo/audio/internal/audiotest"
|
||||
"github.com/egoist/mygo/audio/mp4"
|
||||
)
|
||||
|
||||
// alac.m4a is the first second of ../flac/testdata/tone.flac in Apple
|
||||
// Lossless: it decodes to exactly those samples, and a seek lands on the
|
||||
// very frame asked for.
|
||||
func TestALAC(t *testing.T) {
|
||||
b := audiotest.Read(t, "testdata/alac.m4a")
|
||||
tr, err := mp4.ReadTrack(bytes.NewReader(b), int64(len(b)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tr.Codec != "alac" || tr.Duration != time.Second || tr.Fragmented || !tr.Decodable() {
|
||||
t.Fatalf("%+v", tr)
|
||||
}
|
||||
d := audiotest.Open(t, b, "mp4")
|
||||
if d.SampleRate() != 44100 || d.Channels() != 2 || d.Len() != 44100 {
|
||||
t.Fatalf("%d Hz, %d channels, %d frames", d.SampleRate(), d.Channels(), d.Len())
|
||||
}
|
||||
got := audiotest.ReadAll(t, d)
|
||||
want := audiotest.ReadAll(t, audiotest.Open(t, audiotest.Read(t, "../flac/testdata/tone.flac"), "flac"))
|
||||
if len(got) != 44100*2 || audiotest.MaxDiff(got, want) != 0 {
|
||||
t.Fatalf("decoded %d samples, off from the FLAC by up to %g", len(got), audiotest.MaxDiff(got, want))
|
||||
}
|
||||
audiotest.SeekLands(t, d, got, 0, 0, 1, 4095, 4096, 30000, 44099)
|
||||
}
|
||||
|
||||
// A track of a codec none registered is described, and fails to decode:
|
||||
// this test doesn't import package aac.
|
||||
func TestNoCodec(t *testing.T) {
|
||||
b := audiotest.Read(t, "../aac/testdata/tone.m4a")
|
||||
tr, err := mp4.ReadTrack(bytes.NewReader(b), int64(len(b)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tr.Codec != "mp4a" || len(tr.Config) < 2 || tr.Duration != 2*time.Second || tr.Decodable() {
|
||||
t.Fatalf("%+v", tr)
|
||||
}
|
||||
if _, err := mp4.NewDecoder(bytes.NewReader(b)); err == nil {
|
||||
t.Fatal("decoded AAC with no codec for it")
|
||||
}
|
||||
}
|
||||
|
||||
// coming reads a file of which only the first n bytes are in, as one
|
||||
// still downloading, failing to read past them.
|
||||
type coming struct {
|
||||
*bytes.Reader
|
||||
n int64
|
||||
}
|
||||
|
||||
var errNotYet = errors.New("not in yet")
|
||||
|
||||
func (c *coming) ReadAt(b []byte, off int64) (int, error) {
|
||||
if off+int64(len(b)) > c.n {
|
||||
return 0, errNotYet
|
||||
}
|
||||
return c.Reader.ReadAt(b, off)
|
||||
}
|
||||
|
||||
// A fragmented MP4 plays with only its first fragment in, its length from
|
||||
// its segment index: the fragments after are read as it plays them.
|
||||
func TestFragmentedComingIn(t *testing.T) {
|
||||
b := audiotest.Read(t, "../flac/testdata/fragmented.m4a")
|
||||
r := &coming{bytes.NewReader(b), 16 << 10}
|
||||
tr, err := mp4.ReadTrack(r, int64(len(b)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !tr.Fragmented || tr.Duration != 2*time.Second {
|
||||
t.Fatalf("%+v", tr)
|
||||
}
|
||||
d, err := mp4.NewDecoder(r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if d.Len() != 88200 {
|
||||
t.Fatalf("length %d", d.Len())
|
||||
}
|
||||
buf := make([]float32, 2*4096)
|
||||
if n, err := d.Read(buf); n != len(buf) || err != nil {
|
||||
t.Fatalf("read %d samples: %v", n, err)
|
||||
}
|
||||
// Then the rest comes in.
|
||||
r.n = int64(len(b))
|
||||
got := append(buf, audiotest.ReadAll(t, d)...)
|
||||
if len(got) != 88200*2 {
|
||||
t.Fatalf("decoded %d samples", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
// A fragmented MP4 with no segment index is read through for its length.
|
||||
func TestFragmentedNoIndex(t *testing.T) {
|
||||
b := bytes.Clone(audiotest.Read(t, "../flac/testdata/fragmented.m4a"))
|
||||
at := bytes.Index(b, []byte("sidx"))
|
||||
copy(b[at:], "free")
|
||||
d := audiotest.Open(t, b, "mp4")
|
||||
if d.Len() != 88200 {
|
||||
t.Fatalf("length %d", d.Len())
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotMP4(t *testing.T) {
|
||||
_, err := mp4.NewDecoder(bytes.NewReader([]byte("\x00\x00\x00\x10ftypM4A \x00\x00\x00\x00")))
|
||||
if err == nil {
|
||||
t.Fatal("decoded an MP4 with no movie header")
|
||||
}
|
||||
if _, err := mp4.NewDecoder(bytes.NewReader(nil)); err == nil {
|
||||
t.Fatal("decoded nothing")
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
Reference in new issue
Block a user