快捷方式

StreamingMediaEncoder

class torio.io.StreamingMediaEncoder(dst: Union[str, Path, BinaryIO], format: Optional[str] = None, buffer_size: int = 4096)[source]

分块编码并写入音频/视频流

参数:
  • dst (str, path-like or file-like object) –

    编码数据将被写入的目标位置。如果为字符串类型,则必须是 FFmpeg 可以处理的资源指示符。支持的值取决于系统中找到的 FFmpeg 版本。

    如果为类文件对象 (file-like object),则必须支持 write 方法,其签名应为 write(data: bytes) -> int

    请参考以下链接,了解 write 方法的预期签名和行为。

  • format (str or None, optional) –

    覆盖输出格式,或指定输出媒体设备。默认值: None (不覆盖格式也不输出到设备)。

    此参数用于两种不同的用例。

    1. 覆盖输出格式。当写入原始数据或使用与文件扩展名不同的格式时非常有用。

    2. 指定输出设备。这允许将媒体流输出到硬件设备,如扬声器和视频屏幕。

    注意

    此选项大致对应于 ffmpeg 命令的 -f 选项。请参考 ffmpeg 文档以获取可能的值。

    https://ffmpeg.cpp.org.cn/ffmpeg-formats.html#Muxers

    请使用 get_muxers() 来列出当前环境中可用的复用器 (muxer)。

    对于设备访问,可用值因硬件(AV 设备)和软件配置(ffmpeg 构建)而异。请参考 ffmpeg 文档以获取可能的值。

    https://ffmpeg.cpp.org.cn/ffmpeg-devices.html#Output-Devices

    请使用 get_output_devices() 来列出当前环境中可用的输出设备。

  • buffer_size (int) –

    内部缓冲区大小(字节)。仅在 dst 是类文件对象时使用。

    默认值: 4096

方法

add_audio_stream

StreamingMediaEncoder.add_audio_stream(sample_rate: int, num_channels: int, format: str = 'flt', *, encoder: Optional[str] = None, encoder_option: Optional[Dict[str, str]] = None, encoder_sample_rate: Optional[int] = None, encoder_num_channels: Optional[int] = None, encoder_format: Optional[str] = None, codec_config: Optional[CodecConfig] = None, filter_desc: Optional[str] = None)[source]

添加一个输出音频流。

参数:
  • sample_rate (int) – 采样率。

  • num_channels (int) – 通道数。

  • format (str, optional) –

    输入采样格式,决定输入张量的 dtype。

    • "u8": 输入张量必须是 torch.uint8 类型。

    • "s16": 输入张量必须是 torch.int16 类型。

    • "s32": 输入张量必须是 torch.int32 类型。

    • "s64": 输入张量必须是 torch.int64 类型。

    • "flt": 输入张量必须是 torch.float32 类型。

    • "dbl": 输入张量必须是 torch.float64 类型。

    默认值: "flt"

  • encoder (str or None, optional) –

    使用的编码器名称。如果提供,则使用指定的编码器而不是默认编码器。

    要列出可用编码器,音频请使用 get_audio_encoders(),视频请使用 get_video_encoders()

    默认值: None

  • encoder_option (dict or None, optional) –

    传递给编码器的选项。键值对均为字符串。

    要列出特定编码器的选项,可以使用命令 ffmpeg -h encoder=<ENCODER>

    默认值: None


    除了编码器特定选项外,还可以传递与多线程相关的选项。这些选项仅在编码器支持时有效。如果两者均未提供,StreamReader 默认为单线程。

    "threads": 线程数(字符串类型)。提供值 "0" 将让 FFmpeg 根据其启发式算法决定。

    "thread_type": 使用哪种多线程方法。有效值为 "frame""slice"。请注意,每种编码器支持的方法集不同。如果未提供,则使用默认值。

    • "frame": 一次编码多个帧。每个线程处理一个帧。这将增加每个线程一个帧的编码延迟。

    • "slice": 一次编码单个帧的多个部分。


  • encoder_sample_rate (int or None, optional) –

    覆盖编码时使用的采样率。有些编码器对编码使用的采样率有限制。如果源采样率不受编码器支持,则使用源采样率,否则选择一个默认值。

    例如,"opus" 编码器仅支持 48k Hz,因此,当使用 "opus" 编码器编码波形时,始终编码为 48k Hz。同时 "mp3" ("libmp3lame") 支持 44.1k, 48k, 32k, 22.05k, 24k, 16k, 11.025k, 12k 和 8k Hz。如果原始采样率是其中之一,则使用原始采样率,否则会重采样到默认值 (44.1k)。当编码为 WAV 格式时,对采样率没有限制,因此将使用原始采样率。

    提供 encoder_sample_rate 将覆盖此行为,并使编码器尝试使用提供的采样率。提供的值必须是编码器支持的值之一。

  • encoder_num_channels (int or None, optional) –

    覆盖编码使用的通道数。

    与采样率类似,某些编码器(如 "opus""vorbis""g722")对编码使用的通道数有限制。

    如果原始通道数受编码器支持,则使用原始通道数,否则编码器尝试将通道混音到支持的通道数之一。

    提供 encoder_num_channels 将覆盖此行为,并使编码器尝试使用提供的通道数。提供的值必须是编码器支持的值之一。

  • encoder_format (str or None, optional) –

    用于编码媒体的格式。当编码器支持多种格式时,传递此参数将覆盖编码使用的格式。

    要列出编码器支持的格式,可以使用命令 ffmpeg -h encoder=<ENCODER>

    默认值: None

    注意

    未提供 encoder_format 选项时,编码器使用其默认格式。

    例如,当将音频编码为 wav 格式时,使用 16 位有符号整数;当将视频编码为 mp4 格式(h264 编码器)时,使用 YUV 格式之一。

    这是因为通常在音频模型中使用 32 位或 16 位浮点数,但这在音频格式中并不常用。类似地,RGB24 在视觉模型中常用,但视频格式通常(且更好地)支持 YUV 格式。

  • codec_config (CodecConfig or None, optional) –

    编解码器配置。请参阅 CodecConfig 获取配置选项。

    默认值: None

  • filter_desc (str or None, optional) – 编码输入媒体之前要应用的额外处理。

add_video_stream

StreamingMediaEncoder.add_video_stream(frame_rate: float, width: int, height: int, format: str = 'rgb24', *, encoder: Optional[str] = None, encoder_option: Optional[Dict[str, str]] = None, encoder_frame_rate: Optional[float] = None, encoder_width: Optional[int] = None, encoder_height: Optional[int] = None, encoder_format: Optional[str] = None, codec_config: Optional[CodecConfig] = None, filter_desc: Optional[str] = None, hw_accel: Optional[str] = None)[source]

添加一个输出视频流。

此方法必须在调用 open 之前调用。

参数:
  • frame_rate (float) – 视频的帧率。

  • width (int) – 视频帧的宽度。

  • height (int) – 视频帧的高度。

  • format (str, optional) –

    输入像素格式,决定输入张量的颜色通道顺序。

    • "gray8": 单通道,灰度。

    • "rgb24": 三通道,顺序为 RGB。

    • "bgr24": 三通道,顺序为 BGR。

    • "yuv444p": 三通道,顺序为 YUV。

    默认值: "rgb24"

    在任何情况下,输入张量必须是 torch.uint8 类型,并且形状必须是 (帧, 通道, 高度, 宽度)。

  • encoder (str or None, optional) –

    使用的编码器名称。如果提供,则使用指定的编码器而不是默认编码器。

    要列出可用编码器,音频请使用 get_audio_encoders(),视频请使用 get_video_encoders()

    默认值: None

  • encoder_option (dict or None, optional) –

    传递给编码器的选项。键值对均为字符串。

    要列出特定编码器的选项,可以使用命令 ffmpeg -h encoder=<ENCODER>

    默认值: None


    除了编码器特定选项外,还可以传递与多线程相关的选项。这些选项仅在编码器支持时有效。如果两者均未提供,StreamReader 默认为单线程。

    "threads": 线程数(字符串类型)。提供值 "0" 将让 FFmpeg 根据其启发式算法决定。

    "thread_type": 使用哪种多线程方法。有效值为 "frame""slice"。请注意,每种编码器支持的方法集不同。如果未提供,则使用默认值。

    • "frame": 一次编码多个帧。每个线程处理一个帧。这将增加每个线程一个帧的编码延迟。

    • "slice": 一次编码单个帧的多个部分。


  • encoder_frame_rate (float or None, optional) –

    覆盖编码时使用的帧率。

    一些编码器(如 "mpeg1""mpeg2")对编码使用的帧率有限制。在这种情况下,如果源帧率(通过 frame_rate 提供)不是受支持的帧率之一,则选择一个默认值,并且帧率会动态更改。否则,使用源帧率。

    提供 encoder_frame_rate 将覆盖此行为,并使编码器尝试使用提供的采样率。提供的值必须是编码器支持的值之一。

  • encoder_width (int or None, optional) – 编码时使用的图像宽度。这允许在编码期间更改图像大小。

  • encoder_height (int or None, optional) – 编码时使用的图像高度。这允许在编码期间更改图像大小。

  • encoder_format (str or None, optional) –

    用于编码媒体的格式。当编码器支持多种格式时,传递此参数将覆盖编码使用的格式。

    要列出编码器支持的格式,可以使用命令 ffmpeg -h encoder=<ENCODER>

    默认值: None

    注意

    未提供 encoder_format 选项时,编码器使用其默认格式。

    例如,当将音频编码为 wav 格式时,使用 16 位有符号整数;当将视频编码为 mp4 格式(h264 编码器)时,使用 YUV 格式之一。

    这是因为通常在音频模型中使用 32 位或 16 位浮点数,但这在音频格式中并不常用。类似地,RGB24 在视觉模型中常用,但视频格式通常(且更好地)支持 YUV 格式。

  • codec_config (CodecConfig or None, optional) –

    编解码器配置。请参阅 CodecConfig 获取配置选项。

    默认值: None

  • filter_desc (str or None, optional) – 编码输入媒体之前要应用的额外处理。

  • hw_accel (str or None, optional) –

    启用硬件加速。

    例如,当视频在 CUDA 硬件上编码(例如 encoder=”h264_nvenc”)时,将 CUDA 设备指示符传递给 hw_accel(即 hw_accel=”cuda:0”)将使 StreamingMediaEncoder 期望视频块是 CUDA Tensor。传递 CPU Tensor 将导致错误。

    如果为 None,则视频块 Tensor 必须是 CPU Tensor。默认值: None

close

StreamingMediaEncoder.close()[source]

关闭输出

StreamingMediaEncoder 也是一个上下文管理器,因此支持 with 语句。推荐使用上下文管理器,因为在退出 with 子句时文件会自动关闭。

有关更多详细信息,请参阅 StreamingMediaEncoder.open()

flush

StreamingMediaEncoder.flush()[source]

清空编码器中的帧并将帧写入目标。

open

StreamingMediaEncoder.open(option: Optional[Dict[str, str]] = None) StreamingMediaEncoder[source]

Open the output file / device and write the header.

StreamingMediaEncoder is also a context manager and therefore supports the with statement. This method returns the instance on which the method is called (i.e. self), so that it can be used in with statement. It is recommended to use context manager, as the file is closed automatically when exiting from with clause.

参数:

option (dict or None, optional) – Private options for protocol, device and muxer. See example.

Example - Protocol option
>>> s = StreamingMediaEncoder(dst="rtmp://localhost:1234/live/app", format="flv")
>>> s.add_video_stream(...)
>>> # Passing protocol option `listen=1` makes StreamingMediaEncoder act as RTMP server.
>>> with s.open(option={"listen": "1"}) as f:
>>>     f.write_video_chunk(...)
Example - Device option
>>> s = StreamingMediaEncoder("-", format="sdl")
>>> s.add_video_stream(..., encoder_format="rgb24")
>>> # Open SDL video player with fullscreen
>>> with s.open(option={"window_fullscreen": "1"}):
>>>     f.write_video_chunk(...)
Example - Muxer option
>>> s = StreamingMediaEncoder("foo.flac")
>>> s.add_audio_stream(...)
>>> s.set_metadata({"artist": "torio contributors"})
>>> # FLAC muxer has a private option to not write the header.
>>> # The resulting file does not contain the above metadata.
>>> with s.open(option={"write_header": "false"}) as f:
>>>     f.write_audio_chunk(...)

set_metadata

StreamingMediaEncoder.set_metadata(metadata: Dict[str, str])[source]

Set file-level metadata

参数:

metadata (dict or None, optional) – File-level metadata.

write_audio_chunk

StreamingMediaEncoder.write_audio_chunk(i: int, chunk: Tensor, pts: Optional[float] = None)[source]

Write audio data

参数:
  • i (int) – Stream index.

  • chunk (Tensor) – Waveform tensor. Shape: (frame, channel). The dtype must match what was passed to add_audio_stream() method.

  • pts (float, optional, or None) –

    If provided, overwrite the presentation timestamp.

    注意

    The provided value is converted to integer value expressed in basis of sample rate. Therefore, it is truncated to the nearest value of n / sample_rate.

write_video_chunk

StreamingMediaEncoder.write_video_chunk(i: int, chunk: Tensor, pts: Optional[float] = None)[source]

Write video/image data

参数:
  • i (int) – Stream index.

  • chunk (Tensor) – Video/image tensor. Shape: (time, channel, height, width). The dtype must be torch.uint8. The shape (height, width and the number of channels) must match what was configured when calling add_video_stream()

  • pts (float, optional or None) –

    If provided, overwrite the presentation timestamp.

    注意

    The provided value is converted to integer value expressed in basis of frame rate. Therefore, it is truncated to the nearest value of n / frame_rate.

Support Structures

CodecConfig

class torio.io.CodecConfig(bit_rate: int = -1, compression_level: int = -1, qscale: Optional[int] = None, gop_size: int = -1, max_b_frames: int = -1)[source]

Codec configuration.

bit_rate: int = -1

Bit rate

compression_level: int = -1

Compression level

qscale: Optional[int] = None

Global quality factor. Enables variable bit rate. Valid values depend on encoder.

For example: MP3 takes 0 - 9 (https://trac.ffmpeg.org/wiki/Encode/MP3) while libvorbis takes -1 - 10.

gop_size: int = -1

The number of pictures in a group of pictures, or 0 for intra_only

max_b_frames: int =-1

maximum number of B-frames between non-B-frames.

文档

访问 PyTorch 开发者文档合集

查看文档

教程

获取适用于初学者和高级开发者的深入教程

查看教程

资源

查找开发资源并解决您的问题

查看资源