没晒干的咸鱼
【FFmpeg】ffplay 命令行参数 ⑧
一、ffplay 命令行参数 - 设置自动旋转视频1、设置自动旋转视频 -autorotate 参数该参数值仅用于参考 , 如果需要开发 视频 根据 旋转元数据 自动旋转的功能 , 只需要阅读 ffplay 程序的 处理 -autorotate 参数 的源码即可 ;ffplay 命令 的 -autorotate 参数 用于 设置自动旋转视频 , 文件中的 元数据 中有视频的方向 , 如 横屏 / 竖屏 ; 该参数值 默认 1 , 自动旋转视频 默认 是 打开的 ;播放 1920 x 1080 像素的 视频 ,如果 视频 旋转元数据 是 横向的 , 直接将视频播放出来 ,如果 视频中的 旋转元数据 是 纵向的 , 则会 旋转 90 度 显示视频画面 ;使用 手机 / 摄像机 录制视频时 会 将 录制视频的 方向 设置到 元数据 中 , 一般 会 根据设备的 自然方向 来设置视频的旋转元数据 ;如 : 手机竖屏录制视频 会设置 竖屏的元数据 , 录制的视频是 1920 x 1080 像素的 , 显然这是横向视频 , 但是播放时 会 根据 元数据 中的 视频方向 将 视频 旋转 90 度 正常显示 ;-autorotate 参数值 只能是 0 或 1 :-autorotate 1 : 当 -autorotate 参数值设置为 1 时 , ffplay 播放视频时 会根据视频文件中的 旋转元数据 自动调整视频的显示方向 ;-autorotate 2 : 当 -autorotate 参数值 设置为 0 时 , ffplay 播放视频时 会忽略旋转元数据 , 按视频的原始像素方向播放 ;2、设置自动旋转视频示例执行ffplay -autorotate fengjing.mp4命令 , 不设置值 , 就是使用默认值 1 ;二、ffplay 命令行参数 - 设置丢弃视频帧1、设置丢弃视频帧 -framedrop 参数ffplay 命令的 -framedrop 参数 用于 设置 丢弃 失去同步的 视频帧 , 当 视频帧 的 播放速度 与 主时钟 不同步时 , 可以丢弃 视频帧 ;默认状态下 , -framedrop 参数值为 -1 , 此时同步时钟 为 视频时钟 时 , 不会丢弃 视频帧 ;同步时钟 为 音频时钟 或 外部时钟 时 , 可能会丢弃 失去同步的 视频帧 ;执行ffplay -framedrop fengjing.mp4命令 , framedrop 的参数值被设置为 1 , 无论同步方式是什么同步到视频同步到音频同步到外部时钟都会 丢弃 失去同步的视频帧 , 可以有效 防止视频播放 卡顿 ;2、设置丢弃视频帧 -noframedrop 参数ffplay 命令的 -noframedrop 参数 用于 设置 不丢弃 失去同步的 视频帧 , 当 视频帧 的 播放速度 与 主时钟 不同步时 , 也不可以丢弃 视频帧 ;显然 , 该操作会导致 视频播放卡顿的情况 ;执行ffplay -noframedrop fengjing.mp4命令 , framedrop 的参数值被设置为 0 , 无论同步方式是什么同步到视频同步到音频同步到外部时钟都不会 丢弃 失去同步的视频帧 , 会导致 视频播放 卡顿 , 但可以保证 视频的 完整显示 和 每一帧显示 ;三、ffplay 命令行参数 - 设置输入缓冲区1、设置输入缓冲区 -infbuf 参数ffplay 命令的 -infbuf 参数 用于 设置输入缓冲区 ;在 流媒体播放 或 处理实时数据 时 , 缓冲区的大小 和 管理方式 对于播放的流畅性和性能至关重要 ;使用 -infbuf 参数 设置 输入缓冲区 , 会增加播放开始的延迟 , 因为播放器会在开始播放前尝试填充缓冲区 ; 在 开始 播放 时 , 能够 很好地 应对 网络波动 和 数据传输的不稳定性 ;2、设置输入缓冲区示例-infbuf 参数 不是一个独立使用的参数 , 该参数 经常 与 -probesize 和 -analyzeduration 等参数一起使用 ,-probesize 参数指定了 ffplay 在尝试确定 输入流格式 时应该读取的 数据量 , 在本示例中 设置为 50MB , 增加这个值可以让 ffplay 对输入流进行更深入的分析 , 这有助于正确识别某些复杂的媒体格式 , 但也会增加启动时的延迟 ;-analyzeduration 参数 通常用于限制输入流的分析时长 , 单位是 微秒 μs ; 本示例中设置 100000 微秒 , 也就是 100 毫秒 , 0.1 秒 ;执行ffplay -infbuf -probesize 50M -analyzeduration 100000 fengjing.mp4命令 , 设置 初始读取 50MB 的数据 , 分析时长 0.1 秒 ;
没晒干的咸鱼
【FFmpeg】ffplay 命令行参数 ③
一、ffplay 命令行参数 - 设置窗口显示1、关闭图形化显示窗口 -nodisp 参数ffplay 命令 的 -nodisp 参数 可以关闭 播放 视频时的 图形化窗口 , 即在播放视频 时不显示视频画面 ;该参数 对于只想 听音频 而 不需要看视频 的情况下使用 ; 使用 -vn 参数 , 也可以关闭视频 , 但是会弹出 频谱窗口 , 使用该 -nodisp 参数 , 连频谱窗口也不显示 ;当使用 -nodisp 参数时 , ffplay 只播放 音频 , 不打开视频窗口 ;特别注意 :关闭 图形化显示窗口 并不意味着 禁用了 视频解码 和 处理 , 只是不显示视频画面 ;如果 视频文件 包含 音频流 , 那么 音频 仍然会正常播放 ;执行ffplay -nodisp yuanshen.mp4命令 , 播放视频 , 使用 -nodisp 参数选项后 , 不再弹出视频窗口 , 只单纯的播放音频 ;关闭图形化显示窗口 与 禁用视频 对比 , 执行ffplay -vn yuanshen.mp4命令 , 禁用视频 , 还是会弹出一个窗口 , 窗口中显示着 音频 的 频谱 ;2、无边框窗口 -noborder 参数ffplay 命令行的 -noborder 参数 可以设置 在 播放视频 时显示 无边框窗口 ;使用 -noborder 参数后 , 以无边框模式打开视频窗口 , 窗口的 标题栏 和 边框 将被隐藏 , 从而提供更大的 视频显示区域 ;通过设置 -noborder 参数 , 可以 隐藏边框 ,需要全屏播放视频 或 需要视频占据尽可能多屏幕空间 ;获得更纯净的视频观看体验 , 没有额外的界面元素干扰 ;开启 无边框窗口 后 , 没有 标题栏 可用 , 需要通过 键盘 操作窗口 ;执行ffplay -x 800 -y 600 -noborder yuanshen.mp4命令 , 使用 无边框模式 播放 视频 , 效果如下 , 无法使用鼠标拖动 ;执行ffplay -x 800 -y 600 yuanshen.mp4命令 , 播放视频 默认 是 有边框 的 , 可以 通过 拖动标题栏 拖动窗口 ;二、ffplay 命令行参数 - 设置起始音量1、设置起始音量 -volume 参数ffplay 命令的 -volume 参数 可以 设置 播放音频 的 起始音量大小 ;-volume 参数 接受一个 整数 或 浮点 数作为输入 , 代表音量的级别 , 取值范围 在 0 到 100 之间进行调整 ,0 表示静音 ;100 表示最大音量 ;播放的 具体的音量效果 受到 系统音量设置 , 音频编码 和 音频设备 等因素的影响 ;执行ffplay -x 800 -y 600 -volume 50 yuanshen.mp4命令 , 此时以 50% 音量 播放 视频中的 音频 ;
没晒干的咸鱼
【FFmpeg】ffplay 命令行参数 ⑥
一、ffplay 命令行参数 - 关闭设置1、设置播放完毕自动退出 -autoexit 参数ffplay 命令的 -autoexit 参数 用于 设置 视频播放完毕后 自动退出播放器 ; 默认情况下 , ffplay 播放完视频后 保持开启状态 , 需要等待用户按下 esc 键手动退出 ;默认情况下 , 执行ffplay fengjing.mp4命令 , 视频播放完毕后 , 会停在结束位置 ;在 播放界面 , 按下 esc 键 , 会自动退出界面 ;使用 -autoexit 参数 , 设置 播放完毕后自动退出 播放界面 , 执行ffplay -autoexit fengjing.mp4命令 , 开始播放 ,播放完毕后 , 自动退出 ;2、设置键盘按下任意键退出 -exitonkeydown 参数ffplay 命令的 -exitonkeydown 参数 用于设置 键盘按下任意键退出播放 ;默认状态下按 esc 键可退出播放 ;启用该参数后 , 只要按下键盘上的任意键 , ffplay 都会立即停止播放并退出 ;注意 : 该参数只响应键盘按键事件 , 对鼠标操作无效 ;使用 -exitonkeydown 参数 , 设置 键盘按下任意键退出 播放界面 , 执行ffplay -exitonkeydown fengjing.mp4命令 , 开始播放 , 按下任意一个键盘按键 , 即可退出播放 ;( 截图按键 也是 任意按键 , 执行截图 , 播放界面自动退出 )3、设置鼠标按下任意键退出 -exitonmousedown 参数ffplay 命令的 -exitonmousedown 参数 用于设置 鼠标按下任意键退出播放 ;默认状态下按 esc 键可退出播放 ;启用该参数后 , 只要按下鼠标上的任意键 ( 鼠标左键 / 右键 / 中间 / 侧键 ) , ffplay 都会立即停止播放并退出 ;注意 : 该参数只响应鼠标按键事件 , 对键盘操作无效 ;使用 -exitonmousedown 参数 , 设置 鼠标按下任意键退出 播放界面 , 执行ffplay -exitonmousedown fengjing.mp4命令 , 开始播放 , 按下任意一个鼠标按键 , 即可退出播放 ;选中播放窗口 , 按下任意一个鼠标按键 , 即可退出播放 ;二、ffplay 命令行参数 - 设置解码器1、设置多媒体解码器 -codec:media_specifier 参数ffplay 命令的 -codec:media_specifier 参数 用于 设置 多媒体解码器 , 通过该参数 可以 为 不同的媒体类型 ( 音频 / 视频 / 字幕 ) 指定解码器 ;上述命令中 , media_specifier 是 特定的 多媒体 解码类型 , 可设置为a: 音频 , -codec:a 用于 设置 音频解码器 ;v : 视频 , -codec:v 用于 设置 视频解码器 ;s : 字幕 , -codec:s 用于 设置 字幕解码器 ;2、设置错误多媒体解码器示例执行ffplay -codec:v h264_qsv fengjing.mp4命令 , 尝试使用 h264_qsv 解码器 解码视频 , 结果 解码出错 ;上面的 h264_qsv 解码器 是 使用 Intel Quick Sync Video 技术的 H.264 解码器 ;报错信息 : 解码器用错了 ;[h264_qsv @ 000001c1d33d95c0] Error initializing an internal MFX session: unsupported (-3)
[h264_qsv @ 000001c1d33d95c0] Error initializing an MFX session
[h264_qsv @ 000001c1d33d95c0] Error initializing the MFX video decoder: invalid handle (-6)
[h264_qsv @ 000001c1d33d95c0] Error initializing an internal MFX session: unsupported (-3)3、设置正确多媒体解码器示例执行ffplay -codec:v h264 fengjing.mp4命令 , 尝试使用 h264 解码器 解码视频 , 视频播放成功 ;
没晒干的咸鱼
【FFmpeg】FFmpeg 相关术语简介
一、FFmpeg 简介FFmpeg 是 " Fast Forward mpeg " 的缩写 , 其符合 mpeg 视频编码标准 ;FFmpeg 功能很强大 , 可以对音视频进行 格式转换 , 内容修改 , 等几乎所有涉及音视频的操作 ;爱奇艺 , 优酷 , YouTube 等公司的音视频产品 , 几乎都是基于 FFmpeg 进行的二次开发 ;二、FFmpeg 相关术语1、容器容器 Container : 容器的本质就是文件 , 是特定的视频文件 , 如 mp4 , mkv , flv 等格式的音视频文件 ;容器的作用 : 容器中可以存放 音频 , 视频 , 字幕流 等信息 , 将这些信息整合在一起 , 按照特定规则放置在容器文件中 ,使用 MediaInfo 打开一个 mp4 格式的视频文件 , 在 " 容器格式和一般信息 " 一栏中 , 可以看到该 mp4 容器文件中包含了 1 11 个 AVC 视频流 , 1 11 个 AAC LC 音频流 ;MediaInfo 工具在 http://mediaarea.net/en/MediaInfo 地址下载 , 或本博客的博客资源中下载 ;2、媒体流媒体流 ( Stream ) : 时间上的一段连续数据 , 一段声音数据 称为 音频流 , 一段视频数据 称为 视频流 , 一段字幕数据 称为 字幕流 ;这些媒体流数据 可以压缩 , 也可以不压缩 , 如视频流以 H.264 格式进行压缩 , 将视频帧编码成 关键帧 , 非关键帧 , 音频流一般是 AAC 编码格式进行压缩 ;媒体流如果是压缩的 , 在播放时 , 先使用解码器解码 , 然后再播放 ; 生成文件时需要使用编码器 , 编码后存储到文件中 ;3、数据帧数据帧 ( Data Frame ) : 媒体流 由 若干 数据帧构成 ; 压缩格式中 , 数据帧是最小的处理单元 ;在容器中如果有多个数据流 , 那么 视频帧 , 音频帧 , 字幕信息 , 交错存储 , 以保证实时性 ;数据帧是未压缩的原始数据 , 如 : 视频帧每一帧都是一张完整的 YUV 图片 , 音频帧是 PCM 格式的 ;4、数据包数据包 ( Data Packet ) : 将 数据帧 压缩后就是 数据包 , 数据帧是未压缩的原始数据 , 数据包时压缩后的数据 ;生成容器文件时 , 压缩数据 , 将数据帧 编码压缩 成 数据包 ;播放容器文件时 , 解压数据 , 将数据包 解码展开 成 数据帧 ;视频编码过程 : YUV 格式的图像 -> H.264 编码器编码 -> H.264 视频帧视频解码过程 : H.264 视频帧 -> H.264 解码器解码 -> YUV 格式的图像音频数据编码过程 : PCM 音频数据 -> ACC 编码器编码 -> AAC 音频帧音频数据解码过程 : AAC 音频帧 -> AAC 解码器解码 -> PCM 音频数据5、编解码器编解码器 ( Codec ) : 数据帧 ( 原始数据 ) 与 数据包 ( 压缩数据 ) 之间的转换工具 ;数据帧 ( 原始数据 ) -> 编解码器 ( 编码 ) -> 数据包 ( 压缩数据 )数据包 ( 压缩数据 ) -> 编解码器 ( 解码 ) -> 数据帧 ( 原始数据 )6、复用复用 ( Mux ) : 将不同的 媒体流流 , 按照一定规则放入容器 ;音频流 , 视频流 , 字幕流 ,按照一定规则封装到 容器 ( 视频文件 ) 中 ;复用的关键工具时 复用器 ( Muxer ) ;7、解复用解复用 ( Demux ) : 从容器中解析不同的流出来 ;从 容器 ( 视频文件 ) 中 ,按照一定规则拆分出 音频流 , 视频流 , 字幕流 ,解复用的关键工具时 解复用器 ( Demuxer ) ;
没晒干的咸鱼
【FFmpeg】ffplay 命令行参数 ⑤
一、ffplay 命令行参数 - 音频滤镜1、设置音频滤镜 -af 参数ffplay 命令的 -af 参数用于 设置 音频滤镜 ( Audio Filter ) , 用于 对 音频流 应用 各种 处理 和 转换 效果 ;多个 音频滤镜 可以组合在一起 , 形成一个 " 音频滤镜链 " , 音频滤镜 之间 使用 逗号 隔开 , 并按照指定的顺序 将 转换效果 应用于 正在播放的 音频 ;" 音频滤镜链 " 是一个 描述 音频滤镜 及其 参数 的字符串 , 可以通过 该参数 来 设置 音效 , 调整音量 , 改变音频 采样率 , 进行 音频 重采样 ;设置 " 音频滤镜链 " 会 降低 音频播放性能 , 尤其是 正在 处理高质量或高采样率的音频时 ;使用 复杂的 " 音频滤镜链 " 时 , 建议关闭不必要的程序和功能 , 以确保流畅的播放体验 ;单个 音频滤镜 示例 : 执行ffplay -af "volume=0.5" fengjing.mp4命令 , 将音量设置为 50% 音量 , 执行效果如下 :2、常用的 音频滤镜 参数ffplay 的 -af 参数 可以 设置 一个或多个 音频滤镜 , 这些 滤镜 可以改变音频的 音量 / 采样率 / 声道数 等效果 , 下面是 一些 常用的 -af 参数选项 :volume=volume : 设置 音频音量 , volume 是一个 乘数 , 可以设置一个 小数 或 整数 ,volume=0.5 就是将音量降低一半 ,volume=2 是 将音量 提高为原来的 2 倍 ;atempo=tempo : 设置 音频播放速度 , 参数值是一个浮点数 , tempo 参数值 > 1 时 音频播放速度加快 , 小于 1 时音频播放速度减慢 ;atempo=0.5 设置 0.5 倍速度播放 ;atempo=2.0 设置 2 倍速度播放 ;aresample=resampler_options : 设置音频重采样 ; 该 音频滤镜 可以用来改变音频的 采样率 / 格式 / 声道布局 ;aresample=44100 可以将 音频的采样率 从 原始值 改变为 44100 Hz ;aformat=sample_fmts : 强制转换音频样本格式 , 如 : 修改 位深度 和 编码方式 ;aformat=sample_fmts=s16 将 播放的音频 转为 16 位 有符号整数 编码 ;ffplay 的 -af 参数主要用于实时应用音频效果 , 如调整音量 / 改变播放速度等 ;在 播放前 转换音频格式 , 建议使用 ffmpeg 命令 , 先转码 , 再使用 ffplay 播放 ;achannelmap=channel_layout : 重新映射音频声道 ;bass=gain : 调整低音增益 ;treble=gain : 调整高音增益 ;3、音频滤镜链 示例多个 音频滤镜 示例 : 执行ffplay -af "volume=0.25,atempo=2.0" fengjing.mp4命令 , 将音量设置为 0.25 倍 , 播放速度设置为 2 倍 , 执行效果如下 :二、ffplay 命令行参数 - 统计信息1、设置统计信息 -stats 参数ffplay 命令的 -stats 参数 用于 在 命令行 中 打印 统计信息 , 这些统计信息 包括显示流的持续时间编解码器参数流中的当前位置音频 / 视频同步差值 ;该 参数 选项 在默认情况下 是 启用状态 , 在 默认的 视频播放 过程中 可以看到这些统计信息 ;执行ffplay fengjing.mp4命令 , 下图中 红色矩形框 中的内容 , 就是 播放时的 统计信息 ;统计信息内容如下 :Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'fengjing.mp4': 0B f=0/0
Metadata:
major_brand : isom
minor_version : 512
compatible_brands: mp41
creation_time : 2024-02-09T06:29:29.000000Z
encoder : Bandicam 4.5.0.1587 / GDI / Nvidia NVENC
encoder-eng : Bandicam 4.5.0.1587 / GDI / Nvidia NVENC
Duration: 00:01:01.78, start: 0.000000, bitrate: 1783 kb/s
Stream #0:0(eng): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 752x420 [SAR 1:1 DAR 188:105], 1580 kb/s, 28.61 fps, 30 tbr, 30k tbn, 60 tbc (default)
Metadata:
creation_time : 2024-02-09T06:29:29.000000Z
handler_name : VideoHandler
vendor_id : [0][0][0][0]
Stream #0:1(eng): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 195 kb/s (default)
Metadata:
creation_time : 2024-02-09T06:29:29.000000Z
handler_name : SoundHandler
vendor_id : [0][0][0][0]
37.74 A-V: -0.030 fd= 67 aq= 30KB vq= 108KB sq= 0B f=0/0部分内容解析 :Duration: 00:01:01.78, start: 0.000000, bitrate: 1783 kb/s : 是 码流长度 1 分钟零 1 秒 , 开始时间 0 , 比特率是 1783 kb/s ;37.74 A-V: -0.030 : 当前播放到了 37.74 秒 , 音视频 差值 -0.030 秒 ;creation_time : 2024-02-09T06:29:29.000000Z : 表示当前音频的创建时间是 2024 年 2 月 9 号 ;2、关闭统计信息 -nostats 参数ffplay 命令的 -nostats 参数 用于 关闭 统计信息 , 使用该参数后 , 不再显示 如下信息 :显示流的持续时间编解码器参数流中的当前位置音频 / 视频同步差值 ;执行ffplay -nostats fengjing.mp4命令 , 可以关闭 统计信息 ;在下图中 , 可以看到 下半部分 都是空白的 , 没有打印出 播放时 的 统计信息 ;三、ffplay 命令行参数 - 同步时钟类型1、设置同步时钟类型 -sync 参数ffplay 命令的 -sync 参数 用于 设置 同步时钟类型 , 可以指定音频流时钟视频流时钟外部时钟三种 时钟 选项 , 同步时钟类型 又称为 " 主时钟 " , 这是 ffplay 播放器 用于同步 音频流 和 视频流 的时钟 ;执行ffplay -sync audio fengjing.mp4命令 , 将 音频流时钟 设置为 主时钟 ;2、同步时钟类型参数选项列举ffplay 命令 -sync 参数值 选项 :audio : 将 音频流时钟 设置为 主时钟 , 该设置 是 默认设置 , ffplay 将 根据 音频流的播放速度 来 调整视频流 的播放速度 , 以确保 音频 和 视频 之间的同步 ;video : 将 视频流时钟 设置为 主时钟 , ffplay 将 根据 视频流的播放速度 来调整 音频流的播放速度 ;ext : 使用 外部时钟 ; 使用 外部设备 或 信号作为 主时钟 , 视频流的播放速度 和 音频流的播放速度 与 其他设备或信号 的 时钟 进行 同步 ;执行ffplay -sync video fengjing.mp4
命令 , 将 视频流时钟 设置为 主时钟 ;执行ffplay -sync ext fengjing.mp4命令 , 将 外部电脑的时钟 设置为 主时钟 ;
没晒干的咸鱼
【FFmpeg】Windows 搭建 FFmpeg 命令行运行环境
前言Android 中需要使用到 FFMPEG , 先在 Windows 中搭建一个 FFMPEG 命令行环境 , 用于进行验证 , 测试 , 学习 ;一、下载 FFMPEG进入 FFMPEG 官网下载界面 http://www.ffmpeg.org/download.html ;选择 Windows 平台的 " Windows builds by BtbN " 下载选项 , 然后会跳转到 GitHub 的 Release 发布版本界面 https://github.com/BtbN/FFmpeg-Builds/releases ;上传到 CSDN 一份 , 放置 GitHub 可能无法访问 https://download.csdn.net/download/han1202012/19523705在 GitHub 界面下载 最近的一个稳定版本 4.4 4.44.4 的文件 , ffmpeg-n4.4-19-g8d172d9409-win64-gpl-shared-4.4.zip , 如下图所示 ;下载 ffmpeg-n4.4-19-g8d172d9409-win64-gpl-shared-4.4.zip 文件后 , 解压该文件 ;上传到 CSDN 一份 , 放置 GitHub 可能无法访问 https://download.csdn.net/download/han1202012/19523705二、拷贝可执行文件bin 目录下是 dll 动态库 , 以及 可执行文件 ;将 3 33 个可执行文件拷贝到 " C:\Windows " 目录下 ,三、拷贝动态库文件将所有的 " .dll " 动态库拷贝到 " C:\Windows\System32 " 目录下 ;吐槽下 , Windows 真会玩 , 64 6464 位的动态库拷贝到 " C:\Windows\System32 " 目录下 , 32 3232 位的动态库拷贝到 " C:\Windows\SysWOW64 " 目录下 ;四、运行 ffmpeg 命令查看 ffmpeg 版本号 :ffmpeg -version执行结果 :C:\Users\octop>ffmpeg -version
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
总结ffmpeg 命令运行环境搭建完毕 , 开始学习 ffmpeg 指令 ;
没晒干的咸鱼
【FFmpeg】ffplay 播放视频命令
一、使用 ffplay 播放视频的基本命令使用 ffplay 播放视频的基本命令 :ffplay 视频路径 播放 " D:\ffmpeg\yuanshen.mp4 " 视频 , 进入 " D:\ffmpeg\ " 目录 , 执行如下命令 :ffplay yuanshen.mp4命令行输出 :D:\ffmpeg>ffplay yuanshen.mp4
ffplay version n4.4-19-g8d172d9409 Copyright (c) 2003-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'yuanshen.mp4': 0B f=0/0
Metadata:
major_brand : isom
minor_version : 512
compatible_brands: isomiso2avc1mp41
encoder : Lavf58.29.100
Duration: 00:06:13.10, start: 0.000000, bitrate: 2623 kb/s
Stream #0:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p(tv, bt709), 1920x1080 [SAR 1:1 DAR 16:9], 2489 kb/s, 25 fps, 25 tbr, 25k tbn, 50 tbc (default)
Metadata:
handler_name : VideoHandler
vendor_id : [0][0][0][0]
Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 128 kb/s (default)
Metadata:
handler_name : SoundHandler
vendor_id : [0][0][0][0]
13.74 A-V: 0.009 fd= 4 aq= 22KB vq= 354KB sq= 0B f=0/0
D:\ffmpeg>执行过程 :二、ffplay 播放过程中的控制命令播放控制 :逐帧播放 : S ;向后 / 向前拖动 10 秒 : Left / Right 箭头按钮 ;向后 / 向前拖动 1 分钟 : Down / Up 箭头按钮 ;暂停播放 : P , 空格 ; 按下 P 或 空格键 , 可以暂停播放 ;停止播放 : Q , Esc ; 开始播放后 , 按下 Q 或 Esc 按键 , 可以退出播放 ;全屏切换 : F 按键可以切换全屏 ; 鼠标左键双击 也可以进行全屏切换 ;音量控制 :静音 : M 键可切换 静音 / 非静音 状态 ;减少音量 : 9 或 / 按键 , 减少音量 ;增加音量 : 0 或 * 按键 , 增加音量 ;循环切换 : 针对有多个音频流以及视频流 , 如电视节目 TS 流 , 多个电视台信号在一个流中 , 可以通过切换 音频流 / 视频流 / 节目 等选择不同的电视台信号进行观看 ;循环切换音频流 : A ; ( Audio )循环切换视频流 : V ; ( Vedio )循环切换字幕流 : T ;循环切换节目 : C ;循环切换过滤器或显示模式 : W ;三、测试 TS 流循环切换 音频流/视频流/字幕流/节目TS 流文件 cctv.ts , 其包含的流信息如下 , 该文件中有 7 77 个视频流 , 7 77 个音频流 ;使用ffplay cctv.ts 命令播放包含多个视频流 / 音频流 ;如果声音太大可以使用 -volume 选项控制声音 :ffplay -volume 3 cctv.ts 播放开始后 , 按下 A 可以切换音频流 , 按下 V 可以切换视频流 , 按下 T 可以切换字幕流 ,按下 C 可以切换完整的节目 , 即同时切换 音频流 , 视频流 , 字幕流 ;
没晒干的咸鱼
【FFmpeg】ffplay 命令行参数 ①
一、ffplay 命令行参数 - 设置播放分辨率1、强制设置通用播放分辨率 -x -y 参数使用 ffplay 播放一个 分辨率 很大的 视频 , 需要 设置 " 强制显示 分辨率 " ;如 : 播放 4K 视频 , 你的电脑显示器屏幕只有 2K , 这种情况下 默认 只能在显示器中 只能 全屏 观看 视频内容 ; 如果想要 在窗口中 观看 完整的 视频画面 , 只能手动 强制 指定一个 视频播放分辨率 ;ffplay 命令 设置 播放分辨率 :-x width 设置 显示 宽度 ;-y height 设置 显示 高度 ;2、命令行示例 - 正常播放视频现有一个视频 yuanshen.mp4 , 视频的 帧 宽高 为 1920 x 1080 像素 ;当前屏幕的像素就是 1920 x 1080 像素 ,执行ffplay yuanshen.mp4命令 , 会全屏播放 视频 , 充满整个屏幕 ;3、命令行示例 - 强制设置播放分辨率执行ffplay -x 800 -y 600 yuanshen.mp4命令 , 设置 播放像素为 800 x 600 像素 , 此时会在 800 x 600 的窗口中播放视频 ;4、设置 YUV 播放分辨率 -video_size 和 像素设置 -pixel_format如果是 没有包含 视频帧 大小 的 yuv 格式的视频 , 可以使用-video_size WxH命令行参数 , 设置 显示 的 视频帧 尺寸 ;使用-pixel_format yuv420p命令行参数 , 设置显示的 yuv 像素格式 ,执行ffplay -pixel_format yuv420p -video_size 320x240 -framerate 5 yuv420p_320x240.yuv命令 , 设置 播放像素为 320x240 像素 , 此时会在 320x240 的窗口中播放视频 ;使用 ffplay 播放 yuv 视频 , 需要设置很多参数 , 包括 : 像素格式 , 视频大小 , 帧率 等 ;如果以错误的分辨率播放 , 如 使用 800x600 分辨率播放 上述 320x240 大小的 yuv 视频 ,执行ffplay -pixel_format yuv420p -video_size 800x600 -framerate 5 yuv420p_320x240.yuv命令 , 执行结果如下 :5、全屏播放 -fs 参数默认情况下 , 播放一个 848x480 大小的视频 , 执行ffplay zhongtu.mp4命令 , 只能在窗口中播放该视频 ;使用 ffplay 命令的 -fs 参数 , 可以全屏播放该视频 ;执行ffplay -fs zhongtu.mp4命令 , 在默认命令基础上 , 添加 -fs 参数 , 可全屏播放该 视频 ;二、ffplay 命令行参数 - 禁用 音频 / 视频 / 字幕 选项1、禁用 音频 / 视频 / 字幕 选项禁用 音频 / 视频 / 字幕 选项 :-an 禁用音频 , 使用该参数 , 播放时 只 播放 视频帧 画面 , 不再播放 音频声音 ;-vn 禁用视频 , 使用该参数 , 播放时 只 播放 音频声音 , 不再播放 视频帧 画面 ;-sn 禁用字幕 , 如果 视频中有字幕信息 , 或使用了外部字幕 , 则 在播放视频时 , 不显示字幕信息 ;2、命令行示例 - 禁用 音频 选项执行ffplay -an zhongtu.mp4命令 , 该命令使用了 -an 禁用音频选项 , 播放视频时 , 只播放画面 , 不播放音频 ;3、命令行示例 - 禁用 视频 选项执行ffplay -vn zhongtu.mp4命令 , 该命令使用了 -vn 禁用音频选项 , 播放视频时 , 只播放音频 , 不播放画面 ;播放时 , 会显示一个窗口 , 在窗口中显示 音频 的 频谱 信息 ;播放画面如下 :
没晒干的咸鱼
【FFmpeg】ffmpeg 命令查询二
一、显示可用的比特流过滤器帮助文档对应内容 :-bsfs show available bit stream filters // 显示可用的比特流 filters 过滤器 显示可用的比特流过滤器命令 :ffmpeg -bsfs执行过程 :命令行输出 :D:\ffmpeg>ffmpeg -bsfs
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
Bitstream filters:
aac_adtstoasc
av1_frame_merge
av1_frame_split
av1_metadata
chomp
dump_extra
dca_core
eac3_core
extract_extradata
filter_units
h264_metadata
h264_mp4toannexb
h264_redundant_pps
hapqa_extract
hevc_metadata
hevc_mp4toannexb
imxdump
mjpeg2jpeg
mjpegadump
mp3decomp
mpeg2_metadata
mpeg4_unpack_bframes
mov2textsub
noise
null
opus_metadata
pcm_rechunk
prores_metadata
remove_extra
setts
text2movsub
trace_headers
truehd_core
vp9_metadata
vp9_raw_reorder
vp9_superframe
vp9_superframe_split
D:\ffmpeg>二、显示可用协议帮助文档对应内容 :-protocols show available protocols // 显示可用协议 , 如 rtmp , rtsp 等 显示可用协议命令 :ffmpeg -protocols执行过程 : 常见的协议如 ftp , http , rtmp 等 ; 注意该协议分 输入 ( Input ) 和 输出 ( Output ) 两类协议 , 输入协议 和 输出协议 可能不同时支持 , 如 async 协议支持输入 , 不支持输出 ; 大部分 如 http 同时支持输入与输出 ;命令行输出 :D:\ffmpeg>ffmpeg -protocols
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
Supported file protocols:
Input:
async
bluray
cache
concat
crypto
data
ffrtmpcrypt
ffrtmphttp
file
ftp
gopher
gophers
hls
http
httpproxy
https
mmsh
mmst
pipe
rtmp
rtmpe
rtmps
rtmpt
rtmpte
rtmpts
rtp
srtp
subfile
tcp
tls
udp
udplite
srt
Output:
crypto
ffrtmpcrypt
ffrtmphttp
file
ftp
gopher
gophers
http
httpproxy
https
icecast
md5
pipe
prompeg
rtmp
rtmpe
rtmps
rtmpt
rtmpte
rtmpts
rtp
srtp
tee
tcp
tls
udp
udplite
srt
D:\ffmpeg>三、显示可用过滤器帮助文档对应内容 :-filters show available filters // 显示可用的过滤器 , 可用于 : 改变播放速度 , 加水印 , 加 Logo 显示可用过滤器命令 : 过滤器 可用于 : 改变播放速度 , 加水印 , 加 Logo ;ffmpeg -filters执行过程 : 过滤器有很多 , 只贴出第一页 ;命令行输出 :D:\ffmpeg>ffmpeg -filters
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
Filters:
T.. = Timeline support
.S. = Slice threading
..C = Command support
A = Audio input/output
V = Video input/output
N = Dynamic number and/or type of input/output
| = Source or sink filter
... abench A->A Benchmark part of a filtergraph.
..C acompressor A->A Audio compressor.
... acontrast A->A Simple audio dynamic range compression/expansion filter.
... acopy A->A Copy the input audio unchanged to the output.
... acue A->A Delay filtering to match a cue.
... acrossfade AA->A Cross fade two input audio streams.
.S. acrossover A->N Split audio into per-bands streams.
..C acrusher A->A Reduce audio bit resolution.
TS. adeclick A->A Remove impulsive noise from input audio.
TS. adeclip A->A Remove clipping from input audio.
T.. adelay A->A Delay one or more audio channels.
TSC adenorm A->A Remedy denormals by adding extremely low-level noise.
... aderivative A->A Compute derivative of input audio.
... aecho A->A Add echoing to the audio.
TSC aemphasis A->A Audio emphasis.
T.. aeval A->A Filter audio signal according to a specified expression.
T.C aexciter A->A Enhance high frequency part of audio.
T.C afade A->A Fade in/out input audio.
TSC afftdn A->A Denoise audio samples using FFT.
... afftfilt A->A Apply arbitrary expressions to samples in frequency domain.
.SC afir N->N Apply Finite Impulse Response filter with supplied coefficients in additional stream(s).
... aformat A->A Convert the input audio to one of the specified formats.
TSC afreqshift A->A Apply frequency shifting to input audio.
T.C agate A->A Audio gate.
.S. aiir A->N Apply Infinite Impulse Response filter with supplied coefficients.
... aintegral A->A Compute integral of input audio.
... ainterleave N->A Temporally interleave audio inputs.
... alimiter A->A Audio lookahead limiter.
TSC allpass A->A Apply a two-pole all-pass filter.
... aloop A->A Loop audio samples.
... amerge N->A Merge two or more audio streams into a single multi-channel stream.
T.. ametadata A->A Manipulate audio frame metadata.
..C amix N->A Audio mixing.
... amultiply AA->A Multiply two audio streams.
TSC anequalizer A->N Apply high-order audio parametric multi band equalizer.
TSC anlmdn A->A Reduce broadband noise from stream using Non-Local Means.
.SC anlms AA->A Apply Normalized Least-Mean-Squares algorithm to first audio stream.四、显示可用像素格式帮助文档对应内容 :-pix_fmts show available pixel formats // 显示可用的像素格式显示可用像素格式命令 :ffmpeg -pix_fmts执行过程 : 像素格式有很多 , 只贴出第一页 ;命令行输出 :D:\ffmpeg>ffmpeg -pix_fmts
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
Pixel formats:
I.... = Supported Input format for conversion
.O... = Supported Output format for conversion
..H.. = Hardware accelerated format
...P. = Paletted format
....B = Bitstream format
FLAGS NAME NB_COMPONENTS BITS_PER_PIXEL
-----
IO... yuv420p 3 12
IO... yuyv422 3 16
IO... rgb24 3 24
IO... bgr24 3 24
IO... yuv422p 3 16
IO... yuv444p 3 24
IO... yuv410p 3 9
IO... yuv411p 3 12
IO... gray 1 8
IO..B monow 1 1
IO..B monob 1 1
I..P. pal8 1 8
IO... yuvj420p 3 12
IO... yuvj422p 3 16
IO... yuvj444p 3 24
IO... uyvy422 3 16
..... uyyvyy411 3 12
IO... bgr8 3 8
.O..B bgr4 3 4
IO... bgr4_byte 3 4
IO... rgb8 3 8
.O..B rgb4 3 4
IO... rgb4_byte 3 4像素格式属性 :Pixel formats:
I.... = Supported Input format for conversion
.O... = Supported Output format for conversion
..H.. = Hardware accelerated format
...P. = Paletted format
....B = Bitstream formatyuv420p 分辨率格式 :NB_COMPONENTS = 3 表示该分辨率格式有 3 33 个成分 , 分别是 Y 分量 , U 分量 , V 分量 ;BITS_PER_PIXEL = 12 表示每个像素点平均下来有多少比特构成 , 12 1212 比特是 1.5 1.51.5 字节 ;FLAGS NAME NB_COMPONENTS BITS_PER_PIXEL
-----
IO... yuv420p 3 12rgb24 分辨率格式 :NB_COMPONENTS = 3 表示该分辨率格式有 3 33 个成分 , 分别是 R 分量 , G 分量 , B 分量 ;BITS_PER_PIXEL = 24 表示每个像素点平均下来有多少比特构成 , 24 2424 比特是 3 33 字节 ;FLAGS NAME NB_COMPONENTS BITS_PER_PIXEL
-----
IO... rgb24 3 24gray 分辨率格式 : 灰度模式只有 1 11 个灰度值 ;NB_COMPONENTS = 1 表示该分辨率格式有 1 11 个成分 , 是灰度分量 , 取值范围 0 00 ~ 255 255255 ;BITS_PER_PIXEL = 8 表示每个像素点平均下来有多少比特构成 , 8 88 比特是 1 11 字节 ;FLAGS NAME NB_COMPONENTS BITS_PER_PIXEL
-----
IO... gray 1 8五、显示标准声道布局帮助文档对应内容 :-layouts show standard channel layouts // 显示标准声道布局显示标准声道布局命令 :ffmpeg -layouts执行过程 :命令行输出 :D:\ffmpeg>ffmpeg -layouts
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
Individual channels:
NAME DESCRIPTION
FL front left
FR front right
FC front center
LFE low frequency
BL back left
BR back right
FLC front left-of-center
FRC front right-of-center
BC back center
SL side left
SR side right
TC top center
TFL top front left
TFC top front center
TFR top front right
TBL top back left
TBC top back center
TBR top back right
DL downmix left
DR downmix right
WL wide left
WR wide right
SDL surround direct left
SDR surround direct right
LFE2 low frequency 2
TSL top side left
TSR top side right
BFC bottom front center
BFL bottom front left
BFR bottom front right
Standard channel layouts:
NAME DECOMPOSITION
mono FC
stereo FL+FR
2.1 FL+FR+LFE
3.0 FL+FR+FC
3.0(back) FL+FR+BC
4.0 FL+FR+FC+BC
quad FL+FR+BL+BR
quad(side) FL+FR+SL+SR
3.1 FL+FR+FC+LFE
5.0 FL+FR+FC+BL+BR
5.0(side) FL+FR+FC+SL+SR
4.1 FL+FR+FC+LFE+BC
5.1 FL+FR+FC+LFE+BL+BR
5.1(side) FL+FR+FC+LFE+SL+SR
6.0 FL+FR+FC+BC+SL+SR
6.0(front) FL+FR+FLC+FRC+SL+SR
hexagonal FL+FR+FC+BL+BR+BC
6.1 FL+FR+FC+LFE+BC+SL+SR
6.1(back) FL+FR+FC+LFE+BL+BR+BC
6.1(front) FL+FR+LFE+FLC+FRC+SL+SR
7.0 FL+FR+FC+BL+BR+SL+SR
7.0(front) FL+FR+FC+FLC+FRC+SL+SR
7.1 FL+FR+FC+LFE+BL+BR+SL+SR
7.1(wide) FL+FR+FC+LFE+BL+BR+FLC+FRC
7.1(wide-side) FL+FR+FC+LFE+FLC+FRC+SL+SR
octagonal FL+FR+FC+BL+BR+BC+SL+SR
hexadecagonal FL+FR+FC+BL+BR+BC+SL+SR+TFL+TFC+TFR+TBL+TBC+TBR+WL+WR
downmix DL+DR
22.2 FL+FR+FC+LFE+BL+BR+FLC+FRC+BC+SL+SR+TC+TFL+TFC+TFR+TBL+TBC+TBR+LFE2+TSL+TSR+BFC+BFL+BFR
D:\ffmpeg>前置左声道 :FL front left前置右声道 :FR front right前置中间声道 :FC front center低音炮 :LFE low frequency立体声 = 前置左声道 + 前置右声道stereo FL+FR单声道 = 前置中间声道mono FC六、显示可用的音频采样格式帮助文档对应内容 :-sample_fmts show available audio sample formats // 显示可用的音频采样格式 显示可用的音频采样格式命令 :ffmpeg -sample_fmts执行过程 :命令行输出 :D:\ffmpeg>ffmpeg -sample_fmts
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
name depth
u8 8
s16 16
s32 32
flt 32
dbl 64
u8p 8
s16p 16
s32p 32
fltp 32
dblp 64
s64 64
s64p 64
D:\ffmpeg>每个音频采样为 16 位 ; 注意 s16 与 s16p 是不同的 ;s16 16
s16p 16七、显示可用的颜色名称帮助文档对应内容 :-colors show available color names // 显示可用的颜色名称 显示可用的颜色名称命令 :ffmpeg -colors执行过程 :命令行输出 :D:\ffmpeg>ffmpeg -colors
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
name #RRGGBB
AliceBlue #f0f8ff
AntiqueWhite #faebd7
Aqua #00ffff
Aquamarine #7fffd4
Azure #f0ffff
Beige #f5f5dc
Bisque #ffe4c4
Black #000000
BlanchedAlmond #ffebcd
Blue #0000ff
BlueViolet #8a2be2
Brown #a52a2a
BurlyWood #deb887
CadetBlue #5f9ea0
Chartreuse #7fff00
Chocolate #d2691e
Coral #ff7f50
CornflowerBlue #6495ed
Cornsilk #fff8dc
Crimson #dc143c
Cyan #00ffff
DarkBlue #00008b
DarkCyan #008b8b
DarkGoldenRod #b8860b
DarkGray #a9a9a9
DarkGreen #006400
DarkKhaki #bdb76b
DarkMagenta #8b008b
DarkOliveGreen #556b2f
Darkorange #ff8c00
DarkOrchid #9932cc
DarkRed #8b0000
DarkSalmon #e9967a
DarkSeaGreen #8fbc8f
DarkSlateBlue #483d8b
DarkSlateGray #2f4f4f
DarkTurquoise #00ced1
DarkViolet #9400d3
DeepPink #ff1493
DeepSkyBlue #00bfff
DimGray #696969
DodgerBlue #1e90ff
FireBrick #b22222
FloralWhite #fffaf0
ForestGreen #228b22
Fuchsia #ff00ff
Gainsboro #dcdcdc
GhostWhite #f8f8ff
Gold #ffd700
GoldenRod #daa520
Gray #808080
Green #008000
GreenYellow #adff2f
HoneyDew #f0fff0
HotPink #ff69b4
IndianRed #cd5c5c
Indigo #4b0082
Ivory #fffff0
Khaki #f0e68c
Lavender #e6e6fa
LavenderBlush #fff0f5
LawnGreen #7cfc00
LemonChiffon #fffacd
LightBlue #add8e6
LightCoral #f08080
LightCyan #e0ffff
LightGoldenRodYellow #fafad2
LightGreen #90ee90
LightGrey #d3d3d3
LightPink #ffb6c1
LightSalmon #ffa07a
LightSeaGreen #20b2aa
LightSkyBlue #87cefa
LightSlateGray #778899
LightSteelBlue #b0c4de
LightYellow #ffffe0
Lime #00ff00
LimeGreen #32cd32
Linen #faf0e6
Magenta #ff00ff
Maroon #800000
MediumAquaMarine #66cdaa
MediumBlue #0000cd
MediumOrchid #ba55d3
MediumPurple #9370d8
MediumSeaGreen #3cb371
MediumSlateBlue #7b68ee
MediumSpringGreen #00fa9a
MediumTurquoise #48d1cc
MediumVioletRed #c71585
MidnightBlue #191970
MintCream #f5fffa
MistyRose #ffe4e1
Moccasin #ffe4b5
NavajoWhite #ffdead
Navy #000080
OldLace #fdf5e6
Olive #808000
OliveDrab #6b8e23
Orange #ffa500
OrangeRed #ff4500
Orchid #da70d6
PaleGoldenRod #eee8aa
PaleGreen #98fb98
PaleTurquoise #afeeee
PaleVioletRed #d87093
PapayaWhip #ffefd5
PeachPuff #ffdab9
Peru #cd853f
Pink #ffc0cb
Plum #dda0dd
PowderBlue #b0e0e6
Purple #800080
Red #ff0000
RosyBrown #bc8f8f
RoyalBlue #4169e1
SaddleBrown #8b4513
Salmon #fa8072
SandyBrown #f4a460
SeaGreen #2e8b57
SeaShell #fff5ee
Sienna #a0522d
Silver #c0c0c0
SkyBlue #87ceeb
SlateBlue #6a5acd
SlateGray #708090
Snow #fffafa
SpringGreen #00ff7f
SteelBlue #4682b4
Tan #d2b48c
Teal #008080
Thistle #d8bfd8
Tomato #ff6347
Turquoise #40e0d0
Violet #ee82ee
Wheat #f5deb3
White #ffffff
WhiteSmoke #f5f5f5
Yellow #ffff00
YellowGreen #9acd32
D:\ffmpeg>前者是别名 , 后面是 RGB 颜色值 , 这 3 33 个分量 , 每个分量占 1 11 字节 , 橙色 的颜色值为 # f f a 500 \rm \#ffa500#ffa500 ;Orange #ffa500
没晒干的咸鱼
【FFmpeg】ffmpeg 命令行参数 ①
一、Windows 搭建 FFmpeg 命令行运行环境在 【FFmpeg】Windows 搭建 FFmpeg 命令行运行环境 博客中 , 搭建 FFmpeg 命令行 运行环境 , 就可以在 任意 目录位置 , 执行 ffmpeg 命令 ,ffmpeg 是一个非常强大的 " 多媒体处理工具 " , 它可以进行 音频 和 视频 的 转码 / 编辑 / 流处理 等操作 ;命令行输出内容 :C:\Users\octop>ffmpeg
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
Hyper fast Audio and Video encoder
usage: ffmpeg [options] [[infile options] -i infile]... {[outfile options] outfile}...
Use -h to get full help or, even better, run 'man ffmpeg'
C:\Users\octop>二、ffpeg 命令 -i 参数 指定 输入文件 / 输入流1、-i 参数 说明ffmpeg 命令 的 -i 参数 的作用是 指定 输入文件 或 输入流 , 后面通常紧跟着 输入文件 / 输入流 的 路径 和 名称 ;如果有一个名为 input.mp4 的视频文件 , 使用 ffmpeg 对其进行处理 , 那么需要 在命令中使用 -i 参数来指定这个文件 :ffmpeg -i input.mp4 ...上述命令的 的 ... 可以使用 其他参数来指定 输出文件 / 编解码器 / 过滤器 等 ;下面 就是 指定一个 avi 格式 的 输出文件 , 将 mp4 格式的 输入文件 input.mp4 转为 avi 格式的输出文件 output.avi ;2、-i 参数 使用示例执行ffmpeg -i input.mp4 output.avi命令 , 即可将 mp4 格式的文件 , 转为 avi 格式的文件 ;执行ffplay output.avi命令 , 使用 ffplay 播放 avi 格式的文件 ;三、ffpeg 命令 -f 参数 指定 输出格式一般情况下 , ffmpeg 的 -f 参数很少用 , 一般是根据 文件名后缀 自动判定文件格式 ;1、-f 参数 说明ffpeg 命令的 -f 参数 用于 指定 输入或输出的格式 , 即 应该如何 解释输入数据 , 或者应该如何 封装输出数据 ;当指定输入文件时 , ffmpeg 能够根据 " 文件扩展名 " 自动判断视频文件格式 , 如果文件名没有 文件扩展名 , 或者 文件格式 与 文件扩展名 不匹配 , 此时就需要使用 -f 参数来手动指定格式 ;下面的命令 就是 将文件转为 avi 格式的文件 , 根据 " output.avi " 文件名称 后面的 " .avi " 扩展名 自动 匹配 文件类型 ;ffmpeg -i input.mp4 output.avi2、-f 参数值列举ffmpeg 命令的 -f 参数用于 指定 输入或输出 的格式 , 下面列举了一些常用的 -f 参数值 :-f mp4 : 表示 输入或输出 的 文件格式是 mp4 格式 ;-f avi : 表示 输入或输出 的文件格式是 avi 格式 ;-f flv : 表示 输入或输出 的文件格式是 flv 格式 ;-f mov : 表示 输入或输出 的文件格式是 mov 格式 ;-f mkv : 表示 输入或输出 的文件格式是 mkv 格式 ;-f wav : 表示 输入或输出 的文件格式是 wav 格式 ;-f rawvideo : 表示 原始视频 数据流格式 , 通常用于一些专业的音视频处理 ;-f null : 特殊的格式 , 用于不产生任何输出文件 , 通常用于测试或性能分析 ;-f image2 : 处理图像序列 , 将 视频帧 保存为一系列的 图片或将图片序列编码成视频 ;-f image2pipe : 用于通过管道传输图像数据的格式 , 通过标准输入/输出 ( stdin/stdout ) 或其他管道机制将图像数据传递给 FFmpeg 或从 FFmpeg 接收图像数据 ;-f mpegts : 表示 MPEG 传输流格式,常用于流媒体传输3、-f 参数使用示例执行ffmpeg -i input.mp4 -f flv output.flv命令 , 即可将 mp4 格式的文件 , 转为 flv 格式的文件 ;执行ffplay output.flv命令 , 播放 转换后的 flv 视频文件 ;输入文件的 信息 : 视频是 AVC 格式的 , 音频是 AAC 格式的 ;输出文件 信息 : 输出文件时 Flash Video 格式的 ;四、ffpeg 命令 指定 时间 相关参数1、设置输入文件起始时间点 -ss 参数ffmpeg 命令 中 使用 -ss position 参数 , 可以 设置 指定 输入文件 的起始时间点 , 可以从 视频 或 音频文件 的指定时间点开始进行处理 , 如 : 裁剪 / 转换格式 等 ;上述参数 中的 position 参数值 的 格式可以是 秒 为单位的时间 , 如 : 10 表示 从 第 10 秒开始播放 ;可以是 时间标记 , 如 : 00:00:15 表示 从第 15 秒开始播放 ;执行ffmpeg -i input.mp4 -ss 00:00:30 output.mp4命令 , 可以将 视频文件 从 第 30 秒处开始裁剪 到 结尾位置 ,转换前的视频信息 :转换后的视频信息 :2、设置输出文件的视频长度 -t 参数ffmpeg 命令 中 使用 -t duration 参数 , 可以 设置 输出 文件的 视频长度 , duration 指的是播放时间 , 单位是 秒 ;从 输入文件 中 裁剪出特定长度的音频或视频片段时 , 可以使用 -t 参数 , -t 参数后面跟的时间值可以是秒 ( 如 : 5 表示 5 秒 ) 或者 更详细的时间格式 ( 如 : 00:00:05 表示 5 秒 ) ;duration 播放时间 参数值 :可以是 秒持续 为单位的时间 , 如 : 5 表示 播放 5 秒钟 ;可以是 时间标记 , 如 : 00:00:05 表示 播放 5 秒钟 ;如果 要 将 输入文件 特定开始点 起的 10 秒视频 进行处理 ,使用 -ss 设置 输入文件的起始时间使用 -t 参数 设置 播放持续时间注意 : -t 参数指定的时间长度是从 -ss 参数指定的开始时间点计算的 ; 如果没有指定 -ss 参数 , 那么 -t 参数将从视频的开头开始计算播放长度 ;执行ffmpeg -i input.mp4 -ss 00:00:30 -t 10 output.mp4命令 , 将 输入文件 input.mp4 的 第 30 秒开始的 10 秒视频 , 输出到 output.mp4 文件中 ;输入文件信息 :输出文件信息 :
没晒干的咸鱼
【FFmpeg】ffplay 命令行参数 ④
一、ffplay 命令行参数 - 修改窗口标题1、修改窗口标题 -window_title 参数ffplay 命令的 -window_title 参数 用于设置 播放视频窗口 的 标题 , 在 同时 打开多个 播放器 窗口时 , 可用于识别 不同的 窗口 ;执行ffplay -x 800 -y 600 -window_title 测试标题 yuanshen.mp4命令 , 可以将标题改为 " 测试标题 " ;执行ffplay -x 800 -y 600 yuanshen.mp4命令 , 可以看到默认的 播放窗口的 默认名称是 视频文件 的名称 " yuanshen " ;二、ffplay 命令行参数 - 设置播放次数1、设置播放次数 -loop 参数ffplay 命令的 -loop 参数用于 设置视频的循环播放次数 ,参数值 : 该参数接受一个 整数 作为输入 , 指定 视频 的 循环播放 次数 ;无限循环 : 设置 0 参数值 , 视频 无限循环 播放 ;示例 : 视频 循环播放 3 次 命令如下 ;ffplay -loop 3 input.mp4执行ffplay -x 800 -y 600 -loop 3 yuanshen.mp4命令 , 将 yuanshen.mp4 视频 循环播放 3 次 ;2、设置 播放 指定视频片段 循环播放次数如果 想在视频的 特定时间点 开始循环播放 , 可以结合使用 -ss 开始时间戳配置参数 和 -t 持续时间配置参数 使用 ;下面的命令 将从 视频的 10 秒处开始 , 播放 5 秒的视频片段 , 并将这个片段循环播放 3 次 ;ffplay -ss 00:00:10 -t 5 -loop 3 input.mp4执行ffplay -x 800 -y 600 -ss 00:00:10 -t 5 -loop 3 yuanshen.mp4命令 , 将 yuanshen.mp4 视频 的 10 秒 ~ 15 秒 循环播放 3 次 ;三、ffplay 命令行参数 - 设置显示模式1、设置显示模式 -showmode 参数ffplay 命令的 -showmode 参数 用于 设置 播放视频 的 显示模式 ; 该参数 设置 几个 固定 的值 , 每个值对应一种特定的显示模式 :-showmode 0 参数值 : 显示视频 ; 默认 的 模式 , 如果不指定 -showmode 参数 , ffplay 将以该方式播放视频 ;-showmode 1 参数值 : 显示音频波形 , 也就是 音频的 时域信号 ; ; 视频窗口 显示当前播放音频的波形图 ;-showmode 2 参数值 : 显示音频带宽 , 也就是音频的 频域信号 , 又称为 " 频谱 " , 通过 实时离散傅里叶变换 将 时域信号 转为 频域信号 ; 该 模式下 , 视频窗口将显示音频的频谱分析 , 这对于音频分析和可视化非常有用 ;2、显示视频执行ffplay -showmode 0 zhongtu.mp4命令 , 显示模式 为 默认的模式 , 显示视频 ; 效果如下图所示 :3、显示波形执行ffplay -showmode 1 zhongtu.mp4命令 , 显示模式 为 显示音频波形 , 这是显示 音频的 时域信息 , 显示的是 声音震动的振幅 ; 效果如下图所示 :3、显示频谱执行ffplay -showmode 2 zhongtu.mp4命令 , 显示模式 为 显示音频频谱 , 这是显示 音频的 频域信息 , 显示的是 声音震动的频率 ; 效果如下图所示 :四、ffplay 命令行参数 - 设置视频滤镜1、设置视频滤镜 -vf 参数ffplay 命令的 -vf 参数 用于 设置 视频滤镜 , 使用 视频滤镜 可以实现 一系列的 视频处理 和 转换效果 , 如 : 画面旋转 , 翻转 , 裁剪 , 缩放 , 色彩调整 等效果 ;视频滤镜 Video Filter , 可以同时设置一个或多个滤镜 , 多个滤镜之间使用逗号隔开 , 因此又称为 " 视频滤镜链 " ;2、常见的视频滤镜参数ffplay 的 -vf 参数 可以 设置视频滤镜 , 实现 画面旋转 , 翻转 , 裁剪 , 缩放 , 色彩调整 等效果 , 下面是常用的滤镜选项 :transpose=direction 滤镜 : 用于旋转视频 ; direction 参数取值如下 :scale=width:height 滤镜 : 调整视频的尺寸 ; 如 scale=640:480 会将视频 分辨率设置为 640x480 的分辨率 ;pad=width:height:x:y:color 滤镜 : 为 视频添加边框 , x 和 y 指定了边框的偏移量 , color 指定了边框的颜色 ;crop=width:height:x:y 滤镜 : 裁剪视频 , x 和 y 指定了裁剪的起始坐标 , width 和 height 指定了裁剪区域的尺寸 ;framestep=number 滤镜 : 快进播放效果 , 每隔 number 帧进行播放 ;setpts=PTS/factor 滤镜 : 改变视频的播放速度 ; factor 大于 1 时视频变慢 , 小于 1 时视频变快 ;3、单个视频滤镜示例执行ffplay -vf "transpose=1" zhongtu.mp4命令 , 可以将 视频 旋转 90 度 ;4、多个视频滤镜示例执行ffplay -vf "transpose=1,scale=640:480" zhongtu.mp4命令 , 可以将 视频 旋转 90 度 , 并将视频窗口设置为 640x480 像素 ;
没晒干的咸鱼
【FFmpeg】使用 FFmpeg 处理音视频格式转换流程
一、视频格式转换1、x264 视频格式转换使用 x264 压缩格式 , 将原始 大小 1920x1040 大小的 mp4 格式的视频转为 960x520 的 flv 格式的视频 ;进入视频所在目录 , 执行如下命令 :ffmpeg -i 1920x1040.mp4 -acodec copy -vcodec libx264 -s 960x520 960x520.flv命令执行过程 :转换前的视频信息 :转换后的视频信息 :2、x265 视频格式转换使用 x265 压缩格式 , 将原始 大小 1920x1040 大小的 mp4 格式的视频转为 960x520 的 mkv 格式的视频 ;进入视频所在目录 , 执行如下命令 :ffmpeg -i 1920x1040.mp4 -acodec copy -vcodec libx265 -s 960x520 960x520.mkv命令执行结果 :转换前的视频信息 :转换后的视频信息 :二、视频格式转换流程分析如下命令的详细流程 :ffmpeg -i 1920x1040.mp4 -acodec copy -vcodec libx264 -s 960x520 960x520.flv将 1920x1040 大小的 mp4 格式的视频文件 , 使用 x264 编解码器 , 转为 960x520 大小的 flv 格式的视频文件 ;蓝色的是 文件 / 中间产物 , 红色的是过程 ;输入文件 : 输入 1920x1040 大小的 mp4 格式文件 , 1920x1040.mp4 ;解复用 : 使用 demuxer 解复用器 , 将输入文件进行解复用操作 , 从容器中分别将 AVC 视频流 , AAC LC 音频流取出 , 得到编码数据包 ;编码数据包 : 该数据包中的音视频数据都是编码后的数据 , 不能直接使用 ; 编码数据包中的视频流数据是 AVC 编码格式的 , 音频流数据是 AAC LC 编码格式的 ;解码 : 使用 decoder 解码器 , 解码 AVC 编码的视频流数据 , AAC LC 编码的音频流数据 , 得到解码后的数据 ;解码后的数据帧 : 音频数据是 PCM 采样 , 视频帧 数据是一张张 YUV 格式的图片 ;帧处理 : 使用 filter 过滤器 处理 解码后的数据帧 , 将其转为 处理后的数据帧 ; 该过程中将视频的分辨率进行了修改 , 分辨率从 1920x1040 转为 960x520 ;如果要修改视频的相关参数 , 如 时间 , 帧率 , 都在该步骤进行操作 , 操作的主体一定是解码后的数据帧 ;处理后的数据帧 : 该数据帧是可以直接用于播放 ; 音频数据是 PCM 采样 , 视频帧 数据是一张张 YUV 格式的图片 ;编码 : 使用 encoder 编码器 , 将处理后的数据帧进行编码 , 音频从 PCM 采样转为 AAC LC 编码格式 , 视频从 YUV 图片编码为 AVC 编码格式 ,编码数据包 : 音频数据是 AAC LC 编码格式 , 视频数据是 AVC 编码格式 ;复用 : 使用 muxer 复用器 , 将编码后的 视频流 和 音频流 封装到 容器中 , 即 flv 格式的视频文件 , 得到输出文件 ;输出文件 : 格式转换完毕的 960x520.flv 视频文件 ;
没晒干的咸鱼
【FFmpeg】ffmpeg 命令查询三
一、查看具体的 ffmpeg 命令分类所支持的参数查看具体的 ffmpeg 命令分类所支持的参数语法如下 :ffmpeg -h 参数类型=参数名称参数类型 指的是下面的参数去掉 s 之后的字符串 , 如 " 显示可用的复用器 " 对应的 参数类型 是 muxer ;-formats show available formats // 显示可用格式 , 其等价于 muxers + demuxers 组合
-muxers show available muxers // 显示可用的复用器
-demuxers show available demuxers // 显示可用的解复用器
-devices show available devices // 显示可用设备
-codecs show available codecs // 显示可用的编解码器 , 其等价于 encoders + decoders 组合
-decoders show available decoders // 显示可用的解码器
-encoders show available encoders // 显示可用的编码器
-bsfs show available bit stream filters // 显示可用的比特流 filters 过滤器
-protocols show available protocols // 显示可用协议 , 如 rtmp , rtsp 等 ;
-filters show available filters // 显示可用的过滤器 , 可用于 : 改变播放速度 , 加水印 , 加 Logo
-pix_fmts show available pixel formats // 显示可用的像素格式
-layouts show standard channel layouts // 显示标准声道名称
-sample_fmts show available audio sample formats // 显示可用的音频采样格式
-colors show available color names // 显示可用的颜色名称
-sources device list sources of the input device // 列出输入设备来源
-sinks device list sinks of the output device // 列出输出设备接收器
-hwaccels show available HW acceleration methods // 显示可用的硬件加速方法 二、查询 " 复用器 " 类型 设置 flv 视频格式时 所支持的参数查询 " 复用器 " 类型 设置 flv 视频格式时 所支持的参数 的 命令 : 如果在命令中使用了 flv 视频 , 其解复用器可以设置的参数类型 ;ffmpeg -h muxer=flv执行过程 : 打印出的 flv 视频格式支持的解复用器 ;命令行输出 :D:\ffmpeg>ffmpeg -h muxer=flv
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
Muxer flv [FLV (Flash Video)]:
Common extensions: flv.
Mime type: video/x-flv.
Default video codec: flv1.
Default audio codec: mp3.
flv muxer AVOptions:
-flvflags <flags> E.......... FLV muxer flags (default 0)
aac_seq_header_detect E.......... Put AAC sequence header based on stream data
no_sequence_end E.......... disable sequence end for FLV
no_metadata E.......... disable metadata for FLV
no_duration_filesize E.......... disable duration and filesize zero value metadata for FLV
add_keyframe_index E.......... Add keyframe index metadata
D:\ffmpeg>三、查询 " 过滤器 " 类型设置 atempo 时所支持的参数查询 " 过滤器 " 类型设置 atempo 时所支持的参数 的 命令 : 如果在命令中使用了 修改视频速率的 过滤器 , 可以设置的参数类型 ;ffmpeg -h filter=atempo执行过程 : 打印出设置 atempo 过滤器时可以设置的参数 ;命令行输出 :D:\ffmpeg>ffmpeg -h filter=atempo
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
Filter atempo
Adjust audio tempo.
Inputs:
#0: default (audio)
Outputs:
#0: default (audio)
atempo AVOptions:
tempo <double> ..F.A....T. set tempo scale factor (from 0.5 to 100) (default 1)
D:\ffmpeg>查询结果 : 可设置 tempo 参数 , 配速取值范围从 0.5 0.50.5 ~ 100 100100 , 默认为 1 11 ;atempo AVOptions:
tempo <double> ..F.A....T. set tempo scale factor (from 0.5 to 100) (default 1)四、查询 " 编码器 " 类型设置 libx264 时所支持的参数查询 " 编码器 " 类型设置 libx264 时所支持的参数 的 命令 : 如果在命令中使用了 libx264 编码器 , 可以设置的参数类型 ;ffmpeg -h encoder=libx264执行过程 : 打印出设置 atempo 过滤器时可以设置的参数 ;命令行输出 :D:\ffmpeg>ffmpeg -h encoder=libx264
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
Encoder libx264 [libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10]:
General capabilities: delay threads
Threading capabilities: other
Supported pixel formats: yuv420p yuvj420p yuv422p yuvj422p yuv444p yuvj444p nv12 nv16 nv21 yuv420p10le yuv422p10le yuv444p10le nv20le gray gray10le
libx264 AVOptions:
-preset <string> E..V....... Set the encoding preset (cf. x264 --fullhelp) (default "medium")
-tune <string> E..V....... Tune the encoding params (cf. x264 --fullhelp)
-profile <string> E..V....... Set profile restrictions (cf. x264 --fullhelp)
-fastfirstpass <boolean> E..V....... Use fast settings when encoding first pass (default true)
-level <string> E..V....... Specify level (as defined by Annex A)
-passlogfile <string> E..V....... Filename for 2 pass stats
-wpredp <string> E..V....... Weighted prediction for P-frames
-a53cc <boolean> E..V....... Use A53 Closed Captions (if available) (default true)
-x264opts <string> E..V....... x264 options
-crf <float> E..V....... Select the quality for constant quality mode (from -1 to FLT_MAX) (default -1)
-crf_max <float> E..V....... In CRF mode, prevents VBV from lowering quality beyond this point. (from -1 to FLT_MAX) (default -1)
-qp <int> E..V....... Constant quantization parameter rate control method (from -1 to INT_MAX) (default -1)
-aq-mode <int> E..V....... AQ method (from -1 to INT_MAX) (default -1)
none 0 E..V.......
variance 1 E..V....... Variance AQ (complexity mask)
autovariance 2 E..V....... Auto-variance AQ
autovariance-biased 3 E..V....... Auto-variance AQ with bias to dark scenes
-aq-strength <float> E..V....... AQ strength. Reduces blocking and blurring in flat and textured areas. (from -1 to FLT_MAX) (default -1)
-psy <boolean> E..V....... Use psychovisual optimizations. (default auto)
-psy-rd <string> E..V....... Strength of psychovisual optimization, in <psy-rd>:<psy-trellis> format.
-rc-lookahead <int> E..V....... Number of frames to look ahead for frametype and ratecontrol (from -1 to INT_MAX) (default -1)
-weightb <boolean> E..V....... Weighted prediction for B-frames. (default auto)
-weightp <int> E..V....... Weighted prediction analysis method. (from -1 to INT_MAX) (default -1)
none 0 E..V.......
simple 1 E..V.......
smart 2 E..V.......
-ssim <boolean> E..V....... Calculate and print SSIM stats. (default auto)
-intra-refresh <boolean> E..V....... Use Periodic Intra Refresh instead of IDR frames. (default auto)
-bluray-compat <boolean> E..V....... Bluray compatibility workarounds. (default auto)
-b-bias <int> E..V....... Influences how often B-frames are used (from INT_MIN to INT_MAX) (default INT_MIN)
-b-pyramid <int> E..V....... Keep some B-frames as references. (from -1 to INT_MAX) (default -1)
none 0 E..V.......
strict 1 E..V....... Strictly hierarchical pyramid
normal 2 E..V....... Non-strict (not Blu-ray compatible)
-mixed-refs <boolean> E..V....... One reference per partition, as opposed to one reference per macroblock (default auto)
-8x8dct <boolean> E..V....... High profile 8x8 transform. (default auto)
-fast-pskip <boolean> E..V....... (default auto)
-aud <boolean> E..V....... Use access unit delimiters. (default auto)
-mbtree <boolean> E..V....... Use macroblock tree ratecontrol. (default auto)
-deblock <string> E..V....... Loop filter parameters, in <alpha:beta> form.
-cplxblur <float> E..V....... Reduce fluctuations in QP (before curve compression) (from -1 to FLT_MAX) (default -1)
-partitions <string> E..V....... A comma-separated list of partitions to consider. Possible values: p8x8, p4x4, b8x8, i8x8, i4x4, none, all
-direct-pred <int> E..V....... Direct MV prediction mode (from -1 to INT_MAX) (default -1)
none 0 E..V.......
spatial 1 E..V.......
temporal 2 E..V.......
auto 3 E..V.......
-slice-max-size <int> E..V....... Limit the size of each slice in bytes (from -1 to INT_MAX) (default -1)
-stats <string> E..V....... Filename for 2 pass stats
-nal-hrd <int> E..V....... Signal HRD information (requires vbv-bufsize; cbr not allowed in .mp4) (from -1 to INT_MAX) (default -1)
none 0 E..V.......
vbr 1 E..V.......
cbr 2 E..V.......
-avcintra-class <int> E..V....... AVC-Intra class 50/100/200 (from -1 to 200) (default -1)
-me_method <int> E..V....... Set motion estimation method (from -1 to 4) (default -1)
dia 0 E..V.......
hex 1 E..V.......
umh 2 E..V.......
esa 3 E..V.......
tesa 4 E..V.......
-motion-est <int> E..V....... Set motion estimation method (from -1 to 4) (default -1)
dia 0 E..V.......
hex 1 E..V.......
umh 2 E..V.......
esa 3 E..V.......
tesa 4 E..V.......
-forced-idr <boolean> E..V....... If forcing keyframes, force them as IDR frames. (default false)
-coder <int> E..V....... Coder type (from -1 to 1) (default default)
default -1 E..V.......
cavlc 0 E..V.......
cabac 1 E..V.......
vlc 0 E..V.......
ac 1 E..V.......
-b_strategy <int> E..V....... Strategy to choose between I/P/B-frames (from -1 to 2) (default -1)
-chromaoffset <int> E..V....... QP difference between chroma and luma (from INT_MIN to INT_MAX) (default 0)
-sc_threshold <int> E..V....... Scene change threshold (from INT_MIN to INT_MAX) (default -1)
-noise_reduction <int> E..V....... Noise reduction (from INT_MIN to INT_MAX) (default -1)
-x264-params <dictionary> E..V....... Override the x264 configuration using a :-separated list of key=value parameters
D:\ffmpeg>五、查询命令设置项以及具体参数想要对一个视频进行编码操作 , 查询编码器 , 如只知道 264 , 不知道具体的编码器名称 , 先使用如下名称 , 查询到具体的编码器名称 ;ffmpeg -encoders | findstr 264查询结果是 V..... libx264 libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (codec h264) , 编码器的名称是 libx264 ;D:\ffmpeg>ffmpeg -encoders | findstr 264
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
V..... libx264 libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (codec h264)
V..... libx264rgb libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 RGB (codec h264)
V....D h264_amf AMD AMF H.264 Encoder (codec h264)
V....D h264_mf H264 via MediaFoundation (codec h264)
V....D h264_nvenc NVIDIA NVENC H.264 encoder (codec h264)
V..... h264_qsv H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (Intel Quick Sync Video acceleration) (codec h264)
V..... nvenc NVIDIA NVENC H.264 encoder (codec h264)
V..... nvenc_h264 NVIDIA NVENC H.264 encoder (codec h264)
D:\ffmpeg>然后查询如果编码器设置为 libx264 都需要设置哪些参数 ;使用ffmpeg -h encoder=libx264命令即可查询 libx264 编码器的详细参数设置 ;
没晒干的咸鱼
【Android FFMPEG 开发】Android 中执行 FFMPEG 指令
一、配置远程 Maven 仓库在 Android Studio 工程 根目录的 build.gradle 构建脚本中 , 配置repositories {
mavenCentral()
}完整代码如下 :// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = "1.5.0"
repositories {
google()
mavenCentral()
}
dependencies {
classpath "com.android.tools.build:gradle:4.2.1"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
mavenCentral()
jcenter() // Warning: this repository is going to shut down soon
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}二、配置依赖在 Module 下的 build.gradle 构建脚本中配置依赖库 :dependencies {
implementation 'com.arthenica:mobile-ffmpeg-full:4.4'
}完整代码如下 :plugins {
id 'com.android.application'
id 'kotlin-android'
}
android {
compileSdkVersion 31
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "kim.hsl.mobileffmpegdemo"
minSdkVersion 24
targetSdkVersion 31
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
implementation 'com.arthenica:mobile-ffmpeg-full:4.4'
}三、Kotlin 中执行 FFmpeg 命令在 kotlin 代码中调用 mobile-ffmpeg 框架中提供的 执行 FFmpeg 命令的方法 :执行的 FFmpeg 命令为 :ffmpeg -version完整代码如下 :package kim.hsl.mobileffmpegdemo
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.arthenica.mobileffmpeg.Config
import com.arthenica.mobileffmpeg.FFmpeg
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val rc = FFmpeg.execute("-version")
if (rc == Config.RETURN_CODE_SUCCESS) {
Log.i(Config.TAG, "命令执行成功")
} else if (rc == Config.RETURN_CODE_CANCEL) {
Log.i(Config.TAG, "用户取消了命令")
} else {
Log.i(Config.TAG, String.format("命令执行失败, 返回值=%d", rc))
}
Config.printLastCommandOutput(Log.INFO)
}
}四、FFmpeg 命令执行结果查看执行结果如下 : 在 华为 Mate30 中 , 对应 Android 10 系统版本也可以执行 ;ffmpeg version v4.4-dev-416
Copyright (c) 2000-2020 the FFmpeg developers
built with Android (6454773 based on r365631c2) clang version 9.0.8 (https://android.googlesource.com/toolchain/llvm-project 98c855489587874b2a325e7a516b99d838599c6f) (based on LLVM 9.0.8svn)
configuration: --cross-prefix=aarch64-linux-android- --sysroot=/files/android-sdk/ndk/21.3.6528147/toolchains/llvm/prebuilt/linux-x86_64/sysroot --prefix=/home/taner/Projects/mobile-ffmpeg/prebuilt/android-arm64/ffmpeg --pkg-config=/usr/bin/pkg-config --enable-version3 --arch=aarch64 --cpu=armv8-a --cc=aarch64-linux-android24-clang --cxx=aarch64-linux-android24-clang++ --extra-libs='-L/home/taner/Projects/mobile-ffmpeg/prebuilt/android-arm64/cpu-features/lib -lndk_compat' --target-os=android --enable-neon --enable-asm --enable-inline-asm --enable-cross-compile --enable-pic --enable-jni --enable-optimizations --enable-swscale --enable-shared --enable-v4l2-m2m --disable-outdev=fbdev --disable-indev=fbdev --enable-small --disable-openssl --disable-xmm-clobber-test --disable-debug --enable-lto --disable-neon-clobber-test --disable-programs --disable-postproc --disable-doc --disable-htmlpages --disable-manpages --disable-podpages --disable-txtpages --disable-static --disable-sndio --disable-schannel --disable-securetransport --disable-xlib --disable-cuda --disable-cuvid --disable-nvenc --disable-vaapi --disable-vdpau --disable-videotoolbox --disable-audiotoolbox --disable-appkit --disable-alsa --disable-cuda --disable-cuvid --disable-nvenc --disable-vaapi --disable-vdpau --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-gmp --enable-gnutls --enable-libmp3lame --enable-libass --enable-iconv --enable-libtheora --enable-libvorbis --enable-libvpx --enable-libwebp --enable-libxml2 --enable-libopencore-amrnb --enable-libshine --enable-libspeex --enable-libwavpack --enable-libkvazaar --enable-libilbc --enable-libopus --enable-libsnappy --enable-libsoxr --enable-libaom --enable-libtwolame --disable-sdl2 --enable-libvo-amrwbenc --enable-zlib --enable-mediacodec
libavutil 56. 55.100 / 56. 55.100
libavcodec 58. 96.100 / 58. 96.100
libavformat 58. 48.100 / 58. 48.100
libavdevice 58. 11.101 / 58. 11.101
libavfilter 7. 87.100 / 7. 87.100
libswscale 5. 8.100 / 5. 8.100
libswresample 3. 8.100 / 3. 8.100五、源码下载源码下载地址 : https://download.csdn.net/download/han1202012/85034217
没晒干的咸鱼
【错误记录】Android 可执行权限报错
一、报错信息在应用中执行二进制可执行程序 , 将二进制文件拷贝到了 data/user/0/cn.example/files/ 目录下 ,2021-11-11 15:23:49.288 15975-16036/cn.example E/FFmpeg: Exception while trying to run: [Ljava.lang.String;@b54f6fa
java.io.IOException: Cannot run program "/data/user/0/cn.example/files/ffmpeg": error=13, Permission denied
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1050)
at java.lang.Runtime.exec(Runtime.java:698)
at java.lang.Runtime.exec(Runtime.java:563)
at com.github.hiteshsondhi88.libffmpeg.ShellCommand.run(ShellCommand.java:10)
at com.github.hiteshsondhi88.libffmpeg.FFmpegExecuteAsyncTask.doInBackground(FFmpegExecuteAsyncTask.java:38)
at com.github.hiteshsondhi88.libffmpeg.FFmpegExecuteAsyncTask.doInBackground(FFmpegExecuteAsyncTask.java:10)
at android.os.AsyncTask$3.call(AsyncTask.java:389)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:292)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:929)
Caused by: java.io.IOException: error=13, Permission denied
at java.lang.UNIXProcess.forkAndExec(Native Method)
at java.lang.UNIXProcess.<init>(UNIXProcess.java:133)
at java.lang.ProcessImpl.start(ProcessImpl.java:141)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
at java.lang.Runtime.exec(Runtime.java:698)
at java.lang.Runtime.exec(Runtime.java:563)
at com.github.hiteshsondhi88.libffmpeg.ShellCommand.run(ShellCommand.java:10)
at com.github.hiteshsondhi88.libffmpeg.FFmpegExecuteAsyncTask.doInBackground(FFmpegExecuteAsyncTask.java:38)
at com.github.hiteshsondhi88.libffmpeg.FFmpegExecuteAsyncTask.doInBackground(FFmpegExecuteAsyncTask.java:10)
at android.os.AsyncTask$3.call(AsyncTask.java:389)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:292)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:929) 二、解决方案开始以为没有可执行权限 , 使用如下代码为 /data/user/0/cn.example/files/ffmpeg 文件赋予执行权限 ;new File(getFilesDir(), "ffmpeg")setExecutable(true);上述代码赋予权限成功 , 仍然报错 ;最终原因是在 Android 10 1010 以上的系统中 , Google 官方禁止应用程序从 /data/user 目录运行二进制文件 ;如果要使用 FFmpeg , 推荐使用 https://github.com/tanersener/mobile-ffmpeg ;
没晒干的咸鱼
【Android FFMPEG 开发】Android 中执行 FFMPEG 指令
一、mobile-ffmpeg 开源项目mobile-ffmpeg 源码主页 : https://github.com/tanersener/mobile-ffmpeg之前使用 FFmpegAndroid 框架 , 地址为 https://github.com/WritingMinds/ffmpeg-android-java , 该框架的原理是在 放置一个编译好的 ffmpeg 可执行文件到 assets 目录中 , 运行时将其拷贝到应用的内置存储空间 , 也就是 " /data/user/0/cn.e/ffmpeg " 路径 ;参考 【Android FFMPEG 开发】Android 中执行 FFMPEG 指令 ( 集成 FFmpegAndroid 框架 ) 博客 ;但是上述框架有个问题 , 就是在 Android 10 系统不再支持可执行程序的运行 , 参考 【错误记录】Android 可执行权限报错 ( Cannot run program “/data/user/0/cn.e/ffmpeg“: error=13,Permission denied ) 博客 , 一旦在应用中执行可执行程序 , 就会报如下错误 ;2021-11-11 15:23:49.288 15975-16036/cn.example E/FFmpeg: Exception while trying to run: [Ljava.lang.String;@b54f6fa
java.io.IOException: Cannot run program "/data/user/0/cn.example/files/ffmpeg": error=13, Permission denied
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1050)这里使用新的 FFmpeg 框架 , mobile-ffmpeg , 该框架执行 FFmpeg 命令的原理是直接集成了函数库 , 使用 jni 调用 ffmpeg.c 中的 main 函数源码 , 没有执行可执行程序 ;可以在 Android 10 及以上的系统中执行 ;不过看该项目主页 https://github.com/tanersener/mobile-ffmpeg 介绍 , 该项目不再维护 , 推荐使用 https://github.com/tanersener/ffmpeg-kit 项目 ;ffmpeg-kit 开源框架支持 Android / iOS / macOS / Flutter / React Native 等平台 , 这个之后再开博客研究 ;二、集成 mobile-ffmpeg 框架在 Android Studio 工程根目录的 build.gradle 构建脚本中 , 配置repositories {
mavenCentral()
}在 Module 下的 build.gradle 脚本中 , 配置dependencies {
implementation 'com.arthenica:mobile-ffmpeg-full:4.4'
}依赖 ;Java 代码 :import com.arthenica.mobileffmpeg.Config;
import com.arthenica.mobileffmpeg.FFmpeg;
int rc = FFmpeg.execute("-version");
if (rc == Config.RETURN_CODE_SUCCESS) {
Log.i(Config.TAG, "命令执行成功");
} else if (rc == Config.RETURN_CODE_CANCEL) {
Log.i(Config.TAG, "用户取消了命令");
} else {
Log.i(Config.TAG, String.format("命令执行失败, 返回值=%d", rc));
}
// 打印命令行输出
Config.printLastCommandOutput(Log.INFO);Kotlin 代码 :import com.arthenica.mobileffmpeg.Config
import com.arthenica.mobileffmpeg.FFmpeg
val rc = FFmpeg.execute("-version")
if (rc == Config.RETURN_CODE_SUCCESS) {
Log.i(Config.TAG, "命令执行成功")
} else if (rc == Config.RETURN_CODE_CANCEL) {
Log.i(Config.TAG, "用户取消了命令")
} else {
Log.i(Config.TAG, String.format("命令执行失败, 返回值=%d", rc))
}
// 打印命令行输出
Config.printLastCommandOutput(Log.INFO)经过测试 , 在 Android 10 的 华为 Mate 30 手机中 , 测试正常 , 可以成功打印出 ffmpeg -version 命令输出结果 ;
没晒干的咸鱼
【FFmpeg】ffplay 命令行参数 ⑦
一、ffplay 命令行参数 - 设置解码器1、设置多媒体解码器 -codec:media_specifier 参数ffplay 命令的 -codec:media_specifier 参数 用于 设置 多媒体解码器 , 通过该参数 可以 为 不同的媒体类型 ( 音频 / 视频 / 字幕 ) 指定解码器 ;上述命令中 , media_specifier 是 特定的 多媒体 解码类型 , 可设置为a: 音频 , -codec:a 用于 设置 音频解码器 ;v : 视频 , -codec:v 用于 设置 视频解码器 ;s : 字幕 , -codec:s 用于 设置 字幕解码器 ;2、设置音频解码器 -acodec 参数ffplay 命令的 -acodec 参数 用于 设置 音频解码器 , 通过该参数 可以 为 音频 指定解码器 ;3、设置视频解码器 -vcodec 参数ffplay 命令的 -vcodec 参数 用于 设置 视频解码器 , 通过该参数 可以 为 视频 指定解码器 ;4、设置字幕解码器 -scodec 参数ffplay 命令的 -scodec 参数 用于 设置 字幕解码器 , 通过该参数 可以 为 字幕 指定解码器 ;二、多媒体解码器参数选项列举1、常用的 音频解码器 选项常用的 音频解码器 :aac :Advanced Audio Coding , 高级音频编码 ,广泛用于 音频编码 和 传输 , 尤其是流媒体 和 网络广播 , 音质比 MP3 更高 , 文件相对较小 ;mp2 :MPEG-1/2 Audio Layer II , MPEG-1/2 音频层 II ,MP2 是 MPEG-1 和 MPEG-2 标准中的 音频编码格式之一 , 是较早的音频压缩格式之一 , 曾经广泛用于数字音频广播和视频文件中 , 现在不是主流编码格式 ;mp3 :MPEG-1/2 Audio Layer III , MPEG-1/2 音频层 III ,MP3 是一种非常流行的音频编码格式 , 该编码 提供 高效的压缩率 和 可接受的音质损失 , 该格式 也是 MPEG-1 和 MPEG-2 标准中的音频编码格式之一 ,该解码器 通常与 libmp3lame 一起进行编解码操作 ;ac3 :Dolby Digital AC-3 , 杜比数字 AC-3 ,AC-3 是由 杜比实验室 开发的一种音频编码格式 , 广泛用于 电影院 / 数字电视 / DVD , 该编码格式 提供了 高质量的音频压缩 , 支持多声道音频 , 如 : 5.1 环绕声 ;vorbis :Ogg Vorbis ,Vorbis 是一种 开放 和 免费 的音频编码格式 , 通常与 Ogg 容器格式一起使用 , 它可以提供比 MP3 更高的音质 , 同时保持较小的文件大小 ;opus :Ogg Opus ,Opus 是一种高效的音频编码格式 , 特别适合用于互联网流媒体和实时通信 , 它提供了出色的音质和非常低的延迟 , 同时保持了较小的文件大小 ;flac :Free Lossless Audio Codec , 免费无损音频编码 ,该音频格式 可以在压缩过程中不损失任何原始音频数据 , 这使得 FLAC 文件比有损压缩格式的文件要大 , 但音质完全等同于原始音频 ,FLAC 广泛用于音频存档和高质量音频播放 ;ffplay 命令 中 使用 -codec:a 配置 音频解码器 , 可以设置上述 音频解码器 , 如 :ffplay -codec:a aac fengjing.mp42、常用的 视频解码器 选项常用的 视频解码器 选项 :h264 :H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 , H.264 编码 , 又称为 高级视频编码 ( AVC , Advanced Video Coding ) , 是 MPEG-4 标准的 第 10 部分 ;最广泛使用的 视频压缩标准 , 压缩效率高 , 视频质量好 , 应用于 高清电视广播 / 视频会议 / 网络流媒体 / 蓝光光盘 ;h264_qsv 是hevc : H.265 / HEVC , 高效视频编码 ( HEVC , High Efficiency Video Coding ) , 比H.264 编码的 压缩效率 更高 , 支持 更高的分辨率 和 更高的帧率 , 文件大小较小 , 被广泛用于 4K 视频编码 和 超高清视频编码 ;vp9 : VP9 是 由 Google 开发的开源视频压缩格式 , 广泛 应用于 Web 视频流 和 在线视频平台 ;mpeg4 :MPEG-4 part 2 , MPEG-4 标准的 第 2 部分 ,该编码标准 , 定义了 MPEG-4 的 视觉对象编码标准 , 包括视频编码和压缩 , 该编码 逐渐被 H.264 和 HEVC 替代 , 不是主流 ;mpeg2video :MPEG-2 video , MPEG-2 视频 ,MPEG-2 视频编码标准 被广泛用于 数字电视广播 / DVD / 视频编辑等领域 ;theora : Theora 视频编码 , Theora 是一种开放和免费的视频编码格式 , 该编码基于 Ogg 容器格式的 , 被广泛用于开源和免费软件社区 ;vp8 : VP8 是 开放 免费 的 编码格式 , 广泛用于WebM多媒体容器格式中 ;ffplay 命令 中 使用 -codec:v 配置 音频解码器 , 可以设置上述 视频解码器 , 如 :ffplay -codec:v h264_qsv fengjing.mp4上面的 h264_qsv 解码器 是 使用 Intel Quick Sync Video 技术的 H.264 解码器 ;3、常用的 字幕解码器 选项常用的 字幕解码器 选项 :srt :SubRip (.srt) , SubRip 字幕格式 , 字幕文件 是 .srt 文件扩展名 ,SRT 是一种简单的纯文本字幕格式 , 用于 电影 / 电视节目 等的字幕显示 ; 它支持基本的字幕样式 , 如时间戳 / 文本内容 / 简单格式设置 ;ass :Advanced SubStation Alpha (.ass) / SSA (.ssa) , 高级 SubStation Alpha 字幕格式 也就是 .ass 文件扩展名 或 SSA .ssa 文件扩展名 的 字幕文件 ;ASS 是一种高级的字幕格式 , 支持更多的字幕样式和特效 , 包括 复杂的布局 / 字体样式 / 颜色 / 阴影 / 边框 等 ;dvbsub :DVB subtitles , Digital Video Broadcasting 数字视频广播 字幕 ;DVBSub 是 数字视频广播 DVB 标准中定义的字幕格式 ; 它通常嵌入在视频流中 , 用于电视节目的字幕显示 , DVBSub 支持多种语言和字幕样式 , 但通常不支持像 ASS 那样复杂的特效 ;hdmv_pgs_subtitle :HDMV Presentation Graphic Stream subtitles , 高清多媒体视频演示图形流字幕 , 常用于 蓝光光盘 ;该字幕格式 , 支持高质量的字幕渲染 , 包括矢量图形 , 图像 和 文本 ;ffplay 命令 中 使用 -codec:s 配置 音频解码器 , 可以设置上述 字幕解码器 , 如 :ffplay -codec:s srt fengjing.mp4
没晒干的咸鱼
【FFmpeg】ffplay 命令行参数 ②
一、ffplay 命令行参数 - 设置播放位置和持续时间1、定位拖动 -ss 参数使用 -ss position 参数 , 可以 设置 跳转到 指定的位置 开始播放 , 指定 输入文件 的起始时间点 , 开始播放 后将跳转到此时间点 , 然后开始 播放视频 ;上述参数 中的 position 参数值 的 格式可以是 秒 为单位的时间 , 如 : 10 表示 从 第 10 秒开始播放 ;可以是 时间标记 , 如 : 00:00:15 表示 从第 15 秒开始播放 ;执行ffplay -ss 00:00:15 zhongtu.mp4命令 , 从 第 0 小时 第 0 分钟 第 15 秒 开始播放 , 从下图中 命令行 的 左下角 可以看到 从 15 秒开始播放 ;执行ffplay -ss 15 zhongtu.mp4命令 , 有相同的效果 ;2、设置播放视频长度 -t 参数使用 -t duration 参数 , 可以 设置 视频 或 音频 播放时间 , duration 指的是播放时间 , 单位是 秒 ;duration 播放时间 参数值 :可以是 秒持续 为单位的时间 , 如 : 5 表示 播放 5 秒钟 ;可以是 时间标记 , 如 : 00:00:05 表示 播放 5 秒钟 ;如果 要 播放从某一 特定开始点 起的10 秒视频 ,使用 -ss 设置 播放起始时间点使用 -t 参数 设置 播放持续时间注意 : -t 参数指定的时间长度是从-ss参数指定的开始时间点计算的。如果没有指定-ss参数,那么-t参数将从视频的开头开始计算播放长度执行ffplay -t 5 zhongtu.mp4命令 , 会播放 5 秒 视频 , 5 秒 播放完成后 , 会 停止播放 ;执行ffplay -t 00:00:05 zhongtu.mp4命令 , 有相同的效果 ;3、命令行示例 - 从指定时间开始播放指定时间的视频执行ffplay -ss 00:00:05 -t 00:00:05 zhongtu.mp4命令 , 可以从 第 5 秒开始 , 播放 5 秒钟的视频 ;二、ffplay 命令行参数 - 按字节定位拖动1、按字节定位拖动 -bytes 参数ffplay 命令的 -bytes 参数 用于 设置 是否启用 按字节 定位拖动 的 功能 ;开启后 , 可以使用 左右箭头 按键 , 控制 按字节 定位拖动 功能 ;默认状态下的参数为 -1 , 自动选择 是否 开启 按字节定位拖动 功能 ;特别注意 : mp4 格式的视频不支持该功能 , flv 格式的视频支持该功能 ;-bytes 参数 的 参数值 : 可以是 0 , 1 或 -1 ;参数值 为 1 时 : 表示 开启 按字节定位拖动 ;参数值 为 0 时 : 表示 关闭 按字节定位拖动 ;参数值 为 -1 时 : 表示 自动选择 是否 开启 按字节定位拖动 ;当 需要 精确地 控制播放位置 时 , 可以通过该参数 , 开启 按字节 定位拖动功能 ;2、命令行示例 - mp4 格式按字节定位拖动失败执行ffplay -bytes 1 zhongtu.mp4命令 , 开始播放视频 , 并同时启动 按字节拖动功能 ;在播放期间 , 选中 视频 , 使用 左右箭头 按键 控制 拖动功能 , 发现 mp4 格式的视频 , 不支持拖动 ;zhongtu.mp4: error while seeking 33KB vq= 39KB sq= 0B f=0/0
zhongtu.mp4: error while seeking 33KB vq= 14KB sq= 0B f=0/03、命令行示例 - flv 格式按字节定位拖动成功执行ffplay -bytes 1 2.flv命令 , 开始播放视频 , 并同时启动 按字节拖动功能 ;播放 flv 格式 视频 文件时 , 开启 按字节定位拖动 功能 , 使用 左右方向键 可以实现 视频的拖动功能 ;4、mp4 与 flv 格式分析mp4 格式的视频不支持该功能 , flv 格式的视频支持该功能 ;这于 视频格式 有很大的关系 ,mp4 容器 格式通常包含复杂的 内部结构 和 元数据 , 视频帧 的 帧头数据 和 帧内容数据 是 分开存储的 , 存储并不连续 , 该 数据结构 会影响字节到时间的映射 , 该格式下 不能 按照 字节 进行 定位拖动 ;flv 容器 格式 更简单 , 该格式中 视频帧 的 帧头 和 数据 是存储在一起的 , 帧数据是连续存储的 , 因此 按照 字节 定位拖动 可实现 ;三、ffplay 命令行参数 - 按时间定位拖动1、 按时间定位拖动 -seek_interval 参数ffplay 命令的 -seek_interval 参数用于 自定义 左右方向键 定位拖动的间隔 , 单位是秒 ; 该参数的 默认值为 10 秒 ,按下 左方向键 向前快退 10 秒 ,按下 右方向键 向后快进 10 秒 ;如 : -seek_interval 2 参数设置 , 就意味着按下左或右键 , 播放位置将 向前或向后 跳动 2 秒 ;该参数对于需要 精确控制 播放位置 的场景特别有用 , 如 : 在编辑或分析视频时 , 通过调整定位间隔 , 可以更快地导航到视频的特定部分 , 而无需每次都手动输入精确的时间码 ;2、 命令行示例 - 按时间定位拖动执行ffplay -x 800 -y 600 -seek_interval 2 yuanshen.mp4
命令 , 播放视频后 , 每次 使用 左右方向键 时 , 都会 前进 / 后退 2 秒 ;
没晒干的咸鱼
【FFmpeg】FFmpeg 帮助文档使用
一、ffmpeg 命令帮助文档查询 ffmpeg 基本信息 :ffmpeg -h 查询 ffmpeg 高级信息 :ffmpeg -h long查询 ffmpeg 所有信息 :ffmpeg -h full 三种帮助信息的关系 : 所有信息 包含 高级信息 , 高级信息 包含 基本信息 ;1、FFmpeg 命令帮助基本信息将 ffmpeg 基本信息输出到文件中 : 将信息输出到文件中 , 使用 > 符号 , 后面跟上文件名称 , 就会将信息输出到该文件名对应的目录中 ;ffmpeg -h > ffmpeg_h.txt在 " D:\ffmpeg " 目录下执行 上述命令 , 在该目录下生成了 ffmpeg_h.txt 文件 ;ffmpeg_h.txt 文件中的输出内容如下 :Hyper fast Audio and Video encoder
usage: ffmpeg [options] [[infile options] -i infile]... {[outfile options] outfile}...
Getting help:
-h -- print basic options
-h long -- print more options
-h full -- print all options (including all format and codec specific options, very long)
-h type=name -- print all options for the named decoder/encoder/demuxer/muxer/filter/bsf/protocol
See man ffmpeg for detailed description of the options.
Print help / information / capabilities:
-L show license
-h topic show help
-? topic show help
-help topic show help
--help topic show help
-version show version
-buildconf show build configuration
-formats show available formats
-muxers show available muxers
-demuxers show available demuxers
-devices show available devices
-codecs show available codecs
-decoders show available decoders
-encoders show available encoders
-bsfs show available bit stream filters
-protocols show available protocols
-filters show available filters
-pix_fmts show available pixel formats
-layouts show standard channel layouts
-sample_fmts show available audio sample formats
-colors show available color names
-sources device list sources of the input device
-sinks device list sinks of the output device
-hwaccels show available HW acceleration methods
Global options (affect whole program instead of just one file):
-loglevel loglevel set logging level
-v loglevel set logging level
-report generate a report
-max_alloc bytes set maximum size of a single allocated block
-y overwrite output files
-n never overwrite output files
-ignore_unknown Ignore unknown stream types
-filter_threads number of non-complex filter threads
-filter_complex_threads number of threads for -filter_complex
-stats print progress report during encoding
-max_error_rate maximum error rate ratio of decoding errors (0.0: no errors, 1.0: 100% errors) above which ffmpeg returns an error instead of success.
-bits_per_raw_sample number set the number of bits per raw sample
-vol volume change audio volume (256=normal)
Per-file main options:
-f fmt force format
-c codec codec name
-codec codec codec name
-pre preset preset name
-map_metadata outfile[,metadata]:infile[,metadata] set metadata information of outfile from infile
-t duration record or transcode "duration" seconds of audio/video
-to time_stop record or transcode stop time
-fs limit_size set the limit file size in bytes
-ss time_off set the start time offset
-sseof time_off set the start time offset relative to EOF
-seek_timestamp enable/disable seeking by timestamp with -ss
-timestamp time set the recording timestamp ('now' to set the current time)
-metadata string=string add metadata
-program title=string:st=number... add program with specified streams
-target type specify target file type ("vcd", "svcd", "dvd", "dv" or "dv50" with optional prefixes "pal-", "ntsc-" or "film-")
-apad audio pad
-frames number set the number of frames to output
-filter filter_graph set stream filtergraph
-filter_script filename read stream filtergraph description from a file
-reinit_filter reinit filtergraph on input parameter changes
-discard discard
-disposition disposition
Video options:
-vframes number set the number of video frames to output
-r rate set frame rate (Hz value, fraction or abbreviation)
-fpsmax rate set max frame rate (Hz value, fraction or abbreviation)
-s size set frame size (WxH or abbreviation)
-aspect aspect set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)
-bits_per_raw_sample number set the number of bits per raw sample
-vn disable video
-vcodec codec force video codec ('copy' to copy stream)
-timecode hh:mm:ss[:;.]ff set initial TimeCode value.
-pass n select the pass number (1 to 3)
-vf filter_graph set video filters
-ab bitrate audio bitrate (please use -b:a)
-b bitrate video bitrate (please use -b:v)
-dn disable data
Audio options:
-aframes number set the number of audio frames to output
-aq quality set audio quality (codec-specific)
-ar rate set audio sampling rate (in Hz)
-ac channels set number of audio channels
-an disable audio
-acodec codec force audio codec ('copy' to copy stream)
-vol volume change audio volume (256=normal)
-af filter_graph set audio filters
Subtitle options:
-s size set frame size (WxH or abbreviation)
-sn disable subtitle
-scodec codec force subtitle codec ('copy' to copy stream)
-stag fourcc/tag force subtitle tag/fourcc
-fix_sub_duration fix subtitles duration
-canvas_size size set canvas size (WxH or abbreviation)
-spre preset set the subtitle options to the indicated preset2、FFmpeg 命令帮助高级信息将 FFmpeg 高级帮助信息导出到 ffmpeg_h_long.txt 文件中 ;ffmpeg -h long > ffmpeg_h_long.txt输出内容展示 :Hyper fast Audio and Video encoder
usage: ffmpeg [options] [[infile options] -i infile]... {[outfile options] outfile}...
Getting help:
-h -- print basic options
-h long -- print more options
-h full -- print all options (including all format and codec specific options, very long)
-h type=name -- print all options for the named decoder/encoder/demuxer/muxer/filter/bsf/protocol
See man ffmpeg for detailed description of the options.
Print help / information / capabilities:
-L show license
-h topic show help
-? topic show help
-help topic show help
--help topic show help
-version show version
-buildconf show build configuration
-formats show available formats
-muxers show available muxers
-demuxers show available demuxers
-devices show available devices
-codecs show available codecs
-decoders show available decoders
-encoders show available encoders
-bsfs show available bit stream filters
-protocols show available protocols
-filters show available filters
-pix_fmts show available pixel formats
-layouts show standard channel layouts
-sample_fmts show available audio sample formats
-colors show available color names
-sources device list sources of the input device
-sinks device list sinks of the output device
-hwaccels show available HW acceleration methods
Global options (affect whole program instead of just one file):
-loglevel loglevel set logging level
-v loglevel set logging level
-report generate a report
-max_alloc bytes set maximum size of a single allocated block
-y overwrite output files
-n never overwrite output files
-ignore_unknown Ignore unknown stream types
-filter_threads number of non-complex filter threads
-filter_complex_threads number of threads for -filter_complex
-stats print progress report during encoding
-max_error_rate maximum error rate ratio of decoding errors (0.0: no errors, 1.0: 100% errors) above which ffmpeg returns an error instead of success.
-bits_per_raw_sample number set the number of bits per raw sample
-vol volume change audio volume (256=normal)
Advanced global options:
-cpuflags flags force specific cpu flags
-hide_banner hide_banner do not show program banner
-copy_unknown Copy unknown stream types
-benchmark add timings for benchmarking
-benchmark_all add timings for each task
-progress url write program-readable progress information
-stdin enable or disable interaction on standard input
-timelimit limit set max runtime in seconds in CPU user time
-dump dump each input packet
-hex when dumping packets, also dump the payload
-vsync video sync method
-frame_drop_threshold frame drop threshold
-async audio sync method
-adrift_threshold threshold audio drift threshold
-copyts copy timestamps
-start_at_zero shift input timestamps to start at 0 when using copyts
-copytb mode copy input stream time base when stream copying
-dts_delta_threshold threshold timestamp discontinuity delta threshold
-dts_error_threshold threshold timestamp error delta threshold
-xerror error exit on error
-abort_on flags abort on the specified condition flags
-filter_complex graph_description create a complex filtergraph
-lavfi graph_description create a complex filtergraph
-filter_complex_script filename read complex filtergraph description from a file
-auto_conversion_filters enable automatic conversion filters globally
-stats_period time set the period at which ffmpeg updates stats and -progress output
-debug_ts print timestamp debugging info
-intra deprecated use -g 1
-sameq Removed
-same_quant Removed
-deinterlace this option is deprecated, use the yadif filter instead
-psnr calculate PSNR of compressed frames
-vstats dump video coding statistics to file
-vstats_file file dump video coding statistics to file
-vstats_version Version of the vstats format to use.
-qphist show QP histogram
-vc channel deprecated, use -channel
-tvstd standard deprecated, use -standard
-isync this option is deprecated and does nothing
-sdp_file file specify a file in which to print sdp information
-qsv_device device set QSV hardware device (DirectX adapter index, DRM path or X11 display name)
-init_hw_device args initialise hardware device
-filter_hw_device device set hardware device used when filtering
Per-file main options:
-f fmt force format
-c codec codec name
-codec codec codec name
-pre preset preset name
-map_metadata outfile[,metadata]:infile[,metadata] set metadata information of outfile from infile
-t duration record or transcode "duration" seconds of audio/video
-to time_stop record or transcode stop time
-fs limit_size set the limit file size in bytes
-ss time_off set the start time offset
-sseof time_off set the start time offset relative to EOF
-seek_timestamp enable/disable seeking by timestamp with -ss
-timestamp time set the recording timestamp ('now' to set the current time)
-metadata string=string add metadata
-program title=string:st=number... add program with specified streams
-target type specify target file type ("vcd", "svcd", "dvd", "dv" or "dv50" with optional prefixes "pal-", "ntsc-" or "film-")
-apad audio pad
-frames number set the number of frames to output
-filter filter_graph set stream filtergraph
-filter_script filename read stream filtergraph description from a file
-reinit_filter reinit filtergraph on input parameter changes
-discard discard
-disposition disposition
Advanced per-file options:
-map [-]input_file_id[:stream_specifier][,sync_file_id[:stream_specifier]] set input stream mapping
-map_channel file.stream.channel[:syncfile.syncstream] map an audio channel from one stream to another
-map_chapters input_file_index set chapters mapping
-accurate_seek enable/disable accurate seeking with -ss
-itsoffset time_off set the input ts offset
-itsscale scale set the input ts scale
-dframes number set the number of data frames to output
-re read input at native frame rate
-shortest finish encoding within shortest input
-bitexact bitexact mode
-copyinkf copy initial non-keyframes
-copypriorss copy or discard frames before start time
-tag fourcc/tag force codec tag/fourcc
-q q use fixed quality scale (VBR)
-qscale q use fixed quality scale (VBR)
-profile profile set profile
-attach filename add an attachment to the output file
-dump_attachment filename extract an attachment into a file
-stream_loop loop count set number of times input stream shall be looped
-thread_queue_size set the maximum number of queued packets from the demuxer
-find_stream_info read and decode the streams to fill missing information with heuristics
-autorotate automatically insert correct rotate filters
-autoscale automatically insert a scale filter at the end of the filter graph
-muxdelay seconds set the maximum demux-decode delay
-muxpreload seconds set the initial demux-decode delay
-time_base ratio set the desired time base hint for output stream (1:24, 1:48000 or 0.04166, 2.0833e-5)
-enc_time_base ratio set the desired time base for the encoder (1:24, 1:48000 or 0.04166, 2.0833e-5). two special values are defined - 0 = use frame rate (video) or sample rate (audio),-1 = match source time base
-bsf bitstream_filters A comma-separated list of bitstream filters
-fpre filename set options from indicated preset file
-max_muxing_queue_size packets maximum number of packets that can be buffered while waiting for all streams to initialize
-muxing_queue_data_threshold bytes set the threshold after which max_muxing_queue_size is taken into account
-dcodec codec force data codec ('copy' to copy stream)
Video options:
-vframes number set the number of video frames to output
-r rate set frame rate (Hz value, fraction or abbreviation)
-fpsmax rate set max frame rate (Hz value, fraction or abbreviation)
-s size set frame size (WxH or abbreviation)
-aspect aspect set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)
-bits_per_raw_sample number set the number of bits per raw sample
-vn disable video
-vcodec codec force video codec ('copy' to copy stream)
-timecode hh:mm:ss[:;.]ff set initial TimeCode value.
-pass n select the pass number (1 to 3)
-vf filter_graph set video filters
-ab bitrate audio bitrate (please use -b:a)
-b bitrate video bitrate (please use -b:v)
-dn disable data
Advanced Video options:
-pix_fmt format set pixel format
-intra deprecated use -g 1
-rc_override override rate control override for specific intervals
-sameq Removed
-same_quant Removed
-passlogfile prefix select two pass log file name prefix
-deinterlace this option is deprecated, use the yadif filter instead
-psnr calculate PSNR of compressed frames
-vstats dump video coding statistics to file
-vstats_file file dump video coding statistics to file
-vstats_version Version of the vstats format to use.
-intra_matrix matrix specify intra matrix coeffs
-inter_matrix matrix specify inter matrix coeffs
-chroma_intra_matrix matrix specify intra matrix coeffs
-top top=1/bottom=0/auto=-1 field first
-vtag fourcc/tag force video tag/fourcc
-qphist show QP histogram
-force_fps force the selected framerate, disable the best supported framerate selection
-streamid streamIndex:value set the value of an outfile streamid
-force_key_frames timestamps force key frames at specified timestamps
-hwaccel hwaccel name use HW accelerated decoding
-hwaccel_device devicename select a device for HW acceleration
-hwaccel_output_format format select output format used with HW accelerated decoding
-vc channel deprecated, use -channel
-tvstd standard deprecated, use -standard
-vbsf video bitstream_filters deprecated
-vpre preset set the video options to the indicated preset
Audio options:
-aframes number set the number of audio frames to output
-aq quality set audio quality (codec-specific)
-ar rate set audio sampling rate (in Hz)
-ac channels set number of audio channels
-an disable audio
-acodec codec force audio codec ('copy' to copy stream)
-vol volume change audio volume (256=normal)
-af filter_graph set audio filters
Advanced Audio options:
-atag fourcc/tag force audio tag/fourcc
-sample_fmt format set sample format
-channel_layout layout set channel layout
-guess_layout_max set the maximum number of channels to try to guess the channel layout
-absf audio bitstream_filters deprecated
-apre preset set the audio options to the indicated preset
Subtitle options:
-s size set frame size (WxH or abbreviation)
-sn disable subtitle
-scodec codec force subtitle codec ('copy' to copy stream)
-stag fourcc/tag force subtitle tag/fourcc
-fix_sub_duration fix subtitles duration
-canvas_size size set canvas size (WxH or abbreviation)
-spre preset set the subtitle options to the indicated preset
3、FFmpeg 命令帮助完整信息执行如下命令 , 将完整帮助信息导出到 ffmpeg_h_full.txt 文件中 , 这个帮助文档有 1001 10011001 KB , 放到博客资源中了 ;ffmpeg -h full > ffmpeg_h_full.txt二、ffplay 命令帮助文档使用如下命令 , 查看 ffplay 命令的帮助文档 ;ffplay -h将帮助文档输出到文件中 :ffplay -h > ffplay_h.txt三、ffprobe 命令帮助文档使用如下命令 , 查看 ffprobe 命令的帮助文档 ;ffprobe -h将帮助文档输出到文件中 :ffprobe -h > ffprobe_h.txt四、帮助命令查找技巧ffmpeg , ffplay , ffprobe 命令部分参数是通用的 , 但是有些不通用 ;命令搜索技巧 : 查找 " 264 " 字符串相关的命令 ;ffmpeg -h full | findstr 264
没晒干的咸鱼
【FFmpeg】FFmpeg 相关术语简介 二
一、码率与帧率帧率 : 帧频率 , 视频中每秒钟含有视频帧的帧数 , 一秒钟刷新多少张图像 , 连续移动的图像至少每秒 15 1515 帧 , 才能形成肉眼观察的连续播放效果 , 低于这个帧率 , 画面有卡顿感 ;码率 : 比特率 , 数据率 ; 每秒处理的位数 ;码率的单位是 bps , 表示每秒处理的位数 , 除以 8 88 就是每秒的字节数 ;该参数决定了音视频文件的播放质量 , 码率越大 , 视频质量越高 ;视频文件 中 码率 和 帧率 决定了视频的质量 ;根据 码率 和 时长 可以计算出视频文件的字节大小 ;二、ffmpeg、ffplay、ffprobe 可执行文件之前安装 Windows 中 FFmpeg 运行环境时 , 向 " C:\Windows " 目录下拷贝了 3 33 个可执行程序 , 分别是 ffmpeg , ffplay , ffprobe ;ffmpeg : 音视频编码器 ; 音视频剪辑 , 格式转换 ;ffplay : 媒体播放器 ; 提供 播放音视频文件 , 音视频同步 , 暂停 , 快进 , 快退 , 逐帧播放 等功能 ;ffprobe : 多媒体流分析器 ;
没晒干的咸鱼
【FFmpeg】ffmpeg 命令查询一
一、FFmpeg 帮助信息在 【FFmpeg】FFmpeg 帮助文档使用 博客中使用ffmpeg -h命令 , 可以在命令行输出 ffmpeg 基本命令帮助信息 , 其中打印出了如下几项信息 , 下面介绍下比较重要的几个配置选项 ;Print help / information / capabilities:
-L show license // 显示许可信息
-h topic show help // 显示帮助信息
-? topic show help // 显示帮助信息
-help topic show help // 显示帮助信息
--help topic show help // 显示帮助信息
-version show version // 显示版本
-buildconf show build configuration // 显示编译配置
-formats show available formats // 显示可用格式 , 其等价于 muxers + demuxers 组合
-muxers show available muxers // 显示可用的复用器
-demuxers show available demuxers // 显示可用的解复用器
-devices show available devices // 显示可用设备
-codecs show available codecs // 显示可用的编解码器 , 其等价于 encoders + decoders 组合
-decoders show available decoders // 显示可用的解码器
-encoders show available encoders // 显示可用的编码器
-bsfs show available bit stream filters // 显示可用的比特流 filters 过滤器
-protocols show available protocols // 显示可用协议 , 如 rtmp , rtsp 等 ;
-filters show available filters // 显示可用的过滤器 , 可用于 : 改变播放速度 , 加水印 , 加 Logo
-pix_fmts show available pixel formats // 显示可用的像素格式
-layouts show standard channel layouts // 显示标准声道名称
-sample_fmts show available audio sample formats // 显示可用的音频采样格式
-colors show available color names // 显示可用的颜色名称
-sources device list sources of the input device // 列出输入设备来源
-sinks device list sinks of the output device // 列出输出设备接收器
-hwaccels show available HW acceleration methods // 显示可用的硬件加速方法 二、显示版本信息 -version帮助文档对应内容 :-version show version // 显示版本 显示版本信息命令 :ffmpeg -version执行过程 : 打印出的版本号是 ffmpeg version n4.4-19-g8d172d9409 ;命令行输出 :D:\ffmpeg>ffmpeg -version
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100三、ffmpeg 命令输出的固定信息关于 ffmpeg 不管执行什么命令 , 都会打印出当前的以下信息 :版本号信息 ffmpeg version n4.4-19-g8d172d9409版权信息 Copyright编译器信息 built with gcc 10-win32 (GCC) 20210408编译配置信息 configuration:各个库的版本信息如下libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100四、显示编译配置信息 -buildconf帮助文档对应内容 :-buildconf show build configuration // 显示编译配置显示编译配置信息命令 : FFmpeg 进行编译时 , 先配置 configure 文件 , 然后根据 configure 配置生成 Makefile 文件 , 再执行编译操作 ;ffmpeg -buildconf执行过程 : 打印出的编译时的 configure 配置信息 ;命令行输出 :D:\ffmpeg>ffmpeg -buildconf
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
configuration:
--prefix=/ffbuild/prefix
--pkg-config-flags=--static
--pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32-
--arch=x86_64
--target-os=mingw32
--enable-gpl
--enable-version3
--disable-debug
--enable-shared
--disable-static
--disable-w32threads
--enable-pthreads
--enable-iconv
--enable-libxml2
--enable-zlib
--enable-libfreetype
--enable-libfribidi
--enable-gmp
--enable-lzma
--enable-fontconfig
--enable-libvorbis
--enable-opencl
--enable-libvmaf
--enable-vulkan
--enable-amf
--enable-libaom
--enable-avisynth
--enable-libdav1d
--enable-libdavs2
--enable-ffnvcodec
--enable-cuda-llvm
--enable-libglslang
--enable-libgme
--enable-libass
--enable-libbluray
--enable-libmp3lame
--enable-libopus
--enable-libtheora
--enable-libvpx
--enable-libwebp
--enable-lv2
--enable-libmfx
--enable-libopencore-amrnb
--enable-libopencore-amrwb
--enable-libopenjpeg
--enable-librav1e
--enable-librubberband
--enable-schannel
--enable-sdl2
--enable-libsoxr
--enable-libsrt
--enable-libsvtav1
--enable-libtwolame
--enable-libuavs3d
--enable-libvidstab
--enable-libx264
--enable-libx265
--enable-libxavs2
--enable-libxvid
--enable-libzimg
--extra-cflags=-DLIBTWOLAME_STATIC
--extra-cxxflags=
--extra-ldflags=-pthread
--extra-ldexeflags=
--extra-libs=-lgomp
D:\ffmpeg>上述的 configuration: 后面的一行配置 与 ffmpeg -buildconf 打印出来的内容是一样的 ,各个模块都编译成动态库 , 不支持静态库 ; --enable-shared
--disable-static支持 sdl2 , 这是做播放显示用的 ; --enable-sdl2支持 H.264 , H.265 编码 : --enable-libx264
--enable-libx265五、显示可用格式 -formats1、基础命令帮助文档对应内容 :-formats show available formats // 显示可用格式 , 其等价于 muxers + demuxers 组合 显示可用格式命令 :ffmpeg -formats执行过程 :命令行输出 :D:\ffmpeg>ffmpeg -formats
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
File formats:
D. = Demuxing supported
.E = Muxing supported
--
D 3dostr 3DO STR
E 3g2 3GP2 (3GPP2 file format)
E 3gp 3GP (3GPP file format)
D 4xm 4X Technologies
E a64 a64 - video for Commodore 64
D aa Audible AA format files
D aac raw ADTS AAC (Advanced Audio Coding)
D aax CRI AAX
DE ac3 raw AC-3
D ace tri-Ace Audio Container
D acm Interplay ACM
D act ACT Voice file format
D adf Artworx Data Format
D adp ADP
D ads Sony PS2 ADS
E adts ADTS AAC (Advanced Audio Coding)
DE adx CRI ADX
D aea MD STUDIO audio
D afc AFC
DE aiff Audio IFF
D aix CRI AIX
DE alaw PCM A-law
D alias_pix Alias/Wavefront PIX image
DE alp LEGO Racers ALP
DE amr 3GPP AMR
D amrnb raw AMR-NB
D amrwb raw AMR-WB
E amv AMV
D anm Deluxe Paint Animation
D apc CRYO APC
D ape Monkey's Audio
DE apm Ubisoft Rayman 2 APM
... 打印的内容太多 , 省略部分 ...
D:\ffmpeg>名称中带 D 说明支持解复用 , 名称中带 E 说明支持复用 ; D. = Demuxing supported
.E = Muxing supported只支持解复用的格式 : 前面带 D ;D 3dostr 3DO STR支持复用的格式 : 前面带 E ;E 3g2 3GP2 (3GPP2 file format)支持复用与解复用的格式 : 前面带 DE ;DE ac3 raw AC-32、查询指定格式信息如果要查询 flv 格式相关的 复用 / 解复用 信息 , 使用如下命令 :ffmpeg -formats | findstr flv执行过程 :命令行输出 :D:\ffmpeg>ffmpeg -formats | findstr flv
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
DE flv FLV (Flash Video)
D live_flv live RTMP FLV (Flash Video)
D:\ffmpeg>flv 格式的文件可以支持复用和解复用 ;DE flv FLV (Flash Video)rtmp 协议的 flv 直播流 只支持解复用 , 不支持复用 ;D live_flv live RTMP FLV (Flash Video)六、显示可用复用器 -muxers1、基础命令帮助文档对应内容 :-muxers show available muxers // 显示可用的复用器显示可用复用器命令 :ffmpeg -muxers执行过程 :命令行输出 : 在命令行中输出的都是支持复用器的格式 , 左侧都是 E , 没有 D ;D:\ffmpeg>ffmpeg -muxers
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
File formats:
D. = Demuxing supported
.E = Muxing supported
--
E 3g2 3GP2 (3GPP2 file format)
E 3gp 3GP (3GPP file format)
E a64 a64 - video for Commodore 64
E ac3 raw AC-3
E adts ADTS AAC (Advanced Audio Coding)
E adx CRI ADX
E aiff Audio IFF
E alaw PCM A-law
E alp LEGO Racers ALP
E amr 3GPP AMR
E amv AMV
E apm Ubisoft Rayman 2 APM
E apng Animated Portable Network Graphics
E aptx raw aptX (Audio Processing Technology for Bluetooth)
E aptx_hd raw aptX HD (Audio Processing Technology for Bluetooth)
E argo_asf Argonaut Games ASF
E asf ASF (Advanced / Active Streaming Format)
E asf_stream ASF (Advanced / Active Streaming Format)
E ass SSA (SubStation Alpha) subtitle
E ast AST (Audio Stream)
E au Sun AU
E avi AVI (Audio Video Interleaved)
E avm2 SWF (ShockWave Flash) (AVM2)
E avs2 raw AVS2-P2/IEEE1857.4 video
E bit G.729 BIT file format
E caf Apple CAF (Core Audio Format)
E cavsvideo raw Chinese AVS (Audio Video Standard) video
E codec2 codec2 .c2 muxer
E codec2raw raw codec2 muxer
E crc CRC testing
E dash DASH Muxer
E data raw data
E daud D-Cinema audio
E dirac raw Dirac
E dnxhd raw DNxHD (SMPTE VC-3)
E dts raw DTS2、查询指定格式信息查找 flv 格式相关信息 : 只打印出了 E flv FLV (Flash Video) 选项 ;ffmpeg -muxers | findstr flvD:\ffmpeg>ffmpeg -muxers | findstr flv
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
E flv FLV (Flash Video)
D:\ffmpeg>七、显示可用解复用器 -demuxers1、基础命令帮助文档对应内容 :-demuxers show available demuxers // 显示可用的解复用器显示可用解复用器命令 :ffmpeg -demuxers执行过程 :命令行输出 : 在命令行中输出的都是支持解复用器的格式 , 左侧都是 D , 没有 E ;D:\ffmpeg>ffmpeg -demuxers
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
File formats:
D. = Demuxing supported
.E = Muxing supported
--
D 3dostr 3DO STR
D 4xm 4X Technologies
D aa Audible AA format files
D aac raw ADTS AAC (Advanced Audio Coding)
D aax CRI AAX
D ac3 raw AC-3
D ace tri-Ace Audio Container
D acm Interplay ACM
D act ACT Voice file format
D adf Artworx Data Format
D adp ADP
D ads Sony PS2 ADS
D adx CRI ADX
D aea MD STUDIO audio
D afc AFC
D aiff Audio IFF
D aix CRI AIX
D alaw PCM A-law
D alias_pix Alias/Wavefront PIX image
D alp LEGO Racers ALP
D amr 3GPP AMR
D amrnb raw AMR-NB
D amrwb raw AMR-WB
D anm Deluxe Paint Animation
D apc CRYO APC
D ape Monkey's Audio
D apm Ubisoft Rayman 2 APM
D apng Animated Portable Network Graphics
D aptx raw aptX
D aptx_hd raw aptX HD
D aqtitle AQTitle subtitles
D argo_asf Argonaut Games ASF
D argo_brp Argonaut Games BRP
D asf ASF (Advanced / Active Streaming Format)
D asf_o ASF (Advanced / Active Streaming Format)
D ass SSA (SubStation Alpha) subtitle2、查询指定格式信息查找 flv 格式解复用器 :ffmpeg -demuxers | findstr flvD:\ffmpeg>ffmpeg -demuxers | findstr flv
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
D flv FLV (Flash Video)
D live_flv live RTMP FLV (Flash Video)
D:\ffmpeg>八、显示可用设备 -devices帮助文档对应内容 :-devices show available devices // 显示可用设备显示可用设备命令 :ffmpeg -devices执行过程 :命令行输出 :D:\ffmpeg>ffmpeg -devices
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
Devices:
D. = Demuxing supported
.E = Muxing supported
--
D dshow DirectShow capture
D gdigrab GDI API Windows frame grabber
D lavfi Libavfilter virtual input device
E sdl,sdl2 SDL2 output device
D vfwcap VfW video capture
D:\ffmpeg>输入与输出标志 : D 开头的是输入设备 , 支持解复用 ; E 开头的是输出设备 , 支持复用 ; D. = Demuxing supported
.E = Muxing supported设备介绍 :设备 D dshow DirectShow capture 指的是录制相关 , 摄像头录制 , 麦克风录制等 ;设备 D lavfi Libavfilter virtual input device 是虚拟的输入设备 , 用于测试 ;设备 E sdl,sdl2 SDL2 output device 输出设备 , 播放视频时 , 使用该模块作为输出 ;设备 D vfwcap VfW video capture 摄像头采集设备 ;九、显示可用的编解码器 -codecs1、基本指令帮助文档对应内容 :-codecs show available codecs // 显示可用的编解码器 , 其等价于 encoders + decoders 组合显示可用的编解码器命令 :ffmpeg -codecs执行过程 :命令行输出 :D:\ffmpeg>ffmpeg -codecs
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
Codecs:
D..... = Decoding supported
.E.... = Encoding supported
..V... = Video codec
..A... = Audio codec
..S... = Subtitle codec
...I.. = Intra frame-only codec
....L. = Lossy compression
.....S = Lossless compression
-------
D.VI.S 012v Uncompressed 4:2:2 10-bit
D.V.L. 4xm 4X Movie
D.VI.S 8bps QuickTime 8BPS video
.EVIL. a64_multi Multicolor charset for Commodore 64 (encoders: a64multi )
.EVIL. a64_multi5 Multicolor charset for Commodore 64, extended with 5th color (colram) (encoders: a64multi5 )
D.V..S aasc Autodesk RLE
D.V.L. agm Amuse Graphics Movie
D.VIL. aic Apple Intermediate Codec
DEVI.S alias_pix Alias/Wavefront PIX image
DEVIL. amv AMV Video
D.V.L. anm Deluxe Paint Animation
D.V.L. ansi ASCII/ANSI art
DEV..S apng APNG (Animated Portable Network Graphics) image
D.V.L. arbc Gryphon's Anim Compressor
D.V.L. argo Argonaut Games Video
DEVIL. asv1 ASUS V1
DEVIL. asv2 ASUS V2
D.VIL. aura Auravision AURA
D.VIL. aura2 Auravision Aura 2
DEV.L. av1 Alliance for Open Media AV1 (decoders: libdav1d libaom-av1 av1 av1_cuvid av1_qsv ) (encoders: libaom-av1 librav1e libsvtav1 )
D.V... avrn Avid AVI Codec
DEVI.S avrp Avid 1:1 10-bit RGB Packer
D.V.L. avs AVS (Audio Video Standard) video
DEV.L. avs2 AVS2-P2/IEEE1857.4 (decoders: libdavs2 ) (encoders: libxavs2 )
D.V.L. avs3 AVS3-P2/IEEE1857.10 (decoders: libuavs3d )
DEVI.S avui Avid Meridien Uncompressed
DEVI.S ayuv Uncompressed packed MS 4:4:4:4
D.V.L. bethsoftvid Bethesda VID video
D.V.L. bfi Brute Force & Ignorance
D.V.L. binkvideo Bink video
D.VI.. bintext Binary text
D.VI.S bitpacked Bitpacked
DEVI.S bmp BMP (Windows and OS/2 bitmap)
D.V..S bmv_video Discworld II BMV video
D.VI.S brender_pix BRender PIX image编码器类型说明 : 下面注释中说明了编码器的支持类型 , 编码 / 解码 / 视频 / 音频 / 字幕 / 内部帧 / 有损 / 无损 ;Codecs:
D..... = Decoding supported 支持解码
.E.... = Encoding supported 支持编码
..V... = Video codec 视频编解码器
..A... = Audio codec 音频编解码器
..S... = Subtitle codec 字幕编解码器
...I.. = Intra frame-only codec 内部帧编码器 , 每帧都独立编码 , 不需要参考其它帧 ;
....L. = Lossy compression 有损压缩
.....S = Lossless compression 无损压缩 2、查询 H.264 编解码器信息查询 H.264 编解码器信息 :ffmpeg -codecs | findstr 264执行过程 :命令行输出 :D:\ffmpeg>ffmpeg -codecs | findstr 264
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
DEV.LS h264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (decoders: h264 h264_qsv h264_cuvid ) (encoders: libx264 libx264rgb h264_amf h264_mf h264_nvenc h264_qsv nvenc nvenc_h264 )
D:\ffmpeg>h264 编解码器的属性是 DEV.LSD 表示支持解码E 表示支持编码V 表示视频编码L 表示有损压缩S 表示无损压缩十、显示可用的解码器 -decoders帮助文档对应内容 :-decoders show available decoders // 显示可用的解码器显示可用的解码器命令 :ffmpeg -decoders执行过程 :命令行输出 :D:\ffmpeg>ffmpeg -decoders
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
Decoders:
V..... = Video
A..... = Audio
S..... = Subtitle
.F.... = Frame-level multithreading
..S... = Slice-level multithreading
...X.. = Codec is experimental
....B. = Supports draw_horiz_band
.....D = Supports direct rendering method 1
------
V....D 012v Uncompressed 4:2:2 10-bit
V....D 4xm 4X Movie
V....D 8bps QuickTime 8BPS video
V....D aasc Autodesk RLE
V....D agm Amuse Graphics Movie
VF...D aic Apple Intermediate Codec
V....D alias_pix Alias/Wavefront PIX image
V....D amv AMV Video
V....D anm Deluxe Paint Animation
V....D ansi ASCII/ANSI art
VF...D apng APNG (Animated Portable Network Graphics) image
V....D arbc Gryphon's Anim Compressor
V....D argo Argonaut Games Video
V....D asv1 ASUS V1
V....D asv2 ASUS V2
V....D aura Auravision AURA
V....D aura2 Auravision Aura 2
V..... libdav1d dav1d AV1 decoder by VideoLAN (codec av1)
V....D libaom-av1 libaom AV1 (codec av1)
V....D av1 Alliance for Open Media AV1
V..... av1_cuvid Nvidia CUVID AV1 decoder (codec av1)
V....D av1_qsv AV1 video (Intel Quick Sync Video acceleration) (codec av1)
V....D avrn Avid AVI Codec
V....D avrp Avid 1:1 10-bit RGB Packer
V....D avs AVS (Audio Video Standard) video
V..... libdavs2 libdavs2 AVS2-P2/IEEE1857.4 (codec avs2)
V....D libuavs3d libuavs3d AVS3-P2/IEEE1857.10 (codec avs3)
V....D avui Avid Meridien Uncompressed
V....D ayuv Uncompressed packed MS 4:4:4:4
V....D bethsoftvid Bethesda VID video
V....D bfi Brute Force & Ignorance
V....D binkvideo Bink video
V....D bintext Binary text
V..X.. bitpacked Bitpacked
V....D bmp BMP (Windows and OS/2 bitmap)十一、显示可用的编码器 -encoders帮助文档对应内容 :-encoders show available encoders // 显示可用的编码器显示可用的编码器命令 :ffmpeg -encoders执行过程 :命令行输出 :D:\ffmpeg>ffmpeg -encoders
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
Encoders:
V..... = Video
A..... = Audio
S..... = Subtitle
.F.... = Frame-level multithreading
..S... = Slice-level multithreading
...X.. = Codec is experimental
....B. = Supports draw_horiz_band
.....D = Supports direct rendering method 1
------
V..... a64multi Multicolor charset for Commodore 64 (codec a64_multi)
V..... a64multi5 Multicolor charset for Commodore 64, extended with 5th color (colram) (codec a64_multi5)
V..... alias_pix Alias/Wavefront PIX image
V..... amv AMV Video
V..... apng APNG (Animated Portable Network Graphics) image
V..... asv1 ASUS V1
V..... asv2 ASUS V2
V..... libaom-av1 libaom AV1 (codec av1)
V....D librav1e librav1e AV1 (codec av1)
V..... libsvtav1 SVT-AV1(Scalable Video Technology for AV1) encoder (codec av1)
V..... avrp Avid 1:1 10-bit RGB Packer
V..... libxavs2 libxavs2 AVS2-P2/IEEE1857.4 (codec avs2)
V..X.. avui Avid Meridien Uncompressed
V..... ayuv Uncompressed packed MS 4:4:4:4
V..... bmp BMP (Windows and OS/2 bitmap)
VF.... cfhd GoPro CineForm HD
V..... cinepak Cinepak
V..... cljr Cirrus Logic AccuPak
V.S... vc2 SMPTE VC-2 (codec dirac)
VFS... dnxhd VC3/DNxHD
V..... dpx DPX (Digital Picture Exchange) image
VFS... dvvideo DV (Digital Video)
VF.... exr OpenEXR image
V.S... ffv1 FFmpeg video codec #1
VF.... ffvhuff Huffyuv FFmpeg variant
V..... fits Flexible Image Transport System
V..... flashsv Flash Screen Video
V..... flashsv2 Flash Screen Video Version 2
V..... flv FLV / Sorenson Spark / Sorenson H.263 (Flash Video) (codec flv1)
V..... gif GIF (Graphics Interchange Format)
V..... h261 H.261
V..... h263 H.263 / H.263-1996
V.S... h263p H.263+ / H.263-1998 / H.263 version 2
V..... libx264 libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (codec h264)
V..... libx264rgb libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 RGB (codec h264)十二、命令行分页显示 " | more"如果命令行中输出命令过多 , 可以进行分页显示 , 在命令后面加上 | more 可以进行分页显示 , 长按回车 , 可以显示后面的内容 ;ffmpeg -codecs | more执行过程 : 打印时会自动命令行输出 :D:\ffmpeg>ffmpeg -codecs | more
ffmpeg version n4.4-19-g8d172d9409 Copyright (c) 2000-2021 the FFmpeg developers
built with gcc 10-win32 (GCC) 20210408
configuration: --prefix=/ffbuild/prefix --pkg-config-flags=--static --pkg-config=pkg-config --cross-prefix=x86_64-w64-mingw32- --arch=x86_64 --target-os=mingw32 --enable-gpl --enable-version3 --disable-debug --enable-shared --disable-static --disable-w32threads --enable-pthreads --enable-iconv --enable-libxml2 --enable-zlib --enable-libfreetype --enable-libfribidi --enable-gmp --enable-lzma --enable-fontconfig --enable-libvorbis --enable-opencl --enable-libvmaf --enable-vulkan --enable-amf --enable-libaom --enable-avisynth --enable-libdav1d --enable-libdavs2 --enable-ffnvcodec --enable-cuda-llvm --enable-libglslang --enable-libgme --enable-libass --enable-libbluray --enable-libmp3lame --enable-libopus --enable-libtheora --enable-libvpx --enable-libwebp --enable-lv2 --enable-libmfx --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-librav1e --enable-librubberband --enable-schannel --enable-sdl2 --enable-libsoxr --enable-libsrt --enable-libsvtav1 --enable-libtwolame --enable-libuavs3d --enable-libvidstab --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libzimg --extra-cflags=-DLIBTWOLAME_STATIC --extra-cxxflags= --extra-ldflags=-pthread --extra-ldexeflags= --extra-libs=-lgomp
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
Codecs:
D..... = Decoding supported
.E.... = Encoding supported
..V... = Video codec
..A... = Audio codec
..S... = Subtitle codec
...I.. = Intra frame-only codec
....L. = Lossy compression
.....S = Lossless compression
-------
D.VI.S 012v Uncompressed 4:2:2 10-bit
D.V.L. 4xm 4X Movie
D.VI.S 8bps QuickTime 8BPS video
.EVIL. a64_multi Multicolor charset for Commodore 64 (encoders: a64multi )
.EVIL. a64_multi5 Multicolor charset for Commodore 64, extended with 5th color (colram) (encoders: a64multi5 )
D.V..S aasc Autodesk RLE
D.V.L. agm Amuse Graphics Movie
D.VIL. aic Apple Intermediate Codec
DEVI.S alias_pix Alias/Wavefront PIX image
DEVIL. amv AMV Video
D.V.L. anm Deluxe Paint Animation
D.V.L. ansi ASCII/ANSI art
DEV..S apng APNG (Animated Portable Network Graphics) image
D.V.L. arbc Gryphon's Anim Compressor
D.V.L. argo Argonaut Games Video
DEVIL. asv1 ASUS V1
DEVIL. asv2 ASUS V2
D.VIL. aura Auravision AURA
D.VIL. aura2 Auravision Aura 2
DEV.L. av1 Alliance for Open Media AV1 (decoders: libdav1d libaom-av1 av1 av1_cuvid av1_qsv ) (encoders: libaom-av1 librav1e libsvtav1 )
D.V... avrn Avid AVI Codec
DEVI.S avrp Avid 1:1 10-bit RGB Packer
D.V.L. avs AVS (Audio Video Standard) video
DEV.L. avs2 AVS2-P2/IEEE1857.4 (decoders: libdavs2 ) (encoders: libxavs2 )
D.V.L. avs3 AVS3-P2/IEEE1857.10 (decoders: libuavs3d )
DEVI.S avui Avid Meridien Uncompressed
DEVI.S ayuv Uncompressed packed MS 4:4:4:4
D.V.L. bethsoftvid Bethesda VID video
D.V.L. bfi Brute Force & Ignorance
D.V.L. binkvideo Bink video
D.VI.. bintext Binary text
D.VI.S bitpacked Bitpacked
DEVI.S bmp BMP (Windows and OS/2 bitmap)
D.V..S bmv_video Discworld II BMV video
D.VI.S brender_pix BRender PIX image
D.V.L. c93 Interplay C93
D.V.L. cavs Chinese AVS (Audio Video Standard) (AVS1-P2, JiZhun profile)
D.V.L. cdgraphics CD Graphics video
D.V..S cdtoons CDToons video
D.VIL. cdxl Commodore CDXL video
DEV.L. cfhd GoPro CineForm HD
DEV.L. cinepak Cinepak
D.V.L. clearvideo Iterated Systems ClearVideo
DEVIL. cljr Cirrus Logic AccuPak
D.VI.S cllc Canopus Lossless Codec
D.V.L. cmv Electronic Arts CMV video (decoders: eacmv )
D.V... cpia CPiA video format
D.VILS cri Cintel RAW
D.V..S cscd CamStudio (decoders: camstudio )
D.VIL. cyuv Creative YUV (CYUV)
..V.LS daala Daala
D.VILS dds DirectDraw Surface image decoder
-- More --
没晒干的咸鱼
深入理解音视频编解码与处理
本专栏将深入探讨音视频编解码与处理的原理和技术。首先,我们将详细分析音视频的采样、编码和封装过程,以及解封装、解码和播放过程,帮助读者理解音视频数据的处理流程和关键技术。其次,我们将介绍图像相关概念,包括视频帧的I、P、B帧概念,码率、帧率、分辨率等视频信息。我们还将讨论常用的视频压缩算法和画面组编解码顺序,以及各类型帧解码错误对画面质量的影响。此外,我们还将探索音频编解码原理,包括声音特性、数字音频、PCM采样振幅值等关键概念。通过阅读本专栏,读者将深入了解音视频编解码与处理的核心原理,从而能够更好地应用于音视频应用开发和处理任务中。
没晒干的咸鱼
1.分布式事务—上
一、简介分布式一致性是分布式系统亟需解决的关键问题之一,根据过去一年的调查问卷,在微服务的实践中分布式事务是用户遇到的最大痛点。目前市面缺少经过洪荒流量验证的分布式事务组件,Seata 在阿里经济体内部经过了漫长的孵化,承载了双 11 洪荒流量,实践证明 Seata 是一款解决分布式数据一致性的的优秀组件。Seata 于 2019 年正式对外开源,开源后就受到了大家的热情追捧,一度蝉联 GitHub 活跃排名榜首。Seata 除了提供了独创的 AT 事务模式外,还扩展了 TCC、Saga 和 XA 事务模式,满足大家对于不同业务场景中的需求。相关详细信息可参考其官网 Seata官网学习目标理解分布式事务在业务中的核心使用场景和常用解决方案理解 Seata AT 事务模式的核心原理掌握 Seata 作为分布式事务组件与 Spring Cloud 的整合如何扩展一个 RPC 框架Seata 实战二、为什么需要分布式事务?分布式事务不是在新架构下产生的新问题,即使在单体应用中同样存在着分布式事务问题,典型的场景是单体应用执行方法中含有多个数据源。X/OPEN 对于这一问题,提出了含有三种角色的 DTP(Distributed Transaction Processing)模型并形成了 XA 规范来解决此问题。各厂商针对 XA 规范做了具体的实现,也就是大家常说的 XA 协议。在 Java 体系中基于 DTP 模型提出了 JTA 规范(参考 JSR 907), 定义了分布式事务中的事务管理器(TM)与资源管理器(RM)、应用程序(AP)等的 Java 接口。在Java EE 时代,应用服务器如 weblogic 充当了 TM 的角色,而传统关系数据库通过实现 XA 协议充当了 RM 的角色。随着互联网的高速发展,庞大的用户群体和快速的需求变化已经成为了传统架构的痛点。在这种情况下,如何从系统架构的角度出发,构建出灵活、易扩展的系统来快速响应需求的变化,同时,随着用户量的增加,如何保证系统的稳定性、高可用性、可伸缩性等等,成为了系统架构面临的挑战。微服务基于此背景应运而生,微服务架构越来越来越成为一种架构趋势,其本质是分布式去中心化。但微服务架构绝不是银弹,它不一定是一种能支撑未来一二十年的架构,引入微服务架构时需要我们根据业务场景,系统复杂性和团队规模有步骤的进行。微服务架构的引入使分布式数据一致性问题更为突出,由原来的单体应用拆分出来几十甚至上百个微服务,如何保证服务间的一致性?当在一条较长的微服务调用链中,位于中间位置的微服务节点出现异常,如何保证整个服务的数据一致性?分布式一致性的引入,一定不可避免带来性能问题,如何更高效的解决分布式一致性问题,一直是我们致力于解决此问题的关键出发点。在“一切都正常”的情况下,我们可以认为我们并不需要分布式事务。但系统很难满足这种理想状态,系统可能因为一个非法的参数校验无法将服务链路继续向下调用下去,系统可能出现令人反感的超时问题,我们不清楚被调用的服务是否真正的执行了,被调用服务可能正在部署,网络抖动亦或者节点宕机导致接口无法继续调用。这些问题普遍存在于我们的系统中,业务的本质体现在数据上,数据不一致的直接后果是可能产生资损,更严重的是如果不一致的数据不能被及时发现,业务再次基于此数据的进行相关逻辑操作,会进一步导致数据错上加错,最终很难溯源。三、常见的分布式事务解决方案从是否满足事务 ACID 特性上,我们可以将事务分为两大类:刚性事务和柔性事务。在常见解决方案中 XA 事务属于刚性事务解决方案,而其他的大多数解决方案如 TCC、Saga、消息最终一致性则属于柔性事务解决方案。以下将对几种常见的事务方案做简要的介绍:消息最终一致性消息最终一致性方案是在 Seata 问世之前,市面上应用最广泛的一种解决方案。它本身具有削峰填谷,可异步化的优点,更多的适应于可异步化的末端链路消息通知场景。但是它本身也存在着一些缺点:需要依赖可靠消息组件,消息的可靠性很重要,大多数的原生消息组件故障时很难降级;实时性比较差,要经过多次网络 IO 开销和持久化,遇到队列积压情形实时性不可控;无法保证隔离性,在已发送消息和消息消费之前,中间数据对外可见,无法满足事务 isolate 特性;只能向前重试不可向后回滚,消息消费无法成功时无法回滚消息生产侧的数据;无法保证多条消息间的数据一致性。XAXA 标准提出后的 20 多年间未能得到持续的演进,在学术界有协议优化和日志协同处理等相关的研究,在工业界使用XA落地方案的相对较少,主要集中在应用服务器的场景。XA方案要求相关的厂商提供其具体协议的实现,目前大部分关系数据库支持了 XA 协议,但是支持程度不尽相同,例如,MySQL 在 5.7 才对 xa_prepare 语义做了完整支持。XA 方案被人诟病的是其性能,其实更为严重的是对于连接资源的占用,导致在高并发未有足够的连接资源来响应请求成为系统的瓶颈。在微服务架构下 XA 事务方案随着微服务链路的扩展成为一种反伸缩模式,进一步加剧了资源的占用。另外 XA 事务方案要求事务链路中的 resource 全部实现 XA 协议方可使用,若其中某一资源不满足,那么就无法保证整个链路的数据一致性。TCCTCC 方案要求用户根据业务场景实现 try,confirm,cancel 三个接口,由框架根据事务所处的事务阶段和决议来自动调用用户实现的三个接口。从概念上 TCC 框架可以认为是一种万能框架,但是其难点是业务对于这三个接口的实现,开发成本相对较高,有较多业务难以做资源预留相关的逻辑处理,以及是否需要在预留资源的同时从业务层面来保证隔离性。因此,这种模式比较适应于金融场景中易于做资源预留的扣减模型。Saga有了 TCC 解决方案为什么还需要 Saga 事务解决方案?上文提到了 TCC 方案中对业务的改造成本较大,对于内部系统可以自上而下大刀阔斧的推进系统的改造,但对于第三方的接口的调用往往很难推动第三方进行 TCC 的改造,让对方为了你这一个用户去改造 TCC 方案而其他用户并不需要,需求上明显也是不合理的。要求第三方业务接口提供正反接口比如扣款和退款,在异常场景下必要的数据冲正是合理的。另外,Saga 方案更加适应于工作流式的长事务方案并且可异步化。上面提到了4种常用的分布式事务解决方案,Seata 集成了TCC、Saga 和 XA 方案。另外,Seata 还提供了独创的 AT 强一致分布式事务解决方案。下文将对 AT 方案进行简要的介绍。三、AT 事务模式一个分布式事务有全局唯一的 xid,由若干个分支事务构成,每个分支事务有全局唯一的 branchId。上图展示了在一个分支事务中 RM 与 TC 的交互过程。其中主要包含的交互动作如下:branchRegister分布式事务一阶段执行,分支事务在 commit 之前与 TC 交互获取 全局锁 和返回 branchId。全局锁为 Seata 应用锁等同于修改数据记录的行锁,若获取锁失败将会进行锁重试,此处提供了两种重试策略是否持有数据库连接重试全局锁,默认为释放数据库连接。若成功,则抢占全局锁并返回 branchId,若重试到最大次数失败,则发起全局事务的回滚,对已完成的分支事务执行回滚。branchReport分布式事务一阶段执行,本地事务 commit 之后与 TC 交互,上报本地事务已完成标识。目前 branchReport 动作已经在 1.0 版本做了相关的优化,本地事务 commit 不上报,本地事务rollback 上报。经过优化分布式事务的整体性能在 globalCommit 场景下最低提升25%,最高提升50%。本地事务 rollback 上报可以帮助 TC 快速决策需要回滚的分支事务。branchCommit分布式事务二阶段执行,在形成 globalCommit 决议后执行。AT 模式中此步骤异步执行来提升其性能,可以认为分布式事务 globalCommit 决议提交到TC 释放完全局锁就已经完成了整个分布式事务的处理。branchCommit 在 AT 模式主要用于删除一阶段的 undo_log,TC 下发到 RM 后并不是立即执行,而是通过定时任务 + SQL 批量合并的方式来提升其处理性能。branchRollback分布式事务二阶段执行,在形成 globalRollback 决议后执行。RM 收到 branchRollback 请求,取 undo_log 表中对应的branchId 记录解析 rollback_info 字段,对现有数据和 undo log 后镜像对比,对比不同则分支事务回滚失败。对比成功则根据前镜像构造 SQL 并执行反向操作和删除 undo log。
没晒干的咸鱼
3.面试题
1. 什么是 Spring Cloud Alibaba ?答案:Spring Cloud Alibaba 是 Spring 官方认证的 Spring Cloud 实现,致力于提供微服务开发的一站式解决方案。此项目包含开发分布式应用服务的必需组件,方便开发者通过 Spring Cloud 编程模型轻松使用这些组件来开发分布式应用服务。依托 Spring Cloud Alibaba,您只需要添加一些注解和少量配置,就可以将 Spring Cloud 应用接入阿里分布式应用解决方案,通过阿里中间件来迅速搭建分布式应用系统。2. Spring Cloud Alibaba 实现了哪些 Spring Cloud 特性,对应的组件分别是什么?答案:3. Spring Cloud Alibaba 提供哪些阿里云商业化组件的支持?答案:Spring Cloud Alibaba 除提供开源组件之外,还支持阿里云商业化组件,以丰富微服务和云计算的 Spring 编程模型:具体请参考 Spring Cloud Alibaba 子工程:https://github.com/alibaba/aliyun-spring-boot/4. 请说明 Spring Cloud Alibaba Nacos Discovery 的核心特性有哪些?答案:Nacos Discovery 核心特性包括:Spring Cloud Commons 服务发现和发现Reactive 服务发现Spring Boot Actuator Endpoint 和 HealthIndicatorNetflix Ribbon(复杂均衡组件)Watch 特性(Spring Cloud 心跳事件)5. 请说明 Spring Cloud Alibaba Nacos Config 的核心特性有哪些?答案:Nacos Config 核心特性包括:Spring Cloud 动态配置源(PropertySourceLocator)Spring Cloud 配置动态更新(@RefreshScope 以及历史追踪)多种配置格式解析(Properties、YAML、XML 和 JSON 等)Nacos 连接诊断分析Spring Boot Actuator Endpoint 和 HealthIndicator6. 同为服务调用组件,请说明 Spring Cloud OpenFeign 与 Dubbo Spring Cloud 的相同点和区别?答案:相同点:编程模型面向 Java 接口编程(动态生成调用代理,屏蔽底层细节)注解驱动外部化配置异步调用REST 支持服务治理:负载均衡服务熔断失败重试服务链路追踪差异点:元信息:Spring Cloud OpenFeign 需要在 Java 接口上预置 Spring MVC 注解以实现 REST 服务路由,而 Dubbo Spring Cloud 仅需要 Java 方法签名即可实现服务路由。同时,后者还能在运行时获取 Dubbo 元信息能力版本支持:Spring Cloud OpenFeign 无法实现单个 Java 接口多版本支持,Dubbo Spring Cloud 可以同时支持多版本泛化调用:Spring Cloud OpenFeign 无法支持服务的泛化调用,而 Dubbo Spring Cloud 内建 GenericService 接口予以支持,类似于 Spring Cloud @LoadBalanced RestTemplate 特性通讯协议:Dubbo Spring Cloud 支持多种通讯协议,比如 dubbo、grpc、thrift 以及 REST, Spring Cloud OpenFeign 仅支持 REST扩展特性:Dubbo Spring Cloud 承继 Apache Dubbo 高扩展特性,包括通讯协议、序列化协议、负载均衡等7. 什么是 Dubbo 服务自省?答案:服务自省是 Dubbo 应用在运行时处理和分析 Dubbo 服务元信息(Metadata)的过程,如当前应用暴露 的Dubbo 服务以及各自的通讯协议等。期间会伴随着事件的广播和处理,如服务暴露事件。Dubbo 服务自省架构是其传统架的一种补充,更是未来 Dubbo 架构,它更适合以下使用场景:超大规模 Dubbo 服务治理场景微服务架构和元原生应用Dubbo 元数据架构的基石
没晒干的咸鱼
2.分布式事务—下
五、Seata 与 Spring Cloud 集成如上图,Seata 与 Spring Cloud Alibaba 集成代码结构如上图所示。从代码上可以分为三大部分:rest、feign 和 web。AutoConfiguration 结尾的类是 @Configuration 类被 spring.factories 加载,负责创建 package 中所属的 bean。rest对应 restTemplate 调用,实现 ClientHttpRequestInterceptor 接口,将当前事务上下文包装到 HttpRequest header 中,加入到拦截器列表中。feign对应 openFeign 调用,这部分实现了事务上下文传递,与 Hystrix、Sentinel 、Ribbon 组件集成功能。需要特别注意是 Hystrix 中跨线程的事务上下文传递。这部分代码大量使用了Builder、Wrapper 模式,有兴趣的同学可深入阅读。web对应 Spring Web Servlet 中的处理,实现了 HandlerInterceptor 接口。在 preHandle 预处理中取 httpRequest header 中 Seata 的事务上下文并使用 API 绑定到当前线程的事务处理上下文中,这种后续的数据源操作就自动加入到了分布式事务的链路中;在 afterCompletion 中做了当前线程事务上下文的清除,防止事务上下文在线程中污染。六、如何扩展一个 RPC 框架?在上一节,我们讲到了 Seata 是如何与 Spring Cloud 相集成的。Seata 目前已经集成了 Spring Cloud、Alibaba Dubbo、Apache Dubbo、Motan、gRPC 和 sofa-RPC 等微服务调用。结合上一节与 Spring Cloud 的集成,扩展一个RPC 框架我们需要做哪些工作呢 ?主要可以分为两大部分:事务上下文传递Seata 的事务上下文目前主要包含:xid 和调用服务的分支事务类型。xid 为一个分布式事务的全局唯一标识,类似于 Tracing 中的 traceId,只有将 xid 传递下去才可能加入到分布式事务的链路中。调用服务的分支事务类型主要用于非 AT 模式,例如在一个 TCC 分支事务中不能再嵌套 AT 分支事务。主流的 RPC 框架大多是基于 TCP 协议之上的私有协议封装或者是基于 HTTP 协议。Seata 的事务上下文标识都是简单的字符串,序列化由 RPC 框架直接完成,大多数 RPC 框架实现了 filter 或者 interceptor 接口,通过将 Seata 的事务上下文填充到协议中的 attachment 字段或者 http header 中,就可以简单的完成事务上下文的传递。事务上下文绑定和清除在 RPC 的 provider 端收到 consumer 的请求,将事务上下文取出,通过 API 绑定到当前的执行线程中,这样后续的业务处理都纳入到了 Seata 的分布式事务链路中。执行完业务处理后,需要对绑定到当前线程的事务上下文清除掉,防止产生线程事务上下文污染。具体 API 可参考官网文档:https://seata.io/zh-cn/docs/user/api.html请大家思考一下如何去与 Dubbo 集成的呢?https://github.com/seata/seata/tree/develop/integration/dubbo七、Seata 实战本节将通过一个基于 Spring Cloud 的订单和库存服务进行 Seata 实战。我们在 沙箱环境 里准备好了一套 seata 的实际应用案例,服务调用结构如下所示:如图所示,服务链路中包含三个微服务:business(微服务入口)、order(订单服务)和 storage(库存服务)。业务逻辑通过 url 调用 business 服务,business 服务会通过 openFeign 的方式分别调用 storage 和 order 服务。每个服务调用后会根据正常(ok)或异常(fail)的返回值决定是否抛出异常,若返回结果不为 ok 那么 business 将抛出异常,触发整个事务回滚,预期数据至 business 方法执行前的数据并且库存总量和与初始值一致。当 order 和 storage 两个服务调用正常,用户可以根据 url 中的 mockException=true 或 false 来注入一个 mock 异常,当注入异常后,期望数据回滚至 business 方法执行前的数据并且库存总量和与初始值一致。异常模拟在 bussiness 中请求超过现有库存,通过参数 count 来指定要扣减的库存数量,当超出库存,将抛出异常进行事务回滚。在 bussiness 中请求中加入 mockException=true 参数,触发事务回滚。启动步骤以下请求 url 中的 localhost 请根据实际值进行替换。1.启动 order 和 storage 服务,最后启动 business 服务。服务的注册和发现,Seata 服务注册和发现 在这里使用了 Nacos 启动成功后,可以通过 Nacos 控制台的 sandbox-seata namespace 看到如下服务:2.访问 business 的url :http://localhost:8080/seata/check 来检查初始化数据3.通过访问 business 的url:http://localhost:8080/seata/feign?count=5&mockException=true 来触发业务逻辑:其中 count 代表扣减库存的数量,当库存不足将触发事务回滚;mockException 代表是否触发业务异常,设置为 true 会触发业务异常,并通过分布式事务实现回滚。4.每次操作完 business 请求后,访问 business 的 url :http://localhost:8080/seata/check 来检查操作后数据。5.重复以上 3(根据实际需要请求,不必每次请求相同),4 步骤,最后再次通过访问 business 的 url :http://localhost:8080/seata/check 来检查结果数据:使用总结1.引入依赖。com.alibaba.cloud:spring-cloud-starter-alibaba-seata 中包含了 io.seata:seata-spring-boot-starter 依赖。若于期望依赖 seata 的版本不一致,可手动排除重引入。com.alibaba.cloud 原生 版本说明。parent:<dependencyManagement>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${alibaba.cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencyManagement>
module:
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
</dependency>
</dependencies>2.添加配置文件,具体配置项说明参考 此处。seata:
enabled: true
application-id: business
tx-service-group: my_test_tx_group
config:
type: nacos
nacos:
namespace: "sandbox-seata"
serverAddr: 139.196.203.133:8848
group: SEATA_GROUP
username: xxx
password: xxx
registry:
type: nacos
nacos:
application: seata-server
serverAddr: 139.196.203.133:8848
group: SEATA_GROUP
namespace: "sandbox-seata"
username: xxx
password: xxx3.在所有业务库中创建 undo_log 表,不同的数据库类型脚本参考 此处 ,示例中已自动完成创建。4.在需要纳入分布式事务链路的入口 service 方法(保证可使 Spring 切面生效的位置亦可)上添加 @GlobalTransactional 注解。八、其他Seata 更多 sample 样例 ,请参考 样例Seata 社区联系方式,请参见 联系我们欢迎大家试用阿里云商业化产品 GTS,更高性能,更稳定,全面兼容 Seata。
没晒干的咸鱼
Spring Cloud Alibaba从入门到实战:分布式事务
了解微服务各模块的实现原理,熟悉 Spring Cloud Alibaba,并带领大家独立开发一个微服务应用。
没晒干的咸鱼
1.前言
近些年随着云技术的发展,越来越多的用户选择使用云技术来代替传统的 IT 基础设施。在云技术发展的早期,业界的关注点集中在虚拟化、分布式、存储等 Iaas 方面的技术。但是随着“云原生”概念的提出,大家的注意力开始转移到如何构建更加适合云环境运行的应用上来。“什么样的架构才是适合在云环境中运行”是一个非常大的问题,在此先不展开讨论,而是到 CNCF 对云原生的定义中寻找答案:云原生技术有利于各组织在公有云、私有云和混合云等新型动态环境中,构建和运行可弹性扩展的应用。云原生的代表技术包括容器、服务网格、微服务、不可变基础设施和声明式 API。这些技术能够构建容错性好、易于管理和便于观察的松耦合系统。结合可靠的自动化手段,云原生技术使工程师能够轻松地对系统作出频繁和可预测的重大变更。从上文的定义中可以发现“微服务”在云原生技术中占有这非常重要的位置。在 jakarta.ee 2019 年的调研报告中也印证了这一点,超过40%公司选择采用微服务架构来构建云上系统:我们继续把视角聚焦到 Java 语言下。Pivotal 依托于 Spring 这个 Java 语言下编程模型的事实标准,结合大量业界经验,为广大 Java 开发者带来了 Spring Cloud 框架。该框架是对云环境下微服务开发中需要解决的各种问题的标准化,以帮助开发者快速实现分布式系统中的某些常见模式(例如,配置管理,服务发现,断路器等)。同时,基于 Pivotal 强大的标准制定能力与影响力,Spring Cloud 拥有一个强大的国际化社区,阿里巴巴作为这个社区里重要的成员,也贡献出了 Spring Cloud Alibaba 这套优秀的实现,这也是目前整个 Spring Cloud 体系下最完善并且在持续更新的实现方案。
没晒干的咸鱼
1.简介和快速上手
一、简介Nacos 提供用于存储配置和其他元数据的 key/value 存储,为分布式系统中的外部化配置提供服务器端和客户端支持。使用 Spring Cloud Alibaba Nacos Config,您可以在 Nacos Server 集中管理你 Spring Cloud 应用的外部属性配置。Spring Cloud Alibaba Nacos Config 是 Config Server 和 Client 的替代方案,客户端和服务器上的概念与 Spring Environment 和 PropertySource 有着一致的抽象,在特殊的 bootstrap 阶段,配置被加载到 Spring 环境中。当应用程序通过部署管道从开发到测试再到生产时,您可以管理这些环境之间的配置,并确保应用程序具有迁移时需要运行的所有内容。Nacos 的获取和启动方式可以参考 Nacos 官网。注:如果读者是阿里云商业化组件 ANS 或 ACM 用户,请使用 Nacos Config 代替对应的组件。学习目标使用 Nacos Config 作为 Spring Cloud 分布式配置使用 Nacos Config 实现 Bean 动态刷新了解 Nacos Config 高级配置详细内容快速上手:使用 Nacos Config 作为外部化配置源多文件扩展名支持:以 YAML 文件扩展名为例,讨论 Nacos Config 多文件扩展名支持动态配置更新:演示 @RefreshScope 特性,实现 Bean 动态刷新自定义扩展:自定义 namespace、Group 以及 Data Id 的配置扩展运维特性:演示 Nacos Config 高级外部化配置以及 Endpoint 内部细节二、快速上手下面会介绍如何使用 Nacos Config 支持和实现分布式配置。如何引入 Nacos Config 支持分布式配置Nacos Config 引入的方式同样也有两种,即 Aliyun Java Initializr 引入和 Maven pom.xml 依赖。官方推荐使用 Aliyun Java Initializr 方式引入 Nacos Discovery,以便简化组件之间的依赖关系。[偷懒] 直接在沙箱里查看应用代码点击 链接,直接访问沙箱环境,这里会有为你准备好的案例代码^_^。[简单] 通过 Aliyun Java Initializr 创建工程并引入 Nacos Config(推荐)由于 Spring Cloud 组件的版本和依赖较为复杂,推荐读者使用 Aliyun Java Initializr 构建应用工程。读者选择偏好的 Web 浏览器访问 Aliyun Java Initializr,其资源网址为:https://start.aliyun.com/bootstrap.html下文以 Google Chrome 浏览器为例,当网页加载后,首先,在 "项目基本信息" 部分输入 Group :“com.alibaba.cloud” 以及 Artifact:“nacos-config-sample”。然后,“组件依赖” 输入框搜索:“Nacos Config”,选择 "Nacos Configuration",如下所示:同上组件操作,增加 “Spring Web” 和 “Spring Boot Actuator” 组件:组件选择后,点击 “生成” 高亮按钮。随后,平台将生成一个名为 “nacos-config-sample.zip” 的压缩文件,将其保存到本地目录,并解压该文件,工程目录将随之生成。打开目录下的 pom.xml 文件,不难发现 Nacos starter 声明其中(以下 XML 内容均来自于项目根路径中的 pom.xml 文件):XML <dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>不过该 starter 并未指定版本,具体的版本声明在 com.alibaba.cloud:spring-cloud-alibaba-dependencies 部分:XML <dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>其中,${spring-cloud-alibaba.version} 和 ${spring-boot.version} 分别为 Spring Cloud Alibaba 和 Spring Boot 组件依赖的版本,它们的版本定义在 <properties>元素中,即 2.2.1.RELEASE 和 2.3.0.RELEASE:XML <properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.3.0.RELEASE</spring-boot.version>
<spring-cloud-alibaba.version>2.2.1.RELEASE</spring-cloud-alibaba.version>
</properties>如果读者非常熟悉 Maven 依赖管理的配置方式,可以考虑 Maven pom.xml 依赖 Nacos Config。[高级] 通过 Maven pom.xml 依赖 Nacos Config如果要在您的项目中使用 Nacos 来实现服务注册/发现,使用 group ID 为 com.alibaba.cloud和 artifact ID 为 spring-cloud-starter-alibaba-nacos-config的 starter。XML<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>该声明方式同样需要声明 com.alibaba.cloud:spring-cloud-alibaba-dependencies,内容与上小节相同,在此不再赘述。下一节将讨论如何使用 Nacos Config 支持分布式配置。使用 Nacos Config 实现分布式配置使用 Nacos Config 实现分布式配置与 Spring Cloud Consul 和 Spring Cloud Zookeeper 的方式非常类似,仅需添加相关外部化配置即可工作。换言之,Nacos Config 同样不会侵入应用代码,方便应用整合和迁移,如果读者熟悉 Spring Cloud Consul 或 Spring Cloud Zookeeper 使用方式 的话,通常需要将 Consul 或 Zookeeper 服务进程预先部署,Nacos Config 也如此。启动 Nacos 服务器我们为开发者提供了一套免费的 Nacos Server :进入 http://139.196.203.133:8848/nacos/ 查看控制台(账号名/密码为 nacos-configuration/nacos-configuration),选择 "配置管理/配置列表":由于服务是公共免费的,为了做好隔离,所以分布式配置的功能,请选择在 sandbox-configuration 的命名空间下操作。具体启动方式参考 Nacos 官网。关于更多的 Nacos Server 版本,可以从 release 页面 下载最新的版本。添加 Nacos 配置点击“配置列表”页面右侧的 "+" 号(红色箭头所指):)浏览器跳转新页面,并填充内容如下:其中,Data ID 由应用名(nacos-config-sample)+ 文件后缀名(.properties) 组成,点击“发布”按钮(红色箭头所指),配置内容为user.name=nacos-config-sample
user.age=90发布成功后,控制台会出现提示弹出框。特别提醒图片中的 Data ID 中的应用名,使用的是 nacos-config-sample 。如果使用我们提供的 Nacos Server ,由于多个用户同时使用,可能存在应用名冲突的问题。建议修改为跟别人都不重复的应用名:spring.application.name=xxxxxx替换上面的 xxxxx 部分配置应用 Nacos Config Server 地址回到应用 nacos-config-sample 工程,在 resources 目录下新建名为 “bootstrap.properties" 文件,并配置以下内容:spring.cloud.nacos.config.server-addr=139.196.203.133:8848
spring.cloud.nacos.config.username=nacos-configuration
spring.cloud.nacos.config.password=nacos-configuration
spring.cloud.nacos.config.namespace=sandbox-configuration注意,Nacos Server 地址必须配置在 bootstrap.properties 文件。注意当你使用域名的方式来访问 Nacos 时, spring.cloud.nacos.config.server-addr 配置的方式为域名:port。 例如 Nacos 的域名为abc.com.nacos,监听的端口为 80,则 spring.cloud.nacos.config.server-addr=abc.com.nacos:80。 注意 80 端口不能省略。添加读取 Nacos Config 实现修改 nacos-config-sample 引导类,如下所示:Java@SpringBootApplication
public class NacosConfigSampleApplication {
@Value("${user.name}")
private String userName;
@Value("${user.age}")
private int userAge;
@PostConstruct
public void init() {
System.out.printf("[init] user name : %s , age : %d%n", userName, userAge);
}
public static void main(String[] args) {
SpringApplication.run(NacosConfigSampleApplication.class, args);
}
}启动 Nacos Config 应用运行 nacos-config-sample 引导类 NacosConfigSampleApplication,观察控制台结果(截取关键日志信息):Bash[init] user name : nacos-config-sample , age : 90如果在沙箱内启动应用,由于暂时还无法看到运行时的日志,可以通过WEB 控制器的方式查看参数,具体操作见 5.1 节。1.如何引入 Nacos Config 支持分布式配置Nacos Config 引入的方式同样也有两种,即 Aliyun Java Initializr 引入和 Maven pom.xml 依赖。官方推荐使用 Aliyun Java Initializr 方式引入 Nacos Discovery,以便简化组件之间的依赖关系。2.使用 Nacos Config 实现分布式配置使用 Nacos Config 实现分布式配置与 Spring Cloud Consul 和 Spring Cloud Zookeeper 的方式非常类似,仅需添加相关外部化配置即可工作。换言之,Nacos Config 同样不会侵入应用代码,方便应用整合和迁移,如果读者熟悉 Spring Cloud Consul 或 Spring Cloud Zookeeper 使用方式 的话,通常需要将 Consul 或 Zookeeper 服务进程预先部署,Nacos Config 也如此。
没晒干的咸鱼
1.简介和快速上手
一、简介服务注册与发现是微服务架构体系中最关键的组件之一。如果尝试着用手动的方式来给每一个客户端来配置所有服务提供者的服务列表是一件非常困难的事,而且也不利于服务的动态扩缩容。Nacos Discovery 可以帮助您将服务自动注册到 Nacos 服务端并且能够动态感知和刷新某个服务实例的服务列表。除此之外,Nacos Discovery 也将服务实例自身的一些元数据信息 - 例如 host,port,健康检查 URL,主页等内容注册到 Nacos。Nacos 的获取和启动方式可以参考 Nacos 官网。学习目标掌握 Nacos Discovery 实现 Spring Cloud 服务注册和发现掌握 Nacos Discovery 整合 Spring Cloud 负载均衡和服务调用理解 Nacos Discovery 高级特性:命名空间、安全控制、元数据、Nacos Watch 等详细内容快速上手:指导读者从使用 Nacos Discovery 进行服务注册/发现服务调用整合:实战 Nacos Discovery 整合 @LoadBalanced RestTemplate 以及 Open Feign运维特性:演示 Nacos Discovery 高级外部化配置以及 Endpoint 内部细节二、快速上手1.如何引入 Nacos Discovery 进行服务注册/发现Nacos Discovery 引入的方式通常有两种,由易到难分别为:Aliyun Java Initializr 引入和 Maven pom.xml 依赖。官方推荐使用 Aliyun Java Initializr 方式引入 Nacos Discovery,以便简化组件之间的依赖关系。[偷懒] 直接在沙箱里查看应用代码点击 链接,直接访问沙箱环境,这里会有为你准备好的案例代码 ^_^。[简单] 通过 Aliyun Java Initializr 创建工程并引入 Nacos Discovery(推荐)由于 Spring Cloud 组件的版本和依赖较为复杂,推荐读者使用 Aliyun Java Initializr 构建应用工程。下文以 Google Chrome 浏览器为例,当网页加载后,首先,在 “项目基本信息” 部分输入 Group :"com.alibaba.cloud" 以及 Artifact:"nacos-discovery-provider-sample"(见下图绿框部分)然而,“组件依赖” 输入框搜索:"Nacos"(见下图红箭头部分),最后,选择 "Nacos Service Discovery"(见下图红框部分),如下所示:Nacos Service Discovery 组件选择后,展开“示例代码”部分,选择合适的示例代码:由于“服务注册 & 发现”是两个独立的端,所以示例代码也被分为两个部分。通过点击“获取代码”来获得由平台生成的代码:点击 下载 按钮后,平台将生成一个名为 "nacos-discovery-provider-sample.zip" 的压缩文件,将其保存到本地目录,并解压该文件,工程目录将随之生成。打开目录下的 pom.xml 文件,不难发现 Nacos Discovery starter 声明其中(以下 XML 内容均来自于项目根路径中的 pom.xml 文件):XML <dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>不过该 starter 并未指定版本,具体的版本声明在 com.alibaba.cloud:spring-cloud-alibaba-dependencies 部分:XML <dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>其中,${spring-cloud-alibaba.version} 和 ${spring-boot.version} 分别为 Spring Cloud Alibaba 和 Spring Boot 组件依赖的版本,它们的版本定义在 <properties> 元素中,即 2.2.1.RELEASE 和 2.3.0.RELEASE:XML <properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.3.0.RELEASE</spring-boot.version>
<spring-cloud-alibaba.version>2.2.1.RELEASE</spring-cloud-alibaba.version>
</properties>如果读者非常熟悉 Maven 依赖管理的配置方式,可以考虑 Maven pom.xml 依赖 Nacos Discovery。[高级] 通过 Maven pom.xml 依赖 Nacos Discovery如果要在您的项目中使用 Nacos 来实现服务注册/发现,使用 group ID 为 com.alibaba.cloud 和 artifact ID 为 spring-cloud-starter-alibaba-nacos-discovery 的 starter。XML<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>该声明方式同样需要声明 com.alibaba.cloud:spring-cloud-alibaba-dependencies,内容与上小节相同,在此不再赘述。下一节将讨论如何使用 Nacos Discovery 进行服务注册/发现。2.使用 Nacos Discovery 进行服务注册/发现使用 Nacos Discovery 进行服务注册/发现与传统 Spring Cloud 的方式并没有本质区别,仅需添加相关外部化配置即可工作。换言之,Nacos Discovery 不会侵入应用代码,方便应用整合和迁移,这归功于 Spring Cloud 的高度抽象。如果读者熟悉 Spring Cloud 服务注册和发现的话,通常需要将注册中心预先部署,Nacos Discovery 也不例外。启动 Nacos 服务器具体启动方式参考 Nacos 官网。Nacos Server 启动后,进入 http://ip:8848 查看控制台(默认账号名/密码为 nacos/nacos):关于更多的 Nacos Server 版本,可以从 release 页面 下载最新的版本。启动服务提供者(Provider)增加 Maven 依赖回到之前构建的应用 nacos-discovery-provider-sample,在此基础增加 Spring WebMVC 以及 Spring Boot Actuator Starter 依赖:XML <dependencies>
<!-- Spring WebMVC Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Actuator Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
...
</dependencies>增加 Nacos Discovery 外部化配置Nacos 基本的配置需要添加到 application.properties(也可以是 application.yaml )文件中。application.proeprties 文件已被 Aliyun Java Initializr 生成,内容如下:spring.application.name=nacos-discovery-provider-sample
management.endpoints.jmx.exposure.include=*
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
# spring cloud access&secret config
# 可以访问如下地址查看: https://usercenter.console.aliyun.com/#/manage/ak
alibaba.cloud.access-key=****
alibaba.cloud.secret-key=****
# 应用服务 WEB 访问端口
server.port=8080
# Actuator Web 访问端口
management.server.port=8081增加 NacosDiscovery 配置,如下所示:spring.application.name=nacos-discovery-provider-sample
management.endpoints.jmx.exposure.include=*
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
# spring cloud access&secret config
# 可以访问如下地址查看: https://usercenter.console.aliyun.com/#/manage/ak
alibaba.cloud.access-key=****
alibaba.cloud.secret-key=****
# 应用服务 WEB 访问端口
server.port=8080
# Actuator Web 访问端口
management.server.port=8081
## Nacos 注册中心配置地址(无需配置 HTTP 协议部分)
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
## Nacos 客户端认证信息(默认用户名和密码均为 nacos)
spring.cloud.nacos.discovery.user-name=nacos
spring.cloud.nacos.discovery.password=naocs请注意,Nacos 服务器默认关闭认证,建议在生产环境开启,详情请参考此 Blog。激活 Nacos Discovery 服务注册与发现Aliyun Java Initializr 默认不会自动激活 Nacos Discovery 服务注册与发现,需要在引导类(main 方法所在类)标注 Spring Cloud 服务注册与发现标准注解@EnableDiscoveryClient,代码如下所示:Javaimport org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class NacosDiscoveryProviderSampleApplication {
public static void main(String[] args) {
SpringApplication.run(NacosDiscoveryProviderSampleApplication.class, args);
}
}启动引导类启动引导类 NacosDiscoveryProviderSampleApplication,观察控制台输出(隐藏时间部分的内容):[ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
[ main] c.a.c.n.registry.NacosServiceRegistry : nacos registry, DEFAULT_GROUP nacos-discovery-provider-sample 30.225.19.241:8080 register finished
[ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8081 (http)
[ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
[ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.35]
[ main] o.a.c.c.C.[Tomcat-1].[localhost].[/] : Initializing Spring embedded WebApplicationContext
[ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 176 ms
[ main] o.s.b.a.e.web.EndpointLinksResolver : Exposing 18 endpoint(s) beneath base path '/actuator'
[ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8081 (http) with context path ''
[ main] .NacosDiscoveryProviderSampleApplication : Started NacosDiscoveryProviderSampleApplication in 3.037 seconds (JVM running for 3.615)按照日志的描述,应用使用了 Tomcat 作为 Web 服务器,并且将 8080 和 8081 作为应用服务和 Actuator Web 端口。同时, "c.a.c.n.registry.NacosServiceRegistry : nacos registry, DEFAULT_GROUP nacos-discovery-provider-sample 30.225.19.241:8080 register finished" 表明服务实例注册成功,其 IP 为 30.225.19.241,服务端口为 8080。下一步,观察 Nacos 控制台 注册情况。观察 Nacos 控制台服务注册打开 Nacos 控制台中的“服务列表”,点击“查询”按钮,观察页面的变化:其中应用 nacos-discovery-provider-sample 出现在列表中,说明该应用已成功注册。至此,使用 Nacos Discovery 进行服务注册/发现演示完毕。接下来的示例将变得更为复杂,实现 Spring Cloud 服务调用。如果不想使用 Nacos 作为您的服务注册与发现,可以将 spring.cloud.nacos.discovery 设置为 false。
没晒干的咸鱼
4.Nacos Config Actuator Endpoint
Nacos Config 内部提供了一个 Endpoint, 对应的 Endpoint ID 为 nacos-config,其 Actuator Web Endpoint URI 为 /actuator/nacos-config注:使用 Nacos Config Spring Cloud 1.x 版本的话,其 URI 地址则为 /nacos-config其中,Endpoint 暴露的 Json 中包含了三种属性:NacosConfigProperties: 当前应用 Nacos 的基础配置信息RefreshHistory: 配置刷新的历史记录Sources: 当前应用配置的数据信息由于 Aliyun Java Initializr 所生成的应用工程默认激活 Spring Boot Actuator Endpoints(JMX 和 Web),具体配置存放在 application.properties 文件中,同时,Actuator Web 端口设置为 8081,内容如下:management.endpoints.jmx.exposure.include=*
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
# Actuator Web 访问端口
management.server.port=8081因此,应用 nacos-config-sample 无需调整,直接访问:http://127.0.0.1:8081/actuator/nacos-config,服务响应的内容如下:Json{
"NacosConfigProperties": {
"serverAddr": "127.0.0.1:8848",
"username": "",
"password": "",
"encode": null,
"group": "DEFAULT_GROUP",
"prefix": null,
"fileExtension": "properties",
"timeout": 3000,
"maxRetry": null,
"configLongPollTimeout": null,
"configRetryTime": null,
"enableRemoteSyncConfig": false,
"endpoint": null,
"namespace": null,
"accessKey": null,
"secretKey": null,
"contextPath": null,
"clusterName": null,
"name": null,
"sharedConfigs": null,
"extensionConfigs": null,
"refreshEnabled": true,
"sharedDataids": null,
"refreshableDataids": null,
"extConfig": null,
"configServiceProperties": {
"secretKey": "",
"namespace": "",
"username": "",
没晒干的咸鱼
3.Nacos Discovery 更多配置项信息和Nacos Discovery Actuator
一、Nacos Discovery 更多配置项信息更多关于 Nacos Discovery Starter 的配置项如下所示:二·、Nacos Discovery Actuator EndpointNacos Discovery 内部提供了一个 Endpoint, 对应的 endpoint id 为 nacos-discovery,其 Actuator Web Endpoint URI 为 /actuator/nacos-discovery注:使用 Nacos Config Spring Cloud 1.x 版本的话,其 URI 地址则为/nacos-discoveryEndpoint 暴露的 json 中包含了两种属性:subscribe: 显示了当前服务有哪些服务订阅者NacosDiscoveryProperties: 当前应用 Nacos 的基础配置信息由于 Aliyun Java Initializr 所生成的应用工程默认激活 Spring Boot Actuator Endpoints(JMX 和 Web),具体配置存放在 application.properties 文件中,同时,Actuator Web 端口设置为 8081,内容如下:management.endpoints.jmx.exposure.include=*
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
# Actuator Web 访问端口
management.server.port=8081因此,应用 nacos-discovery-provider-sample 无需调整,直接访问:http://127.0.0.1:8081/actuator/nacos-discovery ,服务响应的内容如下:JSON{
"subscribe": [
{
"jsonFromServer": "",
"name": "nacos-provider",
"clusters": "",
"cacheMillis": 10000,
"hosts": [
{
"instanceId": "30.5.124.156#8081#DEFAULT#nacos-provider",
"ip": "30.5.124.156",
"port": 8081,
"weight": 1.0,
"healthy": true,
"enabled": true,
"cluster": {
"serviceName": null,
"name": null,
"healthChecker": {
"type": "TCP"
},
"defaultPort": 80,
"defaultCheckPort": 80,
"useIPPort4Check": true,
"metadata": {
}
},
"service": null,
"metadata": {
}
}
],
"lastRefTime": 1541755293119,
"checksum": "e5a699c9201f5328241c178e804657e11541755293119",
"allIPs": false,
"key": "nacos-provider",
"valid": true
}
],
"NacosDiscoveryProperties": {
"serverAddr": "127.0.0.1:8848",
"endpoint": "",
"namespace": "",
"logName": "",
"service": "nacos-provider",
"weight": 1.0,
"clusterName": "DEFAULT",
"metadata": {
},
"registerEnabled": true,
"ip": "30.5.124.201",
"networkInterface": "",
"port": 8082,
"secure": false,
"accessKey": "",
"secretKey": ""
}
}
没晒干的咸鱼
3.框架篇
从 Spring 到 Spring CloudSpring熟悉 java 语言的同学,对 Spring 框架应该都不陌生。从 2004 年 1.0 版本发布开始,便由于其灵活易用的特性受到了整个 Java 行业的广泛关注。经过十多年的发展,Spring 框架早已经成为 Java 语言下编程模型的事实标准。其所倡导的 IOC/AOP 概念也早已深入人心。在 Spring 框架的早期,大家都喜欢称其为“轻量化”框架(现在好像早就没人提这个词了^_^),“轻量”是相对于 EJB 等企业级开发框架而言的。其“轻”的特性体现在:框架本身的大小很小,早期版本的jar包不超过1MB;同时不依赖于运行容器,也是说任何容器里都可以运行Spring框架;更加重要的是 Spring 是非侵入的,使用Spring开发的应用可以不完全依赖Spring的类;Spring Boot但是事情总会发生变化,随着 Spring 的不断发展,越来越多的组件被集成到了框架中。Spring 框架也从一个小巧精简的 IOC 容器框架变成了一套大而全的框架集合。开发者为了实现组件的整合工作,往往需要在大量的 xml 文件、java 注解 中完成各种 bean 的配置。曾经屠龙的少年,如今也变成了恶龙。那个时候,很多比 Spring 更加简单小巧的 IOC 容器如雨后春笋般的出现。业界开始出现一种声音:Spring 是不是已经不行了,或者是在走下坡路了。就在这个时候 Pivotal 推出了 Spring Boot 来彻底的解决这些问题。使用 Spring Boot 可以大大简化 Spring 应用的开发工作。在 Spring Boot 中无论是官方组件还是第三方框架都会提供各种“starter”来方便开发者进行依赖和集成。由于采用了“约定大于配置”的思想,开发者在引入“stater”以后只需要做少量的配置工作就可以完成框架集成工作。往往开发者只需要很少量的代码就可以实现以前大量配置文件才能做到的功能。同时 Spring Boot 还是一套面向生产环境设计的框架。配置外化、运行情况检查功能,可以很方便的在系统外部实现对系统的管理。同时 Spring Boot 还是一个运行时容器。通过内嵌 Tomcat 、Jetty 等使得程序的运行不在依赖传统的应用服务器。这一点在云原生时代意义尤其重大。Spring 官方对 Spring Boot 特色定义如下:创建独立的Spring应用程序直接嵌入Tomcat,Jetty或Undertow(无需部署WAR文件)提供自以为是的“starter”依赖项,以简化构建配置尽可能自动配置Spring和三方类库提供可用于生产的功能,例如指标,运行状况检查和外部化配置完全没有代码生成,也不需要XML配置Spring CloudSpring Cloud 是什么,没有比官方的定义更能说明问题了:Spring Cloud provides tools for developers to quickly build some of the common patterns in distributed systems (e.g. configuration management, service discovery, circuit breakers, intelligent routing, micro-proxy, control bus, one-time tokens, global locks, leadership election, distributed sessions, cluster state). Coordination of distributed systems leads to boiler plate patterns, and using Spring Cloud developers can quickly stand up services and applications that implement those patterns. They will work well in any distributed environment, including the developer’s own laptop, bare metal data centres, and managed platforms such as Cloud Foundry.这里面提到几个关键词:分布式系统中的常见模式任何分布式环境“分布式系统中的常见模式”给了 Spring Cloud 一个清晰的定位,即“模式”。也就是说 Spring Cloud 是针对分布式系统开发所做的通用抽象,是标准模式的实现。这个定义非常抽象,看完之后并不能知道 Spring Cloud 具体包含什么功能。再来看一下 Spring 官方给出的一个 High Light 的架构图,就可以对这套模式有更清晰的认识:可以看到这个图中间就是各个Microservice,也就是我们的这个微服务的实现,周边周围的话就是去围绕这个微服务来去做各种辅助的信息事情。例如分布式追踪、服务注册、配置服务等,都绕微服务运行时所依赖的必不可少的的支持性功能。我们可以得出这样一个结论:Spring Cloud 是以微服务为核心的分布式系统的一个构建标准。Spring Cloud Alibaba既然说 Spring Cloud 是标准,那么自然少不了针对标准的实现。参与这个标准实现的公司有很多,例如:Google 的 Spring Cloud GCP,Netflix 的 Spring Cloud Netflix,Microsoft 的 Spring Cloud Azure 等等。当然还有我们阿里巴巴的 Spring Cloud Alibaba。Spring Cloud Alibaba 从 19 年初开始提交代码就获得了业界的广泛关注,从下面这张图中可以看到,在很短的时间之内,Spring Cloud Alibaba 就成为了 Spring Cloud 家族中最受关注的框架:下面这张图很好的说明了 Spring Cloud Alibaba 的组成以及与 Spring Cloud 的关系:图中深色的部分,其实它就是 Spring Cloud 标准,一共有 3 层。中间颜色最深的部分是微服务的核心组件,包括了“ RPC 调用”以及“服务注册与发现”。第二层,也就是围绕着核心的这一圈,是一些辅助微服务更好的工作功能,包括了负载均衡、路由、网关、断路器,还有分布式追踪等等这些内容。再外层的话,主要是些分布式云环境里通用能力。最外面这一圈,是 Spring Cloud Alibaba 对 Spring Cloud 的实现。右上部分是对于 Spring Cloud 标准的实现。例如,我们通过 Dubbo 实现了 RPC 调用功能,通过 Nacos 实现了“服务注册与发现”、“分布式配置”,通过 Sentinel 实现了断路器等等,这里就不一一列举了。左下部分是我们 Spring Cloud Alibaba 对阿里云各种服务的集成。可能很多同学会有这样的一个问题:为什么要加上这一部分呢?此时回头审视一下 Spring Cloud ,它仅仅是一个微服务的一个框架。但是在实际生产过程中,单独使用微服务框架其实并不足以支撑我们去构建一个完整的系统。所以这部分是用阿里帮助开发者完成微服务以外的云产品集成的功能。为什么要分成两个部分呢,这也是为了打消大家对于使用了 Spring Cloud Alibaba 以后就会被平台绑定的担忧。虽然在品牌商都叫做SpringCloudAlibaba,但是在代码上,我们采用了两个独立的项目维护。分别是 Spring Cloud Alibaba 和 Aliyun Spring Boot目前,Spring Cloud Alibaba 包含如下组件:开源部分Sentinel:把流量作为切入点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性。Nacos:一个更易于构建云原生应用的动态服务发现、配置管理和服务管理平台。RocketMQ:一款开源的分布式消息系统,基于高可用分布式集群技术,提供低延时的、高可靠的消息发布与订阅服务。Dubbo:Apache Dubbo 是一款高性能 Java RPC 框架。Seata:阿里巴巴开源产品,一个易于使用的高性能微服务分布式事务解决方案。平台服务部分Alibaba Cloud OSS: 阿里云对象存储服务(Object Storage Service,简称 OSS),是阿里云提供的海量、安全、低成本、高可靠的云存储服务。您可以在任何应用、任何时间、任何地点存储和访问任意类型的数据。Alibaba Cloud SchedulerX: 阿里中间件团队开发的一款分布式任务调度产品,提供秒级、精准、高可靠、高可用的定时(基于 Cron 表达式)任务调度服务。Alibaba Cloud SMS: 覆盖全球的短信服务,友好、高效、智能的互联化通讯能力,帮助企业迅速搭建客户触达通道。
没晒干的咸鱼
2.Nacos Discovery 整合 Spring Cloud 服务调用
从应用架构上,Spring Cloud 服务调用通常需要两个应用,一个为服务提供者(Provider),一个为服务消费者(Consumer)。从技术上,传统的 Spring Cloud 服务通讯方式是基于 REST 实现的,包好两种内建实现方法,分别是 @LoadBalanced RestTemplate 以及 Open Feign,两者均作用于服务消费者,而服务提供者仅为 WebMVC 或者 WebFlux 应用(需注册到注册中心)。同时,还允许整合 Spring Cloud 负载均衡 API,实现自定义 REST 服务调用。至于,Spring Cloud Alibaba 引入 Dubbo 服务通讯方式,会在后续内容中单独讨论。一、服务提供者添加 Web 服务复用应用 nacos-discovery-provider-sample,在引导类 NacosDiscoveryProviderSampleApplication 同包下增加 @RestController 实现类:Javaimport org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ServiceController {
@GetMapping("/echo/{message}")
public String echo(@PathVariable String message) {
return "[ECHO] : " + message;
}
}重启应用 nacos-discovery-provider-sample,测试该 Web 服务端口:% curl http://127.0.0.1:8080/echo/Hello,World
[ECHO] : Hello,World结果符合期望,下一步增加消费者应用。二·、Nacos Discovery 整合 @LoadBalanced RestTemplate继续使用 Aliyun Java Initializr 创建消费者应用 - nacos-discovery-consumer-sample,选择 Nacos Service Discovery 和 Spring Web 组件:生成项目,并使用 IDE 导入工程。增加 Nacos Discovery 外部化配置与应用 nacos-discovery-provider-sample 配置类似,增加 Nacos Discovery 外部化配置。如果是本地部署的话,请调整应用服务和 Actuator 端口,以免与应用 nacos-discovery-provider-sample 端口冲突 ,完整配置如下:spring.application.name=nacos-discovery-consumer-sample
management.endpoints.jmx.exposure.include=*
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
# spring cloud access&secret config
# 可以访问如下地址查看: https://usercenter.console.aliyun.com/#/manage/ak
alibaba.cloud.access-key=****
alibaba.cloud.secret-key=****
# 应用服务 WEB 访问端口
server.port=9090
# Actuator Web 访问端口
management.server.port=9091
## Nacos 注册中心配置地址(无需配置 HTTP 协议部分)
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
## Nacos 客户端认证信息(默认用户名和密码均为 nacos)
spring.cloud.nacos.discovery.user-name=nacos
spring.cloud.nacos.discovery.password=naocs服务消费者激活 Nacos Discovery 服务注册与发现与应用 nacos-discovery-provider-sample 实现一样,在引导类上标注 @EnableDiscoveryClient,代码如下:Javaimport org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class NacosDiscoveryConsumerSampleApplication {
public static void main(String[] args) {
SpringApplication.run(NacosDiscoveryConsumerSampleApplication.class, args);
}
}服务消费者使用 @LoadBalanced RestTemplate 实现服务调用前文提到 @LoadBalanced RestTemplate 是 Spring Cloud 内建的服务调用方式,因此需要在应用 nacos-discovery-consumer-sample 增加执行代码,消费应用 nacos-discovery-provider-sample REST 服务 /echo/{message},故在引导类同包下新增 RestController 实现:Javaimport org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class RestTemplateController {
@LoadBalanced
@Autowired
public RestTemplate restTemplate;
@LoadBalanced
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@GetMapping("/call/echo/{message}")
public String callEcho(@PathVariable String message) {
// 访问应用 nacos-discovery-provider-sample 的 REST "/echo/{message}"
return restTemplate.getForObject("http://nacos-discovery-provider-sample/echo/" + message, String.class);
}
}以上代码实现方式与传统 Spring Cloud 的方式无异,下一步启动引导类 NacosDiscoveryConsumerSampleApplication,并测试运行结果:Bash% curl http://127.0.0.1:9090/call/echo/Hello,World
[ECHO] : Hello,World结果符合期望,说明 Nacos Discovery 整合 @LoadBalanced RestTemplate 的实现与标准 Spring Cloud 实现的差异仅体现在 Maven 依赖 starter 以及外部化配置上。接下来,应用 nacos-discovery-consumer-sample 将继续与 Spring Cloud OpenFeign 整合。三、Nacos Discovery 整合 Spring Cloud OpenFeignSpring Cloud OpenFeign 是 Spring Cloud 基于 REST 客户端框架 OpenFeign 而构建,使得服务发现和负载均衡透明,开发人员只需关注服务消费者接口契约。同时,Spring Cloud OpenFeign 可以与 @LoadBalanced RestTemplate 共存,因此,可在原有应用 nacos-discovery-consumer-sample 的基础上,增加 Maven 依赖和代码实现整合。关于 Spring Cloud OpenFeign 的技术细节,可参考官方文档: https://docs.spring.io/spring-cloud-openfeign/docs/current/reference/html/服务消费者增加 Spring Cloud OpenFeign Maven 依赖在 nacos-discovery-consumer-sample 项目 pom.xml 中追加 Spring Cloud OpenFeign Maven 依赖:XML <!-- Spring Cloud OpenFeign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>下一步,则是新增 Spring Cloud OpenFeign 服务声明接口服务消费者增加 Spring Cloud OpenFeign 服务声明接口由于需要消费应用 nacos-discovery-provider-sample 提供的 REST 服务 /echo/{message},根据 Spring Cloud OpenFeign 的要求,需要在消费者应用增加 REST 服务声明接口,即:Java@FeignClient("nacos-discovery-provider-sample") // 指向服务提供者应用
public interface EchoService {
@GetMapping("/echo/{message}")
String echo(@PathVariable("message") String message);
}不难发现,echo(String) 方法在 Spring MVC 请求映射的方式与 nacos-discovery-provider-sample 中的 ServiceController 基本相同,唯一区别在于 @PathVariable 注解指定了 value 属性 "message",这是因为默认情况,Java 编译器不会讲接口方法参数名添加到 Java 字节码中。下一步,激活 Spring Cloud OpenFeign 服务声明接口。服务消费者激活 Spring Cloud OpenFeign 服务声明接口激活 Spring Cloud OpenFeign 服务声明接口的方法非常简单,仅需在引导类标注 @EnableFeignClients,如果声明接口与引导类不在同一个包的话,请使用 basePackages属性指定。由于本例的 EchoService 与引导类位于同一包下,因此,无需指定:Java@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients // 激活 @FeignClient
public class NacosDiscoveryConsumerSampleApplication {
public static void main(String[] args) {
SpringApplication.run(NacosDiscoveryConsumerSampleApplication.class, args);
}
}激活步骤就此完成,下一步为 Spring Cloud OpenFeign 服务接口增加 RestController 实现。服务消费者使用 Spring Cloud OpenFeign 服务声明接口实现服务调用新增名为 OpenFeignController 的实现类:Javaimport org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class OpenFeignController {
@Autowired
private EchoService echoService;
@GetMapping("/feign/echo/{message}")
public String feignEcho(@PathVariable String message) {
return echoService.echo(message);
}
}重启引导类NacosDiscoveryConsumerSampleApplication,并测试/feign/echo/{message}结果:Bash% curl http://127.0.0.1:9090/feign/echo/Hello,World
[ECHO] : Hello,World结果符合期望,说明 Nacos Discovery 整合 Spring Cloud OpenFeign 与传统方式也是相同的。综上所述,Nacos Discovery 在 Spring Cloud 服务调用是无侵入的。
没晒干的咸鱼
1.简介和理解Spring消息编程模型
一、简介事件驱动架构(Event-driven 架构,简称 EDA)是软件设计领域内的一套程序设计模型。这套模型的意义是所有的操作通过事件的发送/接收来完成。举个例子,比如一个订单的创建在传统软件设计中服务端通过接口暴露创建订单的动作,然后客户端访问创建订单。在事件驱动设计里,订单的创建通过接收订单事件来完成,这个过程中有事件发送者和事件接受者这两个模块,事件发送者的作用是发送订单事件,事件接受者的作用的接收订单事件。Spring Cloud Stream 是一套基于消息的事件驱动开发框架,它提供了一套全新的消息编程模型,此模型屏蔽了底层具体消息中间件的使用方式。开发者们使用这套模型可以完成基于消息的事件驱动应用开发。学习目标掌握 Spring 对消息的编程模型封装掌握 RocketMQ 整合 Spring Cloud Stream 完成消息的发送和接收掌握 RocketMQ 整合 Spring Cloud Bus 完成远程事件的发送和接收详细内容概念理解:指导读者理解 Spring 的消息编程模型消息发送/接收:实战 Spring Cloud Steam RocketMQ Binder事件发送/接收: 实战 Spring Cloud Bus RocketMQ二、理解 Spring 消息编程模型首先我们来看这个场景,不同的消息中间件发送消息的代码:每个消息中间件都有自己的消息模型编程,他们的代码编写方式都不一致。同样地,在消息的订阅方面,也是不同的代码。这个时候如果某天想把 Kafka 切换到 RocketMQ,必须得修改大量代码。Spring 生态里有两个消息相关的模块和项目,分别是 spring-messaging 模块和 Spring Integration 项目,它们对消息的编程模型进行了统一,不论是 Apache RocketMQ 的 Message,或者是 Apache Kafka 的 ProducerRecord,都被统一称为 org.springframework.messaging.Message 接口。Message 接口有两个方法,分别是 getPayload 以及 getHeaders 用于获取消息体以及消息头。如图所示,这也意味着一个消息 Message 由 Header 和 Payload 组成:Payload 是一个泛型,意味是消息体可以放任意数据类型。Header 是一个 MessageHeaders 类型的消息头。有了消息之后,这个消息被发送到哪里呢?Spring 提供了消息通道 MessageChannel 的概念。消息可以被发送到消息通道里,然后再通过消息处理器 MessageHandler 去处理消息通道里的消息:消息处理这里又会遇到一个问题。如果消息通道里只有 1 个消息,但是消息处理器有 N 个,这个时候要被哪个消息处理器处理呢?这里又涉及一个消息分发器的问题。UnicastingDispatcher 表示单播的处理方式,消息会通过负载均衡被分发到某一个消息处理器上,BroadcastingDispatcher 表示广播的方式,消息会被所有的消息处理器处理。
没晒干的咸鱼
2.Spring Cloud Stream
一、Spring Cloud Stream 是一套基于消息的事件驱动开发框架。Spring Cloud Stream 在 Spring Integration 项目的基础上再进行了一些封装,提出一些新的概念,让开发者能够更简单地使用这套消息编程模型。如图所示,这是三者之间的关系:如下图所示,这是 Spring Cloud Stream 的编程模型。通过 RabbitMQ Binder 构建 input Binding 用于读取 RabbitMQ 上的消息,将 payload 内容转成大写再通过 Kafka Binder 构建的 output Binding 写入到 Kafka 中。图上中间的 4 行非常简单的代码就可以完成从 RabbitMQ 读取消息再写入到 Kafka 的动作。以下代码是使用 Spring Cloud Stream 以最简单的方式完成消息的发送和接收:@SpringBootApplication@EnableBinding({Source.class, Sink.class}) // ①
public class SCSApplication {
public static void main(String[] args) {
new SpringApplicationBuilder().sources(SCSApplication.class)
.web(WebApplicationType.NONE).run(args);
}
@Autowired
Source source; // ②
@Bean
public CommandLineRunner runner() {
return (args) -> {
source.output().send(MessageBuilder.withPayload("custom payload").setHeader("k1", "v1").build()); // ③
};
}
@StreamListener(Sink.INPUT) // ④
@SendTo(Source.OUTPUT) // ⑤
public String receive(String msg) {
return msg.toUpperCase();
}
}使用 @EnableBinding 注解,注解里面有两个参数 Source 和 Sink,它们都是接口。Source 接口内部有个 MessageChannel 类型返回值的 output 方法,被 @Output 注解修饰表示这是一个 Output Binding;Sink 接口内部有个 SubscribableChannel 类型返回值的 intput 方法,被 @Input 注解修饰表示这是一个 Input Binding。@EnableBinding 注解会针对这两个接口生成动态代理。注入 @EnableBinding 注解对于 Source 接口生成的动态代理。使用 @EnableBinding 注解对于 Source 接口生成的动态代理内部的 MessageChannel 发送一条消息。最终消息会被发送到消息中间件对应的 topic 里。@StreamListener 注解订阅 @EnableBinding 注解对于 Sink 接口生成的动态代理内部的 SubscribableChannel 中的消息,这里会订阅到消息中间件对应的 topic 和 group。消息处理结果发送到 @EnableBinding 注解对于 Source 接口生成的动态代理内部的 MessageChannel。最终消息会被发送到消息中间件对应的topic 里。上述代码需要配置信息:spring.cloud.stream.bindings.input.destination=test-input
spring.cloud.stream.bindings.input.group=test-input-binder
spring.cloud.stream.bindings.input.binder=kafka
spring.cloud.stream.bindings.output.destination=test-output
spring.cloud.stream.bindings.output.binder=rocketmq这里的 Input Binding 对应的 topic 是 test-input,group 是 test-input-binder,对应的 MQ 是 Kafka,Output Binding 对应的 topic 是 test-output,对应的 MQ 是 RocketMQ。所以这段代码的意思是 以 test-input-binder 这个 group 去 Kafka 上读取 test-input 这个 topic 下的消息,把消息的内容转换成大写再发送给 RocketMQ 的 test-output topic 上。当然,你也可以直接通过 沙箱环境 直接查看案例
没晒干的咸鱼
1.前言:为什么需要流控降级
我们的生产环境经常会出现一些不稳定的情况,如:大促时瞬间洪峰流量导致系统超出最大负载,load 飙高,系统崩溃导致用户无法下单“黑马”热点商品击穿缓存,DB 被打垮,挤占正常流量调用端被不稳定服务拖垮,线程池被占满,导致整个调用链路卡死这些不稳定的场景可能会导致严重后果。大家可能想问:如何做到均匀平滑的用户访问?如何预防流量过大或服务不稳定带来的影响?这时候我们就要请出微服务稳定性的法宝 —— 高可用流量防护,其中重要的手段就是流量控制和熔断降级,它们是保障微服务稳定性重要的一环。一、为什么需要流量控制?流量是非常随机性的、不可预测的。前一秒可能还风平浪静,后一秒可能就出现流量洪峰了(例如双十一零点的场景)。然而我们系统的容量总是有限的,如果突然而来的流量超过了系统的承受能力,就可能会导致请求处理不过来,堆积的请求处理缓慢,CPU/Load 飙高,最后导致系统崩溃。因此,我们需要针对这种突发的流量来进行限制,在尽可能处理请求的同时来保障服务不被打垮,这就是流量控制。二、为什么需要熔断降级?一个服务常常会调用别的模块,可能是另外的一个远程服务、数据库,或者第三方 API 等。例如,支付的时候,可能需要远程调用银联提供的 API;查询某个商品的价格,可能需要进行数据库查询。然而,这个被依赖服务的稳定性是不能保证的。如果依赖的服务出现了不稳定的情况,请求的响应时间变长,那么调用服务的方法的响应时间也会变长,线程会产生堆积,最终可能耗尽业务自身的线程池,服务本身也变得不可用。现代微服务架构都是分布式的,由非常多的服务组成。不同服务之间相互调用,组成复杂的调用链路。以上的问题在链路调用中会产生放大的效果。复杂链路上的某一环不稳定,就可能会层层级联,最终导致整个链路都不可用。因此我们需要对不稳定的弱依赖服务进行熔断降级,暂时切断不稳定调用,避免局部不稳定因素导致整体的雪崩。
没晒干的咸鱼
1.简介和功能特性
一、简介在《Spring Cloud Alibaba 服务注册与发现》篇中曾提到,Spring Cloud Alibaba Nacos Discovery 能无缝整合 Spring Cloud OpenFeign。换言之,Spring Cloud Alibaba 延续了 Spring Cloud 分布式服务调用的特性。除此之外,Spring Cloud Alibaba 引入了 Dubbo Spring Cloud,扩展了分布式服务调用能力,不仅能使 Apache Dubbo 和 OpenFeign 共存,还允许 Spring Cloud 标准调用底层通过 Dubbo 支持的通讯协议传输。无论开发人员是 Dubbo 用户还是 Spring Cloud 用户,都能轻松地驾驭,并以接近“零”成本的代价使应用向上迁移。Dubbo Spring Cloud 致力于简化 Cloud Native 开发成本,提高研发效能以及提升应用性能等目的。学习目标使用 Dubbo Spring Cloud 实现 Spring Cloud 分布式服务调用使用 Dubbo Spring Cloud 替换 Spring Cloud 分布式服务调用底层协议理解 Dubbo Spring Cloud 高级特性:服务订阅、元数据、Actuator详细内容快速上手:使用 Apache Dubbo适配整合:使用注解 @DubboTransported 适配 Spring Cloud OpenFeign 和 @LoadBalanced RestTemplate运维特性:演示服务订阅、元信息(服务、REST)以及 Actuator Endpoints二、功能特性由于 Dubbo Spring Cloud 构建在原生的 Spring Cloud 之上,其服务治理方面的能力可认为是 Spring Cloud Plus,不仅完全覆盖 Spring Cloud 原生特性,而且提供更为稳定和成熟的实现,特性比对如下表所示:三、高亮特性Dubbo 使用 Spring Cloud 服务注册与发现Dubbo Spring Cloud 基于 Spring Cloud Commons 抽象实现 Dubbo 服务注册与发现,无需添加任何外部化配置,就能轻松地桥接到所有原生 Spring Cloud 注册中心,包括:NacosEurekaZookeeperConsul注:Dubbo Spring Cloud 将在下个版本支持 Spring Cloud 注册中心与 Dubbo 注册中心并存,提供双注册机制,实现无缝迁移。Dubbo 作为 Spring Cloud 服务调用默认情况,Spring Cloud Open Feign 以及 @LoadBalanced,RestTemplate 作为 Spring Cloud 的两种服务调用方式。Dubbo Spring Cloud 为其提供了第三种选择,即 Dubbo 服务将作为 Spring Cloud 服务调用的同等公民出现,应用可通过 Apache Dubbo 注解 @Service 和 @Reference 暴露和引用 Dubbo 服务,实现服务间多种协议的通讯。同时,也可以利用 Dubbo 泛化接口轻松实现服务网关。Dubbo 服务自省Dubbo Spring Cloud 引入了全新的服务治理特性 - 服务自省 (Service Introspection),其设计目的在于最大化减轻注册中心负载,去 Dubbo 注册元信息中心化。假设一个 Spring Cloud 应用引入 Dubbo Spring Boot Starter,并暴露 N 个 Dubbo 服务,以Dubbo Nacos 注册中心为例,当前应用将注册 N+1 个 Nacos 应用,除 Spring Cloud 应用本身之前,其余 N 个应用均来自于 Dubbo 服务,当 N 越大时,注册中心负载越重。因此,Dubbo Spring Cloud 应用对注册中心的负载相当于传统 Dubbo 的 N 分之一,在不增加基础设施投入的前提下,理论上,使其集群规模扩大 N 倍。当然,未来的 Dubbo 也将提供服务自省的能力。Dubbo 迁移 Spring Cloud 服务调用尽管 Dubbo Spring Cloud 完全地保留了原生 Spring Cloud 服务调用特性,不过 Dubbo 服务治理的能力是 Spring Cloud Open Feign 所不及的,如高性能、高可用以及负载均衡稳定性等方面。因此,建议开发人员将 Spring Cloud Open Feign 或者 @LoadBalanced RestTemplate 迁移为 Dubbo 服务。考虑到迁移过程并非一蹴而就,因此,Dubbo Spring Cloud 提供了方案,即 @DubboTransported 注解。该注解能够帮助服务消费端的 Spring Cloud Open Feign 接口以及 @LoadBalanced,RestTemplate Bean 底层走 Dubbo 调用(可切换 Dubbo 支持的协议),而服务提供方则只需在原有@RestController类上追加 Dubbo @Servce 注解(需要抽取接口)即可,换言之,在不调整 Feign 接口以及 RestTemplate URL 的前提下,实现无缝迁移。如果迁移时间充分的话,建议使用 Dubbo 服务重构系统中的原生 Spring Cloud 服务的定义。
没晒干的咸鱼
5.如何选择流控降级组件和总结和总结
一、如何选择流控降级组件讲到这里,大家可能会有疑问:Sentinel 和其它同类产品(如 Hystrix)相比有什么优缺点?是否有必要迁移到 Sentinel?如何快速迁移?以下是 Sentinel 与其它 fault-tolerance 组件的对比:二、总结通过本教程,我们了解了流控降级作为高可用防护手段的重要性,了解了 Sentinel 的核心特性和原理,并通过动手实践学习了如何快速接入 SCA Sentinel 来为微服务进行流控降级。Sentinel 还有着非常多的高级特性等着大家去发掘,如热点防护、集群流控等,大家可以参考 Sentinel 官方文档来了解更多的特性和场景。那么是不是服务的量级很小就不用进行限流防护了呢?是不是微服务的架构比较简单就不用引入熔断保护机制了呢?其实,这与请求的量级、架构的复杂程度无关。很多时候,可能正是一个非常边缘的服务出现故障而导致整体业务受影响,造成巨大损失。我们需要具有面向失败设计的意识,在平时就做好容量规划和强弱依赖的梳理,合理地配置流控降级规则,做好事前防护,而不是在线上出现问题以后再进行补救。同时,我们也在阿里云上提供了 Sentinel 的企业版本 AHAS Sentinel,提供开箱即用的企业级高可用防护能力。与开源版本相比,AHAS 还提供以下的专业能力:可靠的实时监控和历史秒级监控数据查询,包含接口维度的 QPS、响应时间及系统 load、CPU 使用率等指标,支持按照调用类型分类,支持同比/环比展示Top K 接口监控统计,快速了解系统的慢调用和大流量接口;热力图概览,快速定位不稳定的机器Java Agent 方式/K8s Java 应用零侵入快速接入,支持近 20 种主流框架和 API Gateway全自动托管、高可用的集群流量控制Nginx 流量控制,支持规则动态配置、集群流控
没晒干的咸鱼
3.Spring Cloud Alibaba Sentinel 服务限流/熔断实战-上
下面到了动手时间了!我们已经将案例代码集成在沙箱中,通过点击 链接 直接访问。我们结合一个实例来对 Spring Cloud 服务限流/熔断进行实战。我们的实例项目由四个模块构成:service-api: 服务接口定义,供 consumer/provider 引用dubbo-provider: Dubbo 服务端,对外提供一些服务web-api-demo: Spring Boot Web 应用,其中的一些 API 会作为 consumer 来调用 dubbo-provider 获取结果。里面一共定义了三个 API path:/demo/hello: 接受一个 name 参数,会 RPC 调用后端的 FooService:sayHello(name) 方法。/demo/time:调用后端的 FooService:getCurrentTime 方法获取当前时间;里面可以通过 slow 请求参数模拟慢调用。/demo/bonjour/{name}: 直接调用本地 DemoService 服务。demo-gateway: Spring Cloud Gateway 网关,作为整个项目的访问入口,将流量转发至后端服务或第三方服务。我们的入口 URL 访问都会经过该 API gateway。demo-gateway 的路由配置如下spring:
cloud:
gateway:
enabled: true
discovery:
locator:
# route ID 转化小写
lower-case-service-id: true
routes:
- id: foo-service-route
uri: http://localhost:9669/
predicates:
- Path=/demo/**
- id: httpbin-route
uri: https://httpbin.org
predicates:
- Path=/httpbin/**
filters:
- RewritePath=/httpbin/(?<segment>.*), /$\{segment}这个路由配置包含两个路由:foo-service-route: 会将 /demo/ 开头的访问路由到 localhost:9669 后端服务上面,即对应我们的 Web 服务。我们访问示例中的 API 都会经过这个路由,比如 localhost:8090/demo/time。httpbin-route: 这是一个示例路由,它会将 /httpbin/ 开头的访问路由到 https://httpbin.org 这个示例网站上,比如 localhost:8090/httpbin/json 实际会映射到 https://httpbin.org/json 上面。同时我们的环境也包含启动好的 Sentinel 控制台,可以直接访问并供各个服务接入。对应的地址:http://139.196.203.133:8080下面我们来一步一步操作接入 SCA Sentinel 并通过控制台/Nacos 动态数据源配置流控降级规则来验证效果。一、spring-cloud-alibaba-dependencies 配置首先第一步我们在项目的父 pom 里面导入最新版本的 spring-cloud-alibaba-dependencies,这样我们在实际引入 SCA 相关依赖的时候就不需要指定版本号了:XML<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.2.2.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
二、服务接入 SCA Sentinel首先我们分别为三个服务模块引入 Spring Cloud Alibaba Sentinel 依赖:XML<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>starter 会自动对 Sentinel 的适配模块进行配置,只需要简单的配置即可快速接入 Sentinel 并连接到 Sentinel 控制台。对于 Dubbo 服务,我们还需要额外引入 Dubbo 的适配模块。Sentinel 为 Apache Dubbo 提供开箱即用的整合模块,仅需引入 sentinel-apache-dubbo-adapter 依赖即可接入 Dubbo 自动埋点统计(支持 provider 和 consumer):XML<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-apache-dubbo-adapter</artifactId>
<version>1.8.0</version>
</dependency>我们在 web-api-demo 和 dubbo-provider 两个应用的 pom 文件添加 adapter 依赖,这样两个应用的 Dubbo consumer/provider 接口就可以自动被 Sentinel 统计。对于 Spring Cloud Gateway、Zuul 1.x 等网关,我们还需要在上面 SCA 依赖的基础上额外引入 spring-cloud-alibaba-sentinel-gateway 依赖:XML<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>这个依赖会自动为网关添加 Sentinel 相关的配置,从而可以让 API gateway 自动接入 Sentinel。我们在 demo-gateway 应用的 pom 文件里面添加这个依赖,这样我们的 gateway 应用就可以接入 Sentinel 了。引入依赖之后,我们只需要进行简单的配置即可快速接入 Sentinel 控制台。我们可以在 application.properties 文件里面配置应用名和连接控制台的地址,以 web-api-demo 为例:spring.application.name=foo-web
spring.cloud.sentinel.transport.dashboard=localhost:8080其中 spring.application.name 相信大家都比较熟悉了,这里 Spring Cloud Alibaba Sentinel 会自动提取这个值作为接入应用的 appName。同时我们通过 spring.cloud.sentinel.transport.dashboard 来配置要连接的控制台地址和端口。完成以上的配置后,我们可以依次启动 dubbo-provider、web-api-demo 和 demo-gateway 应用,并通过网关入口访问 localhost:8090/demo/time 获取当前时间。触发服务后,我们稍后可以在 Sentinel 控制台看到我们的三个应用,可以在监控页面看到访问信息,代表接入成功。我们可以在每个应用的簇点链路页面看到当前应用的一些埋点调用,比如 Web 应用可以看到 Web URL 和 Dubbo consumer 调用:三、流控规则下面我们来配一条最简单的流控规则。在 Dubbo provider 端,我们进入簇点链路页面,针对 com.alibaba.csp.sentinel.demo.dubbo.FooService:getCurrentTime(boolean) 这个服务调用配置限流规则(需要有过访问量才能看到)。我们配一条 QPS 为 1 的流控规则,这代表针对该服务方法的调用每秒钟不能超过 1 次,超出会直接拒绝。点击“新增”按钮,成功添加规则。我们可以在浏览器反复请求 localhost:8090/demo/time(频率不要太慢),可以看到会出现限流异常信息(Dubbo provider 默认的限流处理逻辑是抛出异常,该异常信息由 Dubbo 直接返回,并由 Spring 展示为默认 error 页面):同时我们也可以在“实时监控”页面看到实时的访问量和拒绝量:我们同样也可以在 Web API 处配置限流规则,观察效果。Spring Web 默认的限流处理逻辑是返回默认的提示信息(Blocked by Sentinel),状态码为 429。在后面的章节我们会介绍如何自定义流控处理逻辑。了解了限流的基本用法,大家可能想问:生产环境我需要针对每个接口都去配置流控规则吗?阈值不会配怎么办?其实,限流降级的配置是需要结合容量规划、依赖梳理来做的。我们可以借助 JMeter 或 阿里云 PTS 等压测工具对我们的服务进行全链路压测,了解每个服务的最大承受能力,来确定核心接口的最大容量并作为 QPS 阈值。四、网关流控规则Sentinel 对 API Gateway 流控的场景进行了定制,支持针对网关的路由(如上面 gateway 定义的 foo-service-route)或自定义的 API 分组进行流控,支持针对请求属性(如某个 header)进行流控。用户可以在 Sentinel 控制台 自定义 API 分组,可以看做是一些 URL 匹配的组合。比如我们可以定义一个 API 叫 my_api,请求 path 模式为 /foo/** 和 /baz/** 的都归到 my_api 这个 API 分组下面。限流的时候可以针对这个自定义的 API 分组维度进行限流。下面我们在控制台针对 gateway 配置一条网关流控规则。我们可以看到 API Gateway 的控制台页面与普通应用的页面有一些差异,这些就是针对网关场景的定制。Sentinel 网关流控规则支持提取某个 route 的请求属性,包括 remote IP、header、URL 参数、cookie 等,支持自动统计其中的热点值并分别进行限制,也支持针对某个具体值进行限制(比如给某个 uid 限量)。我们给 foo-service-route 这个路由配一条针对请求属性的网关流控规则。这条规则会针对 URL 参数中提取出来的每个热点 uid 参数分别进行限制,每分钟的请求量最多允许 2 次。保存规则后,我们可以构造一些向后端服务的请求,携带上不同的 uid 参数(即使没有用到),比如 localhost:8090/demo/time?uid=xxx。我们可以观察到,每个 uid 的访问每分钟超出两次后会出现限流页面。关于 Sentinel 网关流控的详细配置指南和实现原理请参考 网关流控文档。
没晒干的咸鱼
3.Nacos Config 高级配置
一、支持自定义 namespace 的配置首先看一下 Nacos 的 Namespace 的概念, Nacos 概念用于进行租户粒度的配置隔离。不同的命名空间下,可以存在相同的 Group 或 Data ID 的配置。Namespace 的常用场景之一是不同环境的配置的区分隔离,例如开发测试环境和生产环境的资源(如配置、服务)隔离等。在没有明确指定 ${spring.cloud.nacos.config.namespace} 配置的情况下, 默认使用的是 Nacos 上 Public 这个namespae。如果需要使用自定义的命名空间,可以通过以下配置来实现:spring.cloud.nacos.config.namespace=b3404bc0-d7dc-4855-b519-570ed34b62d7注:该配置必须放在 bootstrap.properties 文件中。此外 spring.cloud.nacos.config.namespace 的值是 namespace 对应的 id,id 值可以在 Nacos 的控制台获取。并且在添加配置时注意不要选择其他的 namespae,否则将会导致读取不到正确的配置二、支持自定义 Group 的配置在没有明确指定 ${spring.cloud.nacos.config.group} 配置的情况下, 默认使用的是 DEFAULT_GROUP 。如果需要自定义自己的 Group,可以通过以下配置来实现:spring.cloud.nacos.config.group=DEVELOP_GROUP注:该配置必须放在 bootstrap.properties 文件中。并且在添加配置时 Group 的值一定要和 spring.cloud.nacos.config.group 的配置值一致。三、支持自定义扩展的 Data Id 配置Spring Cloud Alibaba Nacos Config 从 0.2.1 版本后,可支持自定义 Data Id 的配置。关于这部分详细的设计可参考 这里。 一个完整的配置案例如下所示:
spring.application.name=opensource-service-provider
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
# config external configuration
# 1、Data Id 在默认的组 DEFAULT_GROUP,不支持配置的动态刷新
spring.cloud.nacos.config.extension-configs[0].data-id=ext-config-common01.properties
# 2、Data Id 不在默认的组,不支持动态刷新
spring.cloud.nacos.config.extension-configs[1].data-id=ext-config-common02.properties
spring.cloud.nacos.config.extension-configs[1].group=GLOBALE_GROUP
# 3、Data Id 既不在默认的组,也支持动态刷新
spring.cloud.nacos.config.extension-configs[2].data-id=ext-config-common03.properties
spring.cloud.nacos.config.extension-configs[2].group=REFRESH_GROUP
spring.cloud.nacos.config.extension-configs[2].refresh=true可以看到:通过 spring.cloud.nacos.config.extension-configs[n].data-id 的配置方式来支持多个 Data Id 的配置。通过 spring.cloud.nacos.config.extension-configs[n].group 的配置方式自定义 Data Id 所在的组,不明确配置的话,默认是 DEFAULT_GROUP。通过 spring.cloud.nacos.config.extension-configs[n].refresh 的配置方式来控制该 Data Id 在配置变更时,是否支持应用中可动态刷新, 感知到最新的配置值。默认是不支持的。注:多个 Data Id 同时配置时,他的优先级关系是 spring.cloud.nacos.config.extension-configs[n].data-id 其中 n 的值越大,优先级越高。spring.cloud.nacos.config.extension-configs[n].data-id 的值必须带文件扩展名,文件扩展名既可支持 properties,又可以支持 yaml/yml。 此时 spring.cloud.nacos.config.file-extension 的配置对自定义扩展配置的 Data Id 文件扩展名没有影响。通过自定义扩展的 Data Id 配置,既可以解决多个应用间配置共享的问题,又可以支持一个应用有多个配置文件。为了更加清晰的在多个应用间配置共享的 Data Id ,你可以通过以下的方式来配置:# 配置支持共享的 Data Id
spring.cloud.nacos.config.shared-configs[0].data-id=common.yaml
# 配置 Data Id 所在分组,缺省默认 DEFAULT_GROUP
spring.cloud.nacos.config.shared-configs[0].group=GROUP_APP1
# 配置Data Id 在配置变更时,是否动态刷新,缺省默认 false
spring.cloud.nacos.config.shared-configs[0].refresh=true可以看到:通过 spring.cloud.nacos.config.shared-configs[n].data-id 来支持多个共享 Data Id 的配置。
通过 spring.cloud.nacos.config.shared-configs[n].group 来配置自定义 Data Id 所在的组,不明确配置的话,默认是 DEFAULT_GROUP。
通过 spring.cloud.nacos.config.shared-configs[n].refresh 来控制该Data Id在配置变更时,是否支持应用中动态刷新,默认false。四、配置的优先级Spring Cloud Alibaba Nacos Config 目前提供了三种配置能力从 Nacos 拉取相关的配置。A: 通过 spring.cloud.nacos.config.shared-configs[n].data-id 支持多个共享 Data Id 的配置B: 通过 spring.cloud.nacos.config.extension-configs[n].data-id 的方式支持多个扩展 Data Id 的配置C: 通过内部相关规则(应用名、应用名+ Profile)自动生成相关的 Data Id 配置当三种方式共同使用时,他们的一个优先级关系是:A < B < C五、完全关闭配置通过设置 spring.cloud.nacos.config.enabled = false 来完全关闭 Spring Cloud Nacos Config六、更多高级配置更多关于 Nacos Config Starter 的配置项如下所示:
没晒干的咸鱼
4.Spring Cloud Alibaba Sentinel 服务限流/熔断实战-下
4.Spring Cloud Alibaba Sentinel 服务限流/熔断实战-下五、熔断降级规则熔断降级通常用于自动切断不稳定的服务,防止调用方被拖垮导致级联故障。熔断降级规则通常在调用端,针对弱依赖调用进行配置,在熔断时返回预定义好的 fallback 值,这样可以保证核心链路不被不稳定的旁路影响。Sentinel 提供以下几种熔断策略:慢调用比例 (SLOW_REQUEST_RATIO):选择以慢调用比例作为阈值,需要设置允许的慢调用 RT(即最大的响应时间),请求的响应时间大于该值则统计为慢调用。当单位统计时长(statIntervalMs,默认为 1s)内请求数目大于设置的最小请求数目,并且慢调用的比例大于阈值,则接下来的熔断时长内请求会自动被熔断。经过熔断时长后熔断器会进入探测恢复状态(HALF-OPEN 状态),若接下来的一个请求响应时间小于设置的慢调用 RT 则结束熔断,若大于设置的慢调用 RT 则会再次被熔断。异常比例 (ERROR_RATIO):当单位统计时长内请求数目大于设置的最小请求数目,并且异常的比例大于阈值,则接下来的熔断时长内请求会自动被熔断。经过熔断时长后熔断器会进入探测恢复状态(HALF-OPEN 状态),若接下来的一个请求成功完成(没有错误)则结束熔断,否则会再次被熔断。异常比率的阈值范围是 [0.0, 1.0],代表 0% - 100%。异常数 (ERROR_COUNT):当单位统计时长内的异常数目超过阈值之后会自动进行熔断。经过熔断时长后熔断器会进入探测恢复状态(HALF-OPEN 状态),若接下来的一个请求成功完成(没有错误)则结束熔断,否则会再次被熔断。下面我们来在 Web 应用中针对 Dubbo consumer 来配置慢调用熔断规则,并模拟慢调用来观察效果。我们在 web-api-demo 中针对 com.alibaba.csp.sentinel.demo.dubbo.FooService 服务调用配置熔断降级规则。控制台配置的统计时长默认为 1s。在上面的这条规则中,我们设定慢调用临界值为 50ms,响应时间超出 50ms 即记为慢调用。当统计时长内的请求数 >=5 且慢调用的比例超出我们配置的阈值(80%)就会触发熔断,熔断时长为 5s,经过熔断时长后会允许一个请求探测通过,若请求正常则恢复,否则继续熔断。我们的实例中 /demo/time API 可以通过 slow 请求参数模拟慢调用,当 slow=true 时该请求耗时会超过 100ms。我们可以用 ab 等压测工具或脚本,批量请求 localhost:8090/demo/time?slow=true,可以观察到熔断的返回如果我们一直模拟慢调用,我们可以观察到熔断后每 5s 会允许通过一个请求,但该请求仍然是慢调用,会重新打回熔断,无法恢复。我们可以在触发熔断后,等待一段时间后手动发一个不带 slow=true 的正常请求,然后再进行请求,可以观察到熔断恢复。需要注意的是,即使服务调用方引入了熔断降级机制,我们还是需要在 HTTP 或 RPC 客户端配置请求超时时间,来做一个兜底的防护。六、注解方式自定义埋点刚才我们看到的埋点都是 Sentinel 适配模块提供的自动埋点。有的时候自动埋点可能没法满足我们的需求,我们希望在某个业务逻辑的位置进行限流,能不能做到呢?当然可以!Sentinel 提供两种方式进行自定义埋点:SphU API 和 @SentinelResource 注解,前者最为通用但是代码比较繁杂,耦合度较高;注解方式侵入性较低,但有使用场景的限制。这里我们来动手在 Web 应用的 DemoService 上添加注解,来达到针对本地服务埋点的目标。在 DemoService 中我们实现了一个简单的打招呼的服务:Java@Service
public class DemoService {
public String bonjour(String name) {
return "Bonjour, " + name;
}
}下面我们给 bonjour 这个函数添加 @SentinelResource 注解,注解的 value 代表这个埋点的名称(resourceName),会显示在簇点链路/监控页面。Java@SentinelResource(value = "DemoService#bonjour")
public String bonjour(String name)加上该注解后,再通过网关访问 /demo/bonjour/{name} 这个 API 的时候,我们就可以在簇点链路页面看到我们自定义的 DemoService#bonjour 埋点了。添加注解埋点只是第一步。一般在生产环境中,我们希望在这些自定义埋点发生限流的时候,有一些 fallback 逻辑,而不是直接对外抛出异常。这里我们可以写一个 fallback 函数:Javapublic String bonjourFallback(Throwable t) {
if (BlockException.isBlockException(t)) {
return "Blocked by Sentinel: " + t.getClass().getSimpleName();
}
return "Oops, failed: " + t.getClass().getCanonicalName();
}我们的 fallback 函数接受一个 Throwable 参数,可以从中获取异常信息。Sentinel 注解的 fallback 会捕获业务异常和流控异常(即 BlockException 及其子类),我们可以在 fallback 逻辑里面进行相应的处理(如日志记录),并返回 fallback 的值。注意:Sentinel 注解对 fallback 和 blockHandler 函数的方法签名有要求,具体请参考 此处文档。写好 fallback 函数的实现后,我们在 @SentinelResource 注解里面指定一下:Java@SentinelResource(value = "DemoService#bonjour", defaultFallback = "bonjourFallback")
public String bonjour(String name)这样当我们自定义的 DemoService#bonjour 资源被限流或熔断的时候,请求会走到 fallback 的逻辑中,返回 fallback 结果,而不会直接抛出异常。我们可以配一个 QPS=1 的限流规则,然后快速请求后观察返回值:? ~ curl http://localhost:8090/demo/bonjour/Sentinel
Bonjour, Sentinel
? ~ curl http://localhost:8090/demo/bonjour/Sentinel
Blocked by Sentinel: FlowException注意:使用 @SentinelResource 注解要求对应的类必须由 Spring 托管(即为 Spring bean),并且不能是内部调用(没法走到代理),不能是 private 方法。Sentinel 注解生效依赖 Spring AOP 动态代理机制。七、配置自定义的流控处理逻辑Sentinel 的各种适配方式均支持自定义的流控处理逻辑。以 Spring Web 适配为例,我们只需要提供自定义的 BlockExceptionHandler 实现并注册为 bean 即可为 Web 埋点提供自定义处理逻辑。其中 BlockExceptionHandler 的定义如下:Javapublic interface BlockExceptionHandler {
// 在此处处理限流异常,可以跳转到指定页面或返回指定的内容
void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception;
}我们的 Web 应用中提供了 Web 埋点自定义流控处理逻辑的示例:Java@Configuration
public class SentinelWebConfig {
@Bean
public BlockExceptionHandler sentinelBlockExceptionHandler() {
return (request, response, e) -> {
// 429 Too Many Requests
response.setStatus(429);
PrintWriter out = response.getWriter();
out.print("Oops, blocked by Sentinel: " + e.getClass().getSimpleName());
out.flush();
out.close();
};
}
}该 handler 会获取流控类型并打印返回信息,返回状态码为 429。我们可以根据实际的业务需求,配置跳转或自定义的返回信息。对于注解方式,我们上一节已经提到,可以指定 fallback 函数来处理流控异常和业务异常,这里不再展开讲解;对于 Dubbo 适配,我们可以通过 DubboAdapterGlobalConfig 注册 provider/consumer fallback 来提供自定义的流控处理逻辑;对于 Spring Cloud Gateway 适配,我们可以注册自定义的 BlockRequestHandler 实现类来为网关流控注册自定义的处理逻辑。八、对 Spring Cloud 其他组件的支持Spring Cloud Alibaba Sentinel 还提供对 Spring Cloud 其它常用组件的支持,包括 RestTemplate、Feign 等。篇幅所限,我们不展开实践。大家可以参考 Spring Cloud Alibaba 文档 来进行接入和配置。
没晒干的咸鱼
2.快速上手-上
2.快速上手一、如何引入 Dubbo Spring CloudDubbo Spring Cloud 引入的方式通常有两种,由易到难分别为:Aliyun Java Initializr 引入和 Maven pom.xml 依赖。官方推荐使用 Aliyun Java Initializr 方式引入 Dubbo Spring Cloud,以便简化组件之间的依赖关系。[偷懒] 直接在沙箱里查看应用代码点击 链接,直接访问沙箱环境,这里会有为你准备好的案例代码 ^_^。[简单] 通过 Aliyun Java Initializr 创建工程并引入 Dubbo Spring Cloud(推荐)Dubbo Spring Cloud 组件的在整个 Spring Cloud Alibaba 版本和依赖最为复杂,推荐读者使用 Aliyun Java Initializr 构建应用工程。读者选择偏好的 Web 浏览器访问 Aliyun Java Initializr,其资源网址为:https://start.aliyun.com/bootstrap.html下文以 Google Chrome 浏览器为例,当网页加载后,首先,在 "项目基本信息" 部分输入 Group :"com.alibaba.cloud" 以及 Artifact:"dubbo-provider-sample"(见下图绿框部分)然而,“组件依赖” 输入框搜索:"Dubbo"(见下图红箭头部分),最后,选择 "Spring Cloud Alibaba Dubbo"(见下图红框部分),如下所示:继续依赖其他组件:Nacos Service Discovery - 服务注册与发现组件Spring Web - Spring Web MVC 组件Spring Boot Actuator - Spring Boot Actator 组件完整组件汇总如下图所示:点击 “生成” 高亮按钮,平台将生成一个名为 "dubbo-provider-sample.zip" 的压缩文件,将其保存到本地目录,并解压该文件,工程目录将随之生成。打开目录下的 pom.xml 文件,不难发现 Dubbo Spring Cloud Starter 声明其中(以下 XML 内容均来自于项目根路径中的 pom.xml 文件):XML <dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-dubbo</artifactId>
</dependency>不过该 starter 并未指定版本,具体的版本声明在 com.alibaba.cloud:spring-cloud-alibaba-dependencies 部分:XML <dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>其中,${spring-cloud-alibaba.version} 和 ${spring-boot.version} 分别为 Spring Cloud Alibaba 和 Spring Boot 组件依赖的版本,它们的版本定义在 <properties> 元素中,即 2.2.1.RELEASE 和 2.3.0.RELEASE:XML <properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.3.0.RELEASE</spring-boot.version>
<spring-cloud-alibaba.version>2.2.1.RELEASE</spring-cloud-alibaba.version>
</properties>如果读者非常熟悉 Maven 依赖管理的配置方式,可以考虑 Maven pom.xml 依赖 Dubbo Spring Cloud。[高级] 通过 Maven pom.xml 依赖 Dubbo Spring Cloud如果要在您 Dubbo Spring Cloud 的项目中使用 Nacos 来实现服务注册/发现,可将两者 Stater 同时依赖:XML <dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-dubbo</artifactId>
</dependency>该声明方式同样需要声明 com.alibaba.cloud:spring-cloud-alibaba-dependencies,内容与上小节相同,在此不再赘述。下一节将讨论如何使用 Dubbo Spring Cloud 构建服务提供者。二、使用 Dubbo Spring Cloud 实现 Dubbo 服务消费方由于 Java 服务仅为 EchoService、服务提供方应用 dubbo-provider-sample 以及 Nacos 服务器均已准备完毕。由于应用创建的步骤类似,构建消费方应用 dubbo-consumer-sample 的操作不再重复。依赖 artifact - dubbo-sample-api与服务提供方 Maven 工程类,需添加 artifact dubbo-sample-api 依赖,完整的组件 Maven 依赖:XML <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-dubbo</artifactId>
</dependency>
<!-- Dubbo 服务 artifact -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>dubbo-sample-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>配置 Dubbo 服务消费方Dubbo 服务消费方配置与服务提供方类似,当前应用 dubbo-consumer-sample 属于纯服务消费方,因此,所需的 boostrap.yaml 文件配置更精简:YAMLdubbo:
cloud:
subscribed-services: dubbo-provider-sample
spring:
cloud:
nacos:
# Nacos 服务发现与注册配置
discovery:
server-addr: 127.0.0.1:8848对比应用 dubbo-provider-sample,除应用名称 spring.application.name 存在差异外,dubbo-consumer-sample 新增了属性 dubbo.cloud.subscribed-services 的设置。并且该值为服务提供方应用 "dubbo-provider-sample"。dubbo.cloud.subscribed-services: 用于服务消费方订阅服务提供方的应用名称的列表,若需订阅多应用,使用 “,” 分割。 不推荐使用默认值为 "*",它将订阅所有应用。当应用使用属性 dubbo.cloud.subscribed-services 默认值时,日志中将会输出一行警告:Current application will subscribe all services(size:x) in registry, a lot of memory and CPU cycles may be used, thus it’s strongly recommend you using the externalized property ‘dubbo.cloud.subscribed-services’ to specify the services由于当前应用属于 Web 应用,它会默认地使用 8080 作为 Web 服务端口,如果 dubbo-provider-sample 和 dubbo-consumer-sample 在本地同步部署的话, 两者 Web 端口会出现冲突,需调整 dubbo-consumer-sample application.properties 中的 server.port 和 management.server.port:# 应用服务 WEB 访问端口
server.port=9090
# Actuator Web 访问端口
management.server.port=9091引导 Dubbo Spring Cloud 服务消费方应用为了减少实现步骤,编辑引导类 DubboConsumerSampleApplication 将 Dubbo 服务消费以及引导功能合二为一:Java@EnableDiscoveryClient
@EnableAutoConfiguration
@RestController
public class DubboConsumerSampleApplication {
@Reference
private EchoService echoService;
@GetMapping("/echo")
public String echo(String message) {
return echoService.echo(message);
}
public static void main(String[] args) {
SpringApplication.run(DubboConsumerSampleApplication.class);
}
}运行该引导类,通过curl命令访问 REST 资源/echo:Bash% curl "http://127.0.0.1:9090/echo?message=Hello,World"
[ECHO] Hello,World不难发现,Dubbo 服务提供方应用 dubbo-provider-sample 的EchoService计算结果返回到 dubbo-consumer-sample 中的 REST 资源/echo。同时,在 dubbo-provider-sample 应用日志出现了以下内容:[DUBBO] The connection of /x.x.x.x:64051 -> /x.x.x.x:20881 is established., dubbo version: 2.7.6, current host: x.x.x.x说明 Dubbo 服务消费端应用 dubbo-consumer-sample(端口:64051) 向服务提供方应用 dubbo-provider-sample 建立连接(端口:20881)。
没晒干的咸鱼
2.理论篇
俗话说,没有最好的架构,只有最合适的架构。微服务架构也是随着信息产业的发展而出现的最有普遍适用性的一套架构模式。通常来说,我们认为架构发展历史经历了这样一个过程:单体架构 -> SOA 面向服务架构 -> 微服务架构,单体架构在我们还是学生的年代,我们创建的绝大部分应用都属于单体应用。那个时候,我们几乎都是一个人在开发导师布置下来的各种实验。我们会把数据库连接、业务逻辑处理、展示逻辑等放在一起,甚至会在处理用户请求的地方直接连接数据库(多么美好的回忆啊 ^_^ )。后来,我们会学习到MVC架构以及由此衍生出来各种多层架构,由此便开启了应用的拆分之旅。多层架构的本质,是按照技术职责将应用做水平拆分,每一层解决的技术问题相对集中,层与层之间做单向依赖。这样做可以帮助我们更好的管理我们的代码,大大提升了后期的维护效率。但是,此时应用还是一个应用,部署时也是按照一个整体运行。我们看到的应用架构应该类似下面的样子:在程序规模不大,开发人员很少的时候,下面的优点是非常显著的:开发简单。单体应用的结构,天然决定了所有代码都集中在一起,开发者不需要在多个应用之间来回跳转来寻找其中的调用逻辑。测试简单。所有代码都在一个应用里,测试人员可以很方便的做到端到端的测试(当然,很多时候测试人员就是开发者自己)。部署简单。因为一个应用就是产品功能的全集,所以在部署的时候,只需要部署一款应用即可。即使是集群部署,也不会增加多少复杂度:只需要将应用部署多份即可。开发迅速。上面的各种简单,带来的就是软件功能可以快速实现。很多时候,实现需求的速度是项目成功与否的决定性因素。所以,在开发简单&独立的产品时,单体架构依然是第一优先选择。如果故事可以一直这么简单就好了。随着功能的持续增加、团队规模的不断扩大,我们很快就会发现单体应用的弊端:应用膨胀。所有代码都在一个应用里,导致应用的代码量迅速上升,对于开发者来说,经常需要在海量的代码里找到自己需要维护的哪一行,这种体验往往是令人崩溃的。同时,对于IDE来说,一个应用内大量代码也会严重拖慢其运行效率。团队合作冲突。这种冲突会体现在多个方面:开发阶段,很容易由于修改相同的代码导致代码冲突。部署阶段,又会因为“运行环境里跑的是谁的分支”而造成新的冲突。所有的这些冲突将会严重影响到团队的合作效率。运行效率&稳定性。单体应用,由于逻辑都集中在一起,启动时需要完成所有的初始化工作;同时单一功能的问题也会因为运行在一个进程内,从而导致整个应用宕机。单体架构原有的迅速、简单的优点,随着规模的扩大(功能、团队),会变得荡然无存。为了能解决这些问题,我们自然而然就会想到分而治之的办法,即将原来的单体应用拆分开来。但是应用该怎么拆分?拆分后又会有哪些新的问题产生?如何解决这些新的问题?就留给下面的 SOA 架构来解答。SOA 架构SOA 是 Service-Oriented Architecture 的简写,直译为“面向服务的架构”,从命名上就可以看出“服务”是 SOA 架构里是非常重要的概念。SOA 的核心思想是“将系统的功能解构为一系列服务”:面向服务的架构(SOA)是一个组件模型,它将应用程序的不同功能单元(称为服务)进行拆分,并通过这些服务之间定义良好的接口和协议联系起来。接口是采用中立的方式进行定义的,它应该独立于实现服务的硬件平台、操作系统和编程语言。这使得构件在各种各样的系统中的服务可以以一种统一和通用的方式进行交互。与单体架构按照技术职责进行水平拆分不同,SOA 会按照业务领域对应用进行粗粒度的垂直拆分,至于拆分到什么程度,哪些领域可以放在一起等类似问题,可以参考一下康威定理。应用从单体应用做了垂直拆分以后,就会变成一些相对独立的应用。此时,应用间的依赖、调用等相关问题自然而然的就会浮现出来。此时就需要下面这些技术方案来解决这些问题:XML - 一种标记语言,用于以文档格式描述消息中的数据。SOAP(Simple Object Access Protocol) - 在计算机网络上交换基于XML的消息的协议,通常是用HTTP。WSDL(Web Services Description Language,Web服务描述语言) - 基于XML的描述语言,用于描述与服务交互所需的服务的公共接口,协议绑定,消息格式。UDDI(Universal Description, Discovery, and Integration,是统一描述、发现和集成) - 基于XML的注册协议,用于发布WSDL并允许第三方发现这些服务。ESB(Enterprise Service Bus, 企业服务总线)- 支持异构环境中的服务、消息,以及基于事件的交互,并且具有适当的服务级别和可管理性。一个典型的 SOA 架构模式如下图:SOA 看似解决了单体架构的所有问题,世界似乎都变得更加美好了 ^_^但是....SOA 并不完美,他也有很多问题的或者说是场景下的不适应。首先就是对 SOA 的解释缺乏统一标准,上文的引用的定义也只是众多解释中使用的较为通用的一种。甚至可以这么说:一千个人眼中,有一千种 SOA 。基于此,很多厂商便借用 SOA 的大旗来推广自己的产品和标准,这又进一步加剧了问题的严重性。除此之外,SOA 还有很多其他的问题或不足:高门槛。ESB 本身就是一套非常复杂的系统,通过 ESB 落地 SOA ,对开发人员的要求很高。甚至还会需要厂商参与;厂商绑定。由于缺乏统一保准,不同厂商的解决方案之间很难做切换。不适应云环境。在如今的互联网时代,速度就是一切。由此诞生了敏捷开发、持续集成等在不同节点提升业务上线速度的办法。但是方向是不一致的。中心化。虽然应用本身实现了分布式与水平扩展,但是 ESB 却成了系统的中枢神经。微服务架构对于微服务架构,一直有一种说法,认为它是SOA架构的一种变体,或者是SOA的子集。关于这个问题,我们不去讨论他的对错(其实也没有对错之分),我们直接从这两者的区别入手来理解到底什么是微服务:通信手段、数据等的不同只是表象,其本质区别还是由于两者诞生于不同历史时期,需要解决的问题域不同。SOA 解决的核心问题是复用,而微服务解决的核心问题是扩展。关于什么是微服务,Martin Fowler 有如下的定义(更多 MartinFowler 关于微服务的内容,可以参考链接):The microservice architectural style is an approach to developing a single application as a suite of small services, each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API. These services are built around business capabilities and independently deployable by fully automated deployment machinery. There is a bare minimum of centralized management of these services, which may be written in different programming languages and use different data storage technologies.这里提到几个重要的概念:一套小服务独立进程轻量级通信协议可独立部署多语言&不同存储技术这个定义对微服务做了一个比较具象化较为易于理解的描述,通常来说我们看到的微服务架构如下图所示:但是事实上,在实际生产环境中,微服务的架构要考虑的问题远比上面的示意图复杂的多,主要包括但不限于如下问题:通过服务实现组件化根据业务组织系统做产品而不是做项目简单高效的通信协议自动化基础设施面向失败的设计具备进化能力的设计纵然有 Martin Fowler 这样的大神在前面引路,但是我们依然认为“微服务”不是一个被设计出来的架构,而是在不断尝试中总结出的一套适合在互联网行业使用的架构模式。以下的是微服务较为完整的架构图(出自 微服务架构模式)今天我们所说的“微服务”是一个庞大且复杂的概念集合,它既是一种架构模式,也是实现这种架构模式时所使用的技术方案的集合。“微服务”不是银弹微服务并不是一劳永逸的解决了所有的问题,相反的,如果不能正确的使用微服务,则有可能被微服务自身的限制拖入另一个泥潭:分布式的代价。原本在单体应用中,很多简单的问题都会在分布式环境下被几何级的放大。例如分布式事务、分布式锁、远程调用等,不光要考虑如何实现他们,相关场景的异常处理也是必须要考虑到的问题。协同代价。如果你经历过一个项目上线需要发布十几个应用,而这些应用又分别由多个团队在维护。你就能深刻的体会到协同是一件多么痛苦的事情了。服务拆分需要很强的设计功力。微服务的各种优势,其中一个重要的基础是对服务领域的正确切分。如果使用了不合适的切分粒度,或者是错误的切分方法,都会让服务不能很好的实现高内聚低耦合的要求。
没晒干的咸鱼
2.使用 Nacos Config 实现 Bean 动态刷新
Nacos Confg 支持标准 Spring Cloud @RefreshScope特性,即应用订阅某个 Nacos 配置后,当配置内容变化时,Refresh Scope Beans 中的绑定配置的属性将有条件的更新。所谓的条件是指 Bean 必须:必须条件:Bean 的声明类必须标注 @RefreshScope二选一条件:属性(非 static 字段)标注 @Value@ConfigurationPropertiesBean使用 Nacos Config 实现 Bean @Value属性动态刷新基于应用 nacos-config-sample 修改,将引导类 NacosConfigSampleApplication标注@RefreshScope和 @RestController,使得该类变为 Spring MVC REST 控制器,同时具备动态刷新能力,具体代码如下:Java@SpringBootApplication
@RestController
@RefreshScope
public class NacosConfigSampleApplication {
@Value("${user.name}")
private String userName;
@Value("${user.age}")
private int userAge;
@PostConstruct
public void init() {
System.out.printf("[init] user name : %s , age : %d%n", userName, userAge);
}
@RequestMapping("/user")
public String user() {
return String.format("[HTTP] user name : %s , age : %d", userName, userAge);
}
public static void main(String[] args) {
SpringApplication.run(NacosConfigSampleApplication.class, args);
}
}重启引导类 NacosConfigSampleApplication,控制台输出如故:[init] user name : nacos-config-sample , age : 90再通过命令行访问 REST 资源 /user:Bash% curl http://127.0.0.1:8080/user
[HTTP] user name : nacos-config-sample , age : 90如果使用沙箱环境,请直接点击应用列表的访问按钮,并在打开的浏览器窗口的地址栏中追加/user,如下图:本文中,其他的基于 http 访问的步骤类似,后面不在赘述本次请求结果中的 user name 和 age 数据与应用启动时的一致,因为此时 Nacos Server 中的配置数据没变化。随后,通过 Nacos 控制台调整 nacos-config-sample.properties 配置,将 user.age 从 90 变更为 99:点击“发布”按钮,观察应用日志变化(部分内容被省略):c.a.n.client.config.impl.ClientWorker : [fixed-127.0.0.1_8848] [data-received] dataId=nacos-config-sample.properties, group=DEFAULT_GROUP, tenant=null, md5=4a8cb29154adb9a0e897e071e1ec8d3c, content=user.name=nacos-config-sample
user.age=99, type=properties
o.s.boot.SpringApplication : Started application in 0.208 seconds (JVM running for 290.765)
o.s.c.e.event.RefreshEventListener : Refresh keys changed: [user.age]第 1 和 2 行代码是由 Nacos Client 输出,通知开发者具体的内容变化,不难发现,这里没有输出完整的配置内容,仅为变更部分,即配置 user.age。第 3 行日志似乎让 SpringApplication 重启了,不过消耗时间较短,这里暂不解释,后文将会具体讨论,只要知道这与 Bootstrap 应用上下文相关即可。最后一行日志是由 Spring Cloud 框架输出,提示开发人员具体变更的 Spring 配置 Property,可能会有多个,不过本例仅修改一处,所以显示单个。接下来,重新访问 REST 资源 /user:Bash% curl http://127.0.0.1:8080/user
[HTTP] user name : nacos-config-sample , age : 99终端日志显示了这次配置变更同步到了 @Value("${user.age}") 属性 userAge 的内容。除此之外,应用控制台也输出了以下内容[init] user name : nacos-config-sample , age : 99而该日志是由 init() 方法输出,那么是否说明该方法被框架调用了呢?答案是肯定的。既然 @PostConstruct 方法执行了,那么 @PreDestroy 方法会不会被调用呢?不妨增加 Spring Bean 销毁回调方法:Java@SpringBootApplication
@RestController
@RefreshScope
public class NacosConfigSampleApplication {
@Value("${user.name}")
private String userName;
@Value("${user.age}")
private int userAge;
@PostConstruct
public void init() {
System.out.printf("[init] user name : %s , age : %d%n", userName, userAge);
}
@PreDestroy
public void destroy() {
System.out.printf("[destroy] user name : %s , age : %d%n", userName, userAge);
}
...
}再次重启引导类 NacosConfigSampleApplication,初始化日志仍旧输出:[init] user name : nacos-config-sample , age : 99将配置 user.age 内容从 99 调整为 18,观察控制台日志变化:c.a.n.client.config.impl.ClientWorker : [fixed-127.0.0.1_8848] [data-received] dataId=nacos-config-sample.properties, group=DEFAULT_GROUP, tenant=null, md5=e25e486af432c403a16d5fc8a5aa4ab2, content=user.name=nacos-config-sample
user.age=18, type=properties
o.s.boot.SpringApplication : Started application in 0.208 seconds (JVM running for 144.467)
[destroy] user name : nacos-config-sample , age : 99
o.s.c.e.event.RefreshEventListener : Refresh keys changed: [user.age]相较于前一个版本,日志插入了 destroy() 方法输出内容,并且Bean 属性 userAge 仍旧是变更前的数据 99。随后,再次访问 REST 资源 /user,其中终端日志:Bash% curl http://127.0.0.1:8080/user
[HTTP] user name : nacos-config-sample , age : 18应用控制台日志[init] user name : nacos-config-sample , age : 18两者与前一版本并无差异,不过新版本给出了一个现象,即当 Nacos Config 接收到服务端配置变更时,对应的 @RefreshScope Bean 生命周期回调方法会被调用,并且是先销毁,然后由重新初始化。本例如此设计,无非想提醒读者,要意识到 Nacos Config 配置变更对 @RefreshScope Bean 生命周期回调方法的影响,避免出现重复初始化等操作。注: Nacos Config 配置变更调用了 Spring Cloud API ContextRefresher,该 API 会执行以上行为。同理,执行 Spring Cloud Acutator Endpoint refresh也会使用 ContextRefresher。通过上述讨论,相信读者已对 Nacos 配置变更操作相当的熟悉,后文将不再赘述相关配置。接下来继续讨论 @ConfigurationPropertiesBean 的场景。使用 Nacos Config 实现 @ConfigurationPropertiesBean 属性动态刷新在应用 nacos-config-sample 新增 User 类,并标注 @RefreshScope 和 @ConfigurationProperties,代码如下:Java@RefreshScope
@ConfigurationProperties(prefix = "user")
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}根据 @ConfigurationProperties 的定义, User 类的属性绑定到了配置属性前缀 user。下一步,调整引导类,代码如下:Java@SpringBootApplication
@RestController
@RefreshScope
@EnableConfigurationProperties(User.class)
public class NacosConfigSampleApplication {
@Value("${user.name}")
private String userName;
@Value("${user.age}")
private int userAge;
@Autowired
private User user;
@PostConstruct
public void init() {
System.out.printf("[init] user name : %s , age : %d%n", userName, userAge);
}
@PreDestroy
public void destroy() {
System.out.printf("[destroy] user name : %s , age : %d%n", userName, userAge);
}
@RequestMapping("/user")
public String user() {
return "[HTTP] " + user;
}
public static void main(String[] args) {
SpringApplication.run(NacosConfigSampleApplication.class, args);
}
}较前一个版本 NacosConfigSampleApplication实现,主要改动点:激活 @ConfigurationPropertiesBean @EnableConfigurationProperties(User.class)通过 @Autowired依赖注入 UserBean使用 user Bean( toString() 方法替换 user()中的实现下一步,重启应用后,再将 user.age 配置从 18 调整为 99,控制台日志输出符合期望[init] user name : nacos-config-sample , age : 18
......
[fixed-127.0.0.1_8848] [data-received] dataId=nacos-config-sample.properties, group=DEFAULT_GROUP, tenant=null, md5=b0f42fac52934faf69757c2b6770d39c, content=user.name=nacos-config-sample
user.age=90, type=properties
......
[destroy] user name : nacos-config-sample , age : 18
o.s.c.e.event.RefreshEventListener : Refresh keys changed: [user.age]接下来,访问 REST 资源 /user,观察终端日志输出:Bash% curl http://127.0.0.1:8080/user
[HTTP] User{name='nacos-config-sample', age=90}User Bean 属性成功地变更为 90,达到实战效果。上小节提到 Nacos Config 配置变更会影响 @RefreshScopeBean 的生命周期方法回调。同理,如果为 User 增加初始化和销毁方法的话,也会出现行文,不过本次将 User实现 Spring 标准的生命周期接口 InitializingBean 和 DisposableBean:Java@RefreshScope
@ConfigurationProperties(prefix = "user")
public class User implements InitializingBean, DisposableBean {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("[afterPropertiesSet()] " + toString());
}
@Override
public void destroy() throws Exception {
System.out.println("[destroy()] " + toString());
}
}代码调整后,重启应用,并修改配置(90 -> 19),观察控制台日志输出:Bash[init] user name : nacos-config-sample , age : 90
......
c.a.n.client.config.impl.ClientWorker : [fixed-127.0.0.1_8848] [data-received] dataId=nacos-config-sample.properties, group=DEFAULT_GROUP, tenant=null, md5=30d26411b8c1ffc1d16b3f9186db498a, content=user.name=nacos-config-sample
user.age=19, type=properties
......
[destroy()] User{name='nacos-config-sample', age=90}
[afterPropertiesSet()] User{name='nacos-config-sample', age=19}
[destroy] user name : nacos-config-sample , age : 90
......
o.s.c.e.event.RefreshEventListener : Refresh keys changed: [user.age]不难发现, UserBean 的生命周期方法不仅被调用,并且仍旧是先销毁,再初始化。那么,这个现象和之前看到的 SpringApplication重启是否有关系呢?答案也是肯定的,不过还是后文再讨论。下一小节将继续讨论怎么利用底层 Nacos 配置监听实现 Bean 属性动态刷新使用 Nacos Config 监听实现 Bean 属性动态刷新前文曾提及 com.alibaba.nacos.api.config.listener.Listener是 Nacos Client API 标准的配置监听器接口,由于仅监听配置内容,并不能直接与 Spring 体系打通,因此,需要借助于 Spring Cloud Alibaba Nacos Config API NacosConfigManager(感谢小伙伴 liaochuntao 和 zkzlx 的代码贡献),代码调整如下:Java@SpringBootApplication
@RestController
@RefreshScope
@EnableConfigurationProperties(User.class)
public class NacosConfigSampleApplication {
@Value("${user.name}")
private String userName;
@Value("${user.age}")
private int userAge;
@Autowired
private User user;
@Autowired
private NacosConfigManager nacosConfigManager;
@Bean
public ApplicationRunner runner() {
return args -> {
String dataId = "nacos-config-sample.properties";
String group = "DEFAULT_GROUP";
nacosConfigManager.getConfigService().addListener(dataId, group, new AbstractListener() {
@Override
public void receiveConfigInfo(String configInfo) {
System.out.println("[Listener] " + configInfo);
}
});
};
}
@PostConstruct
public void init() {
System.out.printf("[init] user name : %s , age : %d%n", userName, userAge);
}
@PreDestroy
public void destroy() {
System.out.printf("[destroy] user name : %s , age : %d%n", userName, userAge);
}
@RequestMapping("/user")
public String user() {
return "[HTTP] " + user;
}
public static void main(String[] args) {
SpringApplication.run(NacosConfigSampleApplication.class, args);
}
}代码主要变化:@Autowired依赖注入 NacosConfigManager新增 runner()方法,通过 NacosConfigManagerBean 获取 ConfigService,并增加了 AbstractListener( Listener抽象类)实现,监听 dataId = "nacos-config-sample.properties" 和 group = "DEFAULT_GROUP" 的配置内容重启应用,并将配置 user.age 从 19 调整到 90,观察日志变化:Bashc.a.n.client.config.impl.ClientWorker : [fixed-127.0.0.1_8848] [data-received] dataId=nacos-config-sample.properties, group=DEFAULT_GROUP, tenant=null, md5=b0f42fac52934faf69757c2b6770d39c, content=user.name=nacos-config-sample
user.age=90, type=properties
[Listener] user.name=nacos-config-sample
user.age=90
......在第 1 行日志下方,新增了监听实现代码的输出内容,不过这段内容是完整的配置,而非变化的内容。读者请务必注意其中的差异。下一步要解决的是将配置映射到 Bean 属性,此处给出一个简单的解决方案,实现步骤有两个:将 String 内容转化为 Properties 对象将 Properties 属性值设置到对应的 Bean 属性代码调整如下:Java@SpringBootApplication
@RestController
@RefreshScope
@EnableConfigurationProperties(User.class)
public class NacosConfigSampleApplication {
......
@Bean
public ApplicationRunner runner() {
return args -> {
String dataId = "nacos-config-sample.properties";
String group = "DEFAULT_GROUP";
nacosConfigManager.getConfigService().addListener(dataId, group, new AbstractListener() {
@Override
public void receiveConfigInfo(String configInfo) {
System.out.println("[Listener] " + configInfo);
System.out.println("[Before User] " + user);
Properties properties = new Properties();
try {
properties.load(new StringReader(configInfo));
String name = properties.getProperty("user.name");
int age = Integer.valueOf(properties.getProperty("user.age"));
user.setName(name);
user.setAge(age);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("[After User] " + user);
}
});
};
}
......
}重启应用,并将配置 user.age 从 90 调整到 19,观察日志变化:[Listener] user.name=nacos-config-sample
user.age= 19
[Before User] User{name='nacos-config-sample', age=90}
[After User] User{name='nacos-config-sample', age=19}上述三个例子均围绕着 Nacos Config 实现 Bean 属性动态更新,不过它们是 Spring Cloud 使用场景。如果读者的应用仅使用 Spring 或者 Spring Boot,可以考虑 Nacos Spring 工程, Github 地址:https://github.com/nacos-group/nacos-spring-project ,其中 @NacosValue 支持属性粒度的更新。除此之外,Nacos Confg 也引入了 Nacos Client 底层数据变化监听接口,即 com.alibaba.nacos.api.config.listener.Listener。下面的内容将分别讨论这三种不同的使用场景。Nacos Client:Nacos 客户端 API,也是 Nacos Config 底层依赖
没晒干的咸鱼
2.Sentinel: 高可用护航的利器
Sentinel 是阿里巴巴开源的,面向分布式服务架构的高可用防护组件,主要以流量为切入点,从流量控制、流量整形、熔断降级、系统自适应保护、热点防护等多个维度来帮助开发者保障微服务的稳定性。Sentinel 承接了阿里巴巴近 10 年的双十一大促流量的核心场景,例如秒杀、冷启动、消息削峰填谷、自适应流量控制、实时熔断下游不可用服务等,是保障微服务高可用的利器,原生支持 Java/Go/C++ 等多种语言,并且提供 Istio/Envoy 全局流控支持来为 Service Mesh 提供高可用防护的能力。Sentinel 的技术亮点:高度可扩展能力:基础核心 + SPI 接口扩展能力,用户可以方便地扩展流控、通信、监控等功能多样化的流量控制策略(资源粒度、调用关系、流控指标、流控效果等多个维度),提供分布式集群流控的能力热点流量探测和防护对不稳定服务进行熔断降级和隔离全局维度的系统负载自适应保护,根据系统水位实时调节流量覆盖 API Gateway 场景,为 Spring Cloud Gateway、Zuul 提供网关流量控制的能力实时监控和规则动态配置管理能力一些普遍的使用场景:在服务提供方(Service Provider)的场景下,我们需要保护服务提供方自身不被流量洪峰打垮。这时候通常根据服务提供方的服务能力进行流量控制,或针对特定的服务调用方进行限制。我们可以结合前期压测评估核心接口的承受能力,配置 QPS 模式的限流,当每秒的请求量超过设定的阈值时,会自动拒绝多余的请求。为了避免调用其他服务时被不稳定的服务拖垮自身,我们需要在服务调用端(Service Consumer)对不稳定服务依赖进行隔离和熔断。手段包括信号量隔离、异常比例降级、RT 降级等多种手段。当系统长期处于低水位的情况下,流量突然增加时,直接把系统拉升到高水位可能瞬间把系统压垮。这时候我们可以借助 Sentinel 的 WarmUp 流控模式控制通过的流量缓慢增加,在一定时间内逐渐增加到阈值上限,而不是在一瞬间全部放行。这样可以给冷系统一个预热的时间,避免冷系统被压垮。利用 Sentinel 的匀速排队模式进行“削峰填谷”,把请求突刺均摊到一段时间内,让系统负载保持在请求处理水位之内,同时尽可能地处理更多请求。利用 Sentinel 的网关流控特性,在网关入口处进行流量防护,或限制 API 的调用频率。Sentinel 有着丰富的开源生态。Sentinel 开源不久就被纳入 CNCF Landscape 版图,并且也成为 Spring Cloud 官方推荐的流控降级组件之一。社区提供 Spring Cloud、Dubbo、gRPC、Quarkus 等常用微服务框架的适配,开箱即用;同时支持 Reactive 生态,支持 Reactor、Spring WebFlux 异步响应式架构。Sentinel 也在逐渐覆盖 API Gateway 和 Service Mesh 场景,在云原生架构中发挥更大的作用。在原来的 Spring Cloud Netflix 系列中,有自带的熔断组件 Hystrix ,是 Netflix 公司提供的一个开源的组件,提供了熔断、隔离的这些特性,不过 Hystrix 在 2018 年 11 月份开始,就不再迭代开发,进入维护的模式。同年开源的 Spring Cloud Alibaba (SCA) 提供了一站式的解决方案,默认为 Sentinel 整合了 Spring Web、RestTemplate、FeignClient 和 Spring WebFlux。Sentinel 在 Spring Cloud 生态中,不仅补全了 Hystrix 在 Servlet、RestTemplate 和 API Gateway 这一块的空白,而且还完全兼容了 Hystrix 在 FeignClient 中限流降级的用法,并且支持运行时灵活地配置和调整限流降级规则。同时 SCA 还集成了 Sentinel 提供的 API gateway 流控模块,可以无缝支持 Spring Cloud Gateway 和 Zuul 网关的流控降级。
没晒干的咸鱼
3.快速上手-下
三、用 Dubbo Spring Cloud 构建服务提供者按照传统的 Dubbo 开发模式,在构建服务提供者之前,第一个步骤是为服务提供者和服务消费者定义 Dubbo 服务接口。为了确保契约的一致性,推荐的做法是将 Dubbo 服务接口打包在第二方或者第三方的 artifact(jar)中,该 artifact 甚至无需添加任何依赖。对于服务提供方而言,不仅通过依赖 artifact 的形式引入 Dubbo 服务接口,而且需要将其实现。对应的服务消费端,同样地需要依赖该 artifact,并以接口调用的方式执行远程方法。接下来的步骤则是创建 artifact。创建 artifact - dubbo-sample-api选择合适的文件目录,通过 Maven 命令行工具构建 artifact dubbo-sample-api,如下所示:Bashmvn archetype:generate -DgroupId=com.alibaba.cloud -DartifactId=dubbo-sample-api -Dversion=0.0.1-SNAPSHOT -DinteractiveMode=false命令执行后,名为“dubbo-sample-api” 的项目目录生成,切换至该目录,并使用 tree 命令(macOS 命令工具)预览器内部接口:% tree
.
├── pom.xml
└── src
├── main
│ └── java
│ └── com
│ └── alibaba
│ └── cloud
│ └── App.java
└── test
└── java
└── com
└── alibaba
└── cloud
└── AppTest.java
11 directories, 3 files其中,App.java 和 AppTest.java 文件并非需要文件,可将其删除。除此之外,当然最重要的是 pom.xmlXML<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.alibaba.cloud</groupId>
<artifactId>dubbo-sample-api</artifactId>
<packaging>jar</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>dubbo-sample-api</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>不难看出,Maven GAV 信息均按照之前的命令来设定,并没有依赖其他组件。接下来,为当前工程定义 Dubbo 服务接口。定义 Dubbo 服务接口Dubbo 服务接口是服务提供方与消费方的远程通讯契约,通常由普通的 Java 接口(interface)来声明,如EchoService接口:Javapackage com.alibaba.cloud;
public interface EchoService {
String echo(String message);
}该接口非常简单,仅有一个方法,接下来将 dubbo-sample-api 部署到本地 Maven 仓库。部署 artifact - dubbo-sample-api利用 Maven 命令, 将 dubbo-sample-api 部署到本地 Maven 仓库:Bash% mvn clean install
...
[INFO] BUILD SUCCESS注:如果读者所使用机器的 JDK 版本过高的话,可能会出现错误提示:"不再支持源选项 5。请使用 7 或更高版本"。本例推荐选择 JDK 8 编译。本地部署成功后,该 artifact 能被 Dubbo 服务提供者应用 dubbo-provider-sample 依赖。依赖 artifact - dubbo-sample-api将 artifact dubbo-sample-api 依赖信息添加到应用 dubbo-provider-sample 中的 pom.xml:XML <!-- Dubbo 服务 artifact -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>dubbo-sample-api</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>依赖增加之后,下一步实现 Dubbo 服务 -EchoService实现 Dubbo 服务在 应用 dubbo-provider-sample 中的 com.alibaba.cloud.dubboprovidersample 包下创建实现类:Javapublic class SimpleEchoService implements EchoService {
@Override
public String echo(String s) {
return "[ECHO] " + s;
}
}其中,@org.apache.dubbo.config.annotation.Service是 Dubbo 服务注解,仅声明该 Java 服务(本地)实现为 Dubbo 服务。 因此,下一步需要将其配置 Dubbo 服务(远程)。配置 Dubbo 服务提供方在暴露 Dubbo 服务方面,推荐开发人员外部化配置的方式,即指定 Java 服务实现类的扫描基准包。Dubbo Spring Cloud 继承了 Dubbo Spring Boot 的外部化配置特性,也可以通过标注 @DubboComponentScan 来实现基准包扫描。同时,Dubbo 远程服务需要暴露网络端口,并设定通讯协议,完整的 bootstrap.yaml 配置如下所示:YAMLdubbo:
scan:
# dubbo 服务扫描基准包
base-packages: org.springframework.cloud.alibaba.dubbo.bootstrap
protocol:
# dubbo 协议
name: dubbo
# dubbo 协议端口( -1 表示自增端口,从 20880 开始)
port: -1
spring:
cloud:
nacos:
# Nacos 服务发现与注册配置
discovery:
server-addr: 127.0.0.1:8848以上 YAML 内容,上半部分为 Dubbo 的配置:-dubbo.scan.base-packages: 指定 Dubbo 服务实现类的扫描基准包-dubbo.protocol: Dubbo 服务暴露的协议配置,其中子属性 name 为协议名称,port 为协议端口( -1 表示自增端口,从 20880 开始)下半部分则是 Spring Cloud 相关配置:-spring.application.name: Spring 应用名称,用于 Spring Cloud 服务注册和发现。该值在 Dubbo Spring Cloud 加持下被视作 dubbo.application.name,因此,无需再显示地配置 dubbo.application.name-spring.cloud.nacos.discovery: Nacos 服务发现与注册配置,其中子属性 server-addr 指定 Nacos 服务器主机和端口完成以上步骤后,还需编写一个 Dubbo Spring Cloud 引导类。引导 Dubbo Spring Cloud 服务提供方应用Dubbo Spring Cloud 引导类与普通 Spring Cloud 应用并无差别,如下所示:Java@EnableDiscoveryClient
@SpringBootApplication
public class DubboProviderSampleApplication {
public static void main(String[] args) {
SpringApplication.run(DubboProviderSampleApplication.class);
}
}在引导 DubboProviderSampleApplication 之前,请提前启动 Nacos 服务器。当DubboProviderSampleApplication 启动后,将应用 dubbo-provider-sample 将出现在 Nacos 控制台界面:当 Dubbo 服务提供方启动后,下一步实现一个 Dubbo 服务消费方。
没晒干的咸鱼
4.工具篇
Java 工程脚手架Java 工程脚手架,用于帮助开发者快速生成工程骨架。解决开发者在创建工程时的组件引入、解决版本依赖、基础配置、查询样例代码等繁琐问题。只需要简单的点点鼠标,就可以生成一套标准工程骨架。脚手架的访问地址是 https://start.aliyun.com/bootstrap.html, 打开后页面见下图:编译框架、坐标&名称、其他基础信息等,根据实际情况按需填写。当然,很多参数默认值就可以满足大部分需求。开发者重点关注的是下面 3 个部分:组件依赖很少有开发者会使用语言最原始的 sdk 来实现所有功能。通常来说,大家都会使用各种技术产品的高级封装来实现相关的技术特性。这里就需要做 2 件事情:引入对应组件的 sdk、在应用中配置组件。而通过 Java 工程脚手架就可以很轻易的完成这些工作。Java 工程脚手架中提供了 2 中寻找组件的方式:根据分类浏览&关键字搜索这里根据组件分类寻找需要使用的组件:也可以根据组件的关键字直接使用搜索功能寻找需要使用的组件:无论通过哪种方式,都可以通过组件右侧的加好实现组件的选择。应用架构在生成的工程里,代码需要根据其逻辑职责进行分层,从而获得更好的代码组织与管理效果。在这里提供了 3 种应用架构供开发者选用。None:不做任何代码分层。分层架构:标准的 4 层架构。分为 WEB层、控制器层、服务层、持久化层。本架构参考了《Java 编码规约》 的 应用分层 章节。COLA:领域驱动设计(DDD)的实现框架之一。采用了标准的六边形架构设计,并且辅之以一套灵活的扩展体系,可以有效提升复杂业务系统开发的效率。具体参考 COLA 的 GIthub工程示例代码我们为组件准备了很多使用方法的参考样例,这样开发者就不需要选择外组件以后,再去别的搜索引擎寻找相关组件的使用方法了。未选择任何组件时,是不会给出任何示例代码的。示例代码是在选择了组件依赖以后,才会出现于用户选择的组件相关的示例,如下图:由于很多案例自身也依赖其他组件,所以在选择了某个案例以后,会多出一些案例,同时依赖的组件也会增多。本次课程使用到的案例,都可以在这里寻找到。生成代码仅仅完成项目配置是不够的,最终开发者需要的是项目的代码。so, show me the code无论是出于查阅组件用法的目的,还是出于需要工程完整代码的目的,脚手架都可以很好的支持:如果仅仅需要查阅代码,而不是下载完整工程,可以直接通过点击“浏览代码”来实现。点击该按钮以后,会打开一个包含了完整代码树以及允许查看每个文件的内容窗口:如果需要获取所有代码内容,则可以通过点击“获取代码”来实现:这里提供了 2 种获取代码的途径:直接下载代码包 & 通过 git 命令 clone 工程。如果选择使用 Git 命令来 Clone 工程,需要注意一下,这个仓库地址只能下载不能上传哦。Sandbox 沙箱环境Sandbox 沙箱环境,为开发者带来一套快速上手、免除任何环境依赖、免费、便捷的开发&运行环境。允许开发者在上面查看、修改、部署示例代码,并且由平台提供相关运行资源。下面来看一下产品的界面:左边是产品的手册&说明部分。这里会包含说当前项目的功能说明、应用架构,以及如何部署和访问这些应用的操作步骤等。一些项目中使用到的技术点以及这些相关知识,也都会在这里呈现给用户。这部分文档的目的,就是方便用户去学习和理解当前的案例。右边的部分是应用列表。一个完整的产品,可能需要多个应用协同才能工作,这里就是用来陈列相关的应用列表,同时也是针对这些应用的操作入口。图片中的案例是一个任务管理器产品,功能相对简单。但是麻雀虽小五脏俱全。这个产品包含两个应用:服务端,的包含了这个任务管理器的所有业务逻辑,以及下层的持久化能力等。WEB客户端,包含了所有前端页面逻辑、与前端通信的控制器层。这两个应用通过一个注册中心来实现服务的注册&发现。最终实现一个完整的任务管理器产品。这些东西都会放到这里面。这就是一个非常典型的一个一个应用拆分的一个方式,对不对?这里的话,其实业务应用上它有两个行动点,一个是开发和访问点,开发之后就会打开一个 IDE。这里面就会有整个工程的代码。这些其实是我们预计好的,大家打开就能直接看到。如果它完全部署以後点了部署按钮,我也会直接访问到这个应用。其暴露出来的这个访问接口,我们点开发之后会看到这样一个情况。对,这个就是我们的外包i d 。开发者可以点击“开发”按钮,打开一个 WEB-IDE 来查看和修改对应应用的代码:这个 WEB-IDE 和开发者日常使用的 IDE 是一样的,都是左侧代码树,右侧代码编辑器的标准布局。即使是不熟悉这个产品的用户,也可以非常快的上手,甚至不需要学习过程。如果需要部署这个应用,只需要在“运维”功能下,点击“部署”按钮,此时只需要等待部署完成即可。在部署过程会有很多的日志输出,都可以通过“输出”窗体浏览:部署完成以后,会向 WEB-IDE 返回一个访问地址,开发者只需要点击这和地址就可以访问这个应用。下图是实际的访问效果。可以看到,两个应用,一个是任务管理器的 web 操作页面、一个是后台数据库管理页面:通过上面的步骤,开发者可以将案例快速部署起来。先部署试用,然后去学习和修改代码,最后再部署验证。通过这样的循环,可以让开发者很快学习和理解案例的功能和相关技术点。
没晒干的咸鱼
Spring Cloud Alibaba 从入门到实战:服务熔断和限流
了解微服务各模块的实现原理,熟悉 Spring Cloud Alibaba,并带领大家独立开发一个微服务应用。
没晒干的咸鱼
Spring Cloud Alibaba从入门到实战:基础知识
了解微服务各模块的实现原理,熟悉 Spring Cloud Alibaba,并带领大家独立开发一个微服务应用。
没晒干的咸鱼
Spring Cloud Alibaba 从入门到实战:分布式服务与调用
了解微服务各模块的实现原理,熟悉 Spring Cloud Alibaba,并带领大家独立开发一个微服务应用。