|
1 | 1 | //! A video's frames to GLM5-Next vision patches as transformers 5.19's Glm5NextVideoProcessor makes them from PyAV's. |
2 | 2 | const std = @import("std"); |
3 | 3 | const picture = @import("../../core/picture/picture.zig"); |
4 | | -const vision = @import("vision.zig"); |
5 | | - |
6 | | -pub const Error = error{ VideoTooShort, VideoTooLarge, BadVideo, OutOfMemory }; |
7 | | - |
8 | | -/// The processor's frame rate and sampling cap. |
9 | | -pub const sample_fps = 2.0; |
10 | | - |
11 | | -/// A decoded video's facts (the PyAV loader's VideoMetadata) and its frames on request. |
12 | | -pub const Source = struct { |
13 | | - frames: u64, // the stream's frame count |
14 | | - rate_num: u64, // its average frame rate, num / den |
15 | | - rate_den: u64, |
16 | | - width: u32, |
17 | | - height: u32, |
18 | | - ctx: *anyopaque, |
19 | | - /// The frames at `indices` (ascending, distinct), each handed to `sink` in order as RGB rows `stride` bytes apart. |
20 | | - decode: *const fn (ctx: *anyopaque, indices: []const u32, sink: *Sink) anyerror!void, |
21 | | - |
22 | | - fn fps(s: Source) f64 { |
23 | | - return @as(f64, @floatFromInt(s.rate_num)) / @as(f64, @floatFromInt(s.rate_den)); |
24 | | - } |
25 | | - |
26 | | - /// total / fps as the loader computes it from the Fraction: the exact ratio, rounded once. |
27 | | - fn duration(s: Source) f64 { |
28 | | - return @as(f64, @floatFromInt(s.frames * s.rate_den)) / @as(f64, @floatFromInt(s.rate_num)); |
29 | | - } |
30 | | -}; |
31 | | - |
32 | | -/// Where decoded frames go: each resized into its slot of the canvas. |
33 | | -pub const Sink = struct { |
34 | | - plan: *const Plan, |
35 | | - frames: []u8, // [n, content_h, content_w, 3] |
36 | | - scratch: std.mem.Allocator, |
37 | | - got: usize = 0, |
38 | | - |
39 | | - /// Frame `k` of the plan, `w` x `h` RGB rows `stride` bytes apart. |
40 | | - pub fn take(s: *Sink, k: usize, rgb: []const u8, w: u32, h: u32, stride: usize) Error!void { |
41 | | - const p = s.plan; |
42 | | - if (k != s.got or k >= p.indices.len or w != p.width or h != p.height) return error.BadVideo; |
43 | | - const dst = s.frames[k * p.frameBytes() ..][0..p.frameBytes()]; |
44 | | - const frame: picture.resample.View = .{ .pixels = rgb, .width = w, .height = h, .stride = stride }; |
45 | | - // torchvision's uint8 resize |
46 | | - try picture.resample.into(s.scratch, .torch, frame, p.content_w, p.content_h, dst); |
47 | | - s.got += 1; |
48 | | - } |
49 | | -}; |
50 | | - |
51 | | -/// What a video becomes before any frame is decoded: the frames to decode and the canvas they land on. |
52 | | -pub const Plan = struct { |
53 | | - indices: []u32, // distinct, ascending: the frames decoded |
54 | | - times: []f64, // one a pair: the pair's first sampled frame's index over the rate (metadata.timestamps[::2]) |
55 | | - width: u32, |
56 | | - height: u32, |
57 | | - target_h: u32, |
58 | | - target_w: u32, |
59 | | - content_h: u32, |
60 | | - content_w: u32, |
61 | | - |
62 | | - fn frameBytes(p: Plan) usize { |
63 | | - return @as(usize, p.content_h) * p.content_w * 3; |
64 | | - } |
65 | | - |
66 | | - pub fn pairs(p: Plan) usize { |
67 | | - return (p.indices.len + 1) / 2; |
68 | | - } |
69 | | - |
70 | | - pub fn tokensPerPair(p: Plan) u32 { |
71 | | - return (p.target_h / vision.patch) * (p.target_w / vision.patch) / vision.patches_per_token; |
72 | | - } |
73 | | -}; |
74 | | - |
75 | | -/// numpy.linspace(start, stop, num, dtype=int): the float steps, the last exactly stop, truncated toward zero. |
76 | | -fn linspace(a: std.mem.Allocator, start: f64, stop: f64, num: usize) ![]u32 { |
77 | | - const out = try a.alloc(u32, num); |
78 | | - const step = if (num > 1) (stop - start) / @as(f64, @floatFromInt(num - 1)) else 0; |
79 | | - for (out, 0..) |*v, i| { |
80 | | - var y = if (num > 1 and step == 0) start else @as(f64, @floatFromInt(i)) * step + start; |
81 | | - if (num > 1 and i == num - 1) y = stop; |
82 | | - v.* = @intFromFloat(@trunc(y)); |
83 | | - } |
84 | | - return out; |
85 | | -} |
86 | | - |
87 | | -/// Python's round(): halves to even. |
88 | | -fn pyRound(x: f64) f64 { |
89 | | - if (@abs(x - @trunc(x)) == 0.5) return 2.0 * @round(x / 2.0); |
90 | | - return @round(x); |
91 | | -} |
92 | | - |
93 | | -/// Glm5NextVideoProcessor.sample_frames on the loader's metadata: distinct indices (its even-count pad decoded once). |
94 | | -pub fn sample(a: std.mem.Allocator, s: Source, max_frames: u32) Error![]u32 { |
95 | | - if (s.frames == 0 or s.rate_num == 0 or s.rate_den == 0) return error.BadVideo; |
96 | | - const total = s.frames; |
97 | | - const fps = s.fps(); |
98 | | - var duration = s.duration(); |
99 | | - if (duration == 0) duration = pyRound(@as(f64, @floatFromInt(total - 1)) / fps) + 1; |
100 | | - const max_seconds: f64 = @trunc(duration); |
101 | | - var extract_t: u64 = @intFromFloat(@trunc(duration * sample_fps)); |
102 | | - extract_t = @min(extract_t, max_frames); |
103 | | - if (extract_t == 0) return error.VideoTooShort; // the processor samples nothing and the loader fails |
104 | | - var picked: std.ArrayList(u32) = .empty; |
105 | | - defer picked.deinit(a); |
106 | | - var indices: []u32 = undefined; |
107 | | - if (total < extract_t) { |
108 | | - indices = try linspace(a, 0, @floatFromInt(total - 1), extract_t); |
109 | | - } else { |
110 | | - const per_frame = 1.0 / fps; |
111 | | - const inv: f64 = 1.0 / sample_fps; |
112 | | - var current: f64 = 0; |
113 | | - for (0..total) |i| { |
114 | | - if (@as(f64, @floatFromInt(i)) * per_frame >= current) { |
115 | | - current += inv; |
116 | | - try picked.append(a, @intCast(i)); |
117 | | - if (current >= max_seconds) break; |
118 | | - } |
119 | | - } |
120 | | - if (picked.items.len < extract_t) { |
121 | | - const start: f64 = if (picked.items.len == 0) 0 else @floatFromInt(picked.items[0]); |
122 | | - const end: f64 = if (picked.items.len == 0) |
123 | | - @floatFromInt(total - 1) |
124 | | - else |
125 | | - @floatFromInt(picked.items[picked.items.len - 1]); |
126 | | - indices = try linspace(a, start, end, extract_t); |
127 | | - } else if (picked.items.len > extract_t) { |
128 | | - indices = try linspace(a, 0, @floatFromInt(total - 1), extract_t); |
129 | | - } else indices = try a.dupe(u32, picked.items); |
130 | | - } |
131 | | - // the order kept, repeats dropped (linspace's are adjacent, the loop's ascending) |
132 | | - var n: usize = 0; |
133 | | - for (indices) |v| { |
134 | | - if (n > 0 and indices[n - 1] == v) continue; |
135 | | - indices[n] = v; |
136 | | - n += 1; |
137 | | - } |
138 | | - return indices[0..n]; |
139 | | -} |
140 | | - |
141 | | -/// The processor's smart_resize: a canvas in multiples of 28, aspect kept, whose frame pairs fit min..max tokens. |
142 | | -pub fn canvas(frames: u64, height: u32, width: u32, min_tokens: u64, max_tokens: u64) Error![2]u32 { |
143 | | - const factor: u64 = vision.patch * vision.merge; |
144 | | - const per_token = vision.temporal * factor * factor; |
145 | | - const min_pixels = min_tokens * per_token; |
146 | | - const max_pixels = max_tokens * per_token; |
147 | | - const align_ = struct { |
148 | | - fn f(v: u64, by: u64) u64 { |
149 | | - return std.math.divCeil(u64, v, by) catch unreachable; |
150 | | - } |
151 | | - }.f; |
152 | | - const frames_f: f64 = @floatFromInt(frames); |
153 | | - const aligned_frames: u64 = @max( |
154 | | - vision.temporal, |
155 | | - @as(u64, @intFromFloat(pyRound(frames_f / vision.temporal))) * vision.temporal, |
156 | | - ); |
157 | | - var ah = align_(height, factor) * factor; |
158 | | - var aw = align_(width, factor) * factor; |
159 | | - if (aligned_frames * ah * aw < min_pixels) { |
160 | | - const scale = @sqrt(@as(f64, @floatFromInt(min_pixels)) / |
161 | | - (frames_f * @as(f64, @floatFromInt(height)) * @as(f64, @floatFromInt(width)))); |
162 | | - ah = align_(@max(1, @as(u64, @intFromFloat(@ceil(@as(f64, @floatFromInt(height)) * scale)))), factor) * factor; |
163 | | - aw = align_(@max(1, @as(u64, @intFromFloat(@ceil(@as(f64, @floatFromInt(width)) * scale)))), factor) * factor; |
164 | | - } |
165 | | - if (aligned_frames * ah * aw > max_pixels) { |
166 | | - if (max_pixels < aligned_frames * factor * factor) return error.VideoTooLarge; |
167 | | - var low: i64 = 1; |
168 | | - var high: i64 = height; |
169 | | - var best_h: u64 = factor; |
170 | | - var best_w: u64 = factor; |
171 | | - while (low <= high) { |
172 | | - const ch: u64 = @intCast(@divFloor(low + high, 2)); |
173 | | - const cw: u64 = @max(1, @as(u64, @intFromFloat(@floor(@as(f64, @floatFromInt(width)) * |
174 | | - @as(f64, @floatFromInt(ch)) / @as(f64, @floatFromInt(height)))))); |
175 | | - const th = align_(ch, factor) * factor; |
176 | | - const tw = align_(cw, factor) * factor; |
177 | | - if (aligned_frames * th * tw <= max_pixels) { |
178 | | - best_h = th; |
179 | | - best_w = tw; |
180 | | - low = @as(i64, @intCast(ch)) + 1; |
181 | | - } else high = @as(i64, @intCast(ch)) - 1; |
182 | | - } |
183 | | - ah = best_h; |
184 | | - aw = best_w; |
185 | | - } |
186 | | - return .{ @intCast(ah), @intCast(aw) }; |
187 | | -} |
188 | | - |
189 | | -/// What `s` becomes at most `max_tokens` tokens and `max_frames` sampled frames: the frames to decode and the canvas. |
190 | | -pub fn plan(a: std.mem.Allocator, s: Source, c: vision.Config, max_tokens: u32, max_frames: u32) Error!Plan { |
191 | | - const indices = try sample(a, s, max_frames); |
192 | | - const n: u64 = indices.len; // the frames decoded: the processor's num_frames |
193 | | - const t = try canvas(n, s.height, s.width, @min(c.min_tokens, max_tokens), max_tokens); |
194 | | - const per_token: u64 = vision.temporal * (vision.patch * vision.merge) * (vision.patch * vision.merge); |
195 | | - const hf: f64 = @floatFromInt(s.height); |
196 | | - const wf: f64 = @floatFromInt(s.width); |
197 | | - var scale = @min(@as(f64, @floatFromInt(t[0])) / hf, @as(f64, @floatFromInt(t[1])) / wf); |
198 | | - if (n * s.height * s.width >= per_token * c.min_tokens) scale = @min(1.0, scale); |
199 | | - const content_h: u32 = @intCast(@max(1, @min(t[0], @as(u64, @intFromFloat(@floor(hf * scale)))))); |
200 | | - const content_w: u32 = @intCast(@max(1, @min(t[1], @as(u64, @intFromFloat(@floor(wf * scale)))))); |
201 | | - // metadata.timestamps[::2] over the sampled indices, the even-making duplicate among them |
202 | | - const pairs = (indices.len + 1) / 2; |
203 | | - const times = try a.alloc(f64, pairs); |
204 | | - for (times, 0..) |*v, g| v.* = @as(f64, @floatFromInt(indices[2 * g])) / s.fps(); |
205 | | - return .{ |
206 | | - .indices = indices, |
207 | | - .times = times, |
208 | | - .width = s.width, |
209 | | - .height = s.height, |
210 | | - .target_h = t[0], |
211 | | - .target_w = t[1], |
212 | | - .content_h = content_h, |
213 | | - .content_w = content_w, |
214 | | - }; |
215 | | -} |
216 | | - |
217 | | -/// One pair of frames ready for the tower, and the video's. |
218 | | -pub const Pair = struct { pixels: []f32, gh: u32, gw: u32, tokens: u32, hash: u64 }; |
219 | | -pub const Prepared = struct { groups: []Pair, times: []f64 }; |
220 | | - |
221 | | -/// `s` decoded, resized as it decodes, then normalized and cut into pairs (allocated in `a`). |
222 | | -pub fn prepare(a: std.mem.Allocator, s: Source, c: vision.Config, max_tokens: u32, max_frames: u32) anyerror!Prepared { |
223 | | - const p = try plan(a, s, c, max_tokens, max_frames); |
224 | | - const frames = try a.alloc(u8, p.indices.len * p.frameBytes()); |
225 | | - var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator); |
226 | | - defer arena.deinit(); |
227 | | - var sink: Sink = .{ .plan = &p, .frames = frames, .scratch = arena.allocator() }; |
228 | | - try s.decode(s.ctx, p.indices, &sink); |
229 | | - if (sink.got != p.indices.len) return error.BadVideo; |
230 | | - return .{ .groups = try patchify(a, p, frames, c.mean, c.std), .times = p.times }; |
231 | | -} |
232 | | - |
233 | | -/// Frames padded black to the canvas, normalized as the fused rescale, odd last repeated, pairs cut into 2x2 windows. |
234 | | -pub fn patchify(a: std.mem.Allocator, p: Plan, frames: []const u8, mean: [3]f32, sd: [3]f32) Error![]Pair { |
235 | | - const P = vision.patch; |
236 | | - const M = vision.merge; |
237 | | - const gh = p.target_h / P; |
238 | | - const gw = p.target_w / P; |
239 | | - var m255: [3]f32 = undefined; |
240 | | - var s255: [3]f32 = undefined; |
241 | | - const by: f32 = @floatCast(@as(f64, 1.0) / (@as(f64, 1.0) / 255.0)); |
242 | | - for (0..3) |ch| { |
243 | | - m255[ch] = mean[ch] * by; |
244 | | - s255[ch] = sd[ch] * by; |
245 | | - } |
246 | | - const n = p.indices.len; |
247 | | - const out = try a.alloc(Pair, p.pairs()); |
248 | | - for (out, 0..) |*pair, g| { |
249 | | - const px = try a.alloc(f32, @as(usize, gh) * gw * vision.patch_width); |
250 | | - var row: usize = 0; |
251 | | - for (0..gh / M) |wy| for (0..gw / M) |wx| for (0..M) |my| for (0..M) |mx| { |
252 | | - const py0 = (wy * M + my) * P; |
253 | | - const px0 = (wx * M + mx) * P; |
254 | | - const dst = px[row * vision.patch_width ..][0..vision.patch_width]; |
255 | | - for (0..3) |ch| for (0..vision.temporal) |t| { |
256 | | - const f = @min(2 * g + t, n - 1); |
257 | | - const frame = frames[f * p.frameBytes() ..][0..p.frameBytes()]; |
258 | | - for (0..P) |dy| for (0..P) |dx| { |
259 | | - const y = py0 + dy; |
260 | | - const x = px0 + dx; |
261 | | - const v: u8 = if (y < p.content_h and x < p.content_w) frame[(y * p.content_w + x) * 3 + ch] else 0; |
262 | | - dst[((ch * vision.temporal + t) * P + dy) * P + dx] = |
263 | | - (@as(f32, @floatFromInt(v)) - m255[ch]) / s255[ch]; |
264 | | - }; |
265 | | - }; |
266 | | - row += 1; |
267 | | - }; |
268 | | - const id = picture.identity.withGrid(picture.identity.ofBytes(0x71de0, std.mem.sliceAsBytes(px)), .{ gh, gw }); |
269 | | - pair.* = .{ .pixels = px, .gh = gh, .gw = gw, .tokens = gh * gw / vision.patches_per_token, .hash = id }; |
270 | | - } |
271 | | - return out; |
272 | | -} |
273 | | - |
274 | | -/// Python's f"{t:.1f} seconds": one decimal, an exact tie rounded to even. |
275 | | -pub fn seconds(buf: []u8, t: f64) ![]const u8 { |
276 | | - // t * 10 exactly from the double's bits, rounded once, ties to even (no 128-bit floats: no compiler-rt is linked) |
277 | | - const bits: u64 = @bitCast(@abs(t)); |
278 | | - const biased: i32 = @intCast(bits >> 52); |
279 | | - const m: u64 = (bits & ((@as(u64, 1) << 52) - 1)) | (if (biased == 0) 0 else @as(u64, 1) << 52); |
280 | | - const e: i32 = (if (biased == 0) 1 else biased) - 1075; |
281 | | - const x = m * 10; // under 2^57 |
282 | | - var r: u64 = 0; |
283 | | - if (e >= 0) { |
284 | | - r = x << @intCast(@min(e, 6)); // times past 2^56 seconds are not times |
285 | | - } else if (e > -64) { |
286 | | - const s: u6 = @intCast(-e); |
287 | | - const q = x >> s; |
288 | | - const rem = x & ((@as(u64, 1) << s) - 1); |
289 | | - const half = @as(u64, 1) << (s - 1); |
290 | | - r = q + @intFromBool(rem > half or (rem == half and q & 1 == 1)); |
291 | | - } |
292 | | - return std.fmt.bufPrint(buf, "{d}.{d} seconds", .{ r / 10, r % 10 }); |
293 | | -} |
| 4 | +const steps = @import("video_core.zig").For(picture); |
| 5 | + |
| 6 | +pub const Error = steps.Error; |
| 7 | +pub const sample_fps = steps.sample_fps; |
| 8 | +pub const Source = steps.Source; |
| 9 | +pub const Sink = steps.Sink; |
| 10 | +pub const Plan = steps.Plan; |
| 11 | +pub const sample = steps.sample; |
| 12 | +pub const canvas = steps.canvas; |
| 13 | +pub const plan = steps.plan; |
| 14 | +pub const Pair = steps.Pair; |
| 15 | +pub const Prepared = steps.Prepared; |
| 16 | +pub const prepare = steps.prepare; |
| 17 | +pub const patchify = steps.patchify; |
| 18 | +pub const seconds = steps.seconds; |
294 | 19 |
|
295 | 20 | test "sampling as Glm5NextVideoProcessor.sample_frames, then the loader's distinct frames" { |
296 | 21 | var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); |
|
0 commit comments