### Install PyAV from source Source: https://pyav.org/docs/stable/_sources/overview/installation.rst.txt Force installation from source to use a custom build of FFmpeg. ```bash pip install av --no-binary av ``` -------------------------------- ### Install PyAV via pip Source: https://pyav.org/docs/stable/_sources/overview/installation.rst.txt The standard method to install PyAV using binary wheels from PyPI. ```bash pip install av ``` -------------------------------- ### Install dependencies on Ubuntu 18.04 LTS Source: https://pyav.org/docs/stable/_sources/overview/installation.rst.txt Install Python development headers and FFmpeg library components using apt-get. ```bash # General dependencies sudo apt-get install -y python-dev pkg-config # Library components sudo apt-get install -y \ libavformat-dev libavcodec-dev libavdevice-dev \ libavutil-dev libswscale-dev libswresample-dev libavfilter-dev ``` -------------------------------- ### Install PyAV via Conda Source: https://pyav.org/docs/stable/_sources/overview/installation.rst.txt Alternative installation method using the conda-forge channel. ```bash conda install av -c conda-forge ``` -------------------------------- ### Open a device with av.open Source: https://pyav.org/docs/stable/api/_globals.html Example of opening a webcam device on OS X using the avfoundation format. ```python >>> # Open webcam on OS X. >>> av.open(format='avfoundation', file='0') ``` -------------------------------- ### Accessing a stream from a container Source: https://pyav.org/docs/stable/api/stream.html An example of opening a container and accessing the first video stream. ```python >>> fh = av.open(video_path) >>> stream = fh.streams.video[0] >>> stream ``` -------------------------------- ### VideoFrame.to_image(**kwargs) Source: https://pyav.org/docs/stable/api/video.html Gets an RGB PIL.Image of this frame. Any **kwargs are passed to VideoReformatter.reformat(). PIL or Pillow must be installed. ```APIDOC ## VideoFrame.to_image(**kwargs) ### Description Gets an RGB PIL.Image of this frame. Any **kwargs are passed to VideoReformatter.reformat(). PIL or Pillow must be installed. ### Method Method ### Parameters - **kwargs** - Optional - Keyword arguments passed to VideoReformatter.reformat(). ### Response #### Success Response - **image** (PIL.Image) - The RGB image representation of the frame. ``` -------------------------------- ### Install FFmpeg dependencies on Mac OS X Source: https://pyav.org/docs/stable/_sources/overview/installation.rst.txt Use Homebrew to install required FFmpeg and pkg-config tools on macOS. ```bash brew install ffmpeg pkg-config ``` -------------------------------- ### Stream.start_time Source: https://pyav.org/docs/stable/_sources/api/stream.rst.txt The start time of the stream. ```APIDOC ## Stream.start_time ### Description The start time of the stream. ### Type - **int** or None ### Usage Get the start time in stream time base units. ``` -------------------------------- ### VideoFrame.to_ndarray(**kwargs) Source: https://pyav.org/docs/stable/api/video.html Gets a numpy array of this frame. Any **kwargs are passed to VideoReformatter.reformat(). Numpy must be installed. For pal8, an (image, palette) tuple will be returned, with the palette being in ARGB (PyAV will swap bytes if needed). ```APIDOC ## VideoFrame.to_ndarray(**kwargs) ### Description Gets a numpy array of this frame. Any **kwargs are passed to VideoReformatter.reformat(). Numpy must be installed. For pal8, an (image, palette) tuple will be returned, with the palette being in ARGB (PyAV will swap bytes if needed). ### Method Method ### Parameters - **kwargs** - Optional - Keyword arguments passed to VideoReformatter.reformat(). ### Response #### Success Response - **array** (numpy.ndarray) - The numpy array representation of the frame. For pal8, a tuple (image, palette) is returned. ``` -------------------------------- ### Dynamic slicing with StreamContainer.get Source: https://pyav.org/docs/stable/api/stream.html Shows how to use the get method to select specific streams using positional arguments. ```python # Get the first channel. streams.get(0) # Get the first two audio channels. streams.get(audio=(0, 1)) ``` -------------------------------- ### Get canonical name for AudioFormat Source: https://pyav.org/docs/stable/api/audio.html Retrieves the canonical name of the sample format. ```python >>> SampleFormat('s16p').name 's16p' ``` -------------------------------- ### Get bytes per sample for AudioFormat Source: https://pyav.org/docs/stable/api/audio.html Retrieves the number of bytes per sample for a given audio format. ```python >>> SampleFormat('s16p').bytes 2 ``` -------------------------------- ### Convert VideoFrame to RGB Source: https://pyav.org/docs/stable/api/video.html Use the to_rgb method to convert a frame to the rgb24 format. This example shows the default format and the result after conversion. ```python >>> frame = VideoFrame(1920, 1080) >>> frame.format.name 'yuv420p' >>> frame.to_rgb().format.name 'rgb24' ``` -------------------------------- ### Build PyAV from GitHub source Source: https://pyav.org/docs/stable/_sources/overview/installation.rst.txt Steps to clone the repository, set up the environment, and build PyAV. ```bash # Get PyAV from GitHub. git clone git@github.com:PyAV-Org/PyAV.git cd PyAV # Prep a virtualenv. source scripts/activate.sh # Install basic requirements. pip install -r tests/requirements.txt # Optionally build FFmpeg. ./scripts/build-deps # Build PyAV. make # or python setup.py build_ext --inplace ``` -------------------------------- ### swr_init Source: https://pyav.org/docs/stable/development/includes.html Initializes the SwrContext after options have been set. ```APIDOC ## `swr_init` ### Description Initializes the SwrContext after options have been set. ### Method Function ### Signature `int swr_init(struct SwrContext *s)` ### Parameters - **s** (struct SwrContext*) - Required - The context to initialize. ### Return Value - **int** - 0 on success, negative error code on failure. ``` -------------------------------- ### Create a VideoFormat and access its name Source: https://pyav.org/docs/stable/api/video.html Shows how to instantiate a VideoFormat with the pixel format 'rgb24' and access its name attribute. ```python >>> format = VideoFormat('rgb24') >>> format.name 'rgb24' ``` -------------------------------- ### sws_getColorspaceDetails Source: https://pyav.org/docs/stable/development/includes.html Gets the colorspace details from a SwsContext. ```APIDOC ## `sws_getColorspaceDetails` ### Description Gets the colorspace details from a SwsContext. ### Method Function ### Signature `int sws_getColorspaceDetails(struct SwsContext *c, int **inv_table, int *srcRange, int **table, int *dstRange, int *brightness, int *contrast, int *saturation)` ### Parameters - **c** (struct SwsContext*) - Required - The context. - **inv_table** (int**) - Required - Output inverse table. - **srcRange** (int*) - Required - Output source range. - **table** (int**) - Required - Output table. - **dstRange** (int*) - Required - Output destination range. - **brightness** (int*) - Required - Output brightness. - **contrast** (int*) - Required - Output contrast. - **saturation** (int*) - Required - Output saturation. ### Return Value - **int** - 0 on success, negative error code on failure. ``` -------------------------------- ### Build and Test PyAV Environment Source: https://pyav.org/docs/stable/development/hacking.html Commands to prepare the development environment, build dependencies, compile the project, and execute the test suite. ```bash # Prep the environment. source scripts/activate.sh # Build FFmpeg. ./scripts/build-deps # Build PyAV. make # Run the tests. make test ``` -------------------------------- ### swr_get_delay Source: https://pyav.org/docs/stable/development/includes.html Gets the delay in the resampler in terms of the given base. ```APIDOC ## `swr_get_delay` ### Description Gets the delay in the resampler in terms of the given base. ### Method Function ### Signature `int64_t swr_get_delay(struct SwrContext *s, int64_t base)` ### Parameters - **s** (struct SwrContext*) - Required - The context. - **base** (int64_t) - Required - The base for the delay calculation. ### Return Value - **int64_t** - The delay. ``` -------------------------------- ### Initialize and Inspect a Codec Source: https://pyav.org/docs/stable/api/codec.html Demonstrates how to initialize a Codec object for decoding and inspect its attributes such as name, type, and encoder status. ```python >>> codec = Codec('mpeg4', 'r') >>> codec.name 'mpeg4' >>> codec.type 'video' >>> codec.is_encoder False ``` -------------------------------- ### AudioResampler.__init__ Source: https://pyav.org/docs/stable/api/audio.html Constructor for AudioResampler. Initializes a resampler with target format, layout, and sample rate. ```APIDOC ## AudioResampler.__init__ ### Description Initializes an AudioResampler instance with the target audio format, channel layout, and sample rate. ### Method Constructor ### Parameters - **format** (AudioFormat) - Optional - The target format, or string that parses to one (e.g. "s16"). - **layout** (AudioLayout) - Optional - The target layout, or an int/string that parses to one (e.g. "stereo"). - **rate** (int) - Optional - The target sample rate. ### Returns An AudioResampler instance. ``` -------------------------------- ### sws_getCachedContext Source: https://pyav.org/docs/stable/development/includes.html Gets a cached SwsContext, reusing an existing one if possible. ```APIDOC ## `sws_getCachedContext` ### Description Gets a cached SwsContext, reusing an existing one if possible. ### Method Function ### Signature `struct SwsContext *sws_getCachedContext(struct SwsContext *context, int srcW, int srcH, enum AVPixelFormat srcFormat, int dstW, int dstH, enum AVPixelFormat dstFormat, int flags, SwsFilter *srcFilter, SwsFilter *dstFilter, const double *param)` ### Parameters - **context** (struct SwsContext*) - Required - Existing context to reuse. - **srcW** (int) - Required - Source width. - **srcH** (int) - Required - Source height. - **srcFormat** (enum AVPixelFormat) - Required - Source pixel format. - **dstW** (int) - Required - Destination width. - **dstH** (int) - Required - Destination height. - **dstFormat** (enum AVPixelFormat) - Required - Destination pixel format. - **flags** (int) - Required - Scaling flags. - **srcFilter** (SwsFilter*) - Required - Source filter. - **dstFilter** (SwsFilter*) - Required - Destination filter. - **param** (const double*) - Required - Scaling parameters. ### Return Value - **struct SwsContext*** - The context, or NULL on failure. ``` -------------------------------- ### Initialize a VideoFrame Source: https://pyav.org/docs/stable/api/video.html Create a new VideoFrame instance by specifying width, height, and pixel format. ```python >>> frame = VideoFrame(1920, 1080, 'rgb24') ``` -------------------------------- ### AudioFrame.to_ndarray Source: https://pyav.org/docs/stable/api/audio.html Converts the audio frame to a numpy array. Requires numpy to be installed. ```APIDOC ## AudioFrame.to_ndarray ### Description Get a numpy array of this frame. Note: Numpy must be installed. ### Method instance ### Signature to_ndarray(**kwargs) ### Parameters - **kwargs** - Optional - Additional keyword arguments for conversion. ### Returns numpy.ndarray - The audio data as a numpy array. ``` -------------------------------- ### VideoFrame.to_rgb(**kwargs) Source: https://pyav.org/docs/stable/api/video.html Gets an RGB version of this frame. Any **kwargs are passed to VideoReformatter.reformat(). ```APIDOC ## VideoFrame.to_rgb(**kwargs) ### Description Gets an RGB version of this frame. Any **kwargs are passed to VideoReformatter.reformat(). ### Method Method ### Parameters - **kwargs** - Optional - Keyword arguments passed to VideoReformatter.reformat(). ### Request Example ``` >>> frame = VideoFrame(1920, 1080) >>> frame.format.name 'yuv420p' >>> frame.to_rgb().format.name 'rgb24' ``` ### Response #### Success Response - **frame** (VideoFrame) - The RGB version of the frame. ``` -------------------------------- ### Create a VideoFrame with width, height, and format Source: https://pyav.org/docs/stable/_sources/api/video.rst.txt Creates a VideoFrame with the given width, height, and format. The format can be a VideoFormat instance or a string such as 'rgb24'. ```python frame = VideoFrame(1920, 1080, 'rgb24') ``` -------------------------------- ### swr_alloc Source: https://pyav.org/docs/stable/development/includes.html Allocates a new SwrContext. ```APIDOC ## `swr_alloc` ### Description Allocates a new SwrContext. ### Method Function ### Signature `struct SwrContext *swr_alloc(void)` ### Parameters None ### Return Value - **struct SwrContext*** - The allocated context, or NULL on failure. ``` -------------------------------- ### swr_alloc_set_opts Source: https://pyav.org/docs/stable/development/includes.html Allocates a SwrContext and sets the options for audio resampling. ```APIDOC ## `swr_alloc_set_opts` ### Description Allocates a SwrContext and sets the options for audio resampling. ### Method Function ### Signature `struct SwrContext *swr_alloc_set_opts(struct SwrContext *s, int64_t out_ch_layout, enum AVSampleFormat out_sample_fmt, int out_sample_rate, int64_t in_ch_layout, enum AVSampleFormat in_sample_fmt, int in_sample_rate, int log_offset, void *log_ctx)` ### Parameters - **s** (struct SwrContext*) - Optional - Existing context to reuse, or NULL to allocate a new one. - **out_ch_layout** (int64_t) - Required - Output channel layout. - **out_sample_fmt** (enum AVSampleFormat) - Required - Output sample format. - **out_sample_rate** (int) - Required - Output sample rate. - **in_ch_layout** (int64_t) - Required - Input channel layout. - **in_sample_fmt** (enum AVSampleFormat) - Required - Input sample format. - **in_sample_rate** (int) - Required - Input sample rate. - **log_offset** (int) - Required - Log offset. - **log_ctx** (void*) - Required - Log context. ### Return Value - **struct SwrContext*** - The allocated context, or NULL on failure. ``` -------------------------------- ### Build PyAV on Windows with custom FFmpeg path Source: https://pyav.org/docs/stable/_sources/overview/installation.rst.txt Specify the directory containing FFmpeg binaries when building on Windows. ```bash python setup.py build --ffmpeg-dir=C:\ffmpeg ``` -------------------------------- ### Dynamic slicing with keyword arguments Source: https://pyav.org/docs/stable/api/stream.html Demonstrates selecting streams using keyword arguments or dictionaries to specify stream types. ```python # Get the first video channel. streams.get(video=0) # or streams.get({'video': 0}) ``` -------------------------------- ### CodecContext.open Source: https://pyav.org/docs/stable/api/codec.html Opens the codec context, making it ready for encoding or decoding. ```APIDOC ## CodecContext.open ### Description Opens the codec context, initializing the codec for use. ### Method Instance method ### Parameters - **strict** (bool) - Optional - If True, strict mode is enabled. Default is True. ### Returns None ``` -------------------------------- ### Get bits per sample for AudioFormat Source: https://pyav.org/docs/stable/api/audio.html Retrieves the number of bits per sample for a given audio format. ```python >>> SampleFormat('s16p').bits 16 ``` -------------------------------- ### StreamContainer.get Source: https://pyav.org/docs/stable/api/stream.html Get a selection of Stream objects as a list. Supports positional int indices, lists/tuples of indices, and keyword arguments for stream types. ```APIDOC ## StreamContainer.get ### Description Get a selection of Stream as a list. Positional arguments may be int (index into streams) or list/tuple of those. Keyword arguments (or dicts) are interpreted as (stream_type, index_value_or_set) pairs. Stream objects are passed through untouched. If nothing is selected, all streams are returned. ### Method N/A (Python method) ### Parameters #### Positional Arguments - **streams** (int, list, tuple, dict) - Optional - Selection of streams by index or type. #### Keyword Arguments - **video** (int, list, tuple) - Optional - Select video streams by index or indices. - **audio** (int, list, tuple) - Optional - Select audio streams by index or indices. - **subtitles** (int, list, tuple) - Optional - Select subtitle streams by index or indices. - **data** (int, list, tuple) - Optional - Select data streams by index or indices. ### Returns - **list** of Stream - The selected streams. ### Examples ```python # Get the first channel. streams.get(0) # Get the first two audio channels. streams.get(audio=(0, 1)) # Get the first video channel. streams.get(video=0) # or streams.get({'video': 0}) ``` ``` -------------------------------- ### Use av.open as context manager Source: https://pyav.org/docs/stable/_sources/overview/caveats.rst.txt Use the container as a context manager to ensure it is closed automatically, avoiding garbage collection issues in tight loops. This is recommended until reference cycles are resolved. ```python with av.open(path) as fh: # Do stuff with it. ``` -------------------------------- ### CodecContext.create Source: https://pyav.org/docs/stable/api/codec.html Static method to create a new CodecContext instance for a given codec and mode. ```APIDOC ## CodecContext.create ### Description Creates a new CodecContext instance for the specified codec and mode. ### Method Static method ### Parameters - **codec** (Codec) - Required - The codec to use. - **mode** (str) - Optional - The mode, either 'r' for read (decode) or 'w' for write (encode). ### Returns CodecContext - The newly created context. ``` -------------------------------- ### Accessing streams from a container Source: https://pyav.org/docs/stable/api/stream.html Demonstrates various ways to retrieve streams from a container, including indexing and filtering by type. ```python # There are a few ways to pulling out streams. first = container.streams[0] video = container.streams.video[0] audio = container.streams.get(audio=(0, 1)) ``` -------------------------------- ### sws_getContext Source: https://pyav.org/docs/stable/development/includes.html Creates a SwsContext for image scaling and format conversion. ```APIDOC ## `sws_getContext` ### Description Creates a SwsContext for image scaling and format conversion. ### Method Function ### Signature `struct SwsContext *sws_getContext(int srcW, int srcH, enum AVPixelFormat srcFormat, int dstW, int dstH, enum AVPixelFormat dstFormat, int flags, SwsFilter *srcFilter, SwsFilter *dstFilter, const double *param)` ### Parameters - **srcW** (int) - Required - Source width. - **srcH** (int) - Required - Source height. - **srcFormat** (enum AVPixelFormat) - Required - Source pixel format. - **dstW** (int) - Required - Destination width. - **dstH** (int) - Required - Destination height. - **dstFormat** (enum AVPixelFormat) - Required - Destination pixel format. - **flags** (int) - Required - Scaling flags. - **srcFilter** (SwsFilter*) - Required - Source filter. - **dstFilter** (SwsFilter*) - Required - Destination filter. - **param** (const double*) - Required - Scaling parameters. ### Return Value - **struct SwsContext*** - The context, or NULL on failure. ``` -------------------------------- ### swresample_configuration Source: https://pyav.org/docs/stable/development/includes.html Returns the configuration string of the libswresample library. ```APIDOC ## `swresample_configuration` ### Description Returns the configuration string of the libswresample library. ### Method Function ### Signature `const char *swresample_configuration(void)` ### Parameters None ### Return Value - **const char*** - The configuration string. ``` -------------------------------- ### swscale_configuration Source: https://pyav.org/docs/stable/development/includes.html Returns the configuration string of the libswscale library. ```APIDOC ## `swscale_configuration` ### Description Returns the configuration string of the libswscale library. ### Method Function ### Signature `const char *swscale_configuration(void)` ### Parameters None ### Return Value - **const char*** - The configuration string. ``` -------------------------------- ### AudioFifo.write Source: https://pyav.org/docs/stable/api/audio.html Pushes a frame of audio samples into the FIFO buffer. The FIFO remembers attributes from the first frame and uses them for output frames. ```APIDOC ## AudioFifo.write ### Description Push a frame of samples into the queue. The FIFO will remember the attributes from the first frame, and use those to populate all output frames. If there is a pts and time_base and sample_rate, then the FIFO will assert that the incoming timestamps are continuous. ### Method instance ### Signature write(frame) ### Parameters - **frame** (AudioFrame) - Required - The frame of samples to push. ### Returns None ``` -------------------------------- ### av.open(file, mode='r', **kwargs) Source: https://pyav.org/docs/stable/api/_globals.html The av.open function is the main entrypoint for opening files or streams in PyAV. It accepts a file path or file-like object, a mode for reading or writing, and various optional parameters for format, options, and timeouts. ```APIDOC ## av.open(file, mode='r', **kwargs) ### Description Main entrypoint to opening files/streams. This function is used to open media files or streams for reading or writing. ### Method Function call ### Endpoint av.open(file, mode='r', **kwargs) ### Parameters #### Positional Parameters - **file** (str) - Required - The file to open, which can be either a string or a file-like object. - **mode** (str) - Optional - `"r"` for reading and `"w"` for writing. Defaults to `"r"`. #### Keyword Parameters - **format** (str) - Optional - Specific format to use. Defaults to autodetect. - **options** (dict) - Optional - Options to pass to the container and all streams. - **container_options** (dict) - Optional - Options to pass to the container. - **stream_options** (list) - Optional - Options to pass to each stream. - **metadata_encoding** (str) - Optional - Encoding to use when reading or writing file metadata. Defaults to `"utf-8"`. - **metadata_errors** (str) - Optional - Specifies how to handle encoding errors; behaves like `str.encode` parameter. Defaults to `"strict"`. - **buffer_size** (int) - Optional - Size of buffer for Python input/output operations in bytes. Honored only when `file` is a file-like object. Defaults to 32768 (32k). - **timeout** (float or tuple) - Optional - How many seconds to wait for data before giving up, as a float, or a (open timeout, read timeout) tuple. ### Request Example ```python # Open webcam on OS X. av.open(format='avfoundation', file='0') ``` ### Response Returns a container object representing the opened file/stream. ### Notes For devices (via `libavdevice`), pass the name of the device to `format`. See also: Garbage Collection. More information on using input and output devices is available on the FFmpeg website. ``` -------------------------------- ### OutputContainer.start_encoding Source: https://pyav.org/docs/stable/api/container.html Writes the file header. Called automatically. ```APIDOC ## OutputContainer.start_encoding ### Description Write the file header. Called automatically. ``` -------------------------------- ### VideoFrame.reformat(width=None, height=None, format=None, src_colorspace=None, dst_colorspace=None, interpolation=None) Source: https://pyav.org/docs/stable/api/video.html Creates a new VideoFrame with the specified width, height, format, and colorspace. ```APIDOC ## VideoFrame.reformat(width=None, height=None, format=None, src_colorspace=None, dst_colorspace=None, interpolation=None) ### Description Creates a new VideoFrame with the given width, height, format, and colorspace. See VideoReformatter.reformat() for arguments. ### Method Method ### Parameters - **width** (int) - Optional - The new width. - **height** (int) - Optional - The new height. - **format** (VideoFormat or str) - Optional - The new format. - **src_colorspace** (str) - Optional - The source colorspace. - **dst_colorspace** (str) - Optional - The destination colorspace. - **interpolation** (str) - Optional - The interpolation method. ### Response #### Success Response - **frame** (VideoFrame) - The reformatted video frame. ``` -------------------------------- ### Initialize Python logging for PyAV Source: https://pyav.org/docs/stable/api/utils.html Initializes Python's logging system so PyAV can translate FFmpeg logs into Python logging. Use this if you are not already using Python's logging system. ```python import logging logging.basicConfig() ``` -------------------------------- ### Calculating duration in seconds Source: https://pyav.org/docs/stable/_sources/api/time.rst.txt Shows how to calculate the duration of a video stream in seconds by multiplying the duration by the time_base. ```python >>> video.duration 168 >>> float(video.duration * video.time_base) 6.72 ``` -------------------------------- ### VideoFrame(width, height, format) Source: https://pyav.org/docs/stable/api/video.html Creates a new video frame with the specified width, height, and pixel format. ```APIDOC ## VideoFrame(width, height, format) ### Description Creates a new video frame with the specified dimensions and pixel format. ### Method Constructor ### Parameters - **width** (int) - Required - The width of the frame. - **height** (int) - Required - The height of the frame. - **format** (VideoFormat or str) - Required - The format of the frame. ### Request Example ``` >>> frame = VideoFrame(1920, 1080, 'rgb24') ``` ### Response #### Success Response - **frame** (VideoFrame) - The newly created video frame. ``` -------------------------------- ### swr_convert Source: https://pyav.org/docs/stable/development/includes.html Converts audio samples from one format to another using the SwrContext. ```APIDOC ## `swr_convert` ### Description Converts audio samples from one format to another using the SwrContext. ### Method Function ### Signature `int swr_convert(struct SwrContext *s, uint8_t **out, int out_count, const uint8_t **in, int in_count)` ### Parameters - **s** (struct SwrContext*) - Required - The context. - **out** (uint8_t**) - Required - Output buffer. - **out_count** (int) - Required - Number of output samples. - **in** (const uint8_t**) - Required - Input buffer. - **in_count** (int) - Required - Number of input samples. ### Return Value - **int** - Number of samples output, or negative error code. ``` -------------------------------- ### FilterContext.init Source: https://pyav.org/docs/stable/api/filter.html Initializes the filter context with arguments. ```APIDOC ## FilterContext.init ### Description Initializes the filter context with arguments. ### Method init ### Parameters - **args** (optional) - Arguments for initialization. - **kwargs** - Optional - Additional keyword arguments. ### Returns None ``` -------------------------------- ### Graph.configure Source: https://pyav.org/docs/stable/api/filter.html Configures the graph. ```APIDOC ## Graph.configure ### Description Configures the graph. ### Method configure ### Parameters - **auto_buffer** (bool) - Optional - Whether to automatically add buffers. - **force** (bool) - Optional - Force configuration. ### Returns None ``` -------------------------------- ### Codec.create() Source: https://pyav.org/docs/stable/api/codec.html Creates a CodecContext for this codec. This method is used to instantiate a context for encoding or decoding with the codec. ```APIDOC ## Codec.create() ### Description Creates a CodecContext for this codec. This is the primary way to obtain a context for encoding or decoding. ### Returns A CodecContext object. ``` -------------------------------- ### VideoFrame.from_image(img) Source: https://pyav.org/docs/stable/api/video.html Constructs a frame from a PIL.Image. ```APIDOC ## VideoFrame.from_image(img) ### Description Constructs a frame from a PIL.Image. ### Method Static Method ### Parameters - **img** (PIL.Image) - Required - The image to construct the frame from. ### Response #### Success Response - **frame** (VideoFrame) - The constructed video frame. ``` -------------------------------- ### AudioFifo.read Source: https://pyav.org/docs/stable/api/audio.html Reads samples from the FIFO queue. Returns a new AudioFrame or None if empty. ```APIDOC ## AudioFifo.read ### Description Read samples from the queue. Returns a new AudioFrame or None if empty. If the incoming frames had valid time_base, sample_rate and pts, the returned frames will have accurate timing. ### Method instance ### Signature read(samples=0, partial=False) ### Parameters - **samples** (int) - Optional - The number of samples to pull; 0 gets all. - **partial** (bool) - Optional - Allow returning less than requested. ### Returns AudioFrame or None - New AudioFrame or None if empty. ``` -------------------------------- ### swresample_license Source: https://pyav.org/docs/stable/development/includes.html Returns the license string of the libswresample library. ```APIDOC ## `swresample_license` ### Description Returns the license string of the libswresample library. ### Method Function ### Signature `const char *swresample_license(void)` ### Parameters None ### Return Value - **const char*** - The license string. ``` -------------------------------- ### Run Code Formatting and Linting Source: https://pyav.org/docs/stable/development/hacking.html Commands to execute isort and flake8 checks, which are required for code to be merged into the develop branch. ```bash ./scripts/test isort ./scripts/test flake8 ``` -------------------------------- ### Generate a synthetic video with PyAV and NumPy Source: https://pyav.org/docs/stable/cookbook/numpy.html Generates a 4-second MPEG-4 video (test.mp4) with 24 fps and 480x320 resolution. Creates synthetic RGB frames with sine-wave color patterns, converts them to VideoFrame objects, encodes them, and flushes the stream before closing the container. ```python import numpy as np import av duration = 4 fps = 24 total_frames = duration * fps container = av.open("test.mp4", mode="w") stream = container.add_stream("mpeg4", rate=fps) stream.width = 480 stream.height = 320 stream.pix_fmt = "yuv420p" for frame_i in range(total_frames): img = np.empty((480, 320, 3)) img[:, :, 0] = 0.5 + 0.5 * np.sin(2 * np.pi * (0 / 3 + frame_i / total_frames)) img[:, :, 1] = 0.5 + 0.5 * np.sin(2 * np.pi * (1 / 3 + frame_i / total_frames)) img[:, :, 2] = 0.5 + 0.5 * np.sin(2 * np.pi * (2 / 3 + frame_i / total_frames)) img = np.round(255 * img).astype(np.uint8) img = np.clip(img, 0, 255) frame = av.VideoFrame.from_ndarray(img, format="rgb24") for packet in stream.encode(frame): container.mux(packet) # Flush stream for packet in stream.encode(): container.mux(packet) # Close the file container.close() ``` -------------------------------- ### OutputContainer.add_stream Source: https://pyav.org/docs/stable/api/container.html Creates a new stream in the output container and returns it. Requires a codec name and optionally a rate for video or audio. ```APIDOC ## OutputContainer.add_stream ### Description Create a new stream in the output container and return it. ### Method add_stream ### Parameters - **codec_name** (str) - Required - The name of a codec. - **rate** - Optional - The frame rate for video, and sample rate for audio. Examples for video include `24`, `23.976`, and `Fraction(30000,1001)`. Examples for audio include `48000` and `44100`. ### Returns The new `Stream`. ``` -------------------------------- ### Codec(name, mode='r') Source: https://pyav.org/docs/stable/api/codec.html Constructor for the Codec class. Creates a Codec object representing an available codec, with a name and mode ('r' for decoding, 'w' for encoding). ```APIDOC ## Codec(name, mode='r') ### Description Creates a Codec object that exposes information about an available codec and provides a way to create a CodecContext for encoding or decoding. ### Parameters - **name** (str) - Required - The codec name. - **mode** (str) - Optional - 'r' for decoding or 'w' for encoding. Default is 'r'. ### Example ```python >>> codec = Codec('mpeg4', 'r') >>> codec.name 'mpeg4' >>> codec.type 'video' >>> codec.is_encoder False ``` ``` -------------------------------- ### av.logging.adapt_level Source: https://pyav.org/docs/stable/api/utils.html Converts a library log level to a Python log level. ```APIDOC ## av.logging.adapt_level ### Description Convert a library log level to a Python log level. ### Parameters - **level** (int) - Required - The library log level to convert. ``` -------------------------------- ### Generate a video barcode with PyAV and NumPy Source: https://pyav.org/docs/stable/cookbook/numpy.html Creates a video barcode by averaging each frame's columns and stacking them horizontally. Uses av.datasets.curated to fetch a sample video, decodes frames with container.decode(video=0), converts to rgb24 ndarray, and saves the result as barcode.jpg with quality=85. ```python from PIL import Image import numpy as np import av import av.datasets container = av.open( av.datasets.curated("pexels/time-lapse-video-of-sunset-by-the-sea-854400.mp4") ) container.streams.video[0].thread_type = "AUTO" # Go faster! columns = [] for frame in container.decode(video=0): print(frame) array = frame.to_ndarray(format="rgb24") # Collapse down to a column. column = array.mean(axis=1) # Convert to bytes, as the `mean` turned our array into floats. column = column.clip(0, 255).astype("uint8") # Get us in the right shape for the `hstack` below. column = column.reshape(-1, 1, 3) columns.append(column) # Close the file, free memory container.close() full_array = np.hstack(columns) full_img = Image.fromarray(full_array, "RGB") full_img = full_img.resize((800, 200)) full_img.save("barcode.jpg", quality=85) ``` -------------------------------- ### InputContainer Properties Source: https://pyav.org/docs/stable/api/container.html Properties of the InputContainer class: bit_rate, duration, size, and start_time. ```APIDOC ## InputContainer Properties ### Description Properties of the InputContainer class. ### Properties - **bit_rate** - The bit rate of the container. - **duration** - The duration of the container. - **size** - The size of the container. - **start_time** - The start time of the container. ``` -------------------------------- ### swscale_license Source: https://pyav.org/docs/stable/development/includes.html Returns the license string of the libswscale library. ```APIDOC ## `swscale_license` ### Description Returns the license string of the libswscale library. ### Method Function ### Signature `const char *swscale_license(void)` ### Parameters None ### Return Value - **const char*** - The license string. ``` -------------------------------- ### sws_freeContext Source: https://pyav.org/docs/stable/development/includes.html Frees a SwsContext. ```APIDOC ## `sws_freeContext` ### Description Frees a SwsContext. ### Method Function ### Signature `void sws_freeContext(struct SwsContext *swsContext)` ### Parameters - **swsContext** (struct SwsContext*) - Required - The context to free. ### Return Value None ``` -------------------------------- ### Compare default SLICE threading vs AUTO threading Source: https://pyav.org/docs/stable/cookbook/basics.html Decodes the same video twice: first with default SLICE threading, then with thread_type = "AUTO". Prints timing for both passes; the author reports AUTO decodes about 5 times faster. ```python import time import av import av.datasets print("Decoding with default (slice) threading...") container = av.open( av.datasets.curated("pexels/time-lapse-video-of-night-sky-857195.mp4") ) start_time = time.time() for packet in container.demux(): print(packet) for frame in packet.decode(): print(frame) default_time = time.time() - start_time container.close() print("Decoding with auto threading...") container = av.open( av.datasets.curated("pexels/time-lapse-video-of-night-sky-857195.mp4") ) # !!! This is the only difference. container.streams.video[0].thread_type = "AUTO" start_time = time.time() for packet in container.demux(): print(packet) for frame in packet.decode(): print(frame) auto_time = time.time() - start_time container.close() print("Decoded with default threading in {:.2f}s.".format(default_time)) print("Decoded with auto threading in {:.2f}s.".format(auto_time)) ```