### Install go-aac Library Source: https://github.com/skrashevich/go-aac/blob/main/README.md This command installs the go-aac library, which is a pure Go implementation of an AAC decoder. It allows developers to integrate AAC decoding capabilities into their Go applications without external dependencies. ```bash go get github.com/skrashevich/go-aac ``` -------------------------------- ### Install aac2pcm Command-Line Tool Source: https://github.com/skrashevich/go-aac/blob/main/README.md This command installs the aac2pcm command-line tool, which is built using the go-aac library. This tool can convert AAC audio files to WAV or raw PCM formats. ```bash go install github.com/skrashevich/go-aac/cmd/aac2pcm@latest ``` -------------------------------- ### Go Library Usage Example: Decoding AAC to PCM Source: https://github.com/skrashevich/go-aac/blob/main/README.md This Go code snippet illustrates the basic usage of the go-aac library for decoding an AAC audio stream. It covers probing ADTS data, creating a decoder, reading headers, decoding frames, and converting samples to PCM format. This example is derived from the aac2pcm command-line tool's implementation. ```go package main import ( "fmt" "io" "os" "github.com/skrashevich/go-aac/adts" "github.com/skrashevich/go-aac/decoder" ) func main() { inputFile := "input.aac" outputFile := "output.wav" // Open the input AAC file inFile, err := os.Open(inputFile) if err != nil { fmt.Fprintf(os.Stderr, "Error opening input file: %v\n", err) return } defer inFile.Close() // Create the output WAV file (or raw PCM if preferred) outFile, err := os.Create(outputFile) if err != nil { fmt.Fprintf(os.Stderr, "Error creating output file: %v\n", err) return } defer outFile.Close() // Probe for ADTS data _, err = adts.Probe(inFile) if err != nil { fmt.Fprintf(os.Stderr, "Error probing ADTS: %v\n", err) return } // Reset file reader after probing if _, err := inFile.Seek(0, io.SeekStart); err != nil { fmt.Fprintf(os.Stderr, "Error seeking input file: %v\n", err) return } // Create a new AAC decoder dec, err := decoder.New(inFile) if err != nil { fmt.Fprintf(os.Stderr, "Error creating decoder: %v\n", err) return } // Example: Write WAV header (simplified) // In a real application, you'd use a proper WAV writer // For raw PCM, you would skip this part. // For simplicity, we'll just write some placeholder bytes. // A full WAV writer implementation is recommended for production. fmt.Println("Writing WAV header (placeholder)...") // Decode frames and write to output for { frame, err := dec.DecodeFrame() if err != nil { if err == io.EOF { break // End of stream } fmt.Fprintf(os.Stderr, "Error decoding frame: %v\n", err) continue } // Convert float32 samples to int16 PCM // This is a simplified conversion. Proper scaling and clipping might be needed. pcmSamples := make([]int16, len(frame.Samples)) for i, sample := range frame.Samples { sample16 := int16(sample * 32767.0) if sample16 > 32767 { sample16 = 32767 } else if sample16 < -32768 { sample16 = -32768 } pcmSamples[i] = sample16 } // Write PCM samples to output file (as raw bytes) // For WAV, you'd interleave channels and write according to WAV format. for _, s := range pcmSamples { if _, err := os.Write(toBytes(s)); err != nil { fmt.Fprintf(os.Stderr, "Error writing PCM sample: %v\n", err) return } } } fmt.Println("AAC decoding complete.") } // Helper function to convert int16 to bytes (little-endian) func toBytes(i int16) []byte { return []byte{ byte(i), byte(i >> 8), } } ``` -------------------------------- ### Initialize AAC Decoder with AudioSpecificConfig (Go) Source: https://context7.com/skrashevich/go-aac/llms.txt Shows how to initialize an AAC decoder using an AudioSpecificConfig (ASC) byte slice. This method is useful when the audio configuration is known separately from the audio data. It sets the profile, sample rate, and channel configuration. ```go package main import ( "fmt" "github.com/skrashevich/go-aac/pkg/decoder" ) func main() { dec := decoder.New() // AudioSpecificConfig: AAC-LC, 44100 Hz, stereo // Byte 0: profile (2=AAC-LC) << 3 | sample_index >> 1 // Byte 1: (sample_index & 1) << 7 | channel_config << 3 asc := []byte{0x12, 0x10} // AAC-LC, 44100Hz, stereo err := dec.SetASC(asc) if err != nil { fmt.Println("Error:", err) return } fmt.Printf("Profile: %d (2=AAC-LC)\n", dec.Config.Profile) fmt.Printf("Sample rate: %d Hz\n", dec.Config.SampleRate) fmt.Printf("Channels: %d\n", dec.Config.ChanConfig) fmt.Printf("Frame length: %d samples\n", dec.Config.FrameLength) // Output: Profile: 2 (2=AAC-LC) // Output: Sample rate: 44100 Hz // Output: Channels: 2 // Output: Frame length: 1024 samples } ``` -------------------------------- ### Convert AAC to WAV using aac2pcm Source: https://github.com/skrashevich/go-aac/blob/main/README.md This command demonstrates how to use the aac2pcm command-line tool to convert an input AAC file (input.aac) into a WAV audio file (output.wav). ```bash aac2pcm input.aac output.wav ``` -------------------------------- ### Create AAC Decoder and Decode ADTS Frame (Go) Source: https://context7.com/skrashevich/go-aac/llms.txt Demonstrates creating a new AAC decoder instance and decoding the first frame from an ADTS audio file. The decoder auto-configures from the ADTS header. It requires reading the audio file and verifying the ADTS format. ```go package main import ( "fmt" "os" "github.com/skrashevich/go-aac/pkg/adts" "github.com/skrashevich/go-aac/pkg/decoder" ) func main() { // Read AAC file data, err := os.ReadFile("audio.aac") if err != nil { fmt.Println("Error:", err) return } // Verify ADTS format if !adts.Probe(data) { fmt.Println("Not a valid ADTS file") return } // Create decoder dec := decoder.New() // Decode first frame (auto-configures from ADTS header) header, _ := adts.ReadHeaderFromBytes(data) frameData := data[:header.FrameLength] samples, err := dec.DecodeFrame(frameData) if err != nil { fmt.Println("Decode error:", err) return } fmt.Printf("Decoded %d samples\n", len(samples)) fmt.Printf("Sample rate: %d Hz\n", dec.Config.SampleRate) fmt.Printf("Channels: %d\n", dec.Config.ChanConfig) // Output: Decoded 2048 samples // Output: Sample rate: 44100 Hz // Output: Channels: 2 } ``` -------------------------------- ### Output Raw PCM to stdout using aac2pcm Source: https://github.com/skrashevich/go-aac/blob/main/README.md This command shows how to use the aac2pcm tool to convert an input AAC file (input.aac) and redirect the raw PCM audio output to standard output, which can then be piped to another command or file. ```bash aac2pcm --raw input.aac > output.pcm ``` -------------------------------- ### Create FilterBank for AAC Decoding with Go Source: https://context7.com/skrashevich/go-aac/llms.txt Initializes a FilterBank for AAC decoding, handling IMDCT, windowing, and overlap-add operations. It converts frequency-domain spectral coefficients back to time-domain audio samples. Requires the `github.com/skrashevich/go-aac/pkg/filterbank` package. ```go package main import ( "fmt" "github.com/skrashevich/go-aac/pkg/filterbank" ) func main() { // Create filterbank for stereo audio channels := 2 smallFrames := false // Standard 1024-sample frames fb, err := filterbank.New(smallFrames, channels) if err != nil { fmt.Println("Error:", err) return } fmt.Printf("FilterBank created for %d channels\n", channels) fmt.Println("Ready to process spectral data") // The filterbank is used internally by the decoder // to convert decoded spectral coefficients to PCM samples _ = fb } ``` -------------------------------- ### decoder.New Source: https://context7.com/skrashevich/go-aac/llms.txt Creates a new AAC decoder instance. The decoder can be configured either by calling SetASC with an AudioSpecificConfig or by directly decoding ADTS frames which auto-configure the decoder from the ADTS header. ```APIDOC ## decoder.New ### Description Creates a new AAC decoder instance. The decoder can be configured either by calling `SetASC` with an AudioSpecificConfig or by directly decoding ADTS frames which auto-configure the decoder from the ADTS header. ### Method `New()` ### Parameters None ### Request Example ```go package main import ( "fmt" "os" "github.com/skrashevich/go-aac/pkg/adts" "github.com/skrashevich/go-aac/pkg/decoder" ) func main() { // Read AAC file data, err := os.ReadFile("audio.aac") if err != nil { fmt.Println("Error:", err) return } // Verify ADTS format if !adts.Probe(data) { fmt.Println("Not a valid ADTS file") return } // Create decoder dec := decoder.New() // Decode first frame (auto-configures from ADTS header) header, _ := adts.ReadHeaderFromBytes(data) frameData := data[:header.FrameLength] samples, err := dec.DecodeFrame(frameData) if err != nil { fmt.Println("Decode error:", err) return } fmt.Printf("Decoded %d samples\n", len(samples)) fmt.Printf("Sample rate: %d Hz\n", dec.Config.SampleRate) fmt.Printf("Channels: %d\n", dec.Config.ChanConfig) } ``` ### Response #### Success Response - `*decoder.Decoder` (pointer) - A new AAC decoder instance. #### Response Example ```go // dec is a *decoder.Decoder instance ``` ``` -------------------------------- ### Generate AudioSpecificConfig with Go Source: https://context7.com/skrashevich/go-aac/llms.txt Generates a 2-byte MPEG-4 AudioSpecificConfig from an ADTS header. This is essential for MP4 containers and streaming protocols. It takes an `adts.Header` struct and returns a byte slice representing the configuration. Requires the `github.com/skrashevich/go-aac/pkg/adts` package. ```go package main import ( "fmt" "github.com/skrashevich/go-aac/pkg/adts" ) func main() { // Create header for AAC-LC, 44100Hz, stereo header := adts.Header{ Profile: 2, // AAC-LC SamplingIndex: 4, // 44100 Hz ChannelConfig: 2, // Stereo } asc, err := adts.AudioSpecificConfig(header) if err != nil { fmt.Println("Error:", err) return } fmt.Printf("AudioSpecificConfig: %02X %02X\n", asc[0], asc[1]) fmt.Printf("Binary: %08b %08b\n", asc[0], asc[1]) // Output: AudioSpecificConfig: 12 10 // Binary: 00010010 00010000 // Breakdown: // - Bits 0-4: Profile (2) << 3 = 00010000 // - Bits 5-8: Sample index (4) = 0100 // - Bits 9-12: Channel config (2) << 3 = 00010000 } ``` -------------------------------- ### FilterBank Creation Source: https://context7.com/skrashevich/go-aac/llms.txt The `filterbank.New` function initializes a FilterBank, which is responsible for IMDCT, windowing, and overlap-add operations to convert frequency-domain spectral coefficients back to time-domain audio samples. ```APIDOC ## New FilterBank ### Description Creates a new FilterBank for AAC decoding. The filterbank performs IMDCT, windowing, and overlap-add operations to convert frequency-domain spectral coefficients back to time-domain audio samples. ### Method `filterbank.New(smallFrames bool, channels int) (*FilterBank, error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "fmt" "github.com/skrashevich/go-aac/pkg/filterbank" ) func main() { // Create filterbank for stereo audio channels := 2 smallFrames := false // Standard 1024-sample frames fb, err := filterbank.New(smallFrames, channels) if err != nil { fmt.Println("Error:", err) return } fmt.Printf("FilterBank created for %d channels\n", channels) fmt.Println("Ready to process spectral data") _ = fb } ``` ### Response #### Success Response (FilterBank) - **fb** (*FilterBank) - A pointer to the initialized FilterBank object. #### Response Example ```json { "FilterBank": "" } ``` #### Error Response - **Error** (error) - Description of the error encountered during FilterBank creation. ``` -------------------------------- ### decoder.SetASC Source: https://context7.com/skrashevich/go-aac/llms.txt Parses an MPEG-4 AudioSpecificConfig (2 bytes) and initializes the decoder with the specified configuration. This is useful when the audio configuration is provided separately from the audio data, such as in MP4 containers or streaming protocols. ```APIDOC ## decoder.SetASC ### Description Parses an MPEG-4 AudioSpecificConfig (2 bytes) and initializes the decoder with the specified configuration. This is useful when the audio configuration is provided separately from the audio data, such as in MP4 containers or streaming protocols. ### Method `SetASC(asc []byte) error` ### Parameters #### Request Body - **asc** ([]byte) - Required - A 2-byte slice representing the AudioSpecificConfig. ### Request Example ```go package main import ( "fmt" "github.com/skrashevich/go-aac/pkg/decoder" ) func main() { dec := decoder.New() // AudioSpecificConfig: AAC-LC, 44100 Hz, stereo // Byte 0: profile (2=AAC-LC) << 3 | sample_index >> 1 // Byte 1: (sample_index & 1) << 7 | channel_config << 3 asc := []byte{0x12, 0x10} // AAC-LC, 44100Hz, stereo err := dec.SetASC(asc) if err != nil { fmt.Println("Error:", err) return } fmt.Printf("Profile: %d (2=AAC-LC)\n", dec.Config.Profile) fmt.Printf("Sample rate: %d Hz\n", dec.Config.SampleRate) fmt.Printf("Channels: %d\n", dec.Config.ChanConfig) fmt.Printf("Frame length: %d samples\n", dec.Config.FrameLength) } ``` ### Response #### Success Response (200) No direct response body, but the decoder configuration is updated. #### Error Response (non-200) - **error** (error) - An error if the ASC is invalid or cannot be parsed. #### Response Example ``` // On success, no output is returned, but decoder configuration is updated. // On error: // Error: invalid AudioSpecificConfig ``` ``` -------------------------------- ### Create MDCT Processor with Go Source: https://context7.com/skrashevich/go-aac/llms.txt Creates an MDCT (Modified Discrete Cosine Transform) processor for a specified transform length. Supported lengths include 2048 and 256 (for AAC-LC), and 1920 and 240 (for AAC-LD). Requires the `github.com/skrashevich/go-aac/pkg/mdct` package. ```go package main import ( "fmt" "github.com/skrashevich/go-aac/pkg/mdct" ) func main() { // Create MDCT for standard AAC-LC long blocks (2048 samples) m, err := mdct.New(2048) if err != nil { fmt.Println("Error:", err) return } fmt.Printf("MDCT length: %d\n", m.Length()) fmt.Printf("Input coefficients: %d\n", m.N2) // N/2 = 1024 fmt.Printf("Output samples: %d\n", m.N) // N = 2048 // Process spectral coefficients (example with zeros) input := make([]float32, 1024) // N/2 spectral coefficients output := make([]float32, 2048) // N time-domain samples m.Process(input, 0, output, 0) fmt.Println("IMDCT processing complete") } ``` -------------------------------- ### Decode All AAC Frames and Output PCM (Go) Source: https://context7.com/skrashevich/go-aac/llms.txt This Go code snippet demonstrates decoding all AAC frames from an audio file and converting the resulting PCM samples to int16 format for raw output. It iterates through the file, reads ADTS headers, decodes each frame, and writes the interleaved PCM data to an output file. ```go package main import ( "encoding/binary" "fmt" "os" "github.com/skrashevich/go-aac/pkg/adts" "github.com/skrashevich/go-aac/pkg/decoder" ) func main() { data, _ := os.ReadFile("audio.aac") dec := decoder.New() offset := 0 var allSamples []float32 // Decode all frames for offset < len(data) { if len(data)-offset < 7 { break } header, err := adts.ReadHeaderFromBytes(data[offset:]) if err != nil { break } frameData := data[offset : offset+header.FrameLength] samples, err := dec.DecodeFrame(frameData) if err != nil { fmt.Printf("Frame decode error: %v\n", err) offset += header.FrameLength continue } allSamples = append(allSamples, samples...) offset += header.FrameLength } // Convert float32 samples to int16 for PCM output int16Samples := make([]int16, len(allSamples)) for i, v := range allSamples { // Clamp and scale to int16 range if v > 1.0 { v = 1.0 } else if v < -1.0 { v = -1.0 } int16Samples[i] = int16(v * 32767) } // Write raw PCM f, _ := os.Create("output.pcm") defer f.Close() binary.Write(f, binary.LittleEndian, int16Samples) fmt.Printf("Decoded %d samples total\n", len(allSamples)) } ``` -------------------------------- ### Create TNS Processor (Go) Source: https://context7.com/skrashevich/go-aac/llms.txt Creates a Temporal Noise Shaping (TNS) processor for a given sample rate index. TNS is used to reduce quantization noise in spectral data. It requires a valid sample rate index as input. ```go package main import ( "fmt" "github.com/skrashevich/go-aac/pkg/tns" ) func main() { // Create TNS for 44100 Hz (sample index 4) sampleIndex := 4 t, err := tns.New(sampleIndex) if err != nil { fmt.Println("Error:", err) return } fmt.Printf("TNS processor created for sample index %d\n", sampleIndex) // TNS is used internally by the ICS decoder // to apply noise shaping to spectral coefficients _ = t } ``` -------------------------------- ### AAC to WAV Conversion in Go Source: https://context7.com/skrashevich/go-aac/llms.txt Converts an AAC audio file to WAV format. It reads the input, decodes AAC frames using the go-aac library, converts samples to PCM, and writes a WAV file. Dependencies include standard Go libraries and the go-aac package. ```go package main import ( "encoding/binary" "fmt" "io" "math" "os" "github.com/skrashevich/go-aac/pkg/adts" "github.com/skrashevich/go-aac/pkg/decoder" ) func main() { // Read input AAC file data, err := os.ReadFile("input.aac") if err != nil { fmt.Fprintf(os.Stderr, "Error reading input: %v\n", err) os.Exit(1) } // Verify ADTS format if !adts.Probe(data) { fmt.Fprintln(os.Stderr, "Error: not a valid ADTS file") os.Exit(1) } // Create decoder and decode all frames dec := decoder.New() var allSamples []float32 offset := 0 frameCount := 0 for offset < len(data) { if len(data)-offset < 7 { break } header, err := adts.ReadHeaderFromBytes(data[offset:]) if err != nil { break } if header.FrameLength < 7 || offset+header.FrameLength > len(data) { break } samples, err := dec.DecodeFrame(data[offset : offset+header.FrameLength]) if err != nil { fmt.Fprintf(os.Stderr, "Warning: frame %d error: %v\n", frameCount, err) offset += header.FrameLength frameCount++ continue } allSamples = append(allSamples, samples...) offset += header.FrameLength frameCount++ } if len(allSamples) == 0 { fmt.Fprintln(os.Stderr, "Error: no samples decoded") os.Exit(1) } // Get audio parameters from decoder config sampleRate := dec.Config.SampleRate numChannels := dec.Config.ChanConfig // Convert float32 to int16 with clipping int16Samples := make([]int16, len(allSamples)) for i, v := range allSamples { clamped := math.Max(-1.0, math.Min(1.0, float64(v))) int16Samples[i] = int16(clamped * 32767.0) } // Write WAV file outFile, err := os.Create("output.wav") if err != nil { fmt.Fprintf(os.Stderr, "Error creating output: %v\n", err) os.Exit(1) } defer outFile.Close() writeWAV(outFile, int16Samples, sampleRate, numChannels) fmt.Printf("Converted %d frames (%d samples) to output.wav\n", frameCount, len(allSamples)) fmt.Printf("Sample rate: %d Hz, Channels: %d\n", sampleRate, numChannels) } func writeWAV(w io.Writer, samples []int16, sampleRate, numChannels int) { dataSize := uint32(len(samples) * 2) fileSize := 36 + dataSize bitsPerSample := uint16(16) blockAlign := uint16(numChannels) * bitsPerSample / 8 byteRate := uint32(sampleRate) * uint32(blockAlign) // RIFF header w.Write([]byte("RIFF")) binary.Write(w, binary.LittleEndian, fileSize) w.Write([]byte("WAVE")) // fmt sub-chunk w.Write([]byte("fmt ")) binary.Write(w, binary.LittleEndian, uint32(16)) // Sub-chunk size binary.Write(w, binary.LittleEndian, uint16(1)) // PCM format binary.Write(w, binary.LittleEndian, uint16(numChannels)) binary.Write(w, binary.LittleEndian, uint32(sampleRate)) binary.Write(w, binary.LittleEndian, byteRate) binary.Write(w, binary.LittleEndian, blockAlign) binary.Write(w, binary.LittleEndian, bitsPerSample) // data sub-chunk w.Write([]byte("data")) binary.Write(w, binary.LittleEndian, dataSize) binary.Write(w, binary.LittleEndian, samples) } ``` -------------------------------- ### Verbose Mode Conversion with aac2pcm Source: https://github.com/skrashevich/go-aac/blob/main/README.md This command utilizes the aac2pcm tool with the verbose flag (-v) to convert an AAC file (input.aac) to a WAV file (output.wav). The verbose mode provides additional details during the conversion process. ```bash aac2pcm -v input.aac output.wav ``` -------------------------------- ### MDCT Processor Creation Source: https://context7.com/skrashevich/go-aac/llms.txt The `mdct.New` function creates an MDCT (Modified Discrete Cosine Transform) processor for a specified transform length, supporting lengths like 2048, 256, 1920, and 240. ```APIDOC ## New MDCT Processor ### Description Creates a new MDCT (Modified Discrete Cosine Transform) processor for the specified transform length. Supported lengths are 2048, 256 (standard AAC-LC), 1920, and 240 (AAC-LD). ### Method `mdct.New(length int) (*MDCT, error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "fmt" "github.com/skrashevich/go-aac/pkg/mdct" ) func main() { // Create MDCT for standard AAC-LC long blocks (2048 samples) m, err := mdct.New(2048) if err != nil { fmt.Println("Error:", err) return } fmt.Printf("MDCT length: %d\n", m.Length()) fmt.Printf("Input coefficients: %d\n", m.N2) // N/2 = 1024 fmt.Printf("Output samples: %d\n", m.N) // N = 2048 input := make([]float32, 1024) // N/2 spectral coefficients output := make([]float32, 2048) // N time-domain samples m.Process(input, 0, output, 0) fmt.Println("IMDCT processing complete") } ``` ### Response #### Success Response (MDCT Processor) - **m** (*MDCT) - A pointer to the initialized MDCT processor. - **Length()** (int) - Returns the transform length. - **N2** (int) - The number of spectral coefficients (N/2). - **N** (int) - The number of time-domain samples (N). #### Response Example ```json { "MDCTProcessor": { "Length": 2048, "N2": 1024, "N": 2048 } } ``` #### Error Response - **Error** (error) - Description of the error encountered during MDCT processor creation (e.g., unsupported length). ``` -------------------------------- ### Audio Specific Config Generation Source: https://context7.com/skrashevich/go-aac/llms.txt The `adts.AudioSpecificConfig` function generates a 2-byte MPEG-4 AudioSpecificConfig from an ADTS header, which is essential for MP4 containers and streaming protocols. ```APIDOC ## AudioSpecificConfig ### Description Generates a 2-byte MPEG-4 AudioSpecificConfig from an ADTS header. This is useful for creating configuration data needed by MP4 containers or streaming protocols like HLS/DASH. ### Method `adts.AudioSpecificConfig(header Header) ([]byte, error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "fmt" "github.com/skrashevich/go-aac/pkg/adts" ) func main() { // Create header for AAC-LC, 44100Hz, stereo header := adts.Header{ Profile: 2, // AAC-LC SamplingIndex: 4, // 44100 Hz ChannelConfig: 2, // Stereo } asc, err := adts.AudioSpecificConfig(header) if err != nil { fmt.Println("Error:", err) return } fmt.Printf("AudioSpecificConfig: %02X %02X\n", asc[0], asc[1]) fmt.Printf("Binary: %08b %08b\n", asc[0], asc[1]) } ``` ### Response #### Success Response (2-byte slice) - **asc** ([]byte) - A 2-byte slice representing the AudioSpecificConfig. #### Response Example ```json { "asc": [ "12", "10" ] } ``` #### Error Response - **Error** (error) - Description of the error encountered during configuration generation. ``` -------------------------------- ### Probe ADTS Syncword with Go Source: https://context7.com/skrashevich/go-aac/llms.txt Scans byte data to detect a valid ADTS syncword (0xFFF), indicating ADTS-formatted AAC audio. It takes a byte slice as input and returns a boolean. ```go package main import ( "fmt" "os" "github.com/skrashevich/go-aac/pkg/adts" ) func main() { // Check if file is ADTS format data, _ := os.ReadFile("audio.aac") if adts.Probe(data) { fmt.Println("Valid ADTS file detected") } else { fmt.Println("Not an ADTS file") } // Probe raw bytes validADTS := []byte{0xFF, 0xF1, 0x50, 0x80, 0x00, 0x1F, 0xFC} invalidData := []byte{0x00, 0x00, 0x00, 0x00} fmt.Printf("Valid header probe: %v\n", adts.Probe(validADTS)) // true fmt.Printf("Invalid data probe: %v\n", adts.Probe(invalidData)) // false } ``` -------------------------------- ### huffman.DecodeScaleFactor Source: https://context7.com/skrashevich/go-aac/llms.txt Decodes a Huffman-coded scalefactor value from the AAC bitstream. Scalefactors are crucial for adjusting spectral band amplitudes during audio reconstruction. ```APIDOC ## huffman.DecodeScaleFactor ### Description Decodes a Huffman-coded scalefactor value from the AAC bitstream. Scalefactors control the amplitude of spectral bands and are essential for accurate audio reconstruction. ### Method `huffman.DecodeScaleFactor(reader huffman.BitReader) uint32` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "fmt" "github.com/skrashevich/go-aac/pkg/huffman" ) // MockBitReader implements huffman.BitReader for demonstration type MockBitReader struct { data []byte offset int } func (r *MockBitReader) ReadBits(n int) uint32 { // Simplified bit reading (production code should handle bit boundaries) if r.offset >= len(r.data)*8 { return 0 } result := uint32(r.data[r.offset/8]) r.offset += n return result >> (8 - n) } func main() { // In actual use, the bit reader comes from the AAC frame parser reader := &MockBitReader{data: []byte{0x80}} value := huffman.DecodeScaleFactor(reader) fmt.Printf("Decoded scalefactor value: %d\n", value) // Scalefactors typically range from 0-255 and are delta-coded // The actual gain is: 2^((scalefactor-100)/4) } ``` ### Response #### Success Response (200) Returns the decoded scalefactor value as a `uint32`. #### Response Example ```json { "decoded_scalefactor": 128 } ``` ``` -------------------------------- ### tns.New Source: https://context7.com/skrashevich/go-aac/llms.txt Creates a Temporal Noise Shaping (TNS) processor for a given sample rate index. TNS is used to reduce quantization noise in spectral data. ```APIDOC ## tns.New ### Description Creates a Temporal Noise Shaping (TNS) processor for the given sample rate index. TNS applies adaptive filtering to spectral data to reduce quantization noise and improve audio quality. ### Method `tns.New(sampleIndex int) (*tns.TNS, error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "fmt" "github.com/skrashevich/go-aac/pkg/tns" ) func main() { // Create TNS for 44100 Hz (sample index 4) sampleIndex := 4 t, err := tns.New(sampleIndex) if err != nil { fmt.Println("Error:", err) return } fmt.Printf("TNS processor created for sample index %d\n", sampleIndex) _ = t } ``` ### Response #### Success Response (200) Returns a pointer to a `tns.TNS` struct and a nil error upon successful creation. #### Response Example ```json { "message": "TNS processor created successfully" } ``` ``` -------------------------------- ### Read ADTS Header from Bytes with Go Source: https://context7.com/skrashevich/go-aac/llms.txt Parses an ADTS header from a byte slice, returning a Header struct. The struct contains details like profile, sample rate, channel configuration, frame length, and CRC status. It requires the `github.com/skrashevich/go-aac/pkg/adts` and `github.com/skrashevich/go-aac/pkg/tables` packages. ```go package main import ( "fmt" "os" "github.com/skrashevich/go-aac/pkg/adts" "github.com/skrashevich/go-aac/pkg/tables" ) func main() { data, _ := os.ReadFile("audio.aac") header, err := adts.ReadHeaderFromBytes(data) if err != nil { fmt.Println("Error:", err) return } fmt.Printf("Profile: %d (1=Main, 2=LC, 3=SSR, 4=LTP)\n", header.Profile) fmt.Printf("Sample rate index: %d\n", header.SamplingIndex) fmt.Printf("Sample rate: %d Hz\n", tables.SampleRates[header.SamplingIndex]) fmt.Printf("Channel config: %d\n", header.ChannelConfig) fmt.Printf("Frame length: %d bytes\n", header.FrameLength) fmt.Printf("Number of frames: %d\n", header.NumFrames) fmt.Printf("Protection absent (no CRC): %v\n", header.ProtectionAbsent) // Output example: // Profile: 2 (1=Main, 2=LC, 3=SSR, 4=LTP) // Sample rate index: 4 // Sample rate: 44100 Hz // Channel config: 2 // Frame length: 372 bytes // Number of frames: 1 // Protection absent (no CRC): true } ``` -------------------------------- ### ADTS Probe Function Source: https://context7.com/skrashevich/go-aac/llms.txt The `adts.Probe` function checks if a given byte slice contains a valid ADTS syncword (0xFFF), indicating ADTS-formatted AAC audio data. ```APIDOC ## Probe ### Description Scans the provided data for an ADTS syncword (0xFFF) to verify if the data contains valid ADTS-formatted AAC audio. Returns true if a valid syncword is found. ### Method `adts.Probe(data []byte) bool` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "fmt" "os" "github.com/skrashevich/go-aac/pkg/adts" ) func main() { data, _ := os.ReadFile("audio.aac") if adts.Probe(data) { fmt.Println("Valid ADTS file detected") } else { fmt.Println("Not an ADTS file") } validADTS := []byte{0xFF, 0xF1, 0x50, 0x80, 0x00, 0x1F, 0xFC} invalidData := []byte{0x00, 0x00, 0x00, 0x00} fmt.Printf("Valid header probe: %v\n", adts.Probe(validADTS)) // true fmt.Printf("Invalid data probe: %v\n", adts.Probe(invalidData)) // false } ``` ### Response #### Success Response (bool) - `true`: If a valid ADTS syncword is found. - `false`: If no valid ADTS syncword is found. #### Response Example ```json { "example": "true" } ``` ``` -------------------------------- ### Decode Scalefactor (Go) Source: https://context7.com/skrashevich/go-aac/llms.txt Decodes a Huffman-coded scalefactor value from an AAC bitstream using a provided bit reader. Scalefactors are crucial for adjusting spectral band amplitudes during audio reconstruction. The input is a Huffman bit reader. ```go package main import ( "fmt" "github.com/skrashevich/go-aac/pkg/huffman" ) // MockBitReader implements huffman.BitReader for demonstration type MockBitReader struct { data []byte offset int } func (r *MockBitReader) ReadBits(n int) uint32 { // Simplified bit reading (production code should handle bit boundaries) if r.offset >= len(r.data)*8 { return 0 } result := uint32(r.data[r.offset/8]) r.offset += n return result >> (8 - n) } func main() { // In actual use, the bit reader comes from the AAC frame parser reader := &MockBitReader{data: []byte{0x80}} value := huffman.DecodeScaleFactor(reader) fmt.Printf("Decoded scalefactor value: %d\n", value) // Scalefactors typically range from 0-255 and are delta-coded // The actual gain is: 2^((scalefactor-100)/4) } ``` -------------------------------- ### ADTS Header Parsing Source: https://context7.com/skrashevich/go-aac/llms.txt The `adts.ReadHeaderFromBytes` function parses an ADTS header from a byte slice, returning a `Header` struct with details like profile, sample rate, channel configuration, frame length, and CRC status. ```APIDOC ## ReadHeaderFromBytes ### Description Parses an ADTS header from a byte slice and returns a `Header` struct containing profile, sample rate index, channel configuration, frame length, and CRC protection status. ### Method `adts.ReadHeaderFromBytes(data []byte) (Header, error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "fmt" "os" "github.com/skrashevich/go-aac/pkg/adts" "github.com/skrashevich/go-aac/pkg/tables" ) func main() { data, _ := os.ReadFile("audio.aac") header, err := adts.ReadHeaderFromBytes(data) if err != nil { fmt.Println("Error:", err) return } fmt.Printf("Profile: %d (1=Main, 2=LC, 3=SSR, 4=LTP)\n", header.Profile) fmt.Printf("Sample rate index: %d\n", header.SamplingIndex) fmt.Printf("Sample rate: %d Hz\n", tables.SampleRates[header.SamplingIndex]) fmt.Printf("Channel config: %d\n", header.ChannelConfig) fmt.Printf("Frame length: %d bytes\n", header.FrameLength) fmt.Printf("Number of frames: %d\n", header.NumFrames) fmt.Printf("Protection absent (no CRC): %v\n", header.ProtectionAbsent) } ``` ### Response #### Success Response (Header) - **Profile** (int) - The AAC profile (e.g., 1=Main, 2=LC, 3=SSR, 4=LTP). - **SamplingIndex** (int) - The index corresponding to the sample rate in the `tables.SampleRates` array. - **ChannelConfig** (int) - The number of audio channels. - **FrameLength** (int) - The length of the ADTS frame in bytes. - **NumFrames** (int) - The number of frames in the ADTS packet. - **ProtectionAbsent** (bool) - Indicates if CRC protection is absent. #### Response Example ```json { "Profile": 2, "SamplingIndex": 4, "ChannelConfig": 2, "FrameLength": 372, "NumFrames": 1, "ProtectionAbsent": true } ``` #### Error Response - **Error** (error) - Description of the error encountered during parsing. ``` -------------------------------- ### decoder.DecodeFrame Source: https://context7.com/skrashevich/go-aac/llms.txt Decodes a single AAC frame and returns interleaved PCM samples as float32 values normalized to the range [-1.0, 1.0]. The frame can include the ADTS header or be raw AAC data if the decoder was pre-configured with SetASC. ```APIDOC ## decoder.DecodeFrame ### Description Decodes a single AAC frame and returns interleaved PCM samples as float32 values normalized to the range [-1.0, 1.0]. The frame can include the ADTS header or be raw AAC data if the decoder was pre-configured with SetASC. ### Method `DecodeFrame(frameData []byte) ([]float32, error)` ### Parameters #### Request Body - **frameData** ([]byte) - Required - The byte slice containing the AAC frame data. This can include the ADTS header or be raw AAC data. ### Request Example ```go package main import ( "encoding/binary" "fmt" "os" "github.com/skrashevich/go-aac/pkg/adts" "github.com/skrashevich/go-aac/pkg/decoder" ) func main() { data, _ := os.ReadFile("audio.aac") dec := decoder.New() offset := 0 var allSamples []float32 // Decode all frames for offset < len(data) { if len(data)-offset < 7 { break } header, err := adts.ReadHeaderFromBytes(data[offset:]) if err != nil { break } frameData := data[offset : offset+header.FrameLength] samples, err := dec.DecodeFrame(frameData) if err != nil { fmt.Printf("Frame decode error: %v\n", err) offset += header.FrameLength continue } allSamples = append(allSamples, samples...) offset += header.FrameLength } // Convert float32 samples to int16 for PCM output int16Samples := make([]int16, len(allSamples)) for i, v := range allSamples { // Clamp and scale to int16 range if v > 1.0 { v = 1.0 } else if v < -1.0 { v = -1.0 } int16Samples[i] = int16(v * 32767) } // Write raw PCM f, _ := os.Create("output.pcm") defer f.Close() binary.Write(f, binary.LittleEndian, int16Samples) fmt.Printf("Decoded %d samples total\n", len(allSamples)) } ``` ### Response #### Success Response (200) - **samples** ([]float32) - A slice of interleaved PCM samples, normalized to the range [-1.0, 1.0]. #### Response Example ```json { "samples": [ 0.12345, -0.56789, 0.98765, ... ] } ``` #### Error Response (non-200) - **error** (error) - An error if the frame cannot be decoded. #### Response Example ``` // Frame decode error: invalid AAC frame data ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.