Effort free video editing!
Partial-lossless render any pixel format the encoder takes
WyattBluefc3ef524f4e3
diff --git a/src/ffmpeg.nim b/src/ffmpeg.nimindex 62d5e06c..248dac96 100644--- a/src/ffmpeg.nim+++ b/src/ffmpeg.nim@@ -83,7 +83,11 @@ func `$`*(pix_fmt: AVPixelFormat): string = $av_get_pix_fmt_name(pix_fmt)const AV_PIX_FMT_NONE* = AVPixelFormat(-1)const AV_PIX_FMT_YUV420P* = AVPixelFormat(0)const AV_PIX_FMT_RGB24* = AVPixelFormat(2)+const AV_PIX_FMT_YUV422P* = AVPixelFormat(4)+const AV_PIX_FMT_YUV444P* = AVPixelFormat(5)const AV_PIX_FMT_YUVJ420P* = AVPixelFormat(12)+const AV_PIX_FMT_YUVJ422P* = AVPixelFormat(13)+const AV_PIX_FMT_YUVJ444P* = AVPixelFormat(14)const AV_PIX_FMT_RGB8* = AVPixelFormat(20)const AV_PIX_FMT_RGBA* = AVPixelFormat(26)const AV_PIX_FMT_GRAY8* = AVPixelFormat(8)diff --git a/src/render/h264.nim b/src/render/h264.nimindex 9311e660..1cd8a89c 100644--- a/src/render/h264.nim+++ b/src/render/h264.nim@@ -67,8 +67,8 @@ func isAnnexB*(data: ptr uint8, size: int): bool =proc annexBToAvcC*(data: ptr uint8, size: int): seq[uint8] =## An avcC record with four-byte lengths for Annex B parameter sets, or- ## nothing without both an SPS and a PPS. Only 8-bit 4:2:0 streams reach- ## partial-lossless, so the High profiles' chroma fields are fixed.+ ## nothing without both an SPS and a PPS, or when the SPS can't be read+ ## for the chroma format and bit depths the High profiles' record ends on.let nals = annexBToLengthPrefixed(data, size)var sps, pps: seq[seq[uint8]]var pos = 0@@ -97,9 +97,21 @@ proc annexBToAvcC*(data: ptr uint8, size: int): seq[uint8] =for p in pps:result.add [uint8(p.len shr 8), uint8(p.len and 0xff)]result.add p- if sps[0][1] in [100'u8, 110, 122, 144]:- # chroma_format_idc 1, 8-bit luma and chroma, no SPS extensions- result.add [0xfd'u8, 0xf8, 0xf8, 0x00]+ if sps[0][1] notin [66'u8, 77, 88]:+ var r = rbspReader(sps[0], 4) # past the NAL header, profile and level+ try:+ discard r.ue # seq_parameter_set_id+ let chroma = r.ue+ if chroma == 3: discard r.bit+ let lumaDepth = r.ue+ let chromaDepth = r.ue+ if chroma > 3 or lumaDepth > 7 or chromaDepth > 7:+ return @[]+ # no SPS extensions+ result.add [0xfc'u8 or uint8(chroma), 0xf8'u8 or uint8(lumaDepth),+ 0xf8'u8 or uint8(chromaDepth), 0x00]+ except ValueError:+ return @[]proc annexBParameterSets*(data: ptr uint8, size: int): seq[uint8] =## The SPS and PPS NAL units of an Annex B packet, still Annex B, or@@ -121,10 +133,12 @@ proc annexBParameterSets*(data: ptr uint8, size: int): seq[uint8] =if not (sawSps and sawPps):result.setLen(0)-proc h264SupportsPartialLossless*(format: cint, header: seq[uint8]): bool =+proc h264SupportsPartialLossless*(format: cint, encoder: ptr AVCodec,+ header: seq[uint8]): bool =## `header` is the stream's extradata, or its in-band parameter sets when## it has none (MPEG-TS).- if format != AV_PIX_FMT_YUV420P.cint or header.len == 0:+ if encoder.encodeFormat(AVPixelFormat(format)) == AV_PIX_FMT_NONE or+ header.len == 0:return falselet extra = addr header[0]# Annex B sources get their samples and an avcC rewritten as they copy.diff --git a/src/render/hevc.nim b/src/render/hevc.nimindex 539015a4..6429469c 100644--- a/src/render/hevc.nim+++ b/src/render/hevc.nim@@ -80,28 +80,6 @@ proc hevcInBandParameterSets*(data: ptr uint8, size: int): seq[uint8] =result.add sets[pos + 4 ..< pos + 4 + n]pos += 4 + n-type BitReader = object- data: seq[uint8]- pos: int--proc bit(r: var BitReader): int =- if r.pos >= r.data.len * 8:- raise newException(ValueError, "SPS ends early")- result = int((r.data[r.pos shr 3] shr (7 - (r.pos and 7))) and 1)- inc r.pos--proc bits(r: var BitReader, n: int): int =- for _ in 0..<n:- result = result shl 1 or r.bit--proc ue(r: var BitReader): int =- var zeros = 0- while r.bit == 0:- inc zeros- if zeros > 31:- raise newException(ValueError, "bad Exp-Golomb code")- (1 shl zeros) - 1 + r.bits(zeros)-proc annexBToHvcC*(data: ptr uint8, size: int): seq[uint8] =## An hvcC record with four-byte lengths for Annex B parameter sets, or## nothing without a VPS, SPS and PPS. Its header fields come from the SPS.@@ -124,14 +102,7 @@ proc annexBToHvcC*(data: ptr uint8, size: int): seq[uint8] =if list.len > 0xffff or list.anyIt(it.len > 0xffff):return- var r = BitReader()- var zeros = 0- for b in sps[2 .. ^1]: # drop emulation prevention bytes- if zeros >= 2 and b == 3:- zeros = 0- else:- zeros = (if b == 0: zeros + 1 else: 0)- r.data.add b+ var r = rbspReader(sps, 2)if r.data.len < 13:returntry:@@ -214,7 +185,8 @@ proc hevcSupportsPartialLossless*(format: cint, encoder: ptr AVCodec,header: seq[uint8]): bool =## `header` is the stream's extradata, or its in-band parameter sets when## it has none (MPEG-TS).- if not encoder.encoderSupports(AVPixelFormat(format)) or header.len == 0:+ if encoder.encodeFormat(AVPixelFormat(format)) == AV_PIX_FMT_NONE or+ header.len == 0:return falselet extra = addr header[0]# Annex B sources get their samples and an hvcC rewritten as they copy.diff --git a/src/render/partialplan.nim b/src/render/partialplan.nimindex e7740550..4db619d6 100644--- a/src/render/partialplan.nim+++ b/src/render/partialplan.nim@@ -108,15 +108,13 @@ proc supportsStream(input: InputContainer, stream: ptr AVStream,encoder: ptr AVCodec, codecId: AVCodecID): bool =let pixelFormat = AVPixelFormat(stream.codecpar.format)if codecId == ID_H264:- h264SupportsPartialLossless(stream.codecpar.format,+ h264SupportsPartialLossless(stream.codecpar.format, encoder,sourceHeader(input, stream, codecId))elif codecId == ID_HEVC:hevcSupportsPartialLossless(stream.codecpar.format, encoder,sourceHeader(input, stream, codecId))- elif codecId == ID_VP9:- pixelFormat == AV_PIX_FMT_YUV420P- elif codecId == ID_AV1:- encoder.encoderSupports(pixelFormat)+ elif codecId == ID_VP9 or codecId == ID_AV1:+ encoder.encodeFormat(pixelFormat) != AV_PIX_FMT_NONEelse:false@@ -263,11 +261,13 @@ proc initPartialEncoder(video: VideoSettings, par: ptr AVCodecParameters,var (_, encoder) = initEncoder(video.codec)encoder.width = par.widthencoder.height = par.height- encoder.pix_fmt = AVPixelFormat(par.format)+ encoder.pix_fmt = encoder.codec.encodeFormat(AVPixelFormat(par.format))encoder.time_base = frameTbencoder.framerate = fpsencoder.sample_aspect_ratio = par.sample_aspect_ratio- encoder.color_range = par.color_range+ encoder.color_range =+ if encoder.pix_fmt == AVPixelFormat(par.format): par.color_range+ else: 2 # AVCOL_RANGE_JPEG, which the source's format said by nameencoder.color_primaries = par.color_primariesencoder.color_trc = par.color_trcencoder.colorspace = par.color_space@@ -519,6 +519,11 @@ proc makePartialLossless*(output: var OutputContainer, tl: v3, video: VideoSetti# A WebCodecs decoder hands over whatever layout the browser# picked (NV12 from hardware decoders), while the encoder was# opened for the stream's own format.+ if AVPixelFormat(frame.format).limitedTwin == encoder.pix_fmt:+ # The same planes under the name the encoder takes; converting+ # would squeeze them into limited range.+ frame.format = encoder.pix_fmt.cint+ frame.color_range = encoder.color_rangesrc = frame.reformat(encoder.pix_fmt)if lastDecoded != nil:av_frame_free(addr lastDecoded)diff --git a/src/render/smart.nim b/src/render/smart.nimindex f4548178..19c339a2 100644--- a/src/render/smart.nim+++ b/src/render/smart.nim@@ -129,6 +129,56 @@ proc encoderSupports*(encoder: ptr AVCodec, format: AVPixelFormat): bool =inc ifalse+func limitedTwin*(format: AVPixelFormat): AVPixelFormat =+ ## The format with a full-range one's planes, which leaves the range to+ ## `color_range`, or none for any other format.+ if format == AV_PIX_FMT_YUVJ420P: AV_PIX_FMT_YUV420P+ elif format == AV_PIX_FMT_YUVJ422P: AV_PIX_FMT_YUV422P+ elif format == AV_PIX_FMT_YUVJ444P: AV_PIX_FMT_YUV444P+ else: AV_PIX_FMT_NONE++proc encodeFormat*(encoder: ptr AVCodec, format: AVPixelFormat): AVPixelFormat =+ ## The format `encoder` takes a source's `format` frames in without+ ## converting them, or none. Hardware encoders don't list the full-range+ ## formats, but take full-range frames under the plain format's name.+ if encoder.encoderSupports(format): format+ elif encoder.encoderSupports(format.limitedTwin): format.limitedTwin+ else: AV_PIX_FMT_NONE++type BitReader* = object+ data*: seq[uint8]+ pos*: int++func rbspReader*(nal: openArray[uint8], header: int): BitReader =+ ## Reads a NAL unit's payload, past its `header` bytes, without the+ ## emulation prevention bytes.+ var zeros = 0+ for i in header ..< nal.len:+ let b = nal[i]+ if zeros >= 2 and b == 3:+ zeros = 0+ else:+ zeros = (if b == 0: zeros + 1 else: 0)+ result.data.add b++proc bit*(r: var BitReader): int =+ if r.pos >= r.data.len * 8:+ raise newException(ValueError, "SPS ends early")+ result = int((r.data[r.pos shr 3] shr (7 - (r.pos and 7))) and 1)+ inc r.pos++proc bits*(r: var BitReader, n: int): int =+ for _ in 0..<n:+ result = result shl 1 or r.bit++proc ue*(r: var BitReader): int =+ var zeros = 0+ while r.bit == 0:+ inc zeros+ if zeros > 31:+ raise newException(ValueError, "bad Exp-Golomb code")+ (1 shl zeros) - 1 + r.bits(zeros)+# --- Annex B <-> four-byte-length NAL conversion, shared by H.264 and HEVC ---func startCodeLen*(data: ptr UncheckedArray[uint8], size, pos: int): int =