Archived
radiance 1.0.0
This commit is contained in:
commit
ae74a8aebf
616 files changed
+338692
No files matched your search
@@ -0,0 +1,30 @@
|
||||
/* item.cpp -- the parts of an Item the step path uses, in a unit of their own. The batch builder
|
||||
* links against this and nothing else in core/mm, so a test that fakes the device layer does not
|
||||
* pull the processor -- and through its metadata reader, the real device layer -- in with it. */
|
||||
#include "mm/processor.h"
|
||||
|
||||
namespace rad {
|
||||
namespace mm {
|
||||
|
||||
void Item::coords(int64_t first, int64_t count, int32_t* planes) const {
|
||||
/* Merge-block order inverted: a patch's index within its segment is
|
||||
* ((block_row * blocks_w + block_col) * merge + in_row) * merge + in_col. */
|
||||
const int64_t seg = (int64_t)grid_h * grid_w;
|
||||
const int32_t merge = grid_h / rows_h;
|
||||
const int64_t bw = grid_w / merge;
|
||||
for (int64_t k = 0; k < count; ++k) {
|
||||
const int64_t within = (first + k) % seg;
|
||||
const int64_t in_col = within % merge;
|
||||
const int64_t in_row = (within / merge) % merge;
|
||||
const int64_t blk = within / (merge * merge);
|
||||
const int64_t row = (blk / bw) * merge + in_row;
|
||||
const int64_t col = (blk % bw) * merge + in_col;
|
||||
planes[k] = (int32_t)row;
|
||||
planes[count + k] = (int32_t)col;
|
||||
planes[2 * count + k] = grid_h;
|
||||
planes[3 * count + k] = grid_w;
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace mm */
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,366 @@
|
||||
/* media.cpp -- image and video decoding through libavformat / libavcodec / libswscale. */
|
||||
#include "mm/media.h"
|
||||
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
|
||||
#ifdef RAD_HAVE_FFMPEG
|
||||
extern "C" {
|
||||
#include <libavcodec/avcodec.h>
|
||||
#include <libavformat/avformat.h>
|
||||
#include <libavutil/imgutils.h>
|
||||
#include <libavutil/opt.h>
|
||||
#include <libswscale/swscale.h>
|
||||
}
|
||||
#endif
|
||||
|
||||
namespace rad {
|
||||
namespace mm {
|
||||
|
||||
#ifndef RAD_HAVE_FFMPEG
|
||||
|
||||
bool decoder_available() { return false; }
|
||||
|
||||
static int no_decoder(std::string* why) {
|
||||
if (why) *why = "this build has no media decoder: it was configured without libavformat / "
|
||||
"libavcodec / libswscale (RAD_WITH_FFMPEG)";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
int decode_image(const uint8_t*, size_t, int64_t, Frame*, std::string* why) {
|
||||
return no_decoder(why);
|
||||
}
|
||||
int decode_video(const uint8_t*, size_t, SampleFn, const void*, int64_t, Video*,
|
||||
std::string* why) {
|
||||
return no_decoder(why);
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
bool decoder_available() { return true; }
|
||||
|
||||
namespace {
|
||||
|
||||
/* THE DEMUXERS A REQUEST MAY REACH, and nothing else. A container format that can name another
|
||||
* file -- a playlist, a concat script, an image sequence pattern -- would otherwise let a request
|
||||
* make the server open a path of its choosing, so the probe only ever considers these, and the
|
||||
* protocol list below is empty so none of them can open anything either. */
|
||||
constexpr const char* kFormats =
|
||||
"mov,mp4,m4a,3gp,3g2,mj2,matroska,webm,avi,mpegts,flv,ogg,gif,apng,image2pipe,png_pipe,"
|
||||
"jpeg_pipe,jpegls_pipe,jpegxl_pipe,webp_pipe,bmp_pipe,tiff_pipe,qoi_pipe,pgm_pipe,ppm_pipe,"
|
||||
"pbm_pipe,pam_pipe,gif_pipe,avif,heif";
|
||||
|
||||
struct MemIO {
|
||||
const uint8_t* p = nullptr;
|
||||
size_t n = 0;
|
||||
size_t at = 0;
|
||||
};
|
||||
|
||||
int mem_read(void* opaque, uint8_t* buf, int size) {
|
||||
MemIO* m = static_cast<MemIO*>(opaque);
|
||||
const size_t left = m->n - m->at;
|
||||
if (left == 0) return AVERROR_EOF;
|
||||
const size_t k = std::min(left, (size_t)size);
|
||||
std::memcpy(buf, m->p + m->at, k);
|
||||
m->at += k;
|
||||
return (int)k;
|
||||
}
|
||||
|
||||
int64_t mem_seek(void* opaque, int64_t off, int whence) {
|
||||
MemIO* m = static_cast<MemIO*>(opaque);
|
||||
if (whence & AVSEEK_SIZE) return (int64_t)m->n;
|
||||
int64_t base = 0;
|
||||
switch (whence & ~AVSEEK_FORCE) {
|
||||
case SEEK_SET: base = 0; break;
|
||||
case SEEK_CUR: base = (int64_t)m->at; break;
|
||||
case SEEK_END: base = (int64_t)m->n; break;
|
||||
default: return AVERROR(EINVAL);
|
||||
}
|
||||
const int64_t to = base + off;
|
||||
if (to < 0 || to > (int64_t)m->n) return AVERROR(EINVAL);
|
||||
m->at = (size_t)to;
|
||||
return to;
|
||||
}
|
||||
|
||||
std::string averr(int e) {
|
||||
char b[AV_ERROR_MAX_STRING_SIZE] = {};
|
||||
av_strerror(e, b, sizeof b);
|
||||
return b;
|
||||
}
|
||||
|
||||
/* One opened input over a memory buffer: the demuxer, its best video stream and a decoder for it.
|
||||
* Every libav object is released in the destructor, so an early return anywhere leaks nothing. */
|
||||
struct Input {
|
||||
MemIO io;
|
||||
AVIOContext* avio = nullptr;
|
||||
AVFormatContext* fmt = nullptr;
|
||||
AVCodecContext* dec = nullptr;
|
||||
int stream = -1;
|
||||
|
||||
~Input() {
|
||||
if (dec) avcodec_free_context(&dec);
|
||||
if (fmt) avformat_close_input(&fmt);
|
||||
if (avio) {
|
||||
av_freep(&avio->buffer);
|
||||
avio_context_free(&avio);
|
||||
}
|
||||
}
|
||||
|
||||
int open(const uint8_t* data, size_t n, bool want_decoder, std::string* why) {
|
||||
io.p = data; io.n = n; io.at = 0;
|
||||
constexpr int kBuf = 64 * 1024;
|
||||
uint8_t* buf = static_cast<uint8_t*>(av_malloc(kBuf));
|
||||
if (!buf) { *why = "out of memory"; return RAD_E_NOMEM; }
|
||||
avio = avio_alloc_context(buf, kBuf, 0, &io, mem_read, nullptr, mem_seek);
|
||||
if (!avio) { av_free(buf); *why = "out of memory"; return RAD_E_NOMEM; }
|
||||
fmt = avformat_alloc_context();
|
||||
if (!fmt) { *why = "out of memory"; return RAD_E_NOMEM; }
|
||||
fmt->pb = avio;
|
||||
fmt->flags |= AVFMT_FLAG_CUSTOM_IO;
|
||||
AVDictionary* opts = nullptr;
|
||||
av_dict_set(&opts, "format_whitelist", kFormats, 0);
|
||||
av_dict_set(&opts, "protocol_whitelist", "", 0);
|
||||
int e = avformat_open_input(&fmt, nullptr, nullptr, &opts);
|
||||
av_dict_free(&opts);
|
||||
if (e < 0) {
|
||||
fmt = nullptr; /* freed by a failed open */
|
||||
*why = "not a recognised image or video format (" + averr(e) + ")";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
e = avformat_find_stream_info(fmt, nullptr);
|
||||
if (e < 0) { *why = "could not read the stream headers (" + averr(e) + ")"; return RAD_E_INVAL; }
|
||||
const AVCodec* codec = nullptr;
|
||||
stream = av_find_best_stream(fmt, AVMEDIA_TYPE_VIDEO, -1, -1, &codec, 0);
|
||||
if (stream < 0 || !codec) { *why = "no picture in it: the media holds no video stream"; return RAD_E_INVAL; }
|
||||
if (!want_decoder) return RAD_OK;
|
||||
dec = avcodec_alloc_context3(codec);
|
||||
if (!dec) { *why = "out of memory"; return RAD_E_NOMEM; }
|
||||
e = avcodec_parameters_to_context(dec, fmt->streams[stream]->codecpar);
|
||||
if (e < 0) { *why = "decoder setup failed (" + averr(e) + ")"; return RAD_E_INVAL; }
|
||||
/* A few threads a decode: this runs on a server worker, one per request in flight, so
|
||||
* handing each one every core would oversubscribe the machine the engine runs on. */
|
||||
dec->thread_count = 4;
|
||||
e = avcodec_open2(dec, codec, nullptr);
|
||||
if (e < 0) { *why = std::string("no decoder for ") + codec->name + " (" + averr(e) + ")"; return RAD_E_UNSUPPORTED; }
|
||||
return RAD_OK;
|
||||
}
|
||||
};
|
||||
|
||||
/* One decoded frame to packed RGB24 at its own size. The YUV coefficients and range are the
|
||||
* frame's own, so a BT.709 video and a full-range JPEG both come out with the colours they were
|
||||
* encoded with; ACCURATE_RND and FULL_CHR_H_INT keep the conversion from truncating and from
|
||||
* sampling chroma at half resolution. */
|
||||
int to_rgb(const AVFrame* f, SwsContext** sws, Frame* out, std::string* why) {
|
||||
const AVPixelFormat src = (AVPixelFormat)f->format;
|
||||
*sws = sws_getCachedContext(*sws, f->width, f->height, src, f->width, f->height,
|
||||
AV_PIX_FMT_RGB24,
|
||||
SWS_BICUBIC | SWS_ACCURATE_RND | SWS_FULL_CHR_H_INT, nullptr,
|
||||
nullptr, nullptr);
|
||||
if (!*sws) { *why = "no colour conversion from this pixel format"; return RAD_E_UNSUPPORTED; }
|
||||
int cs = f->colorspace;
|
||||
if (cs == AVCOL_SPC_UNSPECIFIED || cs == AVCOL_SPC_RGB) cs = AVCOL_SPC_BT470BG;
|
||||
const int* coef = sws_getCoefficients(cs);
|
||||
const int src_full = f->color_range == AVCOL_RANGE_JPEG ||
|
||||
src == AV_PIX_FMT_YUVJ420P || src == AV_PIX_FMT_YUVJ422P ||
|
||||
src == AV_PIX_FMT_YUVJ444P || src == AV_PIX_FMT_YUVJ440P;
|
||||
sws_setColorspaceDetails(*sws, coef, src_full, sws_getCoefficients(SWS_CS_DEFAULT), 1, 0,
|
||||
1 << 16, 1 << 16);
|
||||
out->w = f->width;
|
||||
out->h = f->height;
|
||||
out->rgb.resize((size_t)f->width * (size_t)f->height * 3);
|
||||
uint8_t* dst[4] = { out->rgb.data(), nullptr, nullptr, nullptr };
|
||||
int dst_ls[4] = { f->width * 3, 0, 0, 0 };
|
||||
const int e = sws_scale(*sws, f->data, f->linesize, 0, f->height, dst, dst_ls);
|
||||
if (e != f->height) { *why = "colour conversion failed"; return RAD_E_INVAL; }
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* THE DECODE LOOP, for both kinds: every frame in presentation order, `keep(i, frame)` told the
|
||||
* index of each and whether to stop.
|
||||
*
|
||||
* AN EMPTY PACKET REPEATS THE FRAME BEFORE IT: it is how Ogg Theora stores a frame that does not
|
||||
* change. Sent to a decoder, an empty packet would read as the end of the stream and the next one
|
||||
* would be refused; it is passed to `keep` as another copy of the last frame instead, so the
|
||||
* frame indices and the stream's length are the ones the frame count promised. */
|
||||
template <class Keep>
|
||||
int decode_frames(Input& in, Keep&& keep, std::string* why) {
|
||||
AVPacket* pkt = av_packet_alloc();
|
||||
AVFrame* frm = av_frame_alloc();
|
||||
AVFrame* last = av_frame_alloc();
|
||||
if (!pkt || !frm || !last) {
|
||||
av_packet_free(&pkt);
|
||||
av_frame_free(&frm);
|
||||
av_frame_free(&last);
|
||||
*why = "out of memory";
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
int64_t idx = 0;
|
||||
int st = RAD_OK;
|
||||
bool done = false, flushing = false;
|
||||
while (!done && st >= 0) {
|
||||
if (!flushing) {
|
||||
const int r = av_read_frame(in.fmt, pkt);
|
||||
if (r == AVERROR_EOF) {
|
||||
flushing = true;
|
||||
avcodec_send_packet(in.dec, nullptr);
|
||||
} else if (r < 0) {
|
||||
*why = "demuxing failed (" + averr(r) + ")";
|
||||
st = RAD_E_INVAL;
|
||||
break;
|
||||
} else {
|
||||
if (pkt->stream_index != in.stream) { av_packet_unref(pkt); continue; }
|
||||
if (pkt->size == 0) {
|
||||
av_packet_unref(pkt);
|
||||
if (!last->buf[0]) continue;
|
||||
const int k = keep(idx++, last);
|
||||
if (k < 0) { st = k; break; }
|
||||
if (k > 0) done = true;
|
||||
continue;
|
||||
}
|
||||
const int s = avcodec_send_packet(in.dec, pkt);
|
||||
av_packet_unref(pkt);
|
||||
if (s < 0 && s != AVERROR(EAGAIN)) {
|
||||
*why = "decoding failed (" + averr(s) + ")";
|
||||
st = RAD_E_INVAL;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (;;) {
|
||||
const int r = avcodec_receive_frame(in.dec, frm);
|
||||
if (r == AVERROR(EAGAIN)) break;
|
||||
if (r == AVERROR_EOF) { done = true; break; }
|
||||
if (r < 0) {
|
||||
*why = "decoding failed (" + averr(r) + ")";
|
||||
st = RAD_E_INVAL;
|
||||
break;
|
||||
}
|
||||
const int k = keep(idx++, frm);
|
||||
av_frame_unref(last);
|
||||
av_frame_move_ref(last, frm);
|
||||
if (k < 0) { st = k; break; }
|
||||
if (k > 0) { done = true; break; }
|
||||
}
|
||||
}
|
||||
av_packet_free(&pkt);
|
||||
av_frame_free(&frm);
|
||||
av_frame_free(&last);
|
||||
return st;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int decode_image(const uint8_t* data, size_t n, int64_t max_pixels, Frame* out, std::string* why) {
|
||||
std::string w;
|
||||
if (!why) why = &w;
|
||||
if (!data || n == 0) { *why = "empty"; return RAD_E_INVAL; }
|
||||
Input in;
|
||||
RAD_TRY(in.open(data, n, true, why));
|
||||
const AVCodecParameters* cp = in.fmt->streams[in.stream]->codecpar;
|
||||
if (cp->width <= 0 || cp->height <= 0) { *why = "the image has no size"; return RAD_E_INVAL; }
|
||||
if ((int64_t)cp->width * cp->height > max_pixels) {
|
||||
*why = "the image is " + std::to_string(cp->width) + "x" + std::to_string(cp->height) +
|
||||
", over the server's " + std::to_string(max_pixels) + "-pixel limit for a source";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
SwsContext* sws = nullptr;
|
||||
bool got = false;
|
||||
const int s = decode_frames(in, [&](int64_t, const AVFrame* f) -> int {
|
||||
const int c = to_rgb(f, &sws, out, why);
|
||||
if (c < 0) return c;
|
||||
got = true;
|
||||
return 1;
|
||||
}, why);
|
||||
sws_freeContext(sws);
|
||||
if (s < 0) return s;
|
||||
if (!got) { *why = "the image decoded to no frame"; return RAD_E_INVAL; }
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* user,
|
||||
int64_t max_pixels, Video* out, std::string* why) {
|
||||
std::string w;
|
||||
if (!why) why = &w;
|
||||
if (!data || n == 0) { *why = "empty"; return RAD_E_INVAL; }
|
||||
|
||||
/* THE FRAME COUNT FIRST, because which frames to keep depends on it. Many containers state it;
|
||||
* those that do not are demuxed once without decoding, which counts packets -- one a frame for
|
||||
* every codec a request is going to send -- at the cost of reading the bytes twice. */
|
||||
VideoInfo info;
|
||||
{
|
||||
Input probe;
|
||||
RAD_TRY(probe.open(data, n, false, why));
|
||||
const AVStream* st = probe.fmt->streams[probe.stream];
|
||||
info.w = st->codecpar->width;
|
||||
info.h = st->codecpar->height;
|
||||
AVRational r = st->avg_frame_rate;
|
||||
if (r.num <= 0 || r.den <= 0) r = st->r_frame_rate;
|
||||
info.fps = (r.num > 0 && r.den > 0) ? av_q2d(r) : 0.0;
|
||||
info.n_frames = st->nb_frames;
|
||||
if (info.n_frames <= 0) {
|
||||
AVPacket* pkt = av_packet_alloc();
|
||||
if (!pkt) { *why = "out of memory"; return RAD_E_NOMEM; }
|
||||
int64_t c = 0;
|
||||
while (av_read_frame(probe.fmt, pkt) >= 0) {
|
||||
if (pkt->stream_index == probe.stream) ++c;
|
||||
av_packet_unref(pkt);
|
||||
}
|
||||
av_packet_free(&pkt);
|
||||
info.n_frames = c;
|
||||
}
|
||||
}
|
||||
if (info.w <= 0 || info.h <= 0) { *why = "the video has no size"; return RAD_E_INVAL; }
|
||||
if ((int64_t)info.w * info.h > max_pixels) {
|
||||
*why = "the video is " + std::to_string(info.w) + "x" + std::to_string(info.h) +
|
||||
", over the server's " + std::to_string(max_pixels) + "-pixel limit for a frame";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (info.n_frames <= 0) { *why = "the video holds no frames"; return RAD_E_INVAL; }
|
||||
|
||||
out->info = info;
|
||||
out->index = sample(info, user);
|
||||
if (out->index.empty()) { *why = "no frames were sampled"; return RAD_E_INVAL; }
|
||||
out->frames.assign(out->index.size(), Frame{});
|
||||
|
||||
Input in;
|
||||
RAD_TRY(in.open(data, n, true, why));
|
||||
SwsContext* sws = nullptr;
|
||||
size_t next = 0;
|
||||
int64_t last_kept = -1;
|
||||
const int s = decode_frames(in, [&](int64_t i, const AVFrame* f) -> int {
|
||||
if ((int64_t)f->width * f->height > max_pixels) {
|
||||
*why = "a frame is larger than the server's pixel limit";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The same frame may be sampled twice when the stream is shorter than its own header
|
||||
* says; each slot that names this index takes a copy. */
|
||||
bool converted = false;
|
||||
while (next < out->index.size() && out->index[next] == i) {
|
||||
if (!converted) {
|
||||
const int c = to_rgb(f, &sws, &out->frames[next], why);
|
||||
if (c < 0) return c;
|
||||
converted = true;
|
||||
} else {
|
||||
out->frames[next] = out->frames[next - 1];
|
||||
}
|
||||
last_kept = (int64_t)next;
|
||||
++next;
|
||||
}
|
||||
return next >= out->index.size() ? 1 : 0;
|
||||
}, why);
|
||||
sws_freeContext(sws);
|
||||
if (s < 0) return s;
|
||||
if (last_kept < 0) { *why = "the video decoded to no frame"; return RAD_E_INVAL; }
|
||||
/* A STREAM SHORTER THAN ITS HEADER leaves the last sampled indices unreached. They take the
|
||||
* last frame that was decoded, which is what a reader that clamps an index past the end
|
||||
* returns. */
|
||||
for (size_t k = next; k < out->index.size(); ++k) out->frames[k] = out->frames[(size_t)last_kept];
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
#endif /* RAD_HAVE_FFMPEG */
|
||||
|
||||
} /* namespace mm */
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,60 @@
|
||||
/* media.h -- turning the bytes of an image or a video into RGB frames (spec §11).
|
||||
*
|
||||
* ONE DECODER FOR BOTH, and it is libavformat/libavcodec. An image is a one-frame stream to it, so
|
||||
* PNG, JPEG, WebP, GIF, BMP and TIFF arrive through the same demuxer probe and the same decode loop
|
||||
* a video takes, and there is one colour conversion (libswscale) rather than one per format. A
|
||||
* build without the libraries has no decoder at all: every call here returns RAD_E_UNSUPPORTED
|
||||
* with the reason, and the server refuses a media part by name rather than guessing at its bytes.
|
||||
*
|
||||
* THE BYTES COME FROM THE REQUEST, never from a URL. The server accepts `data:` URLs only, so
|
||||
* nothing here opens a file or a network stream: the demuxer reads a memory buffer through its own
|
||||
* I/O context, and the protocol whitelist is empty.
|
||||
*
|
||||
* WHAT A FRAME IS: packed 8-bit RGB, row-major, no padding. An alpha channel is DROPPED, not
|
||||
* composited -- the reference processor converts with PIL's convert("RGB"), which does the same,
|
||||
* so a transparent PNG reaches the encoder with the colours under its alpha.
|
||||
*/
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace mm {
|
||||
|
||||
struct Frame {
|
||||
int32_t w = 0, h = 0;
|
||||
std::vector<uint8_t> rgb; /* [h, w, 3] */
|
||||
};
|
||||
|
||||
/* Is there a decoder in this build. */
|
||||
bool decoder_available();
|
||||
|
||||
/* The first frame of an image (or of anything with a video stream). Refuses more than
|
||||
* `max_pixels` in the SOURCE, which is what bounds the memory a request can make the server
|
||||
* allocate before any resize happens. */
|
||||
int decode_image(const uint8_t* data, size_t n, int64_t max_pixels, Frame* out, std::string* why);
|
||||
|
||||
/* HOW A VIDEO IS SAMPLED, and it happens INSIDE the decode rather than after it: a minute of 1080p
|
||||
* is 10 GB of RGB, so frames that are not sampled are never converted or kept. The choice of which
|
||||
* frames is the processor's (it depends on the stream's length and rate, which only the decoder
|
||||
* knows), so it is a callback: given the stream's frame count and rate, return the frame indices to
|
||||
* keep, ascending. */
|
||||
struct VideoInfo {
|
||||
int64_t n_frames = 0; /* frames in the stream; counted by demuxing when the header omits it */
|
||||
double fps = 0.0; /* the stream's average rate */
|
||||
int32_t w = 0, h = 0;
|
||||
};
|
||||
typedef std::vector<int64_t> (*SampleFn)(const VideoInfo& info, const void* user);
|
||||
|
||||
struct Video {
|
||||
VideoInfo info;
|
||||
std::vector<int64_t> index; /* the frame each of `frames` is */
|
||||
std::vector<Frame> frames;
|
||||
};
|
||||
|
||||
int decode_video(const uint8_t* data, size_t n, SampleFn sample, const void* user,
|
||||
int64_t max_pixels, Video* out, std::string* why);
|
||||
|
||||
} /* namespace mm */
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,549 @@
|
||||
/* processor.cpp -- see processor.h. */
|
||||
#include "mm/processor.h"
|
||||
|
||||
#include "rad_internal.h"
|
||||
#include "rad_plugin.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <sstream>
|
||||
|
||||
namespace rad {
|
||||
namespace mm {
|
||||
|
||||
/* ================================================================== configuration */
|
||||
|
||||
static bool read_triple(const RadModelMeta& m, const char* key, float out[3]) {
|
||||
const char* v = rad_meta_gets(&m, key, nullptr);
|
||||
if (!v || !*v) return false;
|
||||
std::istringstream is(v);
|
||||
float t[3];
|
||||
for (int i = 0; i < 3; ++i)
|
||||
if (!(is >> t[i])) return false;
|
||||
for (int i = 0; i < 3; ++i) out[i] = t[i];
|
||||
return true;
|
||||
}
|
||||
|
||||
int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) {
|
||||
patch = (int32_t)rad_meta_geti(&m, "vision_config.patch_size", 0);
|
||||
temporal = (int32_t)rad_meta_geti(&m, "vision_config.temporal_patch_size", 0);
|
||||
merge = (int32_t)rad_meta_geti(&m, "vision_config.spatial_merge_size", 0);
|
||||
if (patch <= 0 || temporal <= 0 || merge <= 0) {
|
||||
if (why) *why = "the container states no vision tower geometry (vision_config.patch_size, "
|
||||
"temporal_patch_size, spatial_merge_size)";
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
tok_image = (int32_t)rad_meta_geti(&m, "image_token_id", -1);
|
||||
tok_video = (int32_t)rad_meta_geti(&m, "video_token_id", -1);
|
||||
tok_start = (int32_t)rad_meta_geti(&m, "vision_start_token_id", -1);
|
||||
tok_end = (int32_t)rad_meta_geti(&m, "vision_end_token_id", -1);
|
||||
if (tok_image < 0 || tok_video < 0 || tok_start < 0 || tok_end < 0) {
|
||||
if (why) *why = "the container states no media token ids (image_token_id, video_token_id, "
|
||||
"vision_start_token_id, vision_end_token_id)";
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
/* THE PROCESSOR-ONLY KEYS DEFAULT TO THE FAMILY'S VALUES. They come from the checkpoint's
|
||||
* preprocessor configs, which a container may not carry; the numbers below are what the
|
||||
* Qwen3.x checkpoints ship. */
|
||||
image_min_pixels = rad_meta_geti(&m, "preprocessor.size.shortest_edge",
|
||||
rad_meta_geti(&m, "preprocessor.min_pixels", 65536));
|
||||
image_max_pixels = rad_meta_geti(&m, "preprocessor.size.longest_edge",
|
||||
rad_meta_geti(&m, "preprocessor.max_pixels", 16777216));
|
||||
video_min_pixels = rad_meta_geti(&m, "video_preprocessor.size.shortest_edge", 4096);
|
||||
video_max_pixels = rad_meta_geti(&m, "video_preprocessor.size.longest_edge", 25165824);
|
||||
fps = rad_meta_getf(&m, "video_preprocessor.fps", 2.0);
|
||||
min_frames = (int32_t)rad_meta_geti(&m, "video_preprocessor.min_frames", 4);
|
||||
max_frames = (int32_t)rad_meta_geti(&m, "video_preprocessor.max_frames", 768);
|
||||
max_frame_rows = (int32_t)rad_meta_geti(&m, "video_preprocessor.max_video_tokens", 768);
|
||||
read_triple(m, "preprocessor.image_mean", mean);
|
||||
read_triple(m, "preprocessor.image_std", stdv);
|
||||
if (image_min_pixels <= 0 || image_max_pixels < image_min_pixels || video_min_pixels <= 0 ||
|
||||
video_max_pixels < video_min_pixels || !(fps > 0.0) || min_frames < 1 ||
|
||||
max_frames < min_frames) {
|
||||
if (why) *why = "the container's preprocessor configuration is inconsistent";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
for (int c = 0; c < 3; ++c)
|
||||
if (!(stdv[c] > 0.0f)) {
|
||||
if (why) *why = "preprocessor.image_std must be positive";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ================================================================== sizes and sampling */
|
||||
|
||||
/* Python's round(), which is round-half-to-even on the double -- the reference computes these in
|
||||
* Python, and a size that lands on .5 rounds the way it does there. */
|
||||
static inline int64_t pyround(double x) { return (int64_t)std::nearbyint(x); }
|
||||
|
||||
int smart_resize_image(int64_t h, int64_t w, int32_t factor, int64_t min_px, int64_t max_px,
|
||||
int64_t* oh, int64_t* ow, std::string* why) {
|
||||
if (h <= 0 || w <= 0) { if (why) *why = "the picture has no size"; return RAD_E_INVAL; }
|
||||
if ((double)std::max(h, w) / (double)std::min(h, w) > 200.0) {
|
||||
if (why) *why = "the picture's aspect ratio is over 200:1";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const double f = factor;
|
||||
int64_t hb = pyround((double)h / f) * factor;
|
||||
int64_t wb = pyround((double)w / f) * factor;
|
||||
if (hb * wb > max_px) {
|
||||
const double beta = std::sqrt((double)(h * w) / (double)max_px);
|
||||
hb = std::max<int64_t>(factor, (int64_t)std::floor((double)h / beta / f) * factor);
|
||||
wb = std::max<int64_t>(factor, (int64_t)std::floor((double)w / beta / f) * factor);
|
||||
} else if (hb * wb < min_px) {
|
||||
const double beta = std::sqrt((double)min_px / (double)(h * w));
|
||||
hb = (int64_t)std::ceil((double)h * beta / f) * factor;
|
||||
wb = (int64_t)std::ceil((double)w * beta / f) * factor;
|
||||
}
|
||||
*oh = hb;
|
||||
*ow = wb;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int smart_resize_video(int64_t t, int64_t h, int64_t w, int32_t tfactor, int32_t factor,
|
||||
int64_t min_px, int64_t max_px, int64_t* oh, int64_t* ow, std::string* why) {
|
||||
if (t < tfactor) { if (why) *why = "too few frames"; return RAD_E_INVAL; }
|
||||
if (h < factor || w < factor) {
|
||||
const double s = std::max((double)factor / (double)h, (double)factor / (double)w);
|
||||
h = (int64_t)((double)h * s);
|
||||
w = (int64_t)((double)w * s);
|
||||
}
|
||||
if (h <= 0 || w <= 0) { if (why) *why = "the video has no size"; return RAD_E_INVAL; }
|
||||
if ((double)std::max(h, w) / (double)std::min(h, w) > 200.0) {
|
||||
if (why) *why = "the video's aspect ratio is over 200:1";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const double f = factor;
|
||||
int64_t hb = pyround((double)h / f) * factor;
|
||||
int64_t wb = pyround((double)w / f) * factor;
|
||||
const int64_t tb = pyround((double)t / (double)tfactor) * tfactor;
|
||||
if (tb * hb * wb > max_px) {
|
||||
const double beta = std::sqrt((double)(t * h * w) / (double)max_px);
|
||||
hb = std::max<int64_t>(factor, (int64_t)std::floor((double)h / beta / f) * factor);
|
||||
wb = std::max<int64_t>(factor, (int64_t)std::floor((double)w / beta / f) * factor);
|
||||
} else if (tb * hb * wb < min_px) {
|
||||
const double beta = std::sqrt((double)min_px / (double)(t * h * w));
|
||||
hb = (int64_t)std::ceil((double)h * beta / f) * factor;
|
||||
wb = (int64_t)std::ceil((double)w * beta / f) * factor;
|
||||
}
|
||||
*oh = hb;
|
||||
*ow = wb;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* THE REFERENCE'S FRAME CHOICE: as many frames as `fps` gives over the clip's duration, clamped to
|
||||
* [min_frames, max_frames] and to what the stream has, spread evenly over it -- numpy's linspace,
|
||||
* rounded half-to-even. A stream that states no rate is taken at 24, as the reference does. */
|
||||
std::vector<int64_t> sample_frames(const VideoInfo& info, double fps, int32_t min_frames,
|
||||
int32_t max_frames) {
|
||||
const int64_t total = info.n_frames;
|
||||
if (total <= 0) return {};
|
||||
const double vfps = info.fps > 0.0 ? info.fps : 24.0;
|
||||
int64_t n = (int64_t)((double)total / vfps * fps);
|
||||
n = std::min<int64_t>(std::max<int64_t>(n, min_frames), max_frames);
|
||||
n = std::min<int64_t>(n, total);
|
||||
std::vector<int64_t> idx((size_t)n);
|
||||
if (n == 1) { idx[0] = 0; return idx; }
|
||||
const double step = (double)(total - 1) / (double)(n - 1);
|
||||
for (int64_t i = 0; i < n; ++i) idx[(size_t)i] = (int64_t)std::nearbyint((double)i * step);
|
||||
idx[(size_t)n - 1] = total - 1;
|
||||
return idx;
|
||||
}
|
||||
|
||||
/* ================================================================== the resample
|
||||
*
|
||||
* Pillow's ImagingResample for an 8-bit RGB image, transcribed: the coefficient table in double,
|
||||
* normalised per output pixel and rounded to 22-bit fixed point; a horizontal pass over only the
|
||||
* source rows the vertical pass will read, into an 8-bit intermediate; then the vertical pass. The
|
||||
* rounding at the intermediate is part of the function -- a single-pass float resample is a
|
||||
* different (and slightly better) function, and not the one the model was trained against. */
|
||||
namespace {
|
||||
|
||||
constexpr int kPrec = 32 - 8 - 2;
|
||||
|
||||
inline double bicubic(double x) {
|
||||
constexpr double a = -0.5;
|
||||
if (x < 0.0) x = -x;
|
||||
if (x < 1.0) return ((a + 2.0) * x - (a + 3.0)) * x * x + 1.0;
|
||||
if (x < 2.0) return (((x - 5.0) * x + 8.0) * x - 4.0) * a;
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
inline uint8_t clip8(int32_t v) {
|
||||
const int32_t s = v >> kPrec;
|
||||
return (uint8_t)(s < 0 ? 0 : (s > 255 ? 255 : s));
|
||||
}
|
||||
|
||||
/* One axis: `bounds` gets (first, count) per output pixel and `kk` its fixed-point weights, `ksize`
|
||||
* a row. */
|
||||
int coeffs(int32_t in_size, int32_t out_size, std::vector<int32_t>* bounds,
|
||||
std::vector<int32_t>* kk) {
|
||||
const double scale = (double)in_size / (double)out_size;
|
||||
const double fscale = scale < 1.0 ? 1.0 : scale;
|
||||
const double support = 2.0 * fscale;
|
||||
const int ksize = (int)std::ceil(support) * 2 + 1;
|
||||
std::vector<double> k((size_t)ksize);
|
||||
bounds->assign((size_t)out_size * 2, 0);
|
||||
kk->assign((size_t)out_size * (size_t)ksize, 0);
|
||||
for (int xx = 0; xx < out_size; ++xx) {
|
||||
const double center = (xx + 0.5) * scale;
|
||||
const double ss = 1.0 / fscale;
|
||||
int xmin = (int)(center - support + 0.5);
|
||||
if (xmin < 0) xmin = 0;
|
||||
int xmax = (int)(center + support + 0.5);
|
||||
if (xmax > in_size) xmax = in_size;
|
||||
xmax -= xmin;
|
||||
double ww = 0.0;
|
||||
int x = 0;
|
||||
for (; x < xmax; ++x) {
|
||||
const double w = bicubic((x + xmin - center + 0.5) * ss);
|
||||
k[(size_t)x] = w;
|
||||
ww += w;
|
||||
}
|
||||
for (x = 0; x < xmax; ++x)
|
||||
if (ww != 0.0) k[(size_t)x] /= ww;
|
||||
for (; x < ksize; ++x) k[(size_t)x] = 0.0;
|
||||
for (x = 0; x < ksize; ++x) {
|
||||
const double v = k[(size_t)x];
|
||||
(*kk)[(size_t)xx * ksize + x] = v < 0 ? (int32_t)(-0.5 + v * (1 << kPrec))
|
||||
: (int32_t)(0.5 + v * (1 << kPrec));
|
||||
}
|
||||
(*bounds)[(size_t)xx * 2] = xmin;
|
||||
(*bounds)[(size_t)xx * 2 + 1] = xmax;
|
||||
}
|
||||
return ksize;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out) {
|
||||
if (in.w == w && in.h == h) { *out = in; return; }
|
||||
std::vector<int32_t> bh, kh, bv, kv;
|
||||
const int ksh = coeffs(in.w, w, &bh, &kh);
|
||||
const int ksv = coeffs(in.h, h, &bv, &kv);
|
||||
|
||||
/* The source rows the vertical pass reads, which is all the horizontal pass has to produce. */
|
||||
const int y_first = bv[0];
|
||||
const int y_last = bv[(size_t)h * 2 - 2] + bv[(size_t)h * 2 - 1];
|
||||
const bool need_h = w != in.w;
|
||||
const bool need_v = h != in.h;
|
||||
|
||||
Frame tmp;
|
||||
const Frame* src = ∈
|
||||
if (need_h) {
|
||||
const int rows = need_v ? y_last - y_first : in.h;
|
||||
const int y0 = need_v ? y_first : 0;
|
||||
tmp.w = w;
|
||||
tmp.h = rows;
|
||||
tmp.rgb.assign((size_t)w * rows * 3, 0);
|
||||
for (int yy = 0; yy < rows; ++yy) {
|
||||
const uint8_t* row = in.rgb.data() + (size_t)(yy + y0) * in.w * 3;
|
||||
uint8_t* o = tmp.rgb.data() + (size_t)yy * w * 3;
|
||||
for (int xx = 0; xx < w; ++xx) {
|
||||
const int xmin = bh[(size_t)xx * 2], xmax = bh[(size_t)xx * 2 + 1];
|
||||
const int32_t* k = kh.data() + (size_t)xx * ksh;
|
||||
int32_t s0 = 1 << (kPrec - 1), s1 = s0, s2 = s0;
|
||||
for (int x = 0; x < xmax; ++x) {
|
||||
const uint8_t* p = row + (size_t)(x + xmin) * 3;
|
||||
s0 += p[0] * k[x];
|
||||
s1 += p[1] * k[x];
|
||||
s2 += p[2] * k[x];
|
||||
}
|
||||
o[xx * 3 + 0] = clip8(s0);
|
||||
o[xx * 3 + 1] = clip8(s1);
|
||||
o[xx * 3 + 2] = clip8(s2);
|
||||
}
|
||||
}
|
||||
src = &tmp;
|
||||
}
|
||||
if (!need_v) { *out = std::move(tmp); return; }
|
||||
const int shift = need_h ? y_first : 0;
|
||||
out->w = src->w;
|
||||
out->h = h;
|
||||
out->rgb.assign((size_t)src->w * h * 3, 0);
|
||||
for (int yy = 0; yy < h; ++yy) {
|
||||
const int ymin = bv[(size_t)yy * 2] - shift, ymax = bv[(size_t)yy * 2 + 1];
|
||||
const int32_t* k = kv.data() + (size_t)yy * ksv;
|
||||
uint8_t* o = out->rgb.data() + (size_t)yy * src->w * 3;
|
||||
for (int xx = 0; xx < src->w; ++xx) {
|
||||
int32_t s0 = 1 << (kPrec - 1), s1 = s0, s2 = s0;
|
||||
for (int y = 0; y < ymax; ++y) {
|
||||
const uint8_t* p = src->rgb.data() + ((size_t)(y + ymin) * src->w + xx) * 3;
|
||||
s0 += p[0] * k[y];
|
||||
s1 += p[1] * k[y];
|
||||
s2 += p[2] * k[y];
|
||||
}
|
||||
o[xx * 3 + 0] = clip8(s0);
|
||||
o[xx * 3 + 1] = clip8(s1);
|
||||
o[xx * 3 + 2] = clip8(s2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== patches */
|
||||
|
||||
namespace {
|
||||
|
||||
inline uint64_t mix64(uint64_t x) {
|
||||
x += 0x9e3779b97f4a7c15ull;
|
||||
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ull;
|
||||
x = (x ^ (x >> 27)) * 0x94d049bb133111ebull;
|
||||
return x ^ (x >> 31);
|
||||
}
|
||||
|
||||
/* Two independent 64-bit lanes over the patch bytes and the grid. The prefix cache folds the key
|
||||
* into a chained 128-bit block identity; a collision would serve one picture's cache for another,
|
||||
* so both lanes are carried. */
|
||||
void content_key(const Item& it, uint64_t* hi, uint64_t* lo) {
|
||||
uint64_t a = 0x6a09e667f3bcc908ull ^ mix64((uint64_t)it.grid_t << 42 ^
|
||||
(uint64_t)it.grid_h << 21 ^ (uint64_t)it.grid_w);
|
||||
uint64_t b = 0xbb67ae8584caa73bull ^ mix64(it.kind == Kind::Image ? 1u : 2u);
|
||||
const uint8_t* p = reinterpret_cast<const uint8_t*>(it.pixels.data());
|
||||
const size_t n = it.pixels.size() * sizeof(uint16_t);
|
||||
size_t i = 0;
|
||||
for (; i + 16 <= n; i += 16) {
|
||||
uint64_t w0, w1;
|
||||
std::memcpy(&w0, p + i, 8);
|
||||
std::memcpy(&w1, p + i + 8, 8);
|
||||
a = mix64(a ^ w0) + w1;
|
||||
b = mix64(b ^ w1) ^ w0;
|
||||
}
|
||||
for (; i < n; ++i) { a = mix64(a ^ p[i]); b = mix64(b + p[i]); }
|
||||
*hi = mix64(a ^ (uint64_t)n);
|
||||
*lo = mix64(b + (uint64_t)n);
|
||||
}
|
||||
|
||||
/* THE PATCH ROWS, in merge-block order, from `frames` (temporal * grid_t of them, already resized
|
||||
* to grid_h * patch by grid_w * patch). Each row is (channel, frame, y, x), each value normalised
|
||||
* as the reference does -- (x - 255 mean) / (255 std) in f32 -- and rounded to bf16. */
|
||||
void patchify(const VisionConfig& c, const std::vector<const Frame*>& frames, Item* it) {
|
||||
const int P = c.patch, T = c.temporal, M = c.merge;
|
||||
const int gh = it->grid_h, gw = it->grid_w;
|
||||
float m255[3], s255[3];
|
||||
for (int ch = 0; ch < 3; ++ch) {
|
||||
/* torch.tensor(mean) * (1 / rescale_factor), in f32: the fused rescale's own constants. */
|
||||
m255[ch] = c.mean[ch] * (float)(1.0 / (1.0 / 255.0));
|
||||
s255[ch] = c.stdv[ch] * (float)(1.0 / (1.0 / 255.0));
|
||||
}
|
||||
/* One lookup per (channel, byte): the normalisation is a function of the byte alone. */
|
||||
uint16_t lut[3][256];
|
||||
for (int ch = 0; ch < 3; ++ch)
|
||||
for (int v = 0; v < 256; ++v)
|
||||
lut[ch][v] = rad_f32_to_bf16(((float)v - m255[ch]) / s255[ch]);
|
||||
|
||||
const int64_t dim = it->patch_dim;
|
||||
it->pixels.assign((size_t)it->n_patch * (size_t)dim, 0);
|
||||
uint16_t* dst = it->pixels.data();
|
||||
for (int g = 0; g < it->grid_t; ++g)
|
||||
for (int bh = 0; bh < gh / M; ++bh)
|
||||
for (int bw = 0; bw < gw / M; ++bw)
|
||||
for (int mh = 0; mh < M; ++mh)
|
||||
for (int mw = 0; mw < M; ++mw) {
|
||||
const int py0 = (bh * M + mh) * P, px0 = (bw * M + mw) * P;
|
||||
for (int ch = 0; ch < 3; ++ch)
|
||||
for (int t = 0; t < T; ++t) {
|
||||
const Frame& f = *frames[(size_t)(g * T + t)];
|
||||
for (int y = 0; y < P; ++y) {
|
||||
const uint8_t* row = f.rgb.data() +
|
||||
((size_t)(py0 + y) * f.w + px0) * 3 + ch;
|
||||
for (int x = 0; x < P; ++x) *dst++ = lut[ch][row[x * 3]];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void finish_item(const VisionConfig& c, Item* it) {
|
||||
it->patch_dim = c.patch_dim();
|
||||
it->n_patch = (int64_t)it->grid_t * it->grid_h * it->grid_w;
|
||||
it->rows_h = it->grid_h / c.merge;
|
||||
it->rows_w = it->grid_w / c.merge;
|
||||
it->seg_rows = it->rows_h * it->rows_w;
|
||||
it->n_seg = it->grid_t;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* ================================================================== the processor */
|
||||
|
||||
int Processor::init(const VisionConfig& cfg,
|
||||
std::function<std::vector<int32_t>(const std::string&)> encode_text) {
|
||||
if (cfg.patch <= 0 || cfg.temporal <= 0 || cfg.merge <= 0 || cfg.max_patches <= 0)
|
||||
return RAD_E_INVAL;
|
||||
cfg_ = cfg;
|
||||
/* The largest image the encoder takes in one pass, in pixels: the band's ceiling comes down to
|
||||
* it, so smart_resize itself keeps every image inside a pass. */
|
||||
const int64_t pass_px = cfg.max_patches * cfg.patch * cfg.patch;
|
||||
if (cfg_.image_max_pixels > pass_px) cfg_.image_max_pixels = pass_px;
|
||||
if (cfg_.image_min_pixels > cfg_.image_max_pixels) cfg_.image_min_pixels = cfg_.image_max_pixels;
|
||||
if (cfg_.max_video_patches <= 0)
|
||||
cfg_.max_video_patches = cfg_.video_max_pixels / ((int64_t)cfg.patch * cfg.patch);
|
||||
encode_text_ = std::move(encode_text);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Processor::image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const {
|
||||
const VisionConfig& c = cfg_;
|
||||
int64_t h = 0, w = 0;
|
||||
RAD_TRY(smart_resize_image(f.h, f.w, c.factor(), c.image_min_pixels, c.image_max_pixels,
|
||||
&h, &w, why));
|
||||
Frame r;
|
||||
resize_bicubic(f, (int32_t)w, (int32_t)h, &r);
|
||||
auto it = std::make_shared<Item>();
|
||||
it->kind = Kind::Image;
|
||||
it->grid_t = 1;
|
||||
it->grid_h = (int32_t)(h / c.patch);
|
||||
it->grid_w = (int32_t)(w / c.patch);
|
||||
finish_item(c, it.get());
|
||||
if (it->n_patch > c.max_patches) {
|
||||
if (why) *why = "the image resizes to more patches than one encoder pass holds";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* An image fills the temporal depth by repetition. */
|
||||
std::vector<const Frame*> frames((size_t)c.temporal, &r);
|
||||
patchify(c, frames, it.get());
|
||||
content_key(*it, &it->key_hi, &it->key_lo);
|
||||
|
||||
it->expand.reserve((size_t)it->seg_rows + 2);
|
||||
it->expand.push_back(c.tok_start);
|
||||
it->seg_at.push_back(1);
|
||||
it->expand.insert(it->expand.end(), (size_t)it->seg_rows, c.tok_image);
|
||||
it->expand.push_back(c.tok_end);
|
||||
*out = std::move(it);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Processor::video_from(const Video& v, std::shared_ptr<Item>* out, std::string* why) const {
|
||||
const VisionConfig& c = cfg_;
|
||||
if (v.frames.empty()) { if (why) *why = "the video decoded to no frames"; return RAD_E_INVAL; }
|
||||
/* The frames and their indices, padded to whole temporal groups by repeating the last. A clip
|
||||
* shorter than one group is padded the same way, so a single-frame video is one group. */
|
||||
std::vector<const Frame*> frames;
|
||||
std::vector<int64_t> idx = v.index;
|
||||
for (const Frame& f : v.frames) frames.push_back(&f);
|
||||
while (frames.size() % (size_t)c.temporal != 0 || frames.size() < (size_t)c.temporal) {
|
||||
frames.push_back(frames.back());
|
||||
idx.push_back(idx.back());
|
||||
}
|
||||
const int64_t nf = (int64_t)v.frames.size() < c.temporal ? c.temporal
|
||||
: (int64_t)v.frames.size();
|
||||
|
||||
/* THE PER-FRAME CAP: at most `max_frame_rows` output rows' worth of pixels a frame, and the
|
||||
* video budget's even share, but never under the band's floor. */
|
||||
int64_t max_px = c.video_max_pixels;
|
||||
if (c.max_frame_rows > 0) {
|
||||
const int64_t f2 = (int64_t)c.factor() * c.factor();
|
||||
const int64_t cap = (int64_t)c.max_frame_rows * f2;
|
||||
const int64_t share = c.video_max_pixels / nf;
|
||||
const int64_t per = std::max<int64_t>(std::min(cap, share),
|
||||
(int64_t)((double)c.video_min_pixels * 1.05));
|
||||
max_px = per * nf;
|
||||
}
|
||||
int64_t h = 0, w = 0;
|
||||
RAD_TRY(smart_resize_video(nf, v.frames[0].h, v.frames[0].w, c.temporal, c.factor(),
|
||||
c.video_min_pixels, max_px, &h, &w, why));
|
||||
|
||||
auto it = std::make_shared<Item>();
|
||||
it->kind = Kind::Video;
|
||||
it->grid_t = (int32_t)(frames.size() / (size_t)c.temporal);
|
||||
it->grid_h = (int32_t)(h / c.patch);
|
||||
it->grid_w = (int32_t)(w / c.patch);
|
||||
finish_item(c, it.get());
|
||||
if ((int64_t)it->grid_h * it->grid_w > c.max_patches) {
|
||||
if (why) *why = "a video frame resizes to more patches than one encoder pass holds";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (it->n_patch > c.max_video_patches) {
|
||||
if (why) *why = "the video is over the server's patch budget for one video";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* Resize each distinct frame once; padding repeats share the resized copy. */
|
||||
std::vector<Frame> resized(v.frames.size());
|
||||
for (size_t i = 0; i < v.frames.size(); ++i)
|
||||
resize_bicubic(v.frames[i], (int32_t)w, (int32_t)h, &resized[i]);
|
||||
std::vector<const Frame*> rframes;
|
||||
for (const Frame* f : frames) rframes.push_back(&resized[(size_t)(f - v.frames.data())]);
|
||||
patchify(c, rframes, it.get());
|
||||
content_key(*it, &it->key_hi, &it->key_lo);
|
||||
|
||||
/* THE TIMESTAMPED EXPANSION: per temporal group, "<T seconds>" then a run of pads between
|
||||
* vision_start and vision_end, T being the mean of the group's first and last frame times.
|
||||
* It stands for the template's whole <|vision_start|><|video_pad|><|vision_end|>, as the
|
||||
* model's own processor wrote it (transformers 4.57, qwen-vl-utils). transformers 5.x swaps
|
||||
* only the pad and leaves that outer pair around the frames -- two tokens the model was not
|
||||
* trained with. */
|
||||
const double vfps = v.info.fps > 0.0 ? v.info.fps : 24.0;
|
||||
for (int32_t g = 0; g < it->grid_t; ++g) {
|
||||
const double t0 = (double)idx[(size_t)g * c.temporal] / vfps;
|
||||
const double t1 = (double)idx[(size_t)g * c.temporal + c.temporal - 1] / vfps;
|
||||
char ts[64];
|
||||
std::snprintf(ts, sizeof ts, "<%.1f seconds>", (t0 + t1) / 2.0);
|
||||
const std::vector<int32_t> tt = encode_text_ ? encode_text_(ts) : std::vector<int32_t>{};
|
||||
if (tt.empty()) {
|
||||
if (why) *why = "the tokenizer produced nothing for a video timestamp";
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
it->expand.insert(it->expand.end(), tt.begin(), tt.end());
|
||||
it->expand.push_back(c.tok_start);
|
||||
it->seg_at.push_back((int32_t)it->expand.size());
|
||||
it->expand.insert(it->expand.end(), (size_t)it->seg_rows, c.tok_video);
|
||||
it->expand.push_back(c.tok_end);
|
||||
}
|
||||
*out = std::move(it);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Processor::image(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out,
|
||||
std::string* why) const {
|
||||
Frame f;
|
||||
RAD_TRY(decode_image(bytes, n, cfg_.max_source_pixels, &f, why));
|
||||
return image_from(f, out, why);
|
||||
}
|
||||
|
||||
namespace {
|
||||
struct SampleArgs { double fps; int32_t lo, hi; };
|
||||
std::vector<int64_t> sample_cb(const VideoInfo& info, const void* user) {
|
||||
const SampleArgs* a = static_cast<const SampleArgs*>(user);
|
||||
return sample_frames(info, a->fps, a->lo, a->hi);
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
int Processor::video(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out,
|
||||
std::string* why) const {
|
||||
Video v;
|
||||
const SampleArgs a{ cfg_.fps, cfg_.min_frames, cfg_.max_frames };
|
||||
RAD_TRY(decode_video(bytes, n, sample_cb, &a, cfg_.max_source_pixels, &v, why));
|
||||
return video_from(v, out, why);
|
||||
}
|
||||
|
||||
/* ================================================================== rotary layout */
|
||||
|
||||
void PromptMedia::layout() {
|
||||
rope.runs.clear();
|
||||
int64_t pos = 0, tok = 0;
|
||||
for (size_t pi = 0; pi < items.size(); ++pi) {
|
||||
const Placed& p = items[pi];
|
||||
const Item& it = *p.item;
|
||||
for (int32_t s = 0; s < it.n_seg; ++s) {
|
||||
const int64_t run_tok = (int64_t)p.tok + it.seg_at[(size_t)s];
|
||||
pos += run_tok - tok; /* the text in front of the run counts up */
|
||||
RopeLayout::Run r;
|
||||
r.tok = (int32_t)run_tok;
|
||||
r.n = it.seg_rows;
|
||||
r.w = it.rows_w;
|
||||
r.base = (int32_t)pos;
|
||||
pos += std::max(it.rows_h, it.rows_w);
|
||||
tok = run_tok + it.seg_rows;
|
||||
r.shift = (int32_t)(pos - tok);
|
||||
r.item = (int32_t)pi;
|
||||
r.row0 = s * it.seg_rows;
|
||||
rope.runs.push_back(r);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace mm */
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,208 @@
|
||||
/* processor.h -- what an image or a video becomes before an encoder sees it (spec §11).
|
||||
*
|
||||
* THIS IS THE QWEN-VL PROCESSOR FAMILY (Qwen2-VL through Qwen3.x), and what is family-specific is
|
||||
* the arithmetic, not the numbers: every size, rate and token id comes from the container, which
|
||||
* carries the checkpoint's config.json and its two preprocessor configs (rad-convert writes them
|
||||
* under `vision_config.*`, `preprocessor.*` and `video_preprocessor.*`). What the family fixes:
|
||||
*
|
||||
* - A picture is resized so both sides are multiples of patch * merge and its area falls in the
|
||||
* configured band, keeping the aspect ratio (smart_resize), with PIL's antialiased bicubic.
|
||||
* - It is cut into patch x patch squares, `temporal` frames deep -- an image is repeated to fill
|
||||
* the depth -- in MERGE-BLOCK ORDER: the merge x merge patches that become one output row are
|
||||
* consecutive. Each patch row is (channel, frame, y, x), normalised by the configured mean and
|
||||
* deviation, in bf16.
|
||||
* - The prompt gets `<vision_start> pad*N <vision_end>` where the template put the media, N
|
||||
* being the encoder's output rows. A video gets one such run per temporal group, each after
|
||||
* the text `<T seconds>` giving the group's time -- which is how the model knows when a frame
|
||||
* is, since the groups share one temporal rotary component.
|
||||
* - Rotary positions are three components (temporal, height, width): text counts up in all
|
||||
* three; a media run holds its start in the first and adds its row and column to the other
|
||||
* two; the text after it continues from start + max(rows, cols). (RopeLayout below.)
|
||||
*
|
||||
* The encoder's input is patches plus each patch's (row, col) in its segment and the segment's
|
||||
* size, which is all a learned position table and a 2-D rotary embedding need; the processor
|
||||
* produces those too, so the core stages them without knowing what they are for.
|
||||
*/
|
||||
#pragma once
|
||||
#include "mm/media.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
struct RadModelMeta;
|
||||
|
||||
namespace rad {
|
||||
namespace mm {
|
||||
|
||||
enum class Kind { Image, Video };
|
||||
|
||||
struct VisionConfig {
|
||||
int32_t patch = 0, temporal = 0, merge = 0;
|
||||
int64_t image_min_pixels = 0, image_max_pixels = 0;
|
||||
int64_t video_min_pixels = 0, video_max_pixels = 0;
|
||||
double fps = 2.0;
|
||||
int32_t min_frames = 4, max_frames = 768;
|
||||
/* The per-frame ceiling on a video's resolution, in output rows: a clip that samples few
|
||||
* frames does not spend the whole video budget on near-native frames, so the cost of a video
|
||||
* grows with its length (the reference processor's per-frame cap). 0 turns the cap off. */
|
||||
int32_t max_frame_rows = 768;
|
||||
float mean[3] = { 0.5f, 0.5f, 0.5f };
|
||||
float stdv[3] = { 0.5f, 0.5f, 0.5f };
|
||||
int32_t tok_image = -1, tok_video = -1, tok_start = -1, tok_end = -1;
|
||||
|
||||
/* THE DEPLOYMENT'S BOUNDS, not the checkpoint's. `max_patches` is the encoder's pass size: an
|
||||
* image is one segment and a segment is never split, so no image may resize past it, and the
|
||||
* image band's ceiling is lowered to fit. `max_source_pixels` bounds what the decoder is asked
|
||||
* to hold before any resize. */
|
||||
int64_t max_patches = 0;
|
||||
int64_t max_source_pixels = (int64_t)1 << 26;
|
||||
/* A whole video's patch budget, across all its passes. */
|
||||
int64_t max_video_patches = 0;
|
||||
|
||||
int64_t patch_dim() const { return 3LL * temporal * patch * patch; }
|
||||
int32_t factor() const { return patch * merge; }
|
||||
|
||||
/* Read from the container. Refuses a container that states no vision tower; the defaults for
|
||||
* the processor-only keys are the family's, used only when the container omits them. */
|
||||
int from_meta(const RadModelMeta& m, std::string* why);
|
||||
};
|
||||
|
||||
/* One media part after processing: its patches, its place in the prompt's token stream, and --
|
||||
* once the encoder has run -- its rows. Shared between the request that owns it and the engine
|
||||
* thread that encodes it; the engine writes `embd` once and nothing reads it before then. */
|
||||
struct Item {
|
||||
Kind kind = Kind::Image;
|
||||
int32_t grid_t = 0, grid_h = 0, grid_w = 0; /* in patches; grid_t temporal groups */
|
||||
int64_t n_patch = 0;
|
||||
int64_t patch_dim = 0;
|
||||
std::vector<uint16_t> pixels; /* [n_patch, patch_dim] bf16 */
|
||||
|
||||
/* The encoder's output: n_seg segments of seg_rows rows, one segment per temporal group.
|
||||
* `rows_w` is a segment's width in output rows, which is where its rotary grid wraps. */
|
||||
int32_t n_seg = 0, seg_rows = 0, rows_w = 0, rows_h = 0;
|
||||
int64_t n_rows() const { return (int64_t)n_seg * seg_rows; }
|
||||
|
||||
/* THE TOKENS THAT REPLACE THE MEDIA MARKER, and where in them each segment's run of
|
||||
* placeholders starts. Placeholders are the checkpoint's own pad ids, not an arbitrary one:
|
||||
* an n-gram embedding hashes them like any other id. */
|
||||
std::vector<int32_t> expand;
|
||||
std::vector<int32_t> seg_at;
|
||||
|
||||
/* A CONTENT KEY over the patches and the grid. It is taken BEFORE the encoder runs, so a
|
||||
* prefix-cache hit over this item skips the encoder as well as the prefill: the patches are
|
||||
* what the encoder is a function of, and they already reflect every preprocessing choice. */
|
||||
uint64_t key_hi = 0, key_lo = 0;
|
||||
|
||||
/* [n_rows, n_embd] bf16, written by the engine after the encoder pass. */
|
||||
std::vector<uint16_t> embd;
|
||||
bool encoded = false;
|
||||
/* Handed to the engine's encoder queue and not yet encoded -- the scheduler's thread only. */
|
||||
bool queued = false;
|
||||
|
||||
/* The (row, col, rows, cols) of each patch in its segment, for the encoder: component-major,
|
||||
* four planes of `count` entries, patches [first, first + count). */
|
||||
void coords(int64_t first, int64_t count, int32_t* planes) const;
|
||||
};
|
||||
|
||||
/* THE ROTARY LAYOUT OF ONE PROMPT: which tokens are media and where each run's grid sits. Built
|
||||
* once when the prompt is tokenised; `at` is what the batch builder asks for every row of every
|
||||
* pass, so it is a binary search over runs rather than an array the length of the prompt. */
|
||||
struct RopeLayout {
|
||||
struct Run {
|
||||
int32_t tok = 0; /* first placeholder token of the run */
|
||||
int32_t n = 0; /* its length: rows_h * rows_w */
|
||||
int32_t w = 0; /* its width in rows */
|
||||
int32_t base = 0; /* the rotary position of its first token */
|
||||
int32_t shift = 0; /* rotary minus token index for the text AFTER the run */
|
||||
int32_t item = 0; /* which of PromptMedia::items the run belongs to */
|
||||
int32_t row0 = 0; /* the item's encoder row that its first token takes */
|
||||
};
|
||||
std::vector<Run> runs; /* ascending */
|
||||
|
||||
bool empty() const { return runs.empty(); }
|
||||
|
||||
/* The last run starting at or before token i, or null. Inline and dependency-free, because
|
||||
* the batch builder asks it for every row of every pass. */
|
||||
const Run* last_at(int64_t i) const {
|
||||
size_t lo = 0, hi = runs.size();
|
||||
while (lo < hi) {
|
||||
const size_t mid = (lo + hi) / 2;
|
||||
if ((int64_t)runs[mid].tok <= i) lo = mid + 1; else hi = mid;
|
||||
}
|
||||
return lo == 0 ? nullptr : &runs[lo - 1];
|
||||
}
|
||||
/* (t, h, w) of token index i. Past the prompt, text continues from the last run's shift. */
|
||||
void at(int64_t i, int32_t out[3]) const {
|
||||
const Run* r = last_at(i);
|
||||
if (!r) { out[0] = out[1] = out[2] = (int32_t)i; return; }
|
||||
const int64_t k = i - r->tok;
|
||||
if (k < r->n) {
|
||||
out[0] = r->base;
|
||||
out[1] = r->base + (int32_t)(k / r->w);
|
||||
out[2] = r->base + (int32_t)(k % r->w);
|
||||
return;
|
||||
}
|
||||
out[0] = out[1] = out[2] = (int32_t)(i + r->shift);
|
||||
}
|
||||
/* Rotary minus index for text at or after token i -- the one number a decode row needs. */
|
||||
int32_t shift_at(int64_t i) const {
|
||||
const Run* r = last_at(i);
|
||||
return r ? r->shift : 0;
|
||||
}
|
||||
/* The run holding token i, or null when i is text. */
|
||||
const Run* run_at(int64_t i) const {
|
||||
const Run* r = last_at(i);
|
||||
return r && i - r->tok < r->n ? r : nullptr;
|
||||
}
|
||||
};
|
||||
|
||||
/* THE MEDIA A PROMPT CARRIES, in prompt order, with where each item's expansion begins. */
|
||||
struct Placed {
|
||||
std::shared_ptr<Item> item;
|
||||
int32_t tok = 0; /* index of item->expand[0] in the prompt */
|
||||
};
|
||||
|
||||
struct PromptMedia {
|
||||
std::vector<Placed> items;
|
||||
RopeLayout rope;
|
||||
/* Build `rope` from `items`, which must be placed and in prompt order. */
|
||||
void layout();
|
||||
};
|
||||
|
||||
class Processor {
|
||||
public:
|
||||
/* `encode_text` tokenises the timestamp text between a video's groups: plain text, no
|
||||
* special tokens added and none parsed. */
|
||||
int init(const VisionConfig& cfg, std::function<std::vector<int32_t>(const std::string&)> encode_text);
|
||||
const VisionConfig& config() const { return cfg_; }
|
||||
|
||||
int image(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
int video(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
|
||||
/* The pieces, exposed for the test suite: an already-decoded picture or frame list. */
|
||||
int image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
int video_from(const Video& v, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
|
||||
private:
|
||||
VisionConfig cfg_{};
|
||||
std::function<std::vector<int32_t>(const std::string&)> encode_text_;
|
||||
};
|
||||
|
||||
/* smart_resize, the image form: (height, width) -> multiples of `factor` in [min, max] pixels. */
|
||||
int smart_resize_image(int64_t h, int64_t w, int32_t factor, int64_t min_px, int64_t max_px,
|
||||
int64_t* oh, int64_t* ow, std::string* why);
|
||||
/* ...and the video form, which counts the frames into the budget. */
|
||||
int smart_resize_video(int64_t t, int64_t h, int64_t w, int32_t tfactor, int32_t factor,
|
||||
int64_t min_px, int64_t max_px, int64_t* oh, int64_t* ow, std::string* why);
|
||||
/* Which frames a video keeps. */
|
||||
std::vector<int64_t> sample_frames(const VideoInfo& info, double fps, int32_t min_frames,
|
||||
int32_t max_frames);
|
||||
/* PIL's antialiased bicubic resample of packed RGB, bit for bit: fixed-point coefficients, a
|
||||
* horizontal pass into an 8-bit intermediate and then a vertical one. */
|
||||
void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out);
|
||||
|
||||
} /* namespace mm */
|
||||
} /* namespace rad */
|
||||
Reference in new issue
Block a user