### Install go-astiav Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/overview.md Commands to install the library using system FFmpeg or a custom FFmpeg path. ```sh # With system FFmpeg go get github.com/asticode/go-astiav # With custom FFmpeg path export CGO_CFLAGS="-I/path/to/ffmpeg/include" export CGO_LDFLAGS="-L/path/to/ffmpeg/lib" export PKG_CONFIG_PATH="/path/to/ffmpeg/lib/pkgconfig" go build ``` -------------------------------- ### Install and Update Packages on Windows Source: https://github.com/asticode/go-astiav/blob/master/README.md Use pacman to update existing packages and install new requirements for building go-astiav on Windows. ```shell # Update Packages pacman -Syu # Install Requirements to Build pacman -S --noconfirm --needed git diffutils mingw-w64-x86_64-toolchain pkg-config make nasm # Clone the repository using git git clone https://github.com/asticode/go-astiav cd go-astiav ``` -------------------------------- ### Configure Output Streams Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/streams-and-programs.md Example of allocating an output format context and adding video and audio streams. ```go // Create output context outFC, _ := astiav.AllocOutputFormatContext(nil, "mp4", "output.mp4") // Add video stream vidStream := outFC.NewStream(astiav.FindEncoder(astiav.CodecIDH264)) vidStream.SetTimeBase(astiav.NewRational(1, 30)) // Add audio stream audStream := outFC.NewStream(astiav.FindEncoder(astiav.CodecIDAAC)) audStream.SetTimeBase(astiav.NewRational(1, 48000)) ``` -------------------------------- ### Use Dictionary for input options Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/utilities-and-logging.md Example of creating, populating, and using a Dictionary to open a format context. ```go opts := astiav.NewDictionary() defer opts.Free() opts.Set("rtbufsize", "100M") opts.Set("max_analyze_duration", "5000000") fc := astiav.AllocFormatContext() if err := fc.OpenInput("input.mp4", nil, opts); err != nil { return err } ``` -------------------------------- ### Use AudioFifo for Sample Buffering Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/image-and-audio-processing.md Example demonstrating allocation, writing, and reading samples using an AudioFifo. ```go // Create 48kHz stereo S16 buffer fifo := astiav.AllocAudioFifo( astiav.SampleFormatS16, 2, // stereo 48000, // 1 second buffer ) defer fifo.Free() // Add samples inFrame := astiav.AllocFrame() fifo.Write(inFrame) // Extract samples outFrame := astiav.AllocFrame() fifo.Read(outFrame) ``` -------------------------------- ### Setup Hardware Acceleration Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/overview.md Creates a hardware device context and assigns it to a codec context for GPU-accelerated operations. ```go // Create device hwDev, _ := astiav.CreateHardwareDeviceContext( astiav.HardwareDeviceTypeCUDA, "0", nil, 0, ) defer hwDev.Free() // Pass to codec context cc := astiav.AllocCodecContext(nil) cc.SetHardwareDeviceContext(hwDev) // ... open codec ... ``` -------------------------------- ### Setup hardware-accelerated decoding Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/hardware-acceleration.md Initializes the hardware device context and codec context for hardware-accelerated decoding. ```go // 1. Create device context hwDev, err := astiav.CreateHardwareDeviceContext( astiav.HardwareDeviceTypeCUDA, "0", nil, 0, ) if err != nil { return err } defer hwDev.Free() // 2. Allocate codec context cc := astiav.AllocCodecContext(nil) defer cc.Free() // 3. Set hardware device cc.SetHardwareDeviceContext(hwDev) // 4. Open decoder codec := astiav.FindDecoder(astiav.CodecIDH264) if err := cc.Open(codec, nil); err != nil { return err } ``` -------------------------------- ### Muxing Loop Example Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/demuxing-and-muxing.md Demonstrates creating an output context, writing the header, writing packets, and finalizing with a trailer. ```go // Create output context fc, err := astiav.AllocOutputFormatContext(nil, "mp4", "output.mp4") if err != nil { return err } defer fc.Free() // Add streams, set codec parameters... // Write if err := fc.WriteHeader(nil); err != nil { return err } // Write packets... pkt := astiav.AllocPacket() for { // ... encode frames to pkt ... if err := fc.WriteFrame(pkt); err != nil { return err } } if err := fc.WriteTrailer(); err != nil { return err } ``` -------------------------------- ### Demuxing Loop Example Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/demuxing-and-muxing.md Demonstrates opening an input file and reading packets in a loop until EOF is reached. ```go // Open file fc := astiav.AllocFormatContext() defer fc.Free() if err := fc.OpenInput("video.mp4", nil, nil); err != nil { return err } if err := fc.FindStreamInfo(nil); err != nil { return err } // Read packets pkt := astiav.AllocPacket() defer pkt.Free() for { if err := fc.ReadFrame(pkt); err != nil { if errors.Is(err, astiav.ErrEOF) { break } return err } defer pkt.Unref() streamIdx := pkt.StreamIndex() fmt.Printf("Packet on stream %d\n", streamIdx) } ``` -------------------------------- ### Initialize CUDA Hardware Device Context Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/hardware-acceleration.md Example of creating a CUDA device context for GPU 0 and ensuring resources are released. ```go // Create CUDA device context for GPU 0 hwDev, err := astiav.CreateHardwareDeviceContext( astiav.HardwareDeviceTypeCUDA, "0", // GPU index nil, 0, ) if err != nil { return err } defer hwDev.Free() ``` -------------------------------- ### Transcoding Pipeline Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/overview.md Performs a full demux-decode-encode-mux cycle. This example demonstrates the orchestration of multiple contexts. ```go // Open input inFC := astiav.AllocFormatContext() inFC.OpenInput("input.mp4", nil, nil) inFC.FindStreamInfo(nil) // Open decoder codec := astiav.FindDecoder(inStream.CodecParameters().CodecID()) decCC := astiav.AllocCodecContext(nil) decCC.Open(codec, nil) // Open output outFC, _ := astiav.AllocOutputFormatContext(nil, "mp4", "output.mp4") outStream := outFC.NewStream(nil) // Open encoder encCC := astiav.AllocCodecContext(nil) encCC.SetWidth(1920) encCC.SetHeight(1080) // ... configure encoder ... encCC.Open(astiav.FindEncoder(astiav.CodecIDH264), nil) outFC.WriteHeader(nil) // Process pkt := astiav.AllocPacket() frame := astiav.AllocFrame() // Decode packets → encode frames → write packets for { inFC.ReadFrame(pkt) if pkt.StreamIndex() == inStream.Index() { decCC.SendPacket(pkt) for decCC.ReceiveFrame(frame) == nil { encCC.SendFrame(frame) for encCC.ReceivePacket(pkt) == nil { pkt.SetStreamIndex(outStream.Index()) outFC.WriteFrame(pkt) } } } pkt.Unref() } outFC.WriteTrailer() ``` -------------------------------- ### Lookup Hardware Device Type by Name Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/hardware-acceleration.md Example of retrieving a device type by name and handling cases where the type is unsupported. ```go devType := astiav.FindHardwareDeviceTypeByName("cuda") if devType == astiav.HardwareDeviceTypeNone { return errors.New("CUDA not supported") } ``` -------------------------------- ### FFmpeg Environment Variables for Go Source: https://github.com/asticode/go-astiav/blob/master/README.md Sets the necessary environment variables for Go to correctly link against a custom FFmpeg installation. Ensure `{{ path to your ffmpeg directory }}` is replaced with the absolute path to your FFmpeg installation. ```sh export CGO_CFLAGS="-I{{ path to your ffmpeg directory }}/include/" export CGO_LDFLAGS="-L{{ path to your ffmpeg directory }}/lib/" export PKG_CONFIG_PATH="{{ path to your ffmpeg directory }}/lib/pkgconfig" ``` -------------------------------- ### Encoding video to MP4 in Go Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/decoding-and-encoding.md Demonstrates the full lifecycle of encoding, including context allocation, stream setup, frame processing, and flushing the encoder. ```go // Create output context outFC, err := astiav.AllocOutputFormatContext(nil, "mp4", "output.mp4") if err != nil { return err } defer outFC.Free() // Create output stream outStream := outFC.NewStream(nil) // Setup encoder cc := astiav.AllocCodecContext(nil) defer cc.Free() cc.SetWidth(1920) cc.SetHeight(1080) cc.SetFormat(astiav.PixelFormatYUV420P) cc.SetTimeBase(astiav.NewRational(1, 30)) cc.SetFrameRate(astiav.NewRational(30, 1)) cc.SetBitRate(5_000_000) h264 := astiav.FindEncoder(astiav.CodecIDH264) if err := cc.Open(h264, nil); err != nil { return err } // Open output I/O pb, err := astiav.OpenIOContext("output.mp4", astiav.NewIOContextFlags(astiav.IOContextFlagWrite), nil, nil) if err != nil { return err } outFC.SetPb(pb) if err := outFC.WriteHeader(nil); err != nil { return err } // Create and encode frames frame := astiav.AllocFrame() defer frame.Free() frame.SetWidth(1920) frame.SetHeight(1080) frame.SetFormat(astiav.PixelFormatYUV420P) if err := frame.AllocBuffer(0); err != nil { return err } pkt := astiav.AllocPacket() defer pkt.Free() // Encode frames... for i := 0; i < 300; i++ { frame.SetPts(int64(i)) if err := cc.SendFrame(frame); err != nil { return err } for { if err := cc.ReceivePacket(pkt); err != nil { if errors.Is(err, astiav.ErrTryAgain) { break } if errors.Is(err, astiav.ErrEOF) { goto writeDone } return err } pkt.SetStreamIndex(outStream.Index()) if err := outFC.WriteFrame(pkt); err != nil { return err } pkt.Unref() } } // Flush encoder cc.SendFrame(nil) for { if err := cc.ReceivePacket(pkt); err != nil { if errors.Is(err, astiav.ErrEOF) { break } return err } pkt.SetStreamIndex(outStream.Index()) if err := outFC.WriteFrame(pkt); err != nil { return err } pkt.Unref() } writeDone: if err := outFC.WriteTrailer(); err != nil { return err } ``` -------------------------------- ### Resample Audio Frames Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/image-and-audio-processing.md Example demonstrating the configuration and conversion process for resampling audio from 44.1kHz to 48kHz. ```go // Resample 44.1kHz stereo S16 to 48kHz stereo S16 swr := astiav.AllocSoftwareResampleContext() defer swr.Free() // Setup input inLayout := astiav.ChannelLayoutStereo() swr.SetChannelLayout(inLayout) swr.SetInSampleRate(44100) swr.SetInSampleFormat(astiav.SampleFormatS16) // Setup output outLayout := astiav.ChannelLayoutStereo() swr.SetOutChannelLayout(outLayout) swr.SetOutSampleRate(48000) swr.SetOutSampleFormat(astiav.SampleFormatS16) if err := swr.Initialize(); err != nil { return err } inFrame := astiav.AllocFrame() // ... populate input frame ... outFrame := astiav.AllocFrame() outFrame.SetChannelLayout(outLayout) outFrame.SetSampleRate(48000) outFrame.SetFormat(astiav.SampleFormatS16) outFrame.SetNbSamples(inFrame.NbSamples()) if err := outFrame.AllocBuffer(0); err != nil { return err } if _, err := swr.Convert(inFrame, outFrame); err != nil { return err } ``` -------------------------------- ### Configure Audio Format Conversion Filter Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/codec-and-filters.md Example of setting up a filter graph for audio format conversion using an aformat filter. ```go fg := astiav.AllocFilterGraph() defer fg.Free() // Format conversion filter if err := fg.Parse("aformat=sample_fmts=s16:sample_rates=48000"); err != nil { return err } if err := fg.Configure(); err != nil { return err } ``` -------------------------------- ### Manage Size Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/packet.md Methods for getting and setting the packet data size in bytes. ```go func (p *Packet) Size() int ``` ```go func (p *Packet) SetSize(s int) ``` -------------------------------- ### Get String Representation Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/codec-context.md Returns a human-readable string representation of the codec context. ```go func (cc *CodecContext) String() string ``` -------------------------------- ### Configure Video Scaling Filter Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/codec-and-filters.md Example of setting up a filter graph for video scaling using a scale filter. ```go // Create filter graph fg := astiav.AllocFilterGraph() defer fg.Free() // Parse and configure if err := fg.Parse("scale=1920:1080"); err != nil { return err } if err := fg.Configure(); err != nil { return err } // Get input and output srcCtx := fg.FilterByName("Parsed_scale_0") // Process frames with srcCtx.SendCommand() or related operations ``` -------------------------------- ### Access Start Time Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/streams-and-programs.md Retrieves the first packet timestamp in time base units. ```go func (s *Stream) StartTime() int64 ``` -------------------------------- ### Manage Duration Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/packet.md Methods for getting and setting the packet duration. ```go func (p *Packet) Duration() int64 ``` ```go func (p *Packet) SetDuration(d int64) ``` -------------------------------- ### Manage Position Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/packet.md Methods for getting and setting the byte position in the input file. ```go func (p *Packet) Pos() int64 ``` ```go func (p *Packet) SetPos(v int64) ``` -------------------------------- ### Validate Pixel Format Lookup Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/image-and-audio-processing.md Example showing how to check if a pixel format exists by name. ```go fmt := astiav.FindPixelFormatByName("yuv420p") if fmt == astiav.PixelFormatNone { return errors.New("unsupported format") } ``` -------------------------------- ### Get Chroma Location Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/codec-context.md Returns the chroma sample location for video codecs. ```go func (cc *CodecContext) ChromaLocation() ChromaLocation ``` -------------------------------- ### Manage Flags Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/packet.md Methods for getting and setting packet flags such as keyframe or corrupt status. ```go func (p *Packet) Flags() PacketFlags ``` ```go func (p *Packet) SetFlags(f PacketFlags) ``` -------------------------------- ### Iterate Over Program Streams Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/streams-and-programs.md Example of accessing stream codec parameters using program stream indices. ```go for _, streamIdx := range program.StreamIndexes() { stream := fc.Streams()[streamIdx] fmt.Printf("Stream %d: %v\n", streamIdx, stream.CodecParameters().CodecID()) } ``` -------------------------------- ### Register All Devices Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/utilities-and-logging.md Initializes all available input and output devices for use with the library. ```go astiav.RegisterAllDevices() // Now can open device inputs like: // fc.OpenInput("dshow:device=...") on Windows // fc.OpenInput("v4l2:device=/dev/video0") on Linux ``` -------------------------------- ### Get Codec ID Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/codec-context.md Returns the codec ID identifying the codec type. ```go func (cc *CodecContext) CodecID() CodecID ``` -------------------------------- ### Create HardwareDeviceContext Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/hardware-acceleration.md Function signature for initializing a hardware device context. ```go func CreateHardwareDeviceContext( t HardwareDeviceType, device string, options *Dictionary, flags int, ) (*HardwareDeviceContext, error) ``` -------------------------------- ### Manage Stream Index Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/packet.md Methods for getting and setting the stream index associated with the packet. ```go func (p *Packet) StreamIndex() int ``` ```go func (p *Packet) SetStreamIndex(i int) ``` -------------------------------- ### Multi-stream Demuxing in Go Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/streams-and-programs.md Demonstrates opening a media file, initializing decoders for each stream, and processing packets in a loop. ```go // Open file and find streams fc := astiav.AllocFormatContext() fc.OpenInput("input.mkv", nil, nil) fc.FindStreamInfo(nil) // Setup decoders for each stream decoders := make(map[int]*astiav.CodecContext) for _, stream := range fc.Streams() { codec := astiav.FindDecoder(stream.CodecParameters().CodecID()) if codec == nil { continue } cc := astiav.AllocCodecContext(nil) if err := cc.Open(codec, nil); err != nil { continue } decoders[stream.Index()] = cc } defer func() { for _, cc := range decoders { cc.Free() } }() // Demux and decode pkt := astiav.AllocPacket() defer pkt.Free() for { if err := fc.ReadFrame(pkt); err != nil { if errors.Is(err, astiav.ErrEOF) { break } return err } if cc, ok := decoders[pkt.StreamIndex()]; ok { cc.SendPacket(pkt) frame := astiav.AllocFrame() for cc.ReceiveFrame(frame) == nil { // Process decoded frame fmt.Printf("Frame from stream %d\n", pkt.StreamIndex()) } frame.Free() } pkt.Unref() } ``` -------------------------------- ### Scale video frames using SoftwareScaleContext Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/image-and-audio-processing.md Demonstrates initializing a scaler, allocating frames, and performing a scale operation from 1080p to 720p. ```go // Scale 1920x1080 YUV420P to 1280x720 YUV420P sws, err := astiav.CreateSoftwareScaleContext( 1920, 1080, astiav.PixelFormatYUV420P, 1280, 720, astiav.PixelFormatYUV420P, astiav.NewSoftwareScaleContextFlags(astiav.SoftwareScaleContextFlagBilinear), ) if err != nil { return err } defer sws.Free() srcFrame := astiav.AllocFrame() defer srcFrame.Free() // ... populate srcFrame ... dstFrame := astiav.AllocFrame() defer dstFrame.Free() dstFrame.SetWidth(1280) dstFrame.SetHeight(720) dstFrame.SetFormat(astiav.PixelFormatYUV420P) if err := dstFrame.AllocBuffer(0); err != nil { return err } if err := sws.Scale(srcFrame, dstFrame); err != nil { return err } ``` -------------------------------- ### Manage Timestamps Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/packet.md Methods for getting and setting decode (DTS) and presentation (PTS) timestamps. ```go func (p *Packet) Dts() int64 ``` ```go func (p *Packet) SetDts(v int64) ``` ```go func (p *Packet) Pts() int64 ``` ```go func (p *Packet) SetPts(v int64) ``` -------------------------------- ### Configure options using Dictionary Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/INDEX.md Use a dictionary to pass key-value pairs to FFmpeg functions like OpenInput. ```go opts := astiav.NewDictionary() opts.Set("key", "value") // Pass to various functions fc.OpenInput("file", nil, opts) ``` -------------------------------- ### Get and Set Frame Width Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/frame.md Methods to retrieve or modify the video frame width in pixels. ```go func (f *Frame) Width() int ``` ```go func (f *Frame) SetWidth(w int) ``` -------------------------------- ### Get Class Descriptor Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/codec-context.md Returns the Class descriptor for this CodecContext, used for option handling and introspection. ```go func (cc *CodecContext) Class() *Class ``` -------------------------------- ### Allocate FormatContext for output Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/format-context.md Use this to initialize a context for writing media files. Requires error handling and manual memory management via Free(). ```go fc, err := astiav.AllocOutputFormatContext(nil, "mp4", "output.mp4") if err != nil { return err } defer fc.Free() ``` -------------------------------- ### Configure via Dictionary Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/overview.md Sets options for operations like opening input files using an astiav Dictionary. ```go opts := astiav.NewDictionary() defer opts.Free() opts.Set("rtbufsize", "100M") opts.Set("max_analyze_duration", "5000000") fc := astiav.AllocFormatContext() fc.OpenInput("input.mp4", nil, opts) ``` -------------------------------- ### Run project tests Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/INDEX.md Execute the standard Go test suite for the project. ```sh go test ./... ``` -------------------------------- ### Allocate and configure video and audio frames Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/frame.md Demonstrates the allocation of memory buffers for video and audio frames and accessing pixel data planes. ```go // Video frame frame := astiav.AllocFrame() frame.SetWidth(1920) frame.SetHeight(1080) frame.SetFormat(astiav.PixelFormatYUV420P) if err := frame.AllocBuffer(0); err != nil { return err } defer frame.Free() // Access pixel data data := frame.Data() lumaPlane := data.Plane(0) // Audio frame audioFrame := astiav.AllocFrame() audioFrame.SetFormat(astiav.SampleFormatS16) audioFrame.SetSampleRate(48000) audioFrame.SetNbSamples(1024) if err := audioFrame.AllocBuffer(0); err != nil { return err } ``` -------------------------------- ### Open Input File Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/demuxing-and-muxing.md Opens a file for reading using the FormatContext. ```go func (fc *FormatContext) OpenInput(filename string, ifmt *InputFormat, options *Dictionary) error ``` -------------------------------- ### Initialize Hardware Encoding Context Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/hardware-acceleration.md Configures the hardware device, allocates frame contexts, and initializes the codec context for H.264 encoding. ```go // 1. Create device context hwDev, err := astiav.CreateHardwareDeviceContext( astiav.HardwareDeviceTypeCUDA, "0", nil, 0, ) if err != nil { return err } defer hwDev.Free() // 2. Allocate frames context hwFrames := astiav.AllocHardwareFramesContext(hwDev) defer hwFrames.Free() hwFrames.SetFormat(astiav.PixelFormatCUDA) hwFrames.SetSwFormat(astiav.PixelFormatNV12) hwFrames.SetWidth(1920) hwFrames.SetHeight(1080) // Initialize frames context if err := hwFrames.Allocate(); err != nil { return err } // 3. Setup encoder cc := astiav.AllocCodecContext(nil) defer cc.Free() cc.SetWidth(1920) cc.SetHeight(1080) cc.SetFormat(astiav.PixelFormatCUDA) cc.SetTimeBase(astiav.NewRational(1, 30)) cc.SetBitRate(5_000_000) cc.SetHardwareFramesContext(hwFrames) // 4. Open encoder h264 := astiav.FindEncoder(astiav.CodecIDH264) if err := cc.Open(h264, nil); err != nil { return err } ``` -------------------------------- ### Configure Output Stream Parameters Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/streams-and-programs.md Sets codec, timing, disposition, and metadata for a newly created stream. ```go // After creating stream with NewStream() // Set codec parameters cp := vidStream.CodecParameters() cp.SetCodecID(astiav.CodecIDH264) cp.SetCodecType(astiav.MediaTypeVideo) cp.SetWidth(1920) cp.SetHeight(1080) cp.SetBitRate(5_000_000) // Set timing vidStream.SetTimeBase(astiav.NewRational(1, 30)) vidStream.SetAvgFrameRate(astiav.NewRational(30, 1)) vidStream.SetSampleAspectRatio(astiav.NewRational(1, 1)) // Set disposition disp := astiav.NewDispositionFlags(astiav.DispositionFlagDefault) vidStream.SetDisposition(disp) // Set metadata meta := astiav.NewDictionary() meta.Set("title", "Main Video") vidStream.SetMetadata(meta) ``` -------------------------------- ### Configure via Flags Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/overview.md Uses type-safe flag combinations to configure IO contexts. ```go flags := astiav.NewIOContextFlags( astiav.IOContextFlagRead, astiav.IOContextFlagNonblock, ) ioc, _ := astiav.OpenIOContext("input.mp4", flags, nil, nil) ``` -------------------------------- ### Construct Rational objects Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/utilities-and-logging.md Creates new Rational instances for common time bases like frame rates and audio sample rates. ```go // 30 fps (30000/1001) fps30 := astiav.NewRational(30000, 1001) // 1 microsecond timebase (1/1000000) microsecondBase := astiav.NewRational(1, 1000000) // 1/48000 for 48kHz audio audioBase := astiav.NewRational(1, 48000) ``` -------------------------------- ### Configure IOContext using Flags Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/INDEX.md Initialize IOContext flags to define read/write permissions for file operations. ```go flags := astiav.NewIOContextFlags( astiav.IOContextFlagRead, ) // Pass to functions ioc, _ := astiav.OpenIOContext("file", flags, nil, nil) ``` -------------------------------- ### Build Commands Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/README.md Commands to build the project using either system-installed FFmpeg or a custom path. ```sh # With system FFmpeg go build ./... # With custom FFmpeg export CGO_CFLAGS="-I/path/to/ffmpeg/include" export CGO_LDFLAGS="-L/path/to/ffmpeg/lib" export PKG_CONFIG_PATH="/path/to/ffmpeg/lib/pkgconfig" go build ./... ``` -------------------------------- ### Decoding a Video Stream in Go Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/decoding-and-encoding.md Demonstrates the full lifecycle of opening a video file, finding the video stream, and decoding frames until EOF. ```go // Demux, decode, process frames dmuxFC := astiav.AllocFormatContext() defer dmuxFC.Free() if err := dmuxFC.OpenInput("video.mp4", nil, nil); err != nil { return err } if err := dmuxFC.FindStreamInfo(nil); err != nil { return err } // Find video stream var videoStream *astiav.Stream for _, stream := range dmuxFC.Streams() { if stream.CodecParameters().CodecType() == astiav.MediaTypeVideo { videoStream = stream break } } // Open decoder cc := astiav.AllocCodecContext(nil) defer cc.Free() codec := astiav.FindDecoder(videoStream.CodecParameters().CodecID()) if err := cc.Open(codec, nil); err != nil { return err } // Read and decode pkt := astiav.AllocPacket() defer pkt.Free() frame := astiav.AllocFrame() defer frame.Free() for { if err := dmuxFC.ReadFrame(pkt); err != nil { if errors.Is(err, astiav.ErrEOF) { // Flush decoder cc.SendPacket(nil) } else { return err } } else { if pkt.StreamIndex() != videoStream.Index() { pkt.Unref() continue } if err := cc.SendPacket(pkt); err != nil { return err } pkt.Unref() } for { if err := cc.ReceiveFrame(frame); err != nil { if errors.Is(err, astiav.ErrTryAgain) { break } if errors.Is(err, astiav.ErrEOF) { goto done } return err } // Process frame fmt.Printf("Frame %dx%d\n", frame.Width(), frame.Height()) } } done: ``` -------------------------------- ### Check hardware support for a codec Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/hardware-acceleration.md Iterate through available hardware configurations for a specific decoder to inspect supported methods, devices, and pixel formats. ```go h264 := astiav.FindDecoder(astiav.CodecIDH264) for _, config := range h264.HardwareConfigs() { fmt.Printf("Method: %v, Device: %v, Format: %v\n", config.Method(), config.Device(), config.PixelFormat(), ) } ``` -------------------------------- ### Create new Dictionary Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/utilities-and-logging.md Function signature for initializing an empty Dictionary. ```go func NewDictionary() *Dictionary ``` -------------------------------- ### Configure H.264 Video Encoder Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/decoding-and-encoding.md Set video parameters on the CodecContext before opening the encoder. ```go // Configure H.264 video encoder cc := astiav.AllocCodecContext(nil) cc.SetWidth(1920) cc.SetHeight(1080) cc.SetFormat(astiav.PixelFormatYUV420P) cc.SetTimeBase(astiav.NewRational(1, 30)) cc.SetBitRate(5_000_000) // 5 Mbps cc.SetGopSize(30) cc.SetMaxBFrames(2) h264 := astiav.FindEncoder(astiav.CodecIDH264) if err := cc.Open(h264, nil); err != nil { return err } ``` -------------------------------- ### Retrieve All Available Codecs Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/codec-and-filters.md Iterate through all system codecs to access their names and long names. ```go allCodecs := astiav.Codecs() for _, codec := range allCodecs { fmt.Printf("%s: %s\n", codec.Name(), codec.LongName()) } ``` -------------------------------- ### Pb() Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/format-context.md Retrieves the I/O context associated with the format context. ```APIDOC ## func (fc *FormatContext) Pb() *IOContext ### Description Returns the I/O context (reader/writer) associated with this format context. ### Returns - ***IOContext** - The I/O context associated with the format context. ``` -------------------------------- ### Allocate FormatContext for input Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/format-context.md Use this to initialize a context for reading or general operations. Always ensure to call Free() to prevent memory leaks. ```go fc := astiav.AllocFormatContext() if fc != nil { defer fc.Free() } ``` -------------------------------- ### CreateHardwareDeviceContext Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/hardware-acceleration.md Creates a new hardware device context for GPU acceleration using the specified device type and configuration. ```APIDOC ## func CreateHardwareDeviceContext(t HardwareDeviceType, device string, options *Dictionary, flags int) (*HardwareDeviceContext, error) ### Description Creates a hardware device context for GPU acceleration. This is the primary entry point for initializing hardware-accelerated decoding or encoding. ### Parameters - **t** (HardwareDeviceType) - Required - Device type (e.g., CUDA, VAAPI) - **device** (string) - Required - Device name or index (use "" for default) - **options** (*Dictionary) - Optional - Device-specific configuration options - **flags** (int) - Required - Initialization flags (typically 0) ### Returns - **(*HardwareDeviceContext, error)** - Returns the initialized hardware device context or an error if creation fails. ``` -------------------------------- ### Create a display rotation matrix in Go Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/image-and-audio-processing.md Initializes a 3x3 transformation matrix based on a clockwise rotation angle in degrees. ```go // Rotate 90 degrees clockwise matrix := astiav.NewDisplayMatrixFromRotation(90) // Apply to frame as side data or use in rendering ``` -------------------------------- ### Manage FFmpeg resources in Go Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/README.md Use allocation and defer patterns to ensure proper memory cleanup for packets and frames. ```go // Allocate once, free when done obj := astiav.Alloc*() defer obj.Free() // Packets and frames can be reused pkt := astiav.AllocPacket() defer pkt.Free() // Unref after use (release internal data) defer pkt.Unref() ``` -------------------------------- ### WriteTrailer Method Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/demuxing-and-muxing.md Writes the format trailer for finalization. ```go func (fc *FormatContext) WriteTrailer() error ``` -------------------------------- ### Allocate and configure a FilterGraph Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/codec-and-filters.md Allocates a new filter graph and demonstrates the parsing and configuration workflow. ```go func AllocFilterGraph() *FilterGraph ``` ```go fg := astiav.AllocFilterGraph() defer fg.Free() if err := fg.Parse("scale=1920:1080"); err != nil { return err } if err := fg.Configure(); err != nil { return err } ``` -------------------------------- ### Retrieve I/O context Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/format-context.md Returns the I/O context associated with the format context. ```go func (fc *FormatContext) Pb() *IOContext ``` -------------------------------- ### Allocate HardwareFramesContext Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/hardware-acceleration.md Allocates a new hardware frames context using a provided hardware device context. ```go func AllocHardwareFramesContext(hdc *HardwareDeviceContext) *HardwareFramesContext ``` -------------------------------- ### OpenIOContext Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/demuxing-and-muxing.md Opens an IOContext for a specific file path. ```APIDOC ## OpenIOContext ### Description Opens an IOContext for a file. ### Parameters - **filename** (string) - Required - File path - **flags** (IOContextFlags) - Required - Read/write mode flags - **ii** (*IOInterrupter) - Optional - Interrupt handler - **d** (*Dictionary) - Optional - Options ### Returns - (*IOContext, error) - File I/O context or error ``` -------------------------------- ### RegisterAllDevices Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/utilities-and-logging.md Registers all available input/output devices such as cameras, screens, and microphones with the library. ```APIDOC ## func RegisterAllDevices() ### Description Registers all available input/output devices (cameras, screens, microphones) with the library. ### Signature `func RegisterAllDevices()` ``` -------------------------------- ### WriteHeader Method Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/demuxing-and-muxing.md Writes the format header before writing frames. Requires a Dictionary for muxer options. ```go func (fc *FormatContext) WriteHeader(options *Dictionary) error ``` -------------------------------- ### Allocate and Free Resources Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/overview.md Standard pattern for allocating astiav objects and ensuring they are freed using defer. ```go // Allocate obj := astiav.Alloc*Type() if obj == nil { return errors.New("allocation failed") } // Use // ... // Free when done defer obj.Free() ``` -------------------------------- ### Program.Metadata() Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/streams-and-programs.md Returns program metadata. ```APIDOC ## func (p *Program) Metadata() *Dictionary ### Description Returns program metadata. ### Returns - ***Dictionary** - Metadata dictionary ``` -------------------------------- ### Channel Layout Management Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/codec-context.md Methods to retrieve or set the audio channel layout. ```go func (cc *CodecContext) ChannelLayout() ChannelLayout ``` ```go func (cc *CodecContext) SetChannelLayout(l ChannelLayout) ``` -------------------------------- ### Open file-based IOContext Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/demuxing-and-muxing.md Opens an IOContext for a specific file path. ```go func OpenIOContext( filename string, flags IOContextFlags, ii *IOInterrupter, d *Dictionary, ) (*IOContext, error) ``` ```go flags := astiav.NewIOContextFlags(astiav.IOContextFlagRead) ioc, err := astiav.OpenIOContext("input.mp4", flags, nil, nil) if err != nil { return err } defer ioc.Free() ``` -------------------------------- ### Allocate custom IOContext Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/demuxing-and-muxing.md Creates an IOContext with custom read/write callbacks for memory-based I/O. ```go func AllocIOContext( bufferSize int, writable bool, readFunc IOContextReadFunc, seekFunc IOContextSeekFunc, writeFunc IOContextWriteFunc, ) (*IOContext, error) ``` ```go // Custom memory I/O var buffer []byte readFunc := func(b []byte) (int, error) { n := copy(b, buffer) buffer = buffer[n:] return n, nil } ioc, err := astiav.AllocIOContext(32768, false, readFunc, nil, nil) if err != nil { return err } defer ioc.Free() ``` -------------------------------- ### HardwareFramesConstraints Methods Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/hardware-acceleration.md Methods to query constraints on hardware frames such as supported formats and dimensions. ```APIDOC ## HardwareFramesConstraints Methods ### Description Defines constraints on hardware frames including supported formats and dimension limits. ### Methods - **PixelFormats()** ([]PixelFormat) - Returns supported pixel formats. - **SwFormats()** ([]PixelFormat) - Returns supported software formats. - **MinWidth()** (int) - Returns the minimum supported width. - **MaxWidth()** (int) - Returns the maximum supported width. - **MinHeight()** (int) - Returns the minimum supported height. - **MaxHeight()** (int) - Returns the maximum supported height. - **Free()** (void) - Releases the resources associated with the constraints. ``` -------------------------------- ### CodecContext Configuration Methods Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/decoding-and-encoding.md Methods to configure the codec context before opening the encoder. ```APIDOC ## CodecContext Configuration ### Description Configure encoder context parameters before opening the codec. ### Methods - **SetWidth(w int)** - **SetHeight(h int)** - **SetFormat(f PixelFormat)** - **SetSampleRate(sr int)** - **SetSampleFormat(f SampleFormat)** - **SetChannelLayout(l ChannelLayout)** - **SetTimeBase(t Rational)** - **SetFrameRate(r Rational)** - **SetGopSize(s int)** - **SetBitRate(b int64)** - **SetMaxBFrames(m int)** ``` -------------------------------- ### Set I/O context Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/format-context.md Associates a specific I/O context with the format context. ```go func (fc *FormatContext) SetPb(i *IOContext) ``` -------------------------------- ### SetPb(i *IOContext) Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/format-context.md Sets the I/O context for the format context. ```APIDOC ## func (fc *FormatContext) SetPb(i *IOContext) ### Description Sets the I/O context for this format context. ### Parameters - **i** (*IOContext) - Required - I/O context to associate ``` -------------------------------- ### Copy Audio Samples to Buffer Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/frame.md Copies audio samples into a provided byte buffer in packed format. ```go func (f *Frame) SamplesCopyToBuffer(b []byte, align int) (int, error) ``` -------------------------------- ### Allocate and use BitStreamFilterContext Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/image-and-audio-processing.md Allocates a filter context and demonstrates the packet filtering workflow. ```go func AllocBitStreamFilterContext(f *BitStreamFilter) (*BitStreamFilterContext, error) ``` ```go // Convert H.264 MP4 to Annex-B filter := astiav.FindBitStreamFilterByName("h264_mp4toannexb") bsfc, err := astiav.AllocBitStreamFilterContext(filter) if err != nil { return err } defer bsfc.Free() if err := bsfc.Initialize(); err != nil { return err } pkt := astiav.AllocPacket() defer pkt.Free() // Read packets, send through filter... if err := bsfc.SendPacket(pkt); err != nil { return err } for { if err := bsfc.ReceivePacket(pkt); err != nil { if errors.Is(err, astiav.ErrTryAgain) { break } if errors.Is(err, astiav.ErrEOF) { break } return err } // Use filtered packet } ``` -------------------------------- ### HardwareDeviceContext Methods Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/hardware-acceleration.md Methods available on the HardwareDeviceContext object. ```APIDOC ## HardwareDeviceContext Methods ### Type() - **Description**: Returns the HardwareDeviceType of the context. - **Returns**: HardwareDeviceType ### Free() - **Description**: Releases the resources associated with the hardware device context. ``` -------------------------------- ### Define CodecHardwareConfig structure Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/codec-and-filters.md Represents the internal C structure for hardware acceleration support. ```go type CodecHardwareConfig struct { // Internal C structure } ``` -------------------------------- ### Allocate SoftwareResampleContext Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/image-and-audio-processing.md Function signature for allocating a new resampler context. ```go func AllocSoftwareResampleContext() *SoftwareResampleContext ``` -------------------------------- ### Open Codec Context in Go Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/decoding-and-encoding.md Opens a codec context with a specific codec. Requires a previously allocated CodecContext and a valid Codec. ```go func (cc *CodecContext) Open(c *Codec, options *Dictionary) error ``` ```go // Setup decoder cc := astiav.AllocCodecContext(nil) defer cc.Free() h264 := astiav.FindDecoder(astiav.CodecIDH264) if err := cc.Open(h264, nil); err != nil { return err } ``` -------------------------------- ### Memory and Lifecycle Management Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/packet.md Methods for freeing, cloning, and copying packet properties. ```go func (p *Packet) Free() ``` ```go func (p *Packet) Clone() *Packet ``` ```go func (p *Packet) CopyProperties(src *Packet) error ``` -------------------------------- ### CreateSoftwareScaleContext Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/image-and-audio-processing.md Creates a new software scaling context for converting video frames between different resolutions and pixel formats. ```APIDOC ## func CreateSoftwareScaleContext(srcW, srcH int, srcFormat PixelFormat, dstW, dstH int, dstFormat PixelFormat, flags SoftwareScaleContextFlags) (*SoftwareScaleContext, error) ### Description Creates a scaler context used for converting video frames between specified dimensions and pixel formats. ### Parameters - **srcW** (int) - Source width - **srcH** (int) - Source height - **srcFormat** (PixelFormat) - Source pixel format - **dstW** (int) - Destination width - **dstH** (int) - Destination height - **dstFormat** (PixelFormat) - Destination pixel format - **flags** (SoftwareScaleContextFlags) - Scaling algorithm flags ### Returns - **(*SoftwareScaleContext, error)** - The created scaler context or an error if initialization fails. ``` -------------------------------- ### Go Astiav Memory Management Pattern Source: https://github.com/asticode/go-astiav/blob/master/README.md Demonstrates the recommended pattern for allocating, freeing, and unreferencing packets using astiav.AllocPacket(), pkt.Free(), and defer pkt.Unref(). This pattern is crucial for managing memory correctly when working with FFmpeg packets. ```go pkt := astiav.AllocPacket() defer pkt.Free() for { func() { formatContext.ReadFrame(pkt) defer pkt.Unref() }() } ``` -------------------------------- ### Access Classer information Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/utilities-and-logging.md Retrieve class name and options from a Classer implementation. ```go // Get class info from any Classer cc := astiav.AllocCodecContext(nil) class := cc.Class() if class != nil { fmt.Printf("Class: %s\n", class.ClassName()) for _, opt := range class.Options() { fmt.Printf(" Option: %s\n", opt.Name()) } } ``` -------------------------------- ### AllocIOContext Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/demuxing-and-muxing.md Creates an IOContext with custom read/write callbacks for memory or custom I/O operations. ```APIDOC ## AllocIOContext ### Description Creates an IOContext with custom read/write callbacks. ### Parameters - **bufferSize** (int) - Required - Internal buffer size (typically 32KB) - **writable** (bool) - Required - True for output, false for input - **readFunc** (IOContextReadFunc) - Required - Read callback (nil if output) - **seekFunc** (IOContextSeekFunc) - Required - Seek callback (optional) - **writeFunc** (IOContextWriteFunc) - Required - Write callback (nil if input) ### Returns - (*IOContext, error) - Newly allocated I/O context or error ``` -------------------------------- ### Codecs() Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/codec-and-filters.md Retrieves a list of all available codecs in the system. ```APIDOC ## func Codecs() ### Description Returns all available codecs in the system. ### Returns - **[]*Codec** - Slice of all available codecs. ``` -------------------------------- ### Retrieve Program Properties Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/streams-and-programs.md Methods to access metadata, identifiers, and stream information from a Program. ```go func (p *Program) ID() int ``` ```go func (p *Program) Flags() ProgramFlags ``` ```go func (p *Program) Duration() int64 ``` ```go func (p *Program) Metadata() *Dictionary ``` ```go func (p *Program) NbStreamIndexes() int ``` ```go func (p *Program) StreamIndexes() []int ``` -------------------------------- ### Create New Stream Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/streams-and-programs.md Adds a new stream to an output format context using a specified codec. ```go func (fc *FormatContext) NewStream(c *Codec) *Stream ``` -------------------------------- ### Find OutputFormat by name Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/demuxing-and-muxing.md Locates an output format descriptor by its name string. ```go func FindOutputFormat(name string) *OutputFormat ``` ```go mp4 := astiav.FindOutputFormat("mp4") ``` -------------------------------- ### AllocHardwareFramesContext Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/hardware-acceleration.md Allocates a new hardware frames context associated with a specific hardware device context. ```APIDOC ## func AllocHardwareFramesContext(hdc *HardwareDeviceContext) *HardwareFramesContext ### Description Allocates a hardware frames context for managing GPU memory and buffer constraints. ### Parameters - **hdc** (*HardwareDeviceContext) - Required - The hardware device context to associate with the frames context. ### Returns - ***HardwareFramesContext** - The allocated frames context. ``` -------------------------------- ### SoftwareScaleContext.Free Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/image-and-audio-processing.md Releases the resources associated with the software scaling context. ```APIDOC ## func (s *SoftwareScaleContext) Free() ### Description Frees the memory and resources allocated for the software scaling context. This should be called when the context is no longer needed. ``` -------------------------------- ### AllocOutputFormatContext Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/format-context.md Allocates a FormatContext with output format information for writing media files. ```APIDOC ## AllocOutputFormatContext ### Description Allocates a FormatContext with output format information for writing media files. ### Signature `func AllocOutputFormatContext(of *OutputFormat, formatName, filename string) (*FormatContext, error)` ### Parameters - **of** (*OutputFormat) - Optional - Output format to associate with the context - **formatName** (string) - Optional - Format name (e.g., "mp4", "h264") to auto-detect format - **filename** (string) - Optional - Output filename to help infer the format ### Returns - **(*FormatContext, error)** - Newly allocated FormatContext or an error ### Errors Returns error if output context allocation fails ### Example ```go fc, err := astiav.AllocOutputFormatContext(nil, "mp4", "output.mp4") if err != nil { return err } defer fc.Free() ``` ``` -------------------------------- ### AllocHardwareBuffer Source: https://github.com/asticode/go-astiav/blob/master/_autodocs/frame.md Allocates GPU/hardware buffers for the frame using hardware acceleration context. ```APIDOC ## func (f *Frame) AllocHardwareBuffer(hfc *HardwareFramesContext) error ### Description Allocates GPU/hardware buffers for the frame using hardware acceleration context. ### Parameters - **hfc** (*HardwareFramesContext) - Required - Hardware frames context ### Returns - error: Error if allocation fails ```