diff --git a/av/codec/hwaccel.pxd b/av/codec/hwaccel.pxd index 7d3b88356..2c1544882 100644 --- a/av/codec/hwaccel.pxd +++ b/av/codec/hwaccel.pxd @@ -1,4 +1,5 @@ cimport libav as lib +from libc.stdbool cimport bool as c_bool cdef class HWConfig: @@ -22,5 +23,5 @@ cdef class HWAccel: cdef int _device_type cdef readonly int device_id cdef public int flags - cdef readonly bint is_hw_owned - cdef public bint allow_software_fallback + cdef readonly c_bool is_hw_owned + cdef public c_bool allow_software_fallback diff --git a/av/filter/context.pxd b/av/filter/context.pxd index fa58fe95a..bd265a525 100644 --- a/av/filter/context.pxd +++ b/av/filter/context.pxd @@ -1,4 +1,5 @@ cimport libav as lib +from libc.stdbool cimport bool as c_bool from av.filter.filter cimport Filter from av.filter.graph cimport Graph @@ -8,7 +9,7 @@ cdef class FilterContext: cdef lib.AVFilterContext *ptr cdef readonly Graph graph cdef readonly Filter filter - cdef bint inited + cdef c_bool inited cdef unsigned char _kind diff --git a/av/video/frame.pxd b/av/video/frame.pxd index ab1f19df5..4caf67a87 100644 --- a/av/video/frame.pxd +++ b/av/video/frame.pxd @@ -1,4 +1,5 @@ cimport libav as lib +from libc.stdbool cimport bool as c_bool from libc.stdint cimport uint8_t, uintptr_t from av.frame cimport Frame @@ -8,8 +9,8 @@ from av.video.reformatter cimport VideoReformatter cdef class CudaContext: cdef readonly int device_id - cdef readonly bint primary_ctx - cdef readonly bint current_ctx + cdef readonly c_bool primary_ctx + cdef readonly c_bool current_ctx cdef readonly uintptr_t cuda_stream cdef lib.AVBufferRef* _device_ref cdef dict _frames_cache diff --git a/tests/test_codec_context.py b/tests/test_codec_context.py index f866db30e..f492700c1 100644 --- a/tests/test_codec_context.py +++ b/tests/test_codec_context.py @@ -128,7 +128,11 @@ def test_skip_frame_default(self) -> None: def test_codec_delay(self) -> None: with av.open(fate_suite("mkv/codec_delay_opus.mkv")) as container: - assert container.streams.audio[0].cctx.delay == 312 + cctx = container.streams.audio[0].cctx + assert cctx.initial_padding == 312 + # Since FFmpeg 9.1 the decoder sets delay itself when opened. + cctx.open() + assert cctx.delay == 312 with av.open(fate_suite("h264/interlaced_crop.mp4")) as container: assert container.streams.video[0].cctx.delay == 0 diff --git a/tools/pxdpad/src/layout.nim b/tools/pxdpad/src/layout.nim index 38cbc922e..a39af40f2 100644 --- a/tools/pxdpad/src/layout.nim +++ b/tools/pxdpad/src/layout.nim @@ -99,6 +99,16 @@ proc sizeOfType*(r: Resolver, typeName: string, ptrDepth, arrayLen: int): if arrayLen < 0: return (0, 0, false) (base.size * arrayLen, base.align, true) +proc isBint*(r: Resolver, f: FieldDecl): bool = + ## A `bint` held by value, seen through any ctypedef aliases. + if f.ptrDepth > 0: return false + var name = simpleName(f.typeName) + var hops = 0 + while r.aliases.hasKey(name) and hops < 8: + name = simpleName(r.aliases[name]) + inc hops + name == "bint" + proc baseOfClass(r: Resolver, a: Aggregate): tuple[size, align: int, ok: bool] = if a.base.len == 0: return (r.target.headSize, r.target.ptrAlign, true) @@ -130,14 +140,18 @@ proc classBase(r: Resolver, a: Aggregate): tuple[size, align: int, ok, vtab: boo (size, align, b.ok, vtab) proc layoutFields(r: Resolver, a: Aggregate, fields: seq[FieldDecl], - baseSize, baseAlign: int, collectHoles: bool): Layout = + baseSize, baseAlign: int, collectHoles: bool, + narrowBint = false): Layout = result.baseSize = baseSize result.align = max(1, baseAlign) result.complete = true var offset = baseSize for f in fields: - let sz = r.sizeOfType(f.typeName, f.ptrDepth, f.arrayLen) + # Cython lowers `bint` to a 4-byte int, but a flag fits in a byte. + let sz: tuple[size, align: int, ok: bool] = + if narrowBint and f.arrayLen >= 0 and r.isBint(f): (f.arrayLen, 1, true) + else: r.sizeOfType(f.typeName, f.ptrDepth, f.arrayLen) if not sz.ok: result.complete = false result.unresolved.add f.name & ": " & f.typeName & @@ -181,11 +195,11 @@ proc layoutAgg*(r: Resolver, a: Aggregate): Layout = func orderKey(f: LaidField): (int, int) = (-f.align, -f.size) -proc sizeUnder*(r: Resolver, a: Aggregate, order: seq[FieldDecl]): - tuple[size: int, ok: bool] = +proc sizeUnder*(r: Resolver, a: Aggregate, order: seq[FieldDecl], + narrowBint = false): tuple[size: int, ok: bool] = ## What this aggregate would measure with its fields in the given order. let b = r.classBase(a) - let lay = r.layoutFields(a, order, b.size, b.align, false) + let lay = r.layoutFields(a, order, b.size, b.align, false, narrowBint) (lay.size, lay.complete and b.ok) proc optimize*(r: Resolver, a: Aggregate, lay: Layout): tuple[size: int, order: seq[FieldDecl]] = @@ -196,10 +210,24 @@ proc optimize*(r: Resolver, a: Aggregate, lay: Layout): tuple[size: int, order: sorted.sort(proc (x, y: LaidField): int = cmp(orderKey(x), orderKey(y))) (r.sizeUnder(a, sorted.mapIt(it.decl)).size, sorted.mapIt(it.decl)) +proc narrowedSize*(r: Resolver, a: Aggregate, lay: Layout): int = + ## The best size with every `bint` field cut to one byte, or 0 when there is + ## no `bint` field or the layout is incomplete. + if not lay.complete or not lay.fields.anyIt(r.isBint(it.decl)): return 0 + var order = lay.fields + if a.kind != akUnion and not a.packed: + for f in order.mitems: + if r.isBint(f.decl): + f.align = 1 + f.size = f.decl.arrayLen + order.sort(proc (x, y: LaidField): int = cmp(orderKey(x), orderKey(y))) + r.sizeUnder(a, order.mapIt(it.decl), narrowBint = true).size + proc analyze*(r: Resolver, a: Aggregate): Finding = let lay = r.layoutAgg(a) let opt = r.optimize(a, lay) - Finding(agg: a, layout: lay, optimalSize: opt.size, order: opt.order) + Finding(agg: a, layout: lay, optimalSize: opt.size, order: opt.order, + narrowedSize: r.narrowedSize(a, lay)) func names(order: seq[FieldDecl]): seq[string] = order.mapIt(it.name) @@ -209,12 +237,14 @@ proc analyzeAll*(resolvers: seq[Resolver], a: Aggregate): Report = ## poor on LLP64 is not a fix; the candidates are each ABI's own best order ## plus the declared one, scored by their total size everywhere. result.agg = a + if resolvers.len > 0: + result.bints = a.fields.filterIt(resolvers[0].isBint(it)).mapIt(it.name) var candidates = @[a.fields] for r in resolvers: let f = r.analyze(a) result.results.add TargetResult(target: r.target.name, layout: f.layout, optimalSize: f.optimalSize, suggested: f.layout.size, - unresolved: f.layout.unresolved) + narrowed: f.narrowedSize, unresolved: f.layout.unresolved) if not f.layout.complete: continue inc result.sized if a.kind == akUnion or a.packed: continue diff --git a/tools/pxdpad/src/main.nim b/tools/pxdpad/src/main.nim index d4101cb74..16769b55d 100644 --- a/tools/pxdpad/src/main.nim +++ b/tools/pxdpad/src/main.nim @@ -20,6 +20,9 @@ is 4 bytes on 64-bit Windows, and pointers are 4 bytes on 32-bit. A .pxd has one field order for all of them, so the suggested order is the one that measures smallest across every ABI checked, not the best for any single one. +A `bint` is lowered to a 4-byte int, though a flag needs only one byte, so the +bytes a `bint` field costs over a 1-byte type count as waste too. + Options: -t, --target:NAMES restrict to these ABIs, comma-separated. One of $2 @@ -95,7 +98,8 @@ proc sig(t: TargetResult): string = ## Two ABIs are worth one row when they measure the type identically. lp64 and ## darwin-arm64 differ only in `long double`, so they usually collapse. if not t.layout.complete: return "n/a" - result = $t.layout.size & "/" & $t.suggested & "/" & $t.layout.align + result = $t.layout.size & "/" & $t.suggested & "/" & $t.narrowed & "/" & + $t.layout.align for h in t.layout.holes: result.add "|" & $h.offset & ":" & $h.size @@ -124,14 +128,14 @@ proc describe(rep: Report, opts: Options, color: bool): string = let t = rep.results[0] result.add " — " & $t.layout.size & " bytes" if waste > 0: - result.add ", " & red & $waste & " wasted" & off & " (" & $t.suggested & + result.add ", " & red & $waste & " wasted" & off & " (" & $t.best & " optimal)" result.add "\n" else: let groups = grouped(rep) var worstGroup = 0 for i, g in groups: - if g.res.wasted > groups[worstGroup].res.wasted: worstGroup = i + if g.res.totalWaste > groups[worstGroup].res.totalWaste: worstGroup = i if waste > 0: result.add " — " & red & $waste & " bytes wasted" & off & " on " & groups[worstGroup].label & "\n" @@ -141,9 +145,9 @@ proc describe(rep: Report, opts: Options, color: bool): string = for g in groups: if not g.res.layout.complete: cells.add g.label & " " & dim & "n/a" & off - elif g.res.wasted > 0: + elif g.res.totalWaste > 0: cells.add g.label & " " & $g.res.layout.size & red & "→" & - $g.res.suggested & off + $g.res.best & off else: cells.add g.label & " " & $g.res.layout.size result.add " " & cells.join(" ") & "\n" @@ -151,7 +155,7 @@ proc describe(rep: Report, opts: Options, color: bool): string = # Holes differ per ABI; show them for the one with the most to gain. var worst = 0 for i, t in rep.results: - if t.wasted > rep.results[worst].wasted: worst = i + if t.totalWaste > rep.results[worst].totalWaste: worst = i let lay = rep.results[worst].layout if lay.holes.len > 0: if not single: @@ -162,6 +166,18 @@ proc describe(rep: Report, opts: Options, color: bool): string = result.add " padding on " & label & ":\n" result.add holeLines(lay) + var bintWaste = 0 + for t in rep.results: bintWaste = max(bintWaste, t.bintWaste) + if bintWaste > 0: + result.add " " & rep.bints.mapIt("`" & it & "`").join(", ") & + (if rep.bints.len == 1: " is a 4-byte bint" else: " are 4-byte bints") & + "; at 1 byte: " + if single: + result.add $rep.results[0].narrowed & " bytes\n" + else: + result.add grouped(rep).filterIt(it.res.layout.complete) + .mapIt(it.label & " " & $it.res.narrowed).join("; ") & "\n" + if rep.changed and not opts.noSuggest: result.add " suggested order" if single: diff --git a/tools/pxdpad/src/model.nim b/tools/pxdpad/src/model.nim index 71071ecd2..8cbc753b9 100644 --- a/tools/pxdpad/src/model.nim +++ b/tools/pxdpad/src/model.nim @@ -57,12 +57,14 @@ type layout*: Layout optimalSize*: int order*: seq[FieldDecl] ## fields in the suggested order + narrowedSize*: int ## best size with `bint` fields as 1 byte, 0 if none TargetResult* = object target*: string layout*: Layout optimalSize*: int ## best this ABI could do on its own suggested*: int ## what the shared suggested order costs here + narrowed*: int ## best size with `bint` fields as 1 byte, 0 if none unresolved*: seq[string] Report* = object @@ -71,6 +73,7 @@ type agg*: Aggregate results*: seq[TargetResult] order*: seq[FieldDecl] + bints*: seq[string] ## `bint` fields that could be a single byte changed*: bool ## the suggestion differs from the declared order sized*: int ## how many targets could be measured @@ -83,14 +86,27 @@ func wasted*(t: TargetResult): int = ## What the suggested order would actually save on this ABI. if t.layout.complete: t.layout.size - t.suggested else: 0 +func bintWaste*(f: Finding): int = + ## What narrowing `bint` fields to one byte saves beyond reordering. + if f.narrowedSize > 0: max(0, f.optimalSize - f.narrowedSize) else: 0 + +func bintWaste*(t: TargetResult): int = + ## What narrowing `bint` fields to one byte saves beyond the suggested order. + if t.layout.complete and t.narrowed > 0: max(0, t.suggested - t.narrowed) + else: 0 + +func totalWaste*(t: TargetResult): int = t.wasted + t.bintWaste + +func best*(t: TargetResult): int = t.layout.size - t.totalWaste + func worstWaste*(r: Report): int = - for t in r.results: result = max(result, t.wasted) + for t in r.results: result = max(result, t.totalWaste) func worstTarget*(r: Report): string = var worst = -1 for t in r.results: - if t.wasted > worst: - worst = t.wasted + if t.totalWaste > worst: + worst = t.totalWaste result = t.target func isArray*(f: FieldDecl): bool = diff --git a/tools/pxdpad/src/parser.nim b/tools/pxdpad/src/parser.nim index a06617a07..98691901a 100644 --- a/tools/pxdpad/src/parser.nim +++ b/tools/pxdpad/src/parser.nim @@ -265,6 +265,14 @@ proc parseFile*(path, src: string, pr: var ParseResult) = let opensBlock = text.endsWith(":") let inExtern = stack.anyIt(it.kind == ckExtern) + # `from libc.stdbool cimport bool as c_bool` + if w.len >= 4 and w[0] == "from" and w[2] == "cimport": + for item in text[text.find("cimport") + 7 .. ^1].strip(chars = {' ', '(', ')'}).split(','): + let parts = item.splitWhitespace() + if parts.len == 3 and parts[1] == "as" and parts[0] != parts[2]: + pr.aliases[parts[2]] = parts[0] + continue + # `cdef extern from "libavutil/x.h" nogil:` if w.len >= 3 and w[0] == "cdef" and w[1] == "extern": stack.add Ctx(kind: ckExtern, indent: ll.indent, agg: -1) diff --git a/tools/pxdpad/tests/test_pxdpad.nim b/tools/pxdpad/tests/test_pxdpad.nim index d3fd77d6f..f2dda2ee9 100644 --- a/tools/pxdpad/tests/test_pxdpad.nim +++ b/tools/pxdpad/tests/test_pxdpad.nim @@ -344,6 +344,8 @@ cdef class HWConfig: """) check f["HWAccel"].layout.size == 80 check f["HWAccel"].wasted == 0 + check f["HWAccel"].narrowedSize == 72 # the two bints as 1 byte each + check f["HWAccel"].bintWaste == 8 check f["HWConfig"].layout.size == 40 # head + vtab + __weakref__ + ptr check f["HWConfig"].layout.vtab @@ -362,6 +364,78 @@ cdef class C: check f.order[0].name == "p" check f.order[^1].name == "tag" +suite "bint": + test "a bint costs 3 bytes over a 1-byte flag": + let f = analyze(""" +cdef struct S: + void *p + bint a + bint b +""")["S"] + check f.layout.size == 16 + check f.wasted == 0 + check f.narrowedSize == 16 # 8 + 2, rounded up to 8: no gain here + check f.bintWaste == 0 + + test "bint waste is reported once it crosses an alignment boundary": + let f = analyze(""" +cdef struct S: + void *p + int n + bint a + bint b +""")["S"] + check f.layout.size == 24 + check f.narrowedSize == 16 # 8 + 4 + 1 + 1, rounded up to 8 + check f.bintWaste == 8 + + test "bint through a ctypedef and in arrays": + let f = analyze(""" +ctypedef bint flag_t +cdef struct S: + void *p + flag_t f[4] +""")["S"] + check f.layout.size == 24 + check f.narrowedSize == 16 + check f.bintWaste == 8 + + test "bint waste counts toward the report": + let r = analyzeMulti(""" +cdef class C: + cdef void *p + cdef int n + cdef bint a + cdef bint b +""", @["lp64", "ilp32"])["C"] + check r.bints == @["a", "b"] + check not r.changed + check r.results[0].bintWaste == 8 # 40 -> 32 + check r.results[1].bintWaste == 4 # 24 -> 20 + check r.worstWaste == 8 + check r.worstTarget == "lp64" + + test "a cimported C bool is one byte": + let f = analyze(""" +from libc.stdbool cimport bool as c_bool +cdef class C: + cdef void *p + cdef int n + cdef c_bool a + cdef c_bool b +""")["C"] + check f.layout.size == 32 + check f.narrowedSize == 0 + check f.bintWaste == 0 + + test "a pointer to bint is not narrowed": + let f = analyze(""" +cdef struct S: + bint *p +""")["S"] + check f.narrowedSize == 0 + check f.bintWaste == 0 + suite "across ABIs": test "a layout clean on lp64 can have a hole on llp64": # `long` is 8 bytes on lp64 and 4 on 64-bit Windows, so this packs on one