Skip to content

Commit

Permalink
Add CBR mode and max-rate, buf-size config options to x264
Browse files Browse the repository at this point in the history
  • Loading branch information
sergystepanov committed Oct 18, 2024
1 parent 0ab6f58 commit 003eb5b
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
7 changes: 7 additions & 0 deletions pkg/config/config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -300,8 +300,15 @@ encoder:
threads: 0
# see: https://trac.ffmpeg.org/wiki/Encode/H.264
h264:
# crf, cbr
mode: crf
# Constant Rate Factor (CRF) 0-51 (default: 23)
crf: 23
# Rate control options
# set the maximum bitrate
maxRate: 0
# set the expected client buffer size
bufSize: 0
# ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow, placebo
preset: superfast
# baseline, main, high, high10, high422, high444
Expand Down
3 changes: 3 additions & 0 deletions pkg/config/worker.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,10 @@ type Video struct {
Codec string
Threads int
H264 struct {
Mode string
Crf uint8
MaxRate int
BufSize int
LogLevel int32
Preset string
Profile string
Expand Down
23 changes: 22 additions & 1 deletion pkg/encoder/h264/x264.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ import "C"

import (
"fmt"
"strings"
"unsafe"
)

Expand All @@ -77,11 +78,16 @@ type H264 struct {
}

type Options struct {
Mode string
// Constant Rate Factor (CRF)
// This method allows the encoder to attempt to achieve a certain output quality for the whole file
// when output file size is of less importance.
// The range of the CRF scale is 0–51, where 0 is lossless, 23 is the default, and 51 is the worst quality possible.
Crf uint8
Crf uint8
// vbv-maxrate
MaxRate int
// vbv-bufsize
BufSize int
LogLevel int32
// ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow, placebo.
Preset string
Expand All @@ -100,6 +106,7 @@ func NewEncoder(w, h int, th int, opts *Options) (encoder *H264, err error) {

if opts == nil {
opts = &Options{
Mode: "crf",
Crf: 23,
Tune: "zerolatency",
Preset: "superfast",
Expand Down Expand Up @@ -144,9 +151,23 @@ func NewEncoder(w, h int, th int, opts *Options) (encoder *H264, err error) {
if th != 1 {
param.b_sliced_threads = 1
}

param.rc.i_rc_method = C.X264_RC_CRF
param.rc.f_rf_constant = C.float(opts.Crf)

if strings.ToLower(opts.Mode) == "cbr" {
param.rc.i_rc_method = C.X264_RC_ABR
param.i_nal_hrd = C.X264_NAL_HRD_CBR
}

if opts.MaxRate > 0 {
param.rc.i_bitrate = C.int(opts.MaxRate)
param.rc.i_vbv_max_bitrate = C.int(opts.MaxRate)
}
if opts.BufSize > 0 {
param.rc.i_vbv_buffer_size = C.int(opts.BufSize)
}

h264 := C.h264_new(&param)
if h264 == nil {
return nil, fmt.Errorf("x264: cannot open the encoder")
Expand Down

0 comments on commit 003eb5b

Please sign in to comment.