196 lines · 5.1 KB · GoRaw
package mainimport ( "bytes" "encoding/binary" "errors" "fmt" "math" "os")// macOS's afconvert writes Opus only into a CAF file; WhatsApp plays a voice note only from an Ogg Opus one. This// moves the Opus packets from one container to the other, unchanged (RFC 7845's OpusHead, OpusTags, one packet a// page, granule positions at 48 kHz).type cafOpus struct { rate float64 channels uint32 frames uint32 // frames per packet, when every packet has the same priming int32 packets [][]byte perPacket []int64 // frames of each packet, when they differ}func readCAF(b []byte) (*cafOpus, error) { if len(b) < 8 || string(b[:4]) != "caff" { return nil, errors.New("not a CAF file") } c := &cafOpus{} var sizes []int64 var data []byte for off := 8; off+12 <= len(b); { kind := string(b[off : off+4]) size := int64(binary.BigEndian.Uint64(b[off+4 : off+12])) body := b[off+12:] if size >= 0 && size <= int64(len(body)) { body = body[:size] } switch kind { case "desc": if len(body) < 32 || string(body[8:12]) != "opus" { return nil, errors.New("the CAF file is not Opus") } c.rate = math.Float64frombits(binary.BigEndian.Uint64(body[0:8])) c.frames = binary.BigEndian.Uint32(body[20:24]) c.channels = binary.BigEndian.Uint32(body[24:28]) case "pakt": if len(body) < 24 { return nil, errors.New("the CAF packet table is short") } n := int64(binary.BigEndian.Uint64(body[0:8])) c.priming = int32(binary.BigEndian.Uint32(body[16:20])) rest := body[24:] for i := int64(0); i < n; i++ { size, used := vlq(rest) if used == 0 { return nil, errors.New("the CAF packet table is cut short") } rest = rest[used:] sizes = append(sizes, size) if c.frames == 0 { frames, used := vlq(rest) if used == 0 { return nil, errors.New("the CAF packet table is cut short") } rest = rest[used:] c.perPacket = append(c.perPacket, frames) } } case "data": if len(body) < 4 { return nil, errors.New("the CAF data is short") } data = body[4:] } if size < 0 { // the data chunk may run to the end of the file break } off += 12 + int(size) } if c.channels == 0 || data == nil || len(sizes) == 0 { return nil, errors.New("the CAF file holds no Opus packets") } for _, s := range sizes { if s <= 0 || s > int64(len(data)) { return nil, errors.New("a CAF packet runs past the data") } c.packets = append(c.packets, data[:s]) data = data[s:] } return c, nil}// vlq reads CAF's variable-length integer: seven bits a byte, high bit set on all but the last.func vlq(b []byte) (int64, int) { var v int64 for i := 0; i < len(b) && i < 9; i++ { v = v<<7 | int64(b[i]&0x7f) if b[i]&0x80 == 0 { return v, i + 1 } } return 0, 0}var oggTable = func() (t [256]uint32) { for i := range t { r := uint32(i) << 24 for j := 0; j < 8; j++ { if r&0x80000000 != 0 { r = r<<1 ^ 0x04c11db7 } else { r <<= 1 } } t[i] = r } return}()func oggPage(w *bytes.Buffer, kind byte, granule int64, serial, seq uint32, packet []byte) { var lacing []byte for n := len(packet); ; n -= 255 { if n < 255 { lacing = append(lacing, byte(n)) break } lacing = append(lacing, 255) } page := make([]byte, 27, 27+len(lacing)+len(packet)) copy(page, "OggS") page[5] = kind binary.LittleEndian.PutUint64(page[6:], uint64(granule)) binary.LittleEndian.PutUint32(page[14:], serial) binary.LittleEndian.PutUint32(page[18:], seq) page[26] = byte(len(lacing)) page = append(page, lacing...) page = append(page, packet...) var crc uint32 for _, b := range page { crc = crc<<8 ^ oggTable[byte(crc>>24)^b] } binary.LittleEndian.PutUint32(page[22:], crc) w.Write(page)}// cafToOgg writes the Opus packets of the CAF file at in as an Ogg Opus file at out.func cafToOgg(in, out string) error { raw, err := os.ReadFile(in) if err != nil { return err } c, err := readCAF(raw) if err != nil { return err } if len(c.packets[0]) > 255*255 { return fmt.Errorf("an Opus packet of %d bytes is too large", len(c.packets[0])) } scale := 1.0 if c.rate > 0 { scale = 48000 / c.rate } preSkip := int64(float64(c.priming) * scale) if preSkip <= 0 { preSkip = 312 // the encoder's usual delay at 48 kHz, when the file does not say } head := make([]byte, 19) copy(head, "OpusHead") head[8], head[9] = 1, byte(c.channels) binary.LittleEndian.PutUint16(head[10:], uint16(preSkip)) binary.LittleEndian.PutUint32(head[12:], uint32(c.rate)) vendor := "Cotton" tags := append([]byte("OpusTags"), make([]byte, 4)...) binary.LittleEndian.PutUint32(tags[8:], uint32(len(vendor))) tags = append(append(tags, vendor...), 0, 0, 0, 0) var w bytes.Buffer const serial = 0x436f7474 // "Cott" oggPage(&w, 0x02, 0, serial, 0, head) oggPage(&w, 0x00, 0, serial, 1, tags) var granule int64 for i, p := range c.packets { frames := int64(c.frames) if c.frames == 0 && i < len(c.perPacket) { frames = c.perPacket[i] } granule += int64(float64(frames) * scale) kind := byte(0) if i == len(c.packets)-1 { kind = 0x04 } oggPage(&w, kind, granule, serial, uint32(i+2), p) } return os.WriteFile(out, w.Bytes(), 0o600)}