- Add chandra-camera-isp.c (C/OpenMP) for Quad-Bayer unpack, CCM, and tone mapping, with a NumPy fallback when it is not built - Add non-blocking contrast-detection VCM autofocus, with lens subdev discovery on the sensor's I2C bus - Tune Quad-Bayer AE: a video-mode vblank cap, damped steps, and full analog gain before extending blanking - Record variable-frame-rate video through a streaming Matroska muxer, and count dropped frames - Ship libcamera IPA tuning files for imx376, imx519, and uncalibrated sensors - Map camera buffers by fd and sync them with dma-buf ioctls
This commit is contained in:
1 parent
851c39d827
commit
52b42890d6
34 files changed
+2851
-364
No files matched your search
+1139
-231
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,219 @@
|
||||
#include <math.h>
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
|
||||
#ifdef _OPENMP
|
||||
#include <omp.h>
|
||||
#endif
|
||||
|
||||
/* Unpack 10-bit CSI-2 packed 4x4 Quad-Bayer SRGGB into 4x4 supercell BGR16 (0..4092). */
|
||||
void quad_csi2p_to_bgr16_4x4(
|
||||
const uint8_t *raw,
|
||||
int width,
|
||||
int height,
|
||||
int stride,
|
||||
uint16_t *out_bgr16
|
||||
) {
|
||||
if (!raw || !out_bgr16 || width < 4 || height < 4 || stride <= 0) {
|
||||
return;
|
||||
}
|
||||
const int out_w = width / 4;
|
||||
const int out_h = height / 4;
|
||||
|
||||
#ifdef _OPENMP
|
||||
#pragma omp parallel for schedule(static) num_threads(4) if (out_h >= 64)
|
||||
#endif
|
||||
for (int cy = 0; cy < out_h; cy++) {
|
||||
const uint8_t *r0 = raw + (size_t)(cy * 4 + 0) * (size_t)stride;
|
||||
const uint8_t *r1 = raw + (size_t)(cy * 4 + 1) * (size_t)stride;
|
||||
const uint8_t *r2 = raw + (size_t)(cy * 4 + 2) * (size_t)stride;
|
||||
const uint8_t *r3 = raw + (size_t)(cy * 4 + 3) * (size_t)stride;
|
||||
uint16_t *dst = out_bgr16 + (size_t)cy * (size_t)out_w * 3;
|
||||
|
||||
for (int cx = 0; cx < out_w; cx++) {
|
||||
const size_t off = (size_t)cx * 5;
|
||||
const uint8_t lo0 = r0[off + 4];
|
||||
const uint8_t lo1 = r1[off + 4];
|
||||
const uint8_t lo2 = r2[off + 4];
|
||||
const uint8_t lo3 = r3[off + 4];
|
||||
|
||||
/* Rows 4y, 4y+1: (p0, p1) = R, (p2, p3) = Gr */
|
||||
uint32_t r_sum = ((uint32_t)r0[off + 0] + r0[off + 1] + r1[off + 0] + r1[off + 1]) << 2;
|
||||
r_sum += (uint32_t)(lo0 & 3U) + ((lo0 >> 2) & 3U) + (lo1 & 3U) + ((lo1 >> 2) & 3U);
|
||||
|
||||
uint32_t gr_sum = ((uint32_t)r0[off + 2] + r0[off + 3] + r1[off + 2] + r1[off + 3]) << 2;
|
||||
gr_sum += (uint32_t)((lo0 >> 4) & 3U) + ((lo0 >> 6) & 3U) + ((lo1 >> 4) & 3U) + ((lo1 >> 6) & 3U);
|
||||
|
||||
/* Rows 4y+2, 4y+3: (p0, p1) = Gb, (p2, p3) = B */
|
||||
uint32_t gb_sum = ((uint32_t)r2[off + 0] + r2[off + 1] + r3[off + 0] + r3[off + 1]) << 2;
|
||||
gb_sum += (uint32_t)(lo2 & 3U) + ((lo2 >> 2) & 3U) + (lo3 & 3U) + ((lo3 >> 2) & 3U);
|
||||
|
||||
uint32_t b_sum = ((uint32_t)r2[off + 2] + r2[off + 3] + r3[off + 2] + r3[off + 3]) << 2;
|
||||
b_sum += (uint32_t)((lo2 >> 4) & 3U) + ((lo2 >> 6) & 3U) + ((lo3 >> 4) & 3U) + ((lo3 >> 6) & 3U);
|
||||
|
||||
uint32_t g_avg = (gr_sum + gb_sum + 1U) >> 1;
|
||||
|
||||
dst[0] = (uint16_t)b_sum;
|
||||
dst[1] = (uint16_t)g_avg;
|
||||
dst[2] = (uint16_t)r_sum;
|
||||
dst += 3;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Unpack 10-bit CSI-2 packed 4x4 Quad-Bayer SRGGB via 2x2 binning into 16-bit Bayer (0..4092). */
|
||||
void quad_csi2p_to_bayer16_2x2(
|
||||
const uint8_t *raw,
|
||||
int width,
|
||||
int height,
|
||||
int stride,
|
||||
uint16_t *out_bayer16
|
||||
) {
|
||||
if (!raw || !out_bayer16 || width < 4 || height < 2 || stride <= 0) {
|
||||
return;
|
||||
}
|
||||
const int nblk = width / 4;
|
||||
const int out_w = nblk * 2;
|
||||
const int out_h = height / 2;
|
||||
|
||||
#ifdef _OPENMP
|
||||
#pragma omp parallel for schedule(static) num_threads(4) if (out_h >= 64)
|
||||
#endif
|
||||
for (int by = 0; by < out_h; by++) {
|
||||
const uint8_t *r0 = raw + (size_t)(by * 2 + 0) * (size_t)stride;
|
||||
const uint8_t *r1 = raw + (size_t)(by * 2 + 1) * (size_t)stride;
|
||||
uint16_t *dst = out_bayer16 + (size_t)by * (size_t)out_w;
|
||||
|
||||
for (int bx = 0; bx < nblk; bx++) {
|
||||
const size_t off = (size_t)bx * 5;
|
||||
const uint8_t lo0 = r0[off + 4];
|
||||
const uint8_t lo1 = r1[off + 4];
|
||||
|
||||
uint32_t c0 = ((uint32_t)r0[off + 0] + r0[off + 1] + r1[off + 0] + r1[off + 1]) << 2;
|
||||
c0 += (uint32_t)(lo0 & 3U) + ((lo0 >> 2) & 3U) + (lo1 & 3U) + ((lo1 >> 2) & 3U);
|
||||
|
||||
uint32_t c1 = ((uint32_t)r0[off + 2] + r0[off + 3] + r1[off + 2] + r1[off + 3]) << 2;
|
||||
c1 += (uint32_t)((lo0 >> 4) & 3U) + ((lo0 >> 6) & 3U) + ((lo1 >> 4) & 3U) + ((lo1 >> 6) & 3U);
|
||||
|
||||
dst[0] = (uint16_t)c0;
|
||||
dst[1] = (uint16_t)c1;
|
||||
dst += 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Fused black-level subtraction, AWB + exposure scaling, 3x3 linear RGB CCM, and LUT tone-map. */
|
||||
void isp_ccm_tone_bgr16_to_bgr8(
|
||||
const uint16_t *in_bgr16,
|
||||
uint8_t *out_bgr8,
|
||||
int pixels,
|
||||
float black,
|
||||
float scale_norm,
|
||||
float gain_b,
|
||||
float gain_g,
|
||||
float gain_r,
|
||||
const float ccm_rgb[9],
|
||||
const uint8_t lut[4096],
|
||||
float lut_max
|
||||
) {
|
||||
if (!in_bgr16 || !out_bgr8 || !ccm_rgb || !lut || pixels <= 0) {
|
||||
return;
|
||||
}
|
||||
const float m00 = ccm_rgb[0], m01 = ccm_rgb[1], m02 = ccm_rgb[2];
|
||||
const float m10 = ccm_rgb[3], m11 = ccm_rgb[4], m12 = ccm_rgb[5];
|
||||
const float m20 = ccm_rgb[6], m21 = ccm_rgb[7], m22 = ccm_rgb[8];
|
||||
const float sb = scale_norm * gain_b;
|
||||
const float sg = scale_norm * gain_g;
|
||||
const float sr = scale_norm * gain_r;
|
||||
const float inv_lut = 4095.0f / (lut_max > 1e-6f ? lut_max : 1.0f);
|
||||
|
||||
#ifdef _OPENMP
|
||||
#pragma omp parallel for schedule(static) num_threads(4) if (pixels >= 16384)
|
||||
#endif
|
||||
for (int i = 0; i < pixels; i++) {
|
||||
const size_t idx = (size_t)i * 3;
|
||||
float b = (float)in_bgr16[idx + 0] - black;
|
||||
float g = (float)in_bgr16[idx + 1] - black;
|
||||
float r = (float)in_bgr16[idx + 2] - black;
|
||||
if (b < 0.0f) b = 0.0f;
|
||||
if (g < 0.0f) g = 0.0f;
|
||||
if (r < 0.0f) r = 0.0f;
|
||||
|
||||
b *= sb;
|
||||
g *= sg;
|
||||
r *= sr;
|
||||
|
||||
float rc = m00 * r + m01 * g + m02 * b;
|
||||
float gc = m10 * r + m11 * g + m12 * b;
|
||||
float bc = m20 * r + m21 * g + m22 * b;
|
||||
|
||||
int ir = (int)(rc * inv_lut + 0.5f);
|
||||
int ig = (int)(gc * inv_lut + 0.5f);
|
||||
int ib = (int)(bc * inv_lut + 0.5f);
|
||||
if (ir < 0) ir = 0; else if (ir > 4095) ir = 4095;
|
||||
if (ig < 0) ig = 0; else if (ig > 4095) ig = 4095;
|
||||
if (ib < 0) ib = 0; else if (ib > 4095) ib = 4095;
|
||||
|
||||
out_bgr8[idx + 0] = lut[ib];
|
||||
out_bgr8[idx + 1] = lut[ig];
|
||||
out_bgr8[idx + 2] = lut[ir];
|
||||
}
|
||||
}
|
||||
|
||||
/* Motion-guarded multi-frame temporal merge in linear 16-bit BGR space. */
|
||||
void burst_merge_bgr16(
|
||||
const uint16_t *base,
|
||||
const uint16_t *const *others,
|
||||
int num_others,
|
||||
uint16_t *out,
|
||||
int pixels,
|
||||
float noise_thresh
|
||||
) {
|
||||
if (!base || !out || pixels <= 0) {
|
||||
return;
|
||||
}
|
||||
const float inv_nt = 1.0f / (noise_thresh > 1.0f ? noise_thresh : 1.0f);
|
||||
|
||||
#ifdef _OPENMP
|
||||
#pragma omp parallel for schedule(static) num_threads(4) if (pixels >= 16384)
|
||||
#endif
|
||||
for (int i = 0; i < pixels; i++) {
|
||||
const size_t idx = (size_t)i * 3;
|
||||
const float b0 = (float)base[idx + 0];
|
||||
const float g0 = (float)base[idx + 1];
|
||||
const float r0 = (float)base[idx + 2];
|
||||
const float l0 = 0.114f * b0 + 0.587f * g0 + 0.299f * r0;
|
||||
|
||||
float acc_b = b0;
|
||||
float acc_g = g0;
|
||||
float acc_r = r0;
|
||||
float w_sum = 1.0f;
|
||||
|
||||
for (int k = 0; k < num_others; k++) {
|
||||
const uint16_t *oth = others[k];
|
||||
if (!oth) continue;
|
||||
const float bk = (float)oth[idx + 0];
|
||||
const float gk = (float)oth[idx + 1];
|
||||
const float rk = (float)oth[idx + 2];
|
||||
const float lk = 0.114f * bk + 0.587f * gk + 0.299f * rk;
|
||||
const float d = fabsf(lk - l0) * inv_nt;
|
||||
const float d2 = d * d;
|
||||
const float w = 1.0f / (1.0f + d2 * d2);
|
||||
acc_b += w * bk;
|
||||
acc_g += w * gk;
|
||||
acc_r += w * rk;
|
||||
w_sum += w;
|
||||
}
|
||||
|
||||
const float inv_w = 1.0f / w_sum;
|
||||
int ob = (int)(acc_b * inv_w + 0.5f);
|
||||
int og = (int)(acc_g * inv_w + 0.5f);
|
||||
int or_v = (int)(acc_r * inv_w + 0.5f);
|
||||
if (ob < 0) ob = 0; else if (ob > 65535) ob = 65535;
|
||||
if (og < 0) og = 0; else if (og > 65535) og = 65535;
|
||||
if (or_v < 0) or_v = 0; else if (or_v > 65535) or_v = 65535;
|
||||
out[idx + 0] = (uint16_t)ob;
|
||||
out[idx + 1] = (uint16_t)og;
|
||||
out[idx + 2] = (uint16_t)or_v;
|
||||
}
|
||||
}
|
||||
+147
-22
@@ -63,19 +63,36 @@ typedef struct {
|
||||
/* Shared latest frame from worker (CAIRO_FORMAT_RGB24 BGRA32) */
|
||||
GMutex frame_mutex;
|
||||
uint8_t *frame_buf;
|
||||
size_t frame_cap;
|
||||
int frame_w;
|
||||
int frame_h;
|
||||
size_t frame_len;
|
||||
uint64_t frame_seq;
|
||||
gboolean draw_pending;
|
||||
|
||||
/* Paint copy owned exclusively by GTK main thread */
|
||||
/* Paint & reader buffers swapped under frame_mutex (zero per-frame alloc/memcpy) */
|
||||
uint8_t *paint_buf;
|
||||
size_t paint_cap;
|
||||
int paint_w;
|
||||
int paint_h;
|
||||
size_t paint_len;
|
||||
uint64_t paint_seq;
|
||||
|
||||
uint8_t *read_buf;
|
||||
size_t read_cap;
|
||||
|
||||
/* Viewfinder draw rect & tap-to-focus reticle */
|
||||
double view_rx;
|
||||
double view_ry;
|
||||
double view_rw;
|
||||
double view_rh;
|
||||
gboolean has_af;
|
||||
gboolean af_active;
|
||||
gboolean af_locked;
|
||||
double af_nx;
|
||||
double af_ny;
|
||||
int64_t af_until_us;
|
||||
|
||||
/* Camera & UI state */
|
||||
int cam_count;
|
||||
gboolean has_flash;
|
||||
@@ -366,18 +383,19 @@ static gboolean draw_viewfinder(GtkWidget *widget, cairo_t *cr, gpointer data) {
|
||||
cairo_set_source_rgb(cr, 0.043, 0.051, 0.078);
|
||||
cairo_paint(cr);
|
||||
|
||||
/* Copy latest frame buffer without holding frame_mutex during Cairo paint. */
|
||||
/* Swap latest frame pointer without holding frame_mutex during Cairo paint. */
|
||||
g_mutex_lock(&app->frame_mutex);
|
||||
if (app->frame_buf && app->frame_seq != app->paint_seq) {
|
||||
uint8_t *nb = (uint8_t *)realloc(app->paint_buf, app->frame_len);
|
||||
if (nb) {
|
||||
app->paint_buf = nb;
|
||||
memcpy(app->paint_buf, app->frame_buf, app->frame_len);
|
||||
app->paint_w = app->frame_w;
|
||||
app->paint_h = app->frame_h;
|
||||
app->paint_len = app->frame_len;
|
||||
app->paint_seq = app->frame_seq;
|
||||
}
|
||||
uint8_t *tmp_buf = app->paint_buf;
|
||||
size_t tmp_cap = app->paint_cap;
|
||||
app->paint_buf = app->frame_buf;
|
||||
app->paint_cap = app->frame_cap;
|
||||
app->paint_w = app->frame_w;
|
||||
app->paint_h = app->frame_h;
|
||||
app->paint_len = app->frame_len;
|
||||
app->paint_seq = app->frame_seq;
|
||||
app->frame_buf = tmp_buf;
|
||||
app->frame_cap = tmp_cap;
|
||||
}
|
||||
g_mutex_unlock(&app->frame_mutex);
|
||||
|
||||
@@ -399,6 +417,10 @@ static gboolean draw_viewfinder(GtkWidget *widget, cairo_t *cr, gpointer data) {
|
||||
ry = y;
|
||||
rw = dw;
|
||||
rh = dh;
|
||||
app->view_rx = rx;
|
||||
app->view_ry = ry;
|
||||
app->view_rw = rw;
|
||||
app->view_rh = rh;
|
||||
|
||||
cairo_surface_t *surf = cairo_image_surface_create_for_data(
|
||||
app->paint_buf, CAIRO_FORMAT_RGB24, iw, ih, iw * 4);
|
||||
@@ -441,6 +463,20 @@ static gboolean draw_viewfinder(GtkWidget *widget, cairo_t *cr, gpointer data) {
|
||||
cairo_stroke(cr);
|
||||
}
|
||||
|
||||
if (app->af_active && g_get_monotonic_time() <= app->af_until_us) {
|
||||
double fx = rx + app->af_nx * rw;
|
||||
double fy = ry + app->af_ny * rh;
|
||||
double sz = app->af_locked ? 46.0 : 54.0;
|
||||
rounded_rect_path(cr, fx - sz / 2.0, fy - sz / 2.0, sz, sz, 10.0);
|
||||
if (app->af_locked) {
|
||||
cairo_set_source_rgba(cr, 0.20, 0.83, 0.60, 0.92);
|
||||
} else {
|
||||
cairo_set_source_rgba(cr, 1.0, 1.0, 1.0, 0.88);
|
||||
}
|
||||
cairo_set_line_width(cr, 2.0);
|
||||
cairo_stroke(cr);
|
||||
}
|
||||
|
||||
if (app->countdown_left > 0) {
|
||||
char buf[16];
|
||||
snprintf(buf, sizeof(buf), "%d", app->countdown_left);
|
||||
@@ -685,6 +721,27 @@ static gboolean handle_worker_line_idle(gpointer data) {
|
||||
gtk_label_set_text(GTK_LABEL(app->rec_label), "● 00:00");
|
||||
}
|
||||
sync_ui_labels(app);
|
||||
} else if (strncmp(line, "af_caps ", 8) == 0) {
|
||||
app->has_af = (atoi(line + 8) != 0);
|
||||
if (!app->has_af) {
|
||||
app->af_active = FALSE;
|
||||
gtk_widget_queue_draw(app->view_area);
|
||||
}
|
||||
} else if (strncmp(line, "af_state ", 9) == 0) {
|
||||
char st[32] = "";
|
||||
double nx = 0.5, ny = 0.5;
|
||||
if (sscanf(line + 9, "%31s %lf %lf", st, &nx, &ny) >= 1) {
|
||||
if (strcmp(st, "idle") == 0) {
|
||||
app->af_active = FALSE;
|
||||
} else {
|
||||
app->af_nx = fmax(0.05, fmin(0.95, nx));
|
||||
app->af_ny = fmax(0.05, fmin(0.95, ny));
|
||||
app->af_locked = (strcmp(st, "locked") == 0);
|
||||
app->af_active = TRUE;
|
||||
app->af_until_us = g_get_monotonic_time() + (app->af_locked ? 1200000LL : 4000000LL);
|
||||
}
|
||||
gtk_widget_queue_draw(app->view_area);
|
||||
}
|
||||
} else if (strncmp(line, "saved_photo ", 12) == 0) {
|
||||
gchar *base = g_path_get_basename(line + 12);
|
||||
gchar *msg = g_strdup_printf("Saved %s", base);
|
||||
@@ -694,15 +751,41 @@ static gboolean handle_worker_line_idle(gpointer data) {
|
||||
refresh_thumbnail(app);
|
||||
} else if (strncmp(line, "saved_video ", 12) == 0) {
|
||||
int frames = 0;
|
||||
int dur_ms = 0;
|
||||
const char *p = line + 12;
|
||||
const char *sp = strchr(p, ' ');
|
||||
if (sp) {
|
||||
frames = atoi(p);
|
||||
gchar *base = g_path_get_basename(sp + 1);
|
||||
gchar *msg = g_strdup_printf("Saved %s (%d frames)", base, frames);
|
||||
show_toast(app, msg, 2.8);
|
||||
g_free(base);
|
||||
g_free(msg);
|
||||
const char *rest = sp + 1;
|
||||
const char *sp2 = strchr(rest, ' ');
|
||||
gboolean has_dur = FALSE;
|
||||
if (sp2 && isdigit((unsigned char)rest[0])) {
|
||||
has_dur = TRUE;
|
||||
for (const char *c = rest; c < sp2; c++) {
|
||||
if (!isdigit((unsigned char)*c)) {
|
||||
has_dur = FALSE;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (has_dur) {
|
||||
dur_ms = atoi(rest);
|
||||
gchar *base = g_path_get_basename(sp2 + 1);
|
||||
double secs = dur_ms > 0 ? (dur_ms / 1000.0) : 0.0;
|
||||
double fps = (secs > 0.05 && frames > 0) ? (frames / secs) : 0.0;
|
||||
gchar *msg = (fps > 0.5)
|
||||
? g_strdup_printf("Saved %s (%.1fs · %.0f fps)", base, secs, fps)
|
||||
: g_strdup_printf("Saved %s (%d frames)", base, frames);
|
||||
show_toast(app, msg, 2.8);
|
||||
g_free(base);
|
||||
g_free(msg);
|
||||
} else {
|
||||
gchar *base = g_path_get_basename(rest);
|
||||
gchar *msg = g_strdup_printf("Saved %s (%d frames)", base, frames);
|
||||
show_toast(app, msg, 2.8);
|
||||
g_free(base);
|
||||
g_free(msg);
|
||||
}
|
||||
}
|
||||
} else if (strncmp(line, "toast ", 6) == 0) {
|
||||
show_toast(app, line + 6, 3.0);
|
||||
@@ -723,25 +806,32 @@ static gpointer worker_reader_func(gpointer data) {
|
||||
if (sscanf(line + 6, "%d %d %lu", &w, &h, &len) == 3 &&
|
||||
w > 0 && h > 0 && len == (unsigned long)w * (unsigned long)h * 4UL &&
|
||||
len <= 16UL * 1024UL * 1024UL) {
|
||||
uint8_t *buf = (uint8_t *)malloc((size_t)len);
|
||||
if (!buf) break;
|
||||
if ((size_t)len > app->read_cap) {
|
||||
uint8_t *nb = (uint8_t *)realloc(app->read_buf, (size_t)len);
|
||||
if (!nb) break;
|
||||
app->read_buf = nb;
|
||||
app->read_cap = (size_t)len;
|
||||
}
|
||||
size_t got = 0;
|
||||
while (got < (size_t)len) {
|
||||
size_t n = fread(buf + got, 1, (size_t)len - got, app->from_worker);
|
||||
size_t n = fread(app->read_buf + got, 1, (size_t)len - got, app->from_worker);
|
||||
if (n == 0) break;
|
||||
got += n;
|
||||
}
|
||||
if (got != (size_t)len) {
|
||||
free(buf);
|
||||
break;
|
||||
}
|
||||
g_mutex_lock(&app->frame_mutex);
|
||||
free(app->frame_buf);
|
||||
app->frame_buf = buf;
|
||||
uint8_t *tmp_buf = app->frame_buf;
|
||||
size_t tmp_cap = app->frame_cap;
|
||||
app->frame_buf = app->read_buf;
|
||||
app->frame_cap = app->read_cap;
|
||||
app->frame_w = w;
|
||||
app->frame_h = h;
|
||||
app->frame_len = (size_t)len;
|
||||
app->frame_seq++;
|
||||
app->read_buf = tmp_buf;
|
||||
app->read_cap = tmp_cap;
|
||||
gboolean need_schedule = !app->draw_pending;
|
||||
if (need_schedule) app->draw_pending = TRUE;
|
||||
g_mutex_unlock(&app->frame_mutex);
|
||||
@@ -774,6 +864,10 @@ static gboolean tick_ui(gpointer data) {
|
||||
app->toast_text = NULL;
|
||||
dirty = TRUE;
|
||||
}
|
||||
if (app->af_active && now > app->af_until_us) {
|
||||
app->af_active = FALSE;
|
||||
dirty = TRUE;
|
||||
}
|
||||
if (app->is_recording) {
|
||||
int secs = (int)((now - app->rec_start_us) / 1000000LL);
|
||||
if (secs < 0) secs = 0;
|
||||
@@ -1100,10 +1194,38 @@ static gboolean start_worker_process(CameraApp *app) {
|
||||
if (!app->to_worker || !app->from_worker) {
|
||||
return FALSE;
|
||||
}
|
||||
setvbuf(app->from_worker, NULL, _IOFBF, 256 * 1024);
|
||||
app->reader_thread = g_thread_new("cam-reader", worker_reader_func, app);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
static gboolean on_view_button_press(GtkWidget *w, GdkEventButton *ev, gpointer data) {
|
||||
(void)w;
|
||||
CameraApp *app = (CameraApp *)data;
|
||||
if (ev->type != GDK_BUTTON_PRESS || ev->button != 1) return FALSE;
|
||||
if (!app->has_af || app->view_rw <= 20.0 || app->view_rh <= 20.0) return FALSE;
|
||||
if (ev->x < app->view_rx || ev->x > app->view_rx + app->view_rw ||
|
||||
ev->y < app->view_ry || ev->y > app->view_ry + app->view_rh) {
|
||||
return FALSE;
|
||||
}
|
||||
double nx = (ev->x - app->view_rx) / app->view_rw;
|
||||
double ny = (ev->y - app->view_ry) / app->view_rh;
|
||||
if (app->active_is_front) nx = 1.0 - nx;
|
||||
nx = fmax(0.1, fmin(0.9, nx));
|
||||
ny = fmax(0.1, fmin(0.9, ny));
|
||||
|
||||
char cmd[64];
|
||||
snprintf(cmd, sizeof(cmd), "focus %.3f %.3f", nx, ny);
|
||||
send_worker(app, cmd);
|
||||
app->af_nx = app->active_is_front ? (1.0 - nx) : nx;
|
||||
app->af_ny = ny;
|
||||
app->af_locked = FALSE;
|
||||
app->af_active = TRUE;
|
||||
app->af_until_us = g_get_monotonic_time() + 4000000LL;
|
||||
gtk_widget_queue_draw(app->view_area);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
static void build_ui(CameraApp *app) {
|
||||
GtkSettings *settings = gtk_settings_get_default();
|
||||
if (settings) {
|
||||
@@ -1165,7 +1287,9 @@ static void build_ui(CameraApp *app) {
|
||||
app->view_area = gtk_drawing_area_new();
|
||||
gtk_widget_set_hexpand(app->view_area, TRUE);
|
||||
gtk_widget_set_vexpand(app->view_area, TRUE);
|
||||
gtk_widget_add_events(app->view_area, GDK_BUTTON_PRESS_MASK);
|
||||
g_signal_connect(app->view_area, "draw", G_CALLBACK(draw_viewfinder), app);
|
||||
g_signal_connect(app->view_area, "button-press-event", G_CALLBACK(on_view_button_press), app);
|
||||
gtk_container_add(GTK_CONTAINER(overlay), app->view_area);
|
||||
|
||||
GtkWidget *top_bar = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 8);
|
||||
@@ -1409,6 +1533,7 @@ int main(int argc, char **argv) {
|
||||
|
||||
free(app.frame_buf);
|
||||
free(app.paint_buf);
|
||||
free(app.read_buf);
|
||||
g_free(app.worker_exe);
|
||||
g_free(app.initial_camera);
|
||||
g_free(app.active_label);
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
# SPDX-License-Identifier: CC0-1.0
|
||||
%YAML 1.1
|
||||
---
|
||||
version: 1
|
||||
algorithms:
|
||||
- BlackLevel:
|
||||
- Awb:
|
||||
- Ccm:
|
||||
ccms:
|
||||
- ct: 3000
|
||||
ccm: [ 1.38, -0.22, -0.16,
|
||||
-0.28, 1.42, -0.14,
|
||||
-0.03, -0.56, 1.59 ]
|
||||
- ct: 4500
|
||||
ccm: [ 1.40, -0.24, -0.16,
|
||||
-0.24, 1.44, -0.20,
|
||||
-0.03, -0.46, 1.49 ]
|
||||
- ct: 6500
|
||||
ccm: [ 1.44, -0.28, -0.16,
|
||||
-0.21, 1.43, -0.22,
|
||||
-0.05, -0.42, 1.47 ]
|
||||
- Adjust:
|
||||
- Agc:
|
||||
...
|
||||
@@ -0,0 +1,32 @@
|
||||
# SPDX-License-Identifier: CC0-1.0
|
||||
%YAML 1.1
|
||||
---
|
||||
version: 1
|
||||
algorithms:
|
||||
- BlackLevel:
|
||||
- Awb:
|
||||
- Ccm:
|
||||
ccms:
|
||||
- ct: 2890
|
||||
ccm: [ 1.36754, -0.18448, -0.18306,
|
||||
-0.32356, 1.44826, -0.12471,
|
||||
-0.00412, -0.69936, 1.70348 ]
|
||||
- ct: 3550
|
||||
ccm: [ 1.42836, -0.27235, -0.15601,
|
||||
-0.28751, 1.41075, -0.12325,
|
||||
-0.01812, -0.54849, 1.56661 ]
|
||||
- ct: 4500
|
||||
ccm: [ 1.36328, -0.19569, -0.16759,
|
||||
-0.25254, 1.52248, -0.26994,
|
||||
-0.01575, -0.53155, 1.54729 ]
|
||||
- ct: 5700
|
||||
ccm: [ 1.49207, -0.37245, -0.11963,
|
||||
-0.21493, 1.40005, -0.18512,
|
||||
-0.03781, -0.38779, 1.42561 ]
|
||||
- ct: 7900
|
||||
ccm: [ 1.34849, -0.05425, -0.29424,
|
||||
-0.22182, 1.77684, -0.55502,
|
||||
-0.07403, -0.55336, 1.62739 ]
|
||||
- Adjust:
|
||||
- Agc:
|
||||
...
|
||||
@@ -0,0 +1,10 @@
|
||||
# SPDX-License-Identifier: CC0-1.0
|
||||
%YAML 1.1
|
||||
---
|
||||
version: 1
|
||||
algorithms:
|
||||
- BlackLevel:
|
||||
- Awb:
|
||||
- Adjust:
|
||||
- Agc:
|
||||
...
|
||||
+241
-36
@@ -1,10 +1,15 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Host-side unit tests for chandra-camera frame/camera helpers (no hardware required)."""
|
||||
"""Host-side unit tests for chandra-camera frame/camera/AE/AF/VFR-mux helpers (no hardware required)."""
|
||||
|
||||
import ctypes
|
||||
import importlib.machinery
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
try:
|
||||
@@ -24,6 +29,65 @@ sys.modules["chandra_camera_mod"] = cam_mod
|
||||
_loader.exec_module(cam_mod)
|
||||
|
||||
|
||||
class _FakeSubdevIO:
|
||||
"""In-memory mock for _V4L2SubdevIO supporting query/get/set/close."""
|
||||
|
||||
def __init__(self, ctrls):
|
||||
# ctrls: cid -> (mn, mx, step, df, val)
|
||||
self.ctrls = {k: list(v) for k, v in ctrls.items()}
|
||||
self.history = []
|
||||
self.closed = False
|
||||
|
||||
def query(self, cid):
|
||||
if cid not in self.ctrls:
|
||||
raise OSError("unsupported ctrl 0x%x" % cid)
|
||||
mn, mx, step, df, _ = self.ctrls[cid]
|
||||
return mn, mx, step, df
|
||||
|
||||
def get(self, cid):
|
||||
if cid not in self.ctrls:
|
||||
raise OSError("unsupported ctrl 0x%x" % cid)
|
||||
return self.ctrls[cid][4]
|
||||
|
||||
def set(self, cid, val):
|
||||
if cid not in self.ctrls:
|
||||
raise OSError("unsupported ctrl 0x%x" % cid)
|
||||
mn, mx, _step, _df, _ = self.ctrls[cid]
|
||||
v = max(mn, min(int(val), mx))
|
||||
self.ctrls[cid][4] = v
|
||||
self.history.append((cid, v))
|
||||
return v
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
def _make_quad_csi2p_image(w=16, h=16, top_val=800, bot_val=800, bg_val=96):
|
||||
"""Build a 10-bit CSI-2 packed 4x4 Quad-Bayer SRGGB frame preserving all 10 bits."""
|
||||
stride = (w // 4) * 5
|
||||
arr = np.zeros((h, stride), dtype=np.uint8)
|
||||
|
||||
def pack4(p0, p1, p2, p3):
|
||||
b0 = (p0 >> 2) & 0xFF
|
||||
b1 = (p1 >> 2) & 0xFF
|
||||
b2 = (p2 >> 2) & 0xFF
|
||||
b3 = (p3 >> 2) & 0xFF
|
||||
b4 = (p0 & 3) | ((p1 & 3) << 2) | ((p2 & 3) << 4) | ((p3 & 3) << 6)
|
||||
return b0, b1, b2, b3, b4
|
||||
|
||||
for y in range(h):
|
||||
top = y < (h // 2)
|
||||
for x_blk in range(w // 4):
|
||||
if (y % 4) < 2:
|
||||
c0 = top_val if top else bg_val # R
|
||||
c1 = bg_val # Gr
|
||||
else:
|
||||
c0 = bg_val # Gb
|
||||
c1 = bg_val if top else bot_val # B
|
||||
arr[y, x_blk * 5:x_blk * 5 + 5] = pack4(c0, c0, c1, c1)
|
||||
return arr.tobytes(), stride
|
||||
|
||||
|
||||
class TestCameraHelpers(unittest.TestCase):
|
||||
def test_sort_and_label_cameras(self):
|
||||
raw = [
|
||||
@@ -41,12 +105,9 @@ class TestCameraHelpers(unittest.TestCase):
|
||||
|
||||
@unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy")
|
||||
def test_convert_abgr8888_with_stride_and_rotations(self):
|
||||
# 2x3 image with stride padding (row = 2*4 + 4 padding bytes = 12)
|
||||
h, w, stride = 3, 2, 12
|
||||
buf = bytearray(h * stride)
|
||||
# Pixel (x=0, y=0): ABGR8888 in LE memory is [R, G, B, A] = [10, 20, 200, 255] -> BGR [200, 20, 10]
|
||||
buf[0:4] = bytes([10, 20, 200, 255])
|
||||
# Pixel (x=1, y=0): R=40, G=50, B=60 -> BGR [60, 50, 40]
|
||||
buf[4:8] = bytes([40, 50, 60, 255])
|
||||
|
||||
bgr0 = cam_mod.convert_frame(buf, w, h, stride, "ABGR8888", rot=0, cv2_mod=cv2, np_mod=np)
|
||||
@@ -56,24 +117,20 @@ class TestCameraHelpers(unittest.TestCase):
|
||||
|
||||
bgr90 = cam_mod.convert_frame(buf, w, h, stride, "ABGR8888", rot=90, cv2_mod=cv2, np_mod=np)
|
||||
self.assertEqual(bgr90.shape, (2, 3, 3))
|
||||
# Libcamera Rotation=90 (CCW mounting) rotates CCW: (row=0, col=0) -> (row=w-1=1, col=0)
|
||||
self.assertEqual(tuple(bgr90[1, 0]), (200, 20, 10))
|
||||
|
||||
bgr270 = cam_mod.convert_frame(buf, w, h, stride, "ABGR8888", rot=270, cv2_mod=cv2, np_mod=np)
|
||||
self.assertEqual(bgr270.shape, (2, 3, 3))
|
||||
# Libcamera Rotation=270 rotates CW: (row=0, col=0) -> (row=0, col=h-1=2)
|
||||
self.assertEqual(tuple(bgr270[0, 2]), (200, 20, 10))
|
||||
|
||||
@unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy")
|
||||
def test_convert_argb_rgb_and_cairo_bgra(self):
|
||||
# ARGB8888 in LE memory is [B, G, R, A]
|
||||
buf = bytes([210, 110, 30, 255, 10, 20, 30, 255])
|
||||
bgr = cam_mod.convert_frame(buf, 2, 1, 8, "ARGB8888", rot=0, cv2_mod=cv2, np_mod=np)
|
||||
self.assertEqual(tuple(bgr[0, 0]), (210, 110, 30))
|
||||
|
||||
rgb_buf = bytes([11, 22, 33, 44, 55, 66])
|
||||
bgr2 = cam_mod.convert_frame(rgb_buf, 2, 1, 6, "RGB888", rot=180, cv2_mod=cv2, np_mod=np)
|
||||
# Inverted horizontally+vertically and channel-flipped -> [66, 55, 44] then [33, 22, 11]
|
||||
self.assertEqual(tuple(bgr2[0, 0]), (66, 55, 44))
|
||||
self.assertEqual(tuple(bgr2[0, 1]), (33, 22, 11))
|
||||
|
||||
@@ -89,41 +146,189 @@ class TestCameraHelpers(unittest.TestCase):
|
||||
|
||||
@unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy")
|
||||
def test_debayer_quad_csi2p(self):
|
||||
# Construct an 8x8 CSI-2 10-bit packed 4x4 Quad-Bayer SRGGB image:
|
||||
# Top half (rows 0..3): strong red (R=200, G=24, B=24)
|
||||
# Bottom half (rows 4..7): strong blue (R=24, G=24, B=200)
|
||||
w, h, stride = 8, 8, 10
|
||||
arr = np.zeros((h, stride), dtype=np.uint8)
|
||||
for y in range(h):
|
||||
top = y < 4
|
||||
for x_blk in range(2): # 4 pixels per block, 5 bytes per block
|
||||
# Row phase inside 4x4 Quad-Bayer: y%4 in {0,1} -> R,R,G,G; {2,3} -> G,G,B,B
|
||||
if (y % 4) < 2:
|
||||
c0 = 200 if top else 24 # R
|
||||
c1 = 24 # G
|
||||
else:
|
||||
c0 = 24 # G
|
||||
c1 = 24 if top else 200 # B
|
||||
base = x_blk * 5
|
||||
arr[y, base + 0] = c0
|
||||
arr[y, base + 1] = c0
|
||||
arr[y, base + 2] = c1
|
||||
arr[y, base + 3] = c1
|
||||
arr[y, base + 4] = 0
|
||||
raw = arr.tobytes()
|
||||
|
||||
raw, stride = _make_quad_csi2p_image(w=8, h=8, top_val=800, bot_val=800, bg_val=96)
|
||||
out_live = cam_mod.debayer_quad_csi2p(
|
||||
raw, w, h, stride, rot=90, target_size=None, high_quality=False, cv2_mod=cv2, np_mod=np
|
||||
raw, 8, 8, stride, rot=90, target_size=None, high_quality=False, cv2_mod=cv2, np_mod=np
|
||||
)
|
||||
out_hq = cam_mod.debayer_quad_csi2p(
|
||||
raw, w, h, stride, rot=0, target_size=(6, 4), high_quality=True, cv2_mod=cv2, np_mod=np
|
||||
raw, 8, 8, stride, rot=0, target_size=(6, 4), high_quality=True, cv2_mod=cv2, np_mod=np
|
||||
)
|
||||
self.assertEqual(out_live.shape, (4, 4, 3)) # 8x8 -> 4x4, rot=90 keeps 4x4
|
||||
self.assertEqual(out_hq.shape, (4, 6, 3)) # resized to WxH = 6x4
|
||||
# Top row in rot=0 should have R > B; bottom row should have B > R.
|
||||
self.assertEqual(out_live.shape, (4, 4, 3))
|
||||
self.assertEqual(out_hq.shape, (4, 6, 3))
|
||||
self.assertGreater(float(out_hq[0, :, 2].mean()), float(out_hq[0, :, 0].mean()) + 30.0)
|
||||
self.assertGreater(float(out_hq[3, :, 0].mean()), float(out_hq[3, :, 2].mean()) + 30.0)
|
||||
|
||||
@unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy")
|
||||
def test_c_isp_vs_numpy_fallback_and_10bit_lsbs(self):
|
||||
lib = cam_mod.load_isp_lib()
|
||||
self.assertIsNotNone(lib, "expected compiled build/libchandra-camera-isp.so")
|
||||
|
||||
raw_a, stride = _make_quad_csi2p_image(w=16, h=16, top_val=803, bot_val=803, bg_val=99)
|
||||
raw_b, _ = _make_quad_csi2p_image(w=16, h=16, top_val=800, bot_val=800, bg_val=96)
|
||||
|
||||
# Verify 10-bit LSBs change raw_a vs raw_b in C 4x4 unpacking.
|
||||
arr_a = np.frombuffer(raw_a, dtype=np.uint8).reshape((16, stride))
|
||||
arr_b = np.frombuffer(raw_b, dtype=np.uint8).reshape((16, stride))
|
||||
out_a = np.empty((4, 4, 3), dtype=np.uint16)
|
||||
out_b = np.empty((4, 4, 3), dtype=np.uint16)
|
||||
lib.quad_csi2p_to_bgr16_4x4(arr_a.ctypes.data, 16, 16, stride, out_a.ctypes.data)
|
||||
lib.quad_csi2p_to_bgr16_4x4(arr_b.ctypes.data, 16, 16, stride, out_b.ctypes.data)
|
||||
self.assertEqual(int(out_a[0, 0, 2]) - int(out_b[0, 0, 2]), 12) # 4 pixels * 3 LSB = 12
|
||||
|
||||
# Compare full C ISP vs NumPy fallback on both 4x4 live and 2x2 HQ paths.
|
||||
c_live = cam_mod.debayer_quad_csi2p(
|
||||
raw_a, 16, 16, stride, rot=90, target_size=(4, 4), high_quality=False, cv2_mod=cv2, np_mod=np
|
||||
)
|
||||
c_hq = cam_mod.debayer_quad_csi2p(
|
||||
raw_a, 16, 16, stride, rot=0, target_size=None, high_quality=True, cv2_mod=cv2, np_mod=np
|
||||
)
|
||||
saved_lib, saved_tried = cam_mod._ISP_LIB, cam_mod._ISP_LIB_TRIED
|
||||
try:
|
||||
cam_mod._ISP_LIB = None
|
||||
cam_mod._ISP_LIB_TRIED = True
|
||||
np_live = cam_mod.debayer_quad_csi2p(
|
||||
raw_a, 16, 16, stride, rot=90, target_size=(4, 4), high_quality=False, cv2_mod=cv2, np_mod=np
|
||||
)
|
||||
np_hq = cam_mod.debayer_quad_csi2p(
|
||||
raw_a, 16, 16, stride, rot=0, target_size=None, high_quality=True, cv2_mod=cv2, np_mod=np
|
||||
)
|
||||
finally:
|
||||
cam_mod._ISP_LIB = saved_lib
|
||||
cam_mod._ISP_LIB_TRIED = saved_tried
|
||||
|
||||
self.assertEqual(c_live.shape, (4, 4, 3))
|
||||
self.assertEqual(c_hq.shape, (8, 8, 3))
|
||||
self.assertLessEqual(int(np.abs(c_live.astype(np.int32) - np_live.astype(np.int32)).max()), 1)
|
||||
self.assertLessEqual(int(np.abs(c_hq.astype(np.int32) - np_hq.astype(np.int32)).max()), 1)
|
||||
|
||||
@unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy")
|
||||
def test_burst_merge_bgr16(self):
|
||||
lib = cam_mod.load_isp_lib()
|
||||
self.assertIsNotNone(lib)
|
||||
rng = np.random.default_rng(42)
|
||||
h, w = 32, 32
|
||||
base_clean = np.full((h, w, 3), 1000, dtype=np.int32)
|
||||
frames = []
|
||||
for _ in range(4):
|
||||
noise = rng.normal(0.0, 25.0, size=(h, w, 3))
|
||||
f = np.clip(base_clean + noise, 0, 4092).astype(np.uint16)
|
||||
frames.append(np.ascontiguousarray(f))
|
||||
# Inject strong motion artifact in frame 2 on top-left 8x8 block.
|
||||
frames[2][:8, :8, :] = 3500
|
||||
|
||||
base = frames[0]
|
||||
others = frames[1:]
|
||||
ptrs = (ctypes.c_void_p * len(others))(*[x.ctypes.data for x in others])
|
||||
out = np.empty_like(base)
|
||||
lib.burst_merge_bgr16(base.ctypes.data, ptrs, len(others), out.ctypes.data, int(h * w), 120.0)
|
||||
|
||||
static_std_before = float(base[12:, 12:, :].std())
|
||||
static_std_after = float(out[12:, 12:, :].std())
|
||||
self.assertLess(static_std_after, static_std_before * 0.7)
|
||||
# Moving patch from frame 2 must not ghost into merged static base.
|
||||
self.assertLess(float(out[:8, :8, :].mean()), 1200.0)
|
||||
|
||||
def test_quad_sensor_ae_gain_priority_and_video_mode(self):
|
||||
io = _FakeSubdevIO({
|
||||
cam_mod.V4L2_CID_VBLANK: (56, 62029, 1, 56, 56),
|
||||
cam_mod.V4L2_CID_EXPOSURE: (4, 3542, 1, 1000, 1000),
|
||||
cam_mod.V4L2_CID_ANALOGUE_GAIN: (0, 480, 1, 0, 0),
|
||||
cam_mod.V4L2_CID_DIGITAL_GAIN: (0, 4096, 1, 1024, 1024),
|
||||
})
|
||||
ae = cam_mod.QuadSensorAE("/dev/null", io=io)
|
||||
# Mid-high EV (e.g. 10x base exposure): should stay at vb_min and raise analogue gain up to 16x first.
|
||||
vb, exp, ag, dg = ae.plan(3542.0 * 10.0)
|
||||
self.assertEqual(vb, 56)
|
||||
self.assertEqual(exp, 3542)
|
||||
self.assertGreater(ag, 400)
|
||||
self.assertEqual(dg, 1024)
|
||||
|
||||
# Very low light: photo mode extends vblank up to vb_cap_photo, video mode tightens to vb_cap_video.
|
||||
vb_photo, _, _, _ = ae.plan(ae.e_max)
|
||||
self.assertEqual(vb_photo, ae.vb_cap_photo)
|
||||
ae.cur_vblank = vb_photo
|
||||
ae.ev_total = ae.e_max
|
||||
ae.set_video_mode(True)
|
||||
self.assertLessEqual(ae.cur_vblank, ae.vb_cap_video)
|
||||
|
||||
ae.close()
|
||||
self.assertTrue(io.closed)
|
||||
self.assertEqual(io.get(cam_mod.V4L2_CID_VBLANK), 56)
|
||||
self.assertEqual(io.get(cam_mod.V4L2_CID_EXPOSURE), 1000)
|
||||
self.assertEqual(io.get(cam_mod.V4L2_CID_ANALOGUE_GAIN), 0)
|
||||
self.assertEqual(io.get(cam_mod.V4L2_CID_DIGITAL_GAIN), 1024)
|
||||
|
||||
@unittest.skipUnless(HAS_CV2_NUMPY, "requires cv2 and numpy")
|
||||
def test_contrast_af_sweep_finds_sharp_peak(self):
|
||||
io = _FakeSubdevIO({
|
||||
cam_mod.V4L2_CID_FOCUS_ABSOLUTE: (0, 1023, 1, 0, 120),
|
||||
})
|
||||
af = cam_mod.ContrastAF("/dev/null", io=io)
|
||||
|
||||
# Build crisp high-contrast checkerboard target.
|
||||
sharp_img = np.zeros((160, 160, 3), dtype=np.uint8)
|
||||
for y in range(0, 160, 8):
|
||||
for x in range(0, 160, 8):
|
||||
if ((x // 8) + (y // 8)) % 2 == 0:
|
||||
sharp_img[y:y + 8, x:x + 8] = 220
|
||||
|
||||
af.trigger(0.5, 0.5)
|
||||
steps = 0
|
||||
while af.state != "locked" and steps < 100:
|
||||
dist = abs(af.cur_pos - 600)
|
||||
sigma = 0.2 + dist / 90.0
|
||||
if sigma > 0.6:
|
||||
frame = cv2.GaussianBlur(sharp_img, (0, 0), sigma)
|
||||
else:
|
||||
frame = sharp_img.copy()
|
||||
af.step(frame, cv2_mod=cv2, np_mod=np)
|
||||
steps += 1
|
||||
|
||||
self.assertEqual(af.state, "locked")
|
||||
self.assertLess(abs(af.best_pos - 600), 60)
|
||||
af.close()
|
||||
self.assertTrue(io.closed)
|
||||
self.assertEqual(io.get(cam_mod.V4L2_CID_FOCUS_ABSOLUTE), 120)
|
||||
|
||||
@unittest.skipUnless(HAS_CV2_NUMPY and shutil.which("ffmpeg") and shutil.which("ffprobe"), "requires cv2, numpy, ffmpeg, ffprobe")
|
||||
def test_matroska_i420_muxer_vfr_and_cluster_rollover(self):
|
||||
w, h = 64, 48
|
||||
muxer = cam_mod.MatroskaI420Muxer(w, h)
|
||||
timestamps = [0, 33, 67, 100, 145, 200, 31000, 31040]
|
||||
bgr = np.full((h, w, 3), 120, dtype=np.uint8)
|
||||
i420 = cv2.cvtColor(bgr, cv2.COLOR_BGR2YUV_I420).tobytes()
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
out_mp4 = os.path.join(td, "vfr.mp4")
|
||||
cmd = [
|
||||
"ffmpeg", "-y", "-loglevel", "error",
|
||||
"-f", "matroska", "-i", "-",
|
||||
"-fps_mode", "passthrough",
|
||||
"-video_track_timescale", "1000",
|
||||
"-c:v", "libx264", "-preset", "superfast", "-crf", "22", "-bf", "0",
|
||||
"-pix_fmt", "yuv420p",
|
||||
"-movflags", "+faststart", out_mp4,
|
||||
]
|
||||
proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
for ts in timestamps:
|
||||
proc.stdin.write(muxer.encode_frame(i420, ts))
|
||||
proc.stdin.close()
|
||||
rc = proc.wait(timeout=15)
|
||||
err = proc.stderr.read().decode("utf-8", "replace")
|
||||
self.assertEqual(rc, 0, msg="ffmpeg failed: " + err)
|
||||
|
||||
info = json.loads(subprocess.check_output([
|
||||
"ffprobe", "-v", "error", "-show_streams", "-show_frames", "-of", "json", out_mp4
|
||||
], text=True))
|
||||
stream = info["streams"][0]
|
||||
frames = info["frames"]
|
||||
self.assertEqual(stream["codec_name"], "h264")
|
||||
self.assertEqual(stream["pix_fmt"], "yuv420p")
|
||||
self.assertEqual(len(frames), len(timestamps))
|
||||
pts_ms = [round(float(f["pts_time"]) * 1000.0) for f in frames]
|
||||
self.assertAlmostEqual(pts_ms[-1], 31040.0, delta=5.0)
|
||||
self.assertAlmostEqual(pts_ms[4], 145.0, delta=5.0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user