Documentation
¶
Overview ¶
Package ogg reads and writes Ogg Opus streams.
Reader parses OpusHead and OpusTags from the initial logical bitstream, verifies page framing and CRCs, and returns packets from that stream. Writer writes OpusHead and OpusTags immediately. Each audio packet starts on a fresh page and spans continuation pages as needed. Close emits a packetless end-of-stream page; it does not flush or close the underlying writer. Page, OpusHead, and OpusTags provide lower- level container primitives; codec encoding and decoding remain in package gopus.
ParsePage and the header parsers return data independent of their input. Page.Packets returns slices that alias Page.Payload. Reader.ReadPacket returns an independently owned packet copy, while Reader.ReadPacketInto writes into the caller's buffer.
Example (RoundTripOgg) ¶
package main
import (
"bytes"
"fmt"
"log"
"math"
"github.com/thesyncim/gopus"
"github.com/thesyncim/gopus/container/ogg"
)
func main() {
// Complete Ogg Opus round-trip: encode to file, decode from file
var buf bytes.Buffer
// Encode to Ogg
w, err := ogg.NewWriter(&buf, uint32(48000), uint8(2))
if err != nil {
log.Fatal(err)
}
enc, err := gopus.NewEncoder(gopus.EncoderConfig{SampleRate: 48000, Channels: 2, Application: gopus.ApplicationAudio})
if err != nil {
log.Fatal(err)
}
// Encode 10 frames
for i := range 10 {
pcm := make([]float32, 960*2)
for j := range pcm {
pcm[j] = float32(math.Sin(float64(i*960*2+j) * 0.005))
}
packetBuf := make([]byte, 4000)
nPacket, err := enc.Encode(pcm, packetBuf)
if err != nil {
log.Fatal(err)
}
if err := w.WritePacket(packetBuf[:nPacket], 960); err != nil {
log.Fatal(err)
}
}
if err := w.Close(); err != nil {
log.Fatal(err)
}
// Decode from Ogg
r, err := ogg.NewReader(bytes.NewReader(buf.Bytes()))
if err != nil {
log.Fatal(err)
}
cfg := gopus.DefaultDecoderConfig(48000, 2)
dec, err := gopus.NewDecoder(cfg)
if err != nil {
log.Fatal(err)
}
pcmOut := make([]float32, cfg.MaxPacketSamples*cfg.Channels)
totalSamples := 0
for {
packet, _, err := r.ReadPacket()
if err != nil {
break
}
n, _ := dec.Decode(packet, pcmOut)
totalSamples += n
}
fmt.Printf("Round-trip: wrote 10 frames, decoded %d samples\n", totalSamples)
}
Output: Round-trip: wrote 10 frames, decoded 9600 samples
Example (WriteOggFile) ¶
package main
import (
"bytes"
"fmt"
"log"
"math"
"github.com/thesyncim/gopus"
"github.com/thesyncim/gopus/container/ogg"
)
func main() {
// Demonstrate creating an Ogg Opus file
var buf bytes.Buffer
// Create writer
w, err := ogg.NewWriter(&buf, uint32(48000), uint8(2))
if err != nil {
log.Fatal(err)
}
// Create encoder
enc, err := gopus.NewEncoder(gopus.EncoderConfig{SampleRate: 48000, Channels: 2, Application: gopus.ApplicationAudio})
if err != nil {
log.Fatal(err)
}
if err := enc.SetBitrate(128000); err != nil {
log.Fatal(err)
}
// Write 1 second of audio (50 frames of 20ms each)
for i := range 50 {
pcm := make([]float32, 960*2)
// Generate stereo sine wave
for j := range 960 {
t := float64(i*960+j) / 48000.0
pcm[j*2] = float32(math.Sin(2 * math.Pi * 440 * t)) // Left: 440 Hz
pcm[j*2+1] = float32(math.Sin(2 * math.Pi * 554 * t)) // Right: 554 Hz
}
packetBuf := make([]byte, 4000)
nPacket, err := enc.Encode(pcm, packetBuf)
if err != nil {
log.Fatal(err)
}
if err := w.WritePacket(packetBuf[:nPacket], 960); err != nil {
log.Fatal(err)
}
}
if err := w.Close(); err != nil {
log.Fatal(err)
}
fmt.Printf("Created 1-second Ogg Opus stream with %d frames\n", 50)
}
Output: Created 1-second Ogg Opus stream with 50 frames
Index ¶
- Constants
- Variables
- func BuildSegmentTable(packetLen int) []byte
- func ParseSegmentTable(segments []byte) []int
- type OpusHead
- func DefaultOpusHead(sampleRate uint32, channels uint8) *OpusHead
- func DefaultOpusHeadMultistream(sampleRate uint32, channels uint8, streams, coupled uint8, mapping []byte) *OpusHead
- func DefaultOpusHeadMultistreamWithFamily(sampleRate uint32, channels uint8, mappingFamily, streams, coupled uint8, ...) *OpusHead
- func ParseOpusHead(data []byte) (*OpusHead, error)
- type OpusTags
- type Page
- type Reader
- func (or *Reader) Channels() uint8
- func (or *Reader) EOF() bool
- func (or *Reader) GranulePos() uint64
- func (or *Reader) PreSkip() uint16
- func (or *Reader) ReadPacket() (packet []byte, granulePos uint64, err error)
- func (or *Reader) ReadPacketInto(dst []byte) (n int, granulePos uint64, err error)
- func (or *Reader) SampleRate() uint32
- func (or *Reader) SeekGranule(target uint64) error
- func (or *Reader) Serial() uint32
- type Writer
- type WriterConfig
Examples ¶
Constants ¶
const ( // MappingFamilyRTP is for mono/stereo with implicit channel order (RTP). MappingFamilyRTP = 0 // MappingFamilyVorbis is for 1-8 channels with Vorbis channel order. MappingFamilyVorbis = 1 // MappingFamilyAmbisonics is for ambisonics ACN/SN3D channel mapping. MappingFamilyAmbisonics = 2 // MappingFamilyProjection is for projection-based ambisonics mapping. MappingFamilyProjection = 3 // MappingFamilyDiscrete is for N channels with no defined relationship. MappingFamilyDiscrete = 255 )
MappingFamily values per RFC 7845.
const ( // PageFlagContinuation indicates this page contains data from a packet // that began on a previous page. PageFlagContinuation = 0x01 // PageFlagBOS (Beginning of Stream) indicates this is the first page // of a logical bitstream. PageFlagBOS = 0x02 // PageFlagEOS (End of Stream) indicates this is the last page of a // logical bitstream. PageFlagEOS = 0x04 )
Page header flag constants.
const ( // DefaultPreSkip is the standard Opus encoder lookahead at 48kHz. // This is the number of samples to discard at the beginning of decode. DefaultPreSkip = 312 )
Opus header constants per RFC 7845.
Variables ¶
var ( // ErrNilReader indicates a nil io.Reader was supplied to NewReader. ErrNilReader = errors.New("ogg: nil reader") // ErrNilWriter indicates a nil io.Writer was supplied to NewWriter. ErrNilWriter = errors.New("ogg: nil writer") // ErrInvalidPage indicates malformed page framing or a page that violates // the stream structure required by Reader. This includes missing "OggS" // magic, a truncated header/lacing table/payload, an invalid first-page BOS // marker, or inconsistent header continuation flags or sequence numbers. // Reader skips other logical streams. ParsePage preserves the version byte // instead of rejecting a nonzero value; checksum mismatches return ErrBadCRC. ErrInvalidPage = errors.New("ogg: invalid page structure") // ErrInvalidHeader indicates an Opus header (OpusHead or OpusTags) is malformed // or exceeds the supported comment-header size. This includes wrong magic // signature, unsupported version, or truncated data. ErrInvalidHeader = errors.New("ogg: invalid Opus header") // ErrBadCRC indicates the page CRC checksum does not match the computed value. // This typically indicates data corruption. ErrBadCRC = errors.New("ogg: CRC mismatch") // ErrUnexpectedEOS indicates that Writer.WritePacket was called after // Writer.Close. Reader reports stream exhaustion with io.EOF; malformed or // truncated page framing is reported separately. ErrUnexpectedEOS = errors.New("ogg: unexpected end of stream") // ErrPacketTooLarge indicates that ReadPacket or SeekGranule encountered a // packet larger than 61,440 octets per coded stream, or that ReadPacketInto // encountered a packet larger than len(dst). The packet is consumed even // though the method returns no packet and this error. ErrPacketTooLarge = errors.New("ogg: packet too large for buffer") // ErrNotSeekable indicates the reader does not support seeking. ErrNotSeekable = errors.New("ogg: reader is not seekable") )
Package-level errors for Ogg parsing and encoding.
Functions ¶
func BuildSegmentTable ¶
BuildSegmentTable creates a lacing table for a packet of nonnegative length. Each 255-byte entry continues the packet; a final entry below 255 terminates it. An empty packet is represented by one zero entry, and lengths divisible by 255 include an extra zero entry to mark packet completion.
func ParseSegmentTable ¶
ParseSegmentTable reconstructs packet lengths from an Ogg lacing table (RFC 3533 §6). Each lacing value of 255 means the packet continues into the next segment; the first value below 255 terminates a packet whose length is the running sum of its segments. The returned slice holds one entry per completed packet.
A table that ends on a 255 value describes a packet continued on the next page; that incomplete trailing packet is not included in the result. An empty table returns nil.
Types ¶
type OpusHead ¶
type OpusHead struct {
// Version is the format version. This package emits 1 and parses compatible
// minor versions 0 through 15.
Version uint8
// Channels is the output channel count (1-255).
Channels uint8
// PreSkip is the number of samples to discard at the start (at 48kHz).
// Typically 312 for standard Opus encoder lookahead.
PreSkip uint16
// SampleRate records the original input rate in hertz. Ogg Opus granule
// positions use 48 kHz sample units.
SampleRate uint32
// OutputGain is the gain to apply in Q7.8 dB format.
// Positive values amplify, negative values attenuate.
OutputGain int16
// MappingFamily identifies the channel mapping format. Defined values are
// MappingFamilyRTP, MappingFamilyVorbis, MappingFamilyAmbisonics,
// MappingFamilyProjection, and MappingFamilyDiscrete.
MappingFamily uint8
// StreamCount is the number of Opus streams in the packet.
StreamCount uint8
// CoupledCount is the number of coupled (stereo) streams.
CoupledCount uint8
// ChannelMapping maps output channels to decoder channels.
// For mapping family 0, this is implicit (not stored).
// For family 1/2/255, length equals Channels.
ChannelMapping []byte
// DemixingMatrix stores RFC 8486 family-3 demixing metadata.
// Size is 2*Channels*(StreamCount+CoupledCount) bytes in S16LE format.
DemixingMatrix []byte
// ExtraData stores opaque trailing fields from a compatible minor version.
// ParseOpusHead preserves these bytes so Encode does not discard extensions.
ExtraData []byte
}
OpusHead stores the identification header fields for an Ogg Opus stream.
func DefaultOpusHead ¶
DefaultOpusHead returns a mapping-family-0 header with the standard pre-skip. sampleRate is the original input rate in hertz; channels is 1 for mono or 2 for stereo.
func DefaultOpusHeadMultistream ¶
func DefaultOpusHeadMultistream(sampleRate uint32, channels uint8, streams, coupled uint8, mapping []byte) *OpusHead
DefaultOpusHeadMultistream returns a mapping-family-1 header for a surround layout. ChannelMapping aliases mapping; the function does not copy that slice.
func DefaultOpusHeadMultistreamWithFamily ¶
func DefaultOpusHeadMultistreamWithFamily(sampleRate uint32, channels uint8, mappingFamily, streams, coupled uint8, mapping []byte) *OpusHead
DefaultOpusHeadMultistreamWithFamily returns a header with the supplied multistream fields. For mapping family 3 it selects the default projection matrix when available, otherwise an identity matrix. For other families, ChannelMapping aliases mapping; the function does not copy that slice.
func ParseOpusHead ¶
ParseOpusHead parses an OpusHead identification header (RFC 7845 §5.1) from data. The returned header owns copies of its channel-mapping table and demixing matrix, so data may be reused afterwards.
It returns ErrInvalidHeader when data is too short, lacks the "OpusHead" magic, uses an incompatible version, has a zero channel count, or carries missing, truncated, or inconsistent fields. Compatible minor versions 0 through 15 are accepted; versions 0 and 1 require the known header length, while later minor versions may append extension data. Checks include coupled streams exceeding streams, more than 255 decoded stream channels, mapping indices outside the decoded streams, more than two channels for mapping family 0, more than eight channels for family 1, and a truncated RFC 8486 family-3 demixing matrix. For nonzero mapping families other than 3, it parses the generic channel-mapping layout and preserves the family byte; it does not reject unknown family numbers.
type OpusTags ¶
type OpusTags struct {
// Vendor is the encoder name (e.g., "gopus").
Vendor string
// Comments contains raw comment vectors, usually NAME=value, in wire order.
// It preserves duplicate names, original name casing, and entries without '='.
Comments []string
// ExtraData contains opaque bytes after the declared comment vectors.
// ParseOpusTags preserves this trailing data so Encode retains it.
ExtraData []byte
}
OpusTags is the comment header for Opus in Ogg.
func DefaultOpusTags ¶
func DefaultOpusTags() *OpusTags
DefaultOpusTags returns tags with the vendor set to "gopus" and no comments.
func ParseOpusTags ¶
ParseOpusTags parses an OpusTags comment header (RFC 7845 §5.2, Vorbis comment layout) from data. The vendor string and comments are copied into the returned struct, so data may be reused afterwards.
Comments preserve each raw vector, including duplicate names, original name casing, and entries without '='. The unsigned 32-bit lengths are bounds- checked against the remaining input, so an over-long vendor or comment length yields ErrInvalidHeader rather than reading past the buffer. Opaque trailing data is preserved in ExtraData.
It returns ErrInvalidHeader when data is too short, lacks the "OpusTags" magic, or declares a vendor, comment count, or comment length that extends past the end of data, or exceeds this package's 120 MiB comment-header bound. RFC 7845 permits unspecified trailing data after the declared comments; ParseOpusTags preserves it without interpreting it.
func (*OpusTags) Encode ¶
Encode returns a serialized copy of the OpusTags without validating comment syntax.
type Page ¶
type Page struct {
// Version is the stream structure version byte. Ogg currently defines
// version 0; ParsePage preserves this field without validating it.
Version byte
// HeaderType contains page flags (continuation, BOS, EOS).
HeaderType byte
// GranulePos is the granule position, representing the number of
// samples decoded (including this page) at the page's end.
// For Opus, this is the sample count at 48kHz.
GranulePos uint64
// SerialNumber identifies the logical bitstream.
SerialNumber uint32
// PageSequence is the page sequence number within the bitstream.
PageSequence uint32
// Segments contains the segment table entries.
// Each entry is the size of a segment (0-255).
Segments []byte
// Payload contains the concatenated packet data.
Payload []byte
}
Page represents a single Ogg page.
func ParsePage ¶
ParsePage parses the first complete Ogg page in data and returns the number of bytes consumed, leaving any following page bytes unconsumed. The returned Page owns copies of its segment table and payload, so data may be reused after the call. It validates the capture pattern, lacing-derived page length, and CRC; it preserves the version and flag bytes without checking stream-level rules. It returns ErrInvalidPage for missing magic or truncated framing, ErrBadCRC for a checksum mismatch, and a consumed count of zero on error.
func (*Page) Encode ¶
Encode returns a serialized copy of the page and computes its Ogg CRC-32 with the checksum field zeroed. It serializes the fields as supplied and does not validate them; callers must keep len(Segments) within 255 and make the segment lengths sum to len(Payload) for a structurally valid page.
func (*Page) IsContinuation ¶
IsContinuation returns true if this page continues a packet from a previous page.
func (*Page) PacketLengths ¶
PacketLengths extracts packet lengths from the segment table. This is equivalent to ParseSegmentTable(p.Segments).
func (*Page) Packets ¶
Packets splits the page payload into individual packet byte slices using the lacing lengths from PacketLengths.
The returned slices alias p.Payload; they remain valid only as long as the page is not modified. A packet whose final lacing value is 255 continues onto the next page and is not returned here. If the payload is shorter than the segment table claims, the final packet is truncated to the bytes actually present and parsing stops, so a malformed page never produces a slice outside p.Payload.
type Reader ¶
type Reader struct {
Header *OpusHead // Parsed ID header (set after NewReader)
Tags *OpusTags // Parsed comment header (set after NewReader)
// contains filtered or unexported fields
}
Reader reads Opus packets from an Ogg stream. It retains parsing state and is not safe for concurrent use.
func NewReader ¶
NewReader returns a Reader for r after parsing the OpusHead and OpusTags headers from the initial logical bitstream. It requires a BOS page containing OpusHead followed by OpusTags pages with the same serial number; pages from other logical bitstreams are skipped. Split OpusTags pages must carry the continuation flag and consecutive sequence numbers. An EOS page before OpusTags completes is invalid; an EOS OpusTags page produces a reader at EOF. OpusTags packets larger than 120 MiB are rejected to bound header memory use; RFC 7845 §5.2 permits rejecting comment headers above this size. Page lengths and CRCs are checked while reading, and nonzero Ogg page versions return ErrInvalidPage. It returns io.ErrNoProgress if the source returns no bytes or error for 100 consecutive reads. It returns ErrNilReader for a nil reader, ErrInvalidPage or ErrBadCRC for invalid page framing or checksums, ErrInvalidHeader for malformed Opus headers, and propagates errors from r. If r implements io.ReadSeeker, the Reader also supports SeekGranule.
Example ¶
package main
import (
"bytes"
"fmt"
"log"
"github.com/thesyncim/gopus"
"github.com/thesyncim/gopus/container/ogg"
)
func main() {
// First create some Ogg Opus data
var buf bytes.Buffer
w, err := ogg.NewWriter(&buf, uint32(48000), uint8(2))
if err != nil {
log.Fatal(err)
}
enc, err := gopus.NewEncoder(gopus.EncoderConfig{SampleRate: 48000, Channels: 2, Application: gopus.ApplicationAudio})
if err != nil {
log.Fatal(err)
}
pcm := make([]float32, 960*2)
packetBuf := make([]byte, 4000)
nPacket, err := enc.Encode(pcm, packetBuf)
if err != nil {
log.Fatal(err)
}
if err := w.WritePacket(packetBuf[:nPacket], 960); err != nil {
log.Fatal(err)
}
if err := w.Close(); err != nil {
log.Fatal(err)
}
// Now read it back
r, err := ogg.NewReader(bytes.NewReader(buf.Bytes()))
if err != nil {
log.Fatal(err)
}
fmt.Printf("Ogg Opus: %d channels, %d Hz\n", r.Channels(), r.SampleRate())
}
Output: Ogg Opus: 2 channels, 48000 Hz
func (*Reader) EOF ¶
EOF reports whether the Reader has seen the selected stream's EOS page or has encountered io.EOF while requesting more input. It can be true while packets already loaded from the EOS page remain unread.
func (*Reader) GranulePos ¶
GranulePos returns the granule position of the most recently assembled packet, in 48 kHz sample units. It is reset to zero by a successful SeekGranule and updated when the selected packet is read; an oversized packet consumed by ReadPacketInto also updates it.
func (*Reader) PreSkip ¶
PreSkip returns the pre-skip value from the OpusHead header. This is the number of samples to discard at the start of decode.
func (*Reader) ReadPacket ¶
ReadPacket returns the next Opus packet and its granule position, reassembling packets that span pages. The returned packet is an independent copy that the caller may retain or modify. Packets larger than 61,440 octets per coded stream return ErrPacketTooLarge. Pages from other logical bitstreams are skipped. Incomplete packets caused by missing pages are discarded. It returns io.EOF when the selected stream is exhausted or no more packet data can be read; an unterminated trailing packet can also end with io.EOF. Page framing, CRC, and underlying read errors are returned to the caller. It returns io.ErrNoProgress if the source returns no bytes or error for 100 consecutive reads.
Example ¶
package main
import (
"bytes"
"fmt"
"log"
"math"
"github.com/thesyncim/gopus"
"github.com/thesyncim/gopus/container/ogg"
)
func main() {
// Create Ogg data with multiple packets
var buf bytes.Buffer
w, err := ogg.NewWriter(&buf, uint32(48000), uint8(1))
if err != nil {
log.Fatal(err)
}
enc, err := gopus.NewEncoder(gopus.EncoderConfig{SampleRate: 48000, Channels: 1, Application: gopus.ApplicationAudio})
if err != nil {
log.Fatal(err)
}
for i := range 5 {
pcm := make([]float32, 960)
for j := range pcm {
pcm[j] = float32(math.Sin(float64(i*960+j) * 0.01))
}
packetBuf := make([]byte, 4000)
nPacket, err := enc.Encode(pcm, packetBuf)
if err != nil {
log.Fatal(err)
}
if err := w.WritePacket(packetBuf[:nPacket], 960); err != nil {
log.Fatal(err)
}
}
if err := w.Close(); err != nil {
log.Fatal(err)
}
// Read packets back
r, err := ogg.NewReader(bytes.NewReader(buf.Bytes()))
if err != nil {
log.Fatal(err)
}
cfg := gopus.DefaultDecoderConfig(48000, 1)
dec, err := gopus.NewDecoder(cfg)
if err != nil {
log.Fatal(err)
}
pcmOut := make([]float32, cfg.MaxPacketSamples*cfg.Channels)
packetCount := 0
for {
packet, _, err := r.ReadPacket()
if err != nil {
break
}
_, _ = dec.Decode(packet, pcmOut)
packetCount++
}
fmt.Printf("Decoded %d packets\n", packetCount)
}
Output: Decoded 5 packets
func (*Reader) ReadPacketInto ¶
ReadPacketInto writes the next Opus packet into dst and returns its length and granule position. len(dst), rather than cap(dst), is the size limit; the method does not grow dst or write beyond its length. Unlike ReadPacket and SeekGranule, it can read larger packets when the caller supplies enough storage. If the packet exceeds len(dst), it discards the excess without allocating packet storage, consumes the packet, and returns n == 0, granulePos == 0, and ErrPacketTooLarge. Pages from other logical bitstreams are skipped, and io.EOF indicates stream exhaustion. It returns io.ErrNoProgress if the source returns no bytes or error for 100 consecutive reads.
func (*Reader) SampleRate ¶
SampleRate returns the original input rate recorded in OpusHead. Ogg Opus granule positions use 48 kHz sample units.
func (*Reader) SeekGranule ¶
SeekGranule rewinds a seekable stream to its first audio page and scans for the first packet whose computed granule position is at least target. On success, the next ReadPacket or ReadPacketInto returns that packet; repeated calls start the scan again from the first audio page. It returns ErrNotSeekable if the source does not implement io.ReadSeeker, ErrPacketTooLarge when a scanned packet exceeds the per-stream size limit, io.EOF if no packet reaches target, and propagates seek or read errors.
type Writer ¶
type Writer struct {
// contains filtered or unexported fields
}
Writer writes Opus packets to an Ogg stream, retaining page and granule state. It writes directly to the supplied io.Writer without buffering and is not safe for concurrent use. Close writes the EOS page but does not flush or close the underlying writer.
func NewWriter ¶
NewWriter returns a Writer with the default mapping family for mono or stereo Opus. sampleRate is the original input rate in hertz and is informational; channels must be 1 or 2. It returns ErrNilWriter for a nil writer and ErrInvalidHeader for an unsupported channel count.
Example ¶
package main
import (
"bytes"
"fmt"
"log"
"github.com/thesyncim/gopus/container/ogg"
)
func main() {
// Create a buffer to write Ogg Opus data
var buf bytes.Buffer
// Create writer for 48kHz stereo
w, err := ogg.NewWriter(&buf, uint32(48000), uint8(2))
if err != nil {
log.Fatal(err)
}
defer w.Close()
fmt.Println("Ogg Opus writer created")
}
Output: Ogg Opus writer created
func NewWriterWithConfig ¶
func NewWriterWithConfig(w io.Writer, config WriterConfig) (*Writer, error)
NewWriterWithConfig returns a Writer configured by config and writes its OpusHead and OpusTags pages before returning. Mapping family 0 permits one or two channels; family 1 permits one through eight channels. Nonzero families require a nonzero stream count, no more coupled streams than streams, and at most 255 decoded stream channels. Nonzero families other than 3 require a channel-mapping entry per output channel. Family 3 accepts a demixing matrix of 2*Channels*(StreamCount+CoupledCount) bytes, or emits a default projection matrix when available and an identity matrix otherwise. The encoded OpusHead must fit on a single Ogg page; an oversized header returns ErrInvalidHeader. Errors from the underlying writer are returned; a failed write may already have written part of a header page.
func (*Writer) Close ¶
Close writes a packetless end-of-stream page and marks the Writer closed, unless WriteFinalPacket has already ended the stream. It does not flush or close the underlying io.Writer; callers must flush or close any wrapped buffered writer themselves. A successful repeated Close is a no-op. If writing the EOS page fails, Close returns the error and leaves the Writer open, although the sink may already contain part of that page.
Example ¶
package main
import (
"bytes"
"fmt"
"log"
"github.com/thesyncim/gopus"
"github.com/thesyncim/gopus/container/ogg"
)
func main() {
var buf bytes.Buffer
w, err := ogg.NewWriter(&buf, uint32(48000), uint8(1))
if err != nil {
log.Fatal(err)
}
// Write some audio
enc, err := gopus.NewEncoder(gopus.EncoderConfig{SampleRate: 48000, Channels: 1, Application: gopus.ApplicationAudio})
if err != nil {
log.Fatal(err)
}
pcm := make([]float32, 960)
packetBuf := make([]byte, 4000)
nPacket, err := enc.Encode(pcm, packetBuf)
if err != nil {
log.Fatal(err)
}
if err := w.WritePacket(packetBuf[:nPacket], 960); err != nil {
log.Fatal(err)
}
// Close writes the EOS page
err = w.Close()
if err != nil {
log.Fatal(err)
}
fmt.Println("Stream closed with EOS page")
}
Output: Stream closed with EOS page
func (*Writer) GranulePos ¶
GranulePos returns the current granule position (samples at 48kHz).
func (*Writer) PageCount ¶
PageCount returns the number of pages successfully written in full. A page that returns a write error is not counted, even if the underlying writer accepted some of its bytes.
func (*Writer) WriteFinalPacket ¶ added in v0.2.0
WriteFinalPacket writes packet across one or more audio pages, sets the EOS flag on its final page, and advances the granule position by samples. samples is the nonnegative contribution of this packet to the stream's final granule position in samples per channel at 48 kHz; callers use it to exclude any encoder padding at the end of the stream. The final granule is the previous granule position plus samples, as permitted for end trimming by RFC 7845 Section 4.4. The Writer does not parse packet or validate samples. Intermediate pages for a large packet have an unknown granule position and do not carry EOS. A successful write closes the Writer, so a later Close is a no-op.
On a page-write error the granule position is restored and the Writer remains open, but the underlying writer may have received earlier pages or part of a page. A short write without an error is reported as io.ErrShortWrite.
func (*Writer) WritePacket ¶
WritePacket writes packet across one or more audio pages and advances the granule position by samples, the nonnegative packet duration in samples per channel at 48 kHz (960 for a 20 ms frame). It does not parse packet or validate samples, so callers must supply a valid nonnegative duration. On a page-write error the granule position is restored, but the underlying writer may have received earlier pages or part of a page. A short write without an error is reported as io.ErrShortWrite. Calling WritePacket after Close or WriteFinalPacket returns ErrUnexpectedEOS.
Example ¶
package main
import (
"bytes"
"fmt"
"log"
"github.com/thesyncim/gopus"
"github.com/thesyncim/gopus/container/ogg"
)
func main() {
var buf bytes.Buffer
w, err := ogg.NewWriter(&buf, uint32(48000), uint8(2))
if err != nil {
log.Fatal(err)
}
// Create an encoder
enc, err := gopus.NewEncoder(gopus.EncoderConfig{SampleRate: 48000, Channels: 2, Application: gopus.ApplicationAudio})
if err != nil {
log.Fatal(err)
}
// Encode and write a frame
pcm := make([]float32, 960*2) // 20ms stereo
packetBuf := make([]byte, 4000)
nPacket, err := enc.Encode(pcm, packetBuf)
if err != nil {
log.Fatal(err)
}
// Write packet with sample count
err = w.WritePacket(packetBuf[:nPacket], 960)
if err != nil {
log.Fatal(err)
}
if err := w.Close(); err != nil {
log.Fatal(err)
}
r, err := ogg.NewReader(bytes.NewReader(buf.Bytes()))
if err != nil {
log.Fatal(err)
}
packet, granule, err := r.ReadPacket()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Stored packet at granule %d: %t\n", granule, len(packet) > 0)
}
Output: Stored packet at granule 960: true
type WriterConfig ¶
type WriterConfig struct {
// SampleRate records the original input rate in hertz. Ogg Opus granule
// positions use 48 kHz sample units.
SampleRate uint32
// Channels is the output channel count (1-255).
Channels uint8
// PreSkip is the number of samples to discard at the start (at 48kHz).
// Default is 312 for standard Opus encoder lookahead.
PreSkip uint16
// OutputGain is the gain to apply in Q7.8 dB format.
// Positive values amplify, negative values attenuate.
OutputGain int16
// MappingFamily specifies the channel mapping:
// 0: Mono/stereo (implicit order) - for 1-2 channels
// 1: Surround 1-8 channels (Vorbis order)
// 2: Ambisonics ACN/SN3D
// 3: Projection-based ambisonics
// 255: Discrete (no defined relationship)
MappingFamily uint8
// StreamCount is the number of Opus streams in the packet (for non-RTP mappings).
StreamCount uint8
// CoupledCount is the number of coupled (stereo) streams (for non-RTP mappings).
CoupledCount uint8
// ChannelMapping maps output channels to decoder channels (for family 1/2/255).
ChannelMapping []byte
// DemixingMatrix stores RFC 8486 family-3 demixing metadata.
// If empty for family 3, libopus default projection matrices are emitted
// when (channels,streams,coupled) matches a valid projection layout;
// otherwise an identity matrix is emitted.
DemixingMatrix []byte
}
WriterConfig configures a Writer.