diff --git a/toolkit/patches/rtsp_sample.patch b/toolkit/patches/rtsp_sample.patch new file mode 100644 index 0000000..add2018 --- /dev/null +++ b/toolkit/patches/rtsp_sample.patch @@ -0,0 +1,87 @@ +--- a/ak_rtsp_server_sample.c ++++ b/ak_rtsp_server_sample.c +@@ -257,9 +257,17 @@ + * @void + * return: 0 - success; otherwise error code; + */ ++extern char g_rtsp_user[64], g_rtsp_pass[64]; ++extern int g_rtsp_port; ++ + int rtsp_server_init() + { +- rtsp_server_init_param(NULL); ++ rtsp_init_param ip; ++ memset(&ip, 0, sizeof ip); /* empty prefixes -> lib defaults (vs...) */ ++ ip.iServerPort = g_rtsp_port; ++ snprintf(ip.cUserName, sizeof ip.cUserName, "%s", g_rtsp_user); ++ snprintf(ip.cPassword, sizeof ip.cPassword, "%s", g_rtsp_pass); ++ rtsp_server_init_param(&ip); + + //设置网络信息 + rtsp_server_set_dev_param_callback(rtsp_server_get_dev_param_cb); +--- a/ak_rtsp_stream.c ++++ b/ak_rtsp_stream.c +@@ -121,6 +121,9 @@ + static char *pc_prog_name = NULL; //demo名称 + + static char *cfg_path = "/etc/config/rtsp.ini"; ++/* [auth] user/password (empty user = no auth), [server] port */ ++char g_rtsp_user[64] = "", g_rtsp_pass[64] = ""; ++int g_rtsp_port = 554; + int audio_enable = 1; + + //static ak_mutex_t refresh_flag_lock; +@@ -146,6 +149,7 @@ + + + int rtsp_server_init(); ++int record_start(const char *ini_path); + + /* + * get_option_short: fill the stort option string. +@@ -548,7 +552,7 @@ + vs->jpeg_qlevel = JPEG_QLEVEL_DEFAULT; //jpeg qlevel + vs->chroma_mode = CHROMA_4_2_0; //chroma mode + vs->max_picture_size = 0; //0 means default +- vs->enc_level = 30; //enc level ++ vs->enc_level = aas_ini_get_int(ini, "video0", "enc_level", 30); /* 50 = level 5.0, fits 2304x1296 */ + vs->smart_mode = 0; //smart mode set + vs->smart_goplen = 100; //smart mode value + vs->smart_quality = 50; //quality +@@ -585,7 +589,7 @@ + vs1->jpeg_qlevel = JPEG_QLEVEL_DEFAULT; //jpeg qlevel + vs1->chroma_mode = CHROMA_4_2_0; //chroma mode + vs1->max_picture_size = 0; //0 means default +- vs1->enc_level = 30; //enc level ++ vs1->enc_level = aas_ini_get_int(ini, "video1", "enc_level", 30); + vs1->smart_mode = 0; //smart mode set + vs1->smart_goplen = 100; //smart mode value + vs1->smart_quality = 50; //quality +@@ -613,6 +617,10 @@ + rtsp_param.audio.sample_bits = 16; + printf("rtsp_param.audio.code_type=%d,rtsp_param.audio.sample_rate=%d,rtsp_param.audio.sample_bits=%d\n", + rtsp_param.audio.code_type,rtsp_param.audio.sample_rate,rtsp_param.audio.sample_bits); ++ snprintf(g_rtsp_user, sizeof g_rtsp_user, "%s", aas_ini_get_string(ini, "auth", "user", "")); ++ snprintf(g_rtsp_pass, sizeof g_rtsp_pass, "%s", aas_ini_get_string(ini, "auth", "password", "")); ++ g_rtsp_port = aas_ini_get_int(ini, "server", "port", 554); ++ printf("rtsp: port %d, auth %s\n", g_rtsp_port, g_rtsp_user[0] ? "ON (digest)" : "off"); + aas_ini_free(ini); + printf("fun=%s line=%d debug here.\n",__FUNCTION__,__LINE__); + +@@ -625,7 +633,7 @@ + ak_thread_mutex_init(&rtsp_param.lock_buffer_video[0][1], NULL); + + //main stream ring buffer +- rtsp_param.ring_buffer_video[0][0] = cirbuf_new(2* 1024 *1024); ++ rtsp_param.ring_buffer_video[0][0] = cirbuf_new(4* 1024 *1024); /* ~4 s at 8 Mbps */ + + //sub stream ring buffer + rtsp_param.ring_buffer_video[0][1] = cirbuf_new(512 *1024); +@@ -1764,6 +1772,7 @@ + ak_thread_create(&(get_tid), audio_get_stream, (void*)chn, ANYKA_THREAD_MIN_STACK_SIZE, 19); + ak_thread_create(&(encode_tid), audio_get_frame_encode, NULL, ANYKA_THREAD_MIN_STACK_SIZE, 19); + rtsp_server_init(); ++ record_start(cfg_path); /* SD recording, [record] in rtsp.ini (ak_record.c) */ + + + /* WAITER for the thread exit */ diff --git a/toolkit/src/rtsp_sample/ak_record.c b/toolkit/src/rtsp_sample/ak_record.c new file mode 100644 index 0000000..81efe7b --- /dev/null +++ b/toolkit/src/rtsp_sample/ak_record.c @@ -0,0 +1,542 @@ +/* + * ak_record.c - SD-card recording for the Anyka RTSP sample. + * + * Reads encoded frames from the same ring buffer the RTSP clients use (as one more + * reader), so streaming is unaffected. Writes MPEG-TS segments: + * /YYYYMMDD/HHMMSS.ts continuous loop (oldest deleted at quota) + * /YYYYMMDD/HHMMSS.ts motion clips incl. pre-roll (own quota) + * Motion = SoC hardware 3DNR motion statistics (ak_vpss_md_get_stat, 32x24 grid). + * + * Threads: reader (ring buffer -> RAM queue, never blocks on SD), + * writer (queue -> files, pre-roll buffer, quota cleanup), + * motion (polls the md grid at 10 Hz). + * All settings come from [record] in rtsp.ini; see record_load_config(). + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ak_common.h" +#include "ak_rtsp_server.h" +#include "aas_ini_parser.h" +#include "ak_vpss.h" + +/* provided by ak_rtsp_stream.c */ +int aa_ls_reg_stream_client(int nDevId, int stream_id, int *pnHandle, char *pReaderName); +int aa_ls_get_frame(int nDevId, int stream_id, int nHandle, rtsp_frame_info *pFrame); +int aa_ls_force_i_frame(int dev, int chn); + +#define LOG(...) do { printf("[record] " __VA_ARGS__); fflush(stdout); } while (0) + +/* ------------------------------------------------------------------ config */ +enum { MODE_OFF, MODE_CONT, MODE_MOTION, MODE_BOTH }; + +static struct { + int mode, stream; + char cont_path[128], motion_path[128]; + int cont_percent, motion_percent; /* share of the folder's filesystem */ + long long cont_max_mb, motion_max_mb; /* >0 overrides the percent */ + int min_free_mb; + int segment_s, pre_s, post_s, clip_max_s; + int sensitivity, threshold, min_cells, trigger_n, md_debug; + char hook[128]; + int queue_max_kb; +} cfg; + +static void record_load_config(const char *ini_path) +{ + AAS_INI_HANDLE ini = aas_ini_load(ini_path); + const char *m; + memset(&cfg, 0, sizeof cfg); + m = ini ? aas_ini_get_string(ini, "record", "mode", "off") : "off"; + cfg.mode = !strcmp(m, "continuous") ? MODE_CONT : !strcmp(m, "motion") ? MODE_MOTION : + !strcmp(m, "both") ? MODE_BOTH : MODE_OFF; + if (!ini) return; +#define S(k, d, dst) snprintf(dst, sizeof dst, "%s", aas_ini_get_string(ini, "record", k, d)) +#define I(k, d) aas_ini_get_int(ini, "record", k, d) + cfg.stream = I("stream", 0) ? 1 : 0; + S("continuous_path", "/mnt/sd/rec/continuous", cfg.cont_path); + S("motion_path", "/mnt/sd/rec/motion", cfg.motion_path); + cfg.cont_percent = I("continuous_percent", 70); + cfg.motion_percent = I("motion_percent", 25); + cfg.cont_max_mb = I("continuous_max_mb", 0); + cfg.motion_max_mb = I("motion_max_mb", 0); + cfg.min_free_mb = I("min_free_mb", 200); + cfg.segment_s = I("segment_seconds", 60); + cfg.pre_s = I("motion_pre_seconds", 5); + cfg.post_s = I("motion_post_seconds", 10); + cfg.clip_max_s = I("motion_clip_max_seconds", 300); + cfg.sensitivity = I("motion_sensitivity", 50); + cfg.threshold = I("motion_threshold", 0); + cfg.min_cells = I("motion_min_cells", 4); + cfg.trigger_n = I("motion_trigger_frames", 2); + cfg.md_debug = I("motion_debug", 0); + S("motion_hook", "", cfg.hook); + cfg.queue_max_kb = I("queue_max_kb", 8192); +#undef S +#undef I + aas_ini_free(ini); + if (cfg.segment_s < 10) cfg.segment_s = 10; + if (cfg.pre_s < 0) cfg.pre_s = 0; + if (cfg.pre_s > 15) cfg.pre_s = 15; /* RAM: ~0.5 MB/s at 4 Mbps */ + if (cfg.post_s < 1) cfg.post_s = 1; + if (cfg.sensitivity < 0) cfg.sensitivity = 0; + if (cfg.sensitivity > 100) cfg.sensitivity = 100; + if (cfg.threshold <= 0) /* ~ the SDK md filter table */ + cfg.threshold = 10000 - 60 * cfg.sensitivity; /* 50 -> 7000, 100 -> 4000 */ + if (cfg.min_cells < 1) cfg.min_cells = 1; + if (cfg.trigger_n < 1) cfg.trigger_n = 1; +} + +/* ------------------------------------------------------------------ frames */ +struct rframe { + struct rframe *next; + unsigned long long ts_ms; + int key, codec; + unsigned int len; + unsigned char data[]; +}; + +static pthread_mutex_t q_lock = PTHREAD_MUTEX_INITIALIZER; +static pthread_cond_t q_cond = PTHREAD_COND_INITIALIZER; +static struct rframe *q_head, *q_tail; +static long q_bytes; +static volatile unsigned long long motion_until_ms; /* motion "active" until */ +static volatile int motion_now; + +static unsigned long long now_ms(void) +{ + struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); + return (unsigned long long)t.tv_sec * 1000 + t.tv_nsec / 1000000; +} + +static void *reader_thread(void *arg) +{ + int h = -1, dropping = 0, warned = 0; + rtsp_frame_info fi; + (void)arg; + while (aa_ls_reg_stream_client(0, cfg.stream, &h, "recorder") != 0 || h < 0) sleep(1); + aa_ls_force_i_frame(0, cfg.stream); + LOG("reader attached to stream %d\n", cfg.stream); + for (;;) { + if (aa_ls_get_frame(0, cfg.stream, h, &fi) < 0 || !fi.pData || !fi.uiDataLen) { + usleep(10000); + continue; + } + int key = fi.iFrameType != 0; /* FRAME_TYPE_I / PI */ + if (!warned && key) { + warned = 1; + if (!(fi.uiDataLen > 4 && fi.pData[0] == 0 && fi.pData[1] == 0 && + (fi.pData[2] == 1 || (fi.pData[2] == 0 && fi.pData[3] == 1)))) + LOG("WARNING: frames lack Annex-B start codes - files may not play\n"); + } + pthread_mutex_lock(&q_lock); + if (q_bytes + (long)fi.uiDataLen > (long)cfg.queue_max_kb * 1024) { + if (!dropping) LOG("SD too slow: queue full, dropping until next keyframe\n"); + dropping = 1; + } + if (dropping && key && q_bytes < (long)cfg.queue_max_kb * 512) dropping = 0; + if (!dropping) { + struct rframe *f = malloc(sizeof *f + fi.uiDataLen); + if (f) { + f->next = NULL; f->ts_ms = fi.u64Time; f->key = key; + f->codec = fi.iCodeType; f->len = fi.uiDataLen; + memcpy(f->data, fi.pData, fi.uiDataLen); + if (q_tail) q_tail->next = f; else q_head = f; + q_tail = f; q_bytes += f->len; + pthread_cond_signal(&q_cond); + } + } + pthread_mutex_unlock(&q_lock); + } + return NULL; +} + +/* ------------------------------------------------------------------ MPEG-TS */ +#define PID_PMT 0x1000 +#define PID_VIDEO 0x0100 + +struct ts_file { + FILE *fp; + char path[256]; + unsigned char cc_pat, cc_pmt, cc_vid; + unsigned long long start_ms, last_ms; + long long bytes; + int err; +}; + +static unsigned int crc32_mpeg(const unsigned char *p, int n) +{ + unsigned int crc = 0xffffffff; + while (n--) { + crc ^= (unsigned int)*p++ << 24; + for (int i = 0; i < 8; i++) crc = crc & 0x80000000 ? (crc << 1) ^ 0x04c11db7 : crc << 1; + } + return crc; +} + +static void ts_put(struct ts_file *t, const unsigned char *pkt) +{ + if (t->err) return; + if (fwrite(pkt, 188, 1, t->fp) != 1) { t->err = errno ? errno : EIO; return; } + t->bytes += 188; +} + +static void ts_psi(struct ts_file *t, int pid, unsigned char *cc, const unsigned char *sec, int len) +{ + unsigned char p[188]; + memset(p, 0xff, 188); + p[0] = 0x47; p[1] = 0x40 | (pid >> 8); p[2] = pid & 0xff; p[3] = 0x10 | (*cc & 0x0f); + (*cc)++; + p[4] = 0; /* pointer field */ + memcpy(p + 5, sec, len); + ts_put(t, p); +} + +static void ts_tables(struct ts_file *t, int codec) +{ + unsigned char s[32]; int n; unsigned int c; + /* PAT: program 1 -> PMT */ + n = 0; + s[n++] = 0x00; s[n++] = 0xb0; s[n++] = 13; s[n++] = 0x00; s[n++] = 0x01; + s[n++] = 0xc1; s[n++] = 0x00; s[n++] = 0x00; + s[n++] = 0x00; s[n++] = 0x01; s[n++] = 0xe0 | (PID_PMT >> 8); s[n++] = PID_PMT & 0xff; + c = crc32_mpeg(s, n); s[n++] = c >> 24; s[n++] = c >> 16; s[n++] = c >> 8; s[n++] = c; + ts_psi(t, 0, &t->cc_pat, s, n); + /* PMT: one video stream, PCR on it */ + n = 0; + s[n++] = 0x02; s[n++] = 0xb0; s[n++] = 18; s[n++] = 0x00; s[n++] = 0x01; + s[n++] = 0xc1; s[n++] = 0x00; s[n++] = 0x00; + s[n++] = 0xe0 | (PID_VIDEO >> 8); s[n++] = PID_VIDEO & 0xff; s[n++] = 0xf0; s[n++] = 0x00; + s[n++] = codec == RTSP_VIDEO_H265 ? 0x24 : 0x1b; /* HEVC : H.264 */ + s[n++] = 0xe0 | (PID_VIDEO >> 8); s[n++] = PID_VIDEO & 0xff; s[n++] = 0xf0; s[n++] = 0x00; + c = crc32_mpeg(s, n); s[n++] = c >> 24; s[n++] = c >> 16; s[n++] = c >> 8; s[n++] = c; + ts_psi(t, PID_PMT, &t->cc_pmt, s, n); +} + +static void ts_frame(struct ts_file *t, const struct rframe *f) +{ + unsigned long long pts = (f->ts_ms * 90ULL + 63000) & 0x1ffffffffULL; /* +0.7s PCR offset */ + unsigned long long pcr = (f->ts_ms * 90ULL) & 0x1ffffffffULL; + unsigned char pes[14], p[188]; + int pes_len = 14, off = 0, first = 1; + const unsigned char *d = f->data; unsigned int left = f->len; + + if (f->key) ts_tables(t, f->codec); + pes[0] = 0; pes[1] = 0; pes[2] = 1; pes[3] = 0xe0; pes[4] = 0; pes[5] = 0; /* len 0 = unbounded */ + pes[6] = 0x80; pes[7] = 0x80; pes[8] = 5; /* PTS only */ + pes[9] = 0x21 | ((pts >> 29) & 0x0e); + pes[10] = pts >> 22; pes[11] = 0x01 | ((pts >> 14) & 0xfe); + pes[12] = pts >> 7; pes[13] = 0x01 | ((pts << 1) & 0xfe); + + while (left > 0 || first) { + int hdr = 4, adapt = 0, payload_room, take, i = 0; + memset(p, 0xff, 188); + p[0] = 0x47; p[1] = (first ? 0x40 : 0) | (PID_VIDEO >> 8); p[2] = PID_VIDEO & 0xff; + if (first) adapt = 8; /* len + flags + 6-byte PCR */ + payload_room = 188 - hdr - adapt - (first ? pes_len : 0); + take = left < (unsigned)payload_room ? (int)left : payload_room; + if (take < payload_room) adapt += payload_room - take; /* stuff the last packet */ + if (adapt) { + p[3] = 0x30 | (t->cc_vid & 0x0f); + p[4] = adapt - 1; + if (adapt > 1) { + p[5] = first ? (0x10 | (f->key ? 0x40 : 0)) : 0x00; /* PCR, random access */ + i = 6; + if (first) { + p[6] = pcr >> 25; p[7] = pcr >> 17; p[8] = pcr >> 9; p[9] = pcr >> 1; + p[10] = ((pcr & 1) << 7) | 0x7e; p[11] = 0; + i = 12; + } + while (i < 4 + adapt) p[i++] = 0xff; + } + } else { + p[3] = 0x10 | (t->cc_vid & 0x0f); + } + t->cc_vid++; + off = 4 + adapt; + if (first) { memcpy(p + off, pes, pes_len); off += pes_len; } + memcpy(p + off, d, take); + d += take; left -= take; first = 0; + ts_put(t, p); + } + t->last_ms = f->ts_ms; +} + +/* ------------------------------------------------------------------ files */ +/* path must be on a real removable/disk filesystem, never on / or tmpfs */ +static int on_storage(const char *path) +{ +#ifdef RECORD_TEST + return 1; +#endif + FILE *m = fopen("/proc/mounts", "r"); + char dev[128], mnt[128], type[32], best_type[32] = ""; + size_t best = 0; + if (!m) return 0; + while (fscanf(m, "%127s %127s %31s %*[^\n]", dev, mnt, type) == 3) { + size_t l = strlen(mnt); + if (l > best && !strncmp(path, mnt, l) && (path[l] == '/' || path[l] == 0) && strcmp(mnt, "/")) { + best = l; snprintf(best_type, sizeof best_type, "%s", type); + } + } + fclose(m); + return best && strcmp(best_type, "tmpfs") && strcmp(best_type, "ramfs") && + strcmp(best_type, "squashfs") && strcmp(best_type, "jffs2") && strcmp(best_type, "proc"); +} + +static void mkdirs(const char *p) +{ + char b[256]; snprintf(b, sizeof b, "%s", p); + for (char *s = b + 1; *s; s++) if (*s == '/') { *s = 0; mkdir(b, 0755); *s = '/'; } + mkdir(b, 0755); +} + +static int ts_open(struct ts_file *t, const char *dir, const char *tag) +{ + char d[200]; time_t now = time(NULL); struct tm tm; + localtime_r(&now, &tm); + if (!on_storage(dir)) return -1; + snprintf(d, sizeof d, "%s/%04d%02d%02d", dir, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday); + mkdirs(d); + memset(t, 0, sizeof *t); + snprintf(t->path, sizeof t->path, "%s/%02d%02d%02d%s.ts", d, tm.tm_hour, tm.tm_min, tm.tm_sec, tag); + for (int i = 1; access(t->path, F_OK) == 0 && i < 100; i++) /* same second: -1, -2... */ + snprintf(t->path, sizeof t->path, "%s/%02d%02d%02d%s-%d.ts", d, tm.tm_hour, tm.tm_min, tm.tm_sec, tag, i); + t->fp = fopen(t->path, "wb"); + if (!t->fp) { LOG("cannot create %s: %s\n", t->path, strerror(errno)); return -1; } + setvbuf(t->fp, NULL, _IOFBF, 128 * 1024); + return 0; +} + +static void ts_close(struct ts_file *t) +{ + if (!t->fp) return; + fflush(t->fp); fsync(fileno(t->fp)); fclose(t->fp); + t->fp = NULL; + if (t->err) LOG("write error on %s: %s\n", t->path, strerror(t->err)); + if (t->bytes == 0) unlink(t->path); +} + +/* ------------------------------------------------------------------ quota */ +struct ent { char path[256]; long long size; }; + +static int cmp_ent(const void *a, const void *b) { return strcmp(((struct ent *)a)->path, ((struct ent *)b)->path); } + +/* collect //.ts sorted oldest first (names are dates/times) */ +static int scan(const char *dir, struct ent **out, long long *total) +{ + DIR *d = opendir(dir), *dd; struct dirent *e, *e2; struct stat st; + int n = 0, cap = 0; struct ent *v = NULL; char sub[256], f[256]; + *total = 0; + if (!d) { *out = NULL; return 0; } + while ((e = readdir(d))) { + if (e->d_name[0] == '.') continue; + snprintf(sub, sizeof sub, "%s/%s", dir, e->d_name); + if (!(dd = opendir(sub))) continue; + while ((e2 = readdir(dd))) { + if (!strstr(e2->d_name, ".ts")) continue; + snprintf(f, sizeof f, "%s/%s", sub, e2->d_name); + if (stat(f, &st)) continue; + if (n == cap) { cap = cap ? cap * 2 : 256; v = realloc(v, cap * sizeof *v); if (!v) break; } + snprintf(v[n].path, sizeof v[n].path, "%s", f); v[n].size = st.st_size; + *total += st.st_size; n++; + } + closedir(dd); + } + closedir(d); + if (v) qsort(v, n, sizeof *v, cmp_ent); + *out = v; + return v ? n : 0; +} + +static long long quota_bytes(const char *dir, int percent, long long max_mb) +{ + struct statvfs vs; + if (max_mb > 0) return max_mb * 1024 * 1024; + if (statvfs(dir, &vs)) return 0; + return (long long)vs.f_blocks * vs.f_frsize / 100 * percent; +} + +static long long fs_free(const char *dir) +{ + struct statvfs vs; + return statvfs(dir, &vs) ? 0 : (long long)vs.f_bavail * vs.f_frsize; +} + +/* delete oldest files until under quota and the filesystem keeps min_free; + * `skip` = file currently being written */ +static void enforce(const char *dir, int percent, long long max_mb, const char *skip) +{ + struct ent *v; long long total; int n, i; + char parent[256], *s; + if (!on_storage(dir)) return; + n = scan(dir, &v, &total); + long long q = quota_bytes(dir, percent, max_mb), need_free = (long long)cfg.min_free_mb << 20; + for (i = 0; i < n && (total > q || fs_free(dir) < need_free); i++) { + if (skip && !strcmp(v[i].path, skip)) continue; + if (unlink(v[i].path) == 0) { + total -= v[i].size; + snprintf(parent, sizeof parent, "%s", v[i].path); + if ((s = strrchr(parent, '/'))) { *s = 0; rmdir(parent); } /* drop empty day dir */ + } + } + free(v); +} + +/* ------------------------------------------------------------------ hook */ +static void run_hook(const char *what) +{ + if (!cfg.hook[0] || access(cfg.hook, X_OK)) return; + pid_t p = fork(); + if (p == 0) { + if (fork() == 0) { execl(cfg.hook, cfg.hook, what, (char *)NULL); _exit(127); } + _exit(0); + } + if (p > 0) waitpid(p, NULL, 0); /* double fork: no zombies */ +} + +/* ------------------------------------------------------------------ motion */ +static void *motion_thread(void *arg) +{ + struct vpss_md_info md; + int hits = 0, was = 0; + unsigned long long last_dbg = 0; + (void)arg; + LOG("motion: threshold %d, min cells %d, trigger frames %d\n", cfg.threshold, cfg.min_cells, cfg.trigger_n); + for (;;) { + usleep(100000); + if (ak_vpss_md_get_stat(0, &md)) continue; + int cells = 0, mx = 0; + for (int y = 0; y < VPSS_MD_DIMENSION_V_MAX; y++) + for (int x = 0; x < VPSS_MD_DIMENSION_H_MAX; x++) { + int v = md.stat[y][x]; + if (v > mx) mx = v; + if (v > cfg.threshold) cells++; + } + hits = cells >= cfg.min_cells ? hits + 1 : 0; + unsigned long long now = now_ms(); + if (hits >= cfg.trigger_n) motion_until_ms = now + cfg.post_s * 1000ULL; + motion_now = now < motion_until_ms; + if (motion_now != was) { + was = motion_now; + FILE *f = fopen("/tmp/motion", "w"); + if (f) { fprintf(f, "%d %ld\n", motion_now, (long)time(NULL)); fclose(f); } + LOG("motion %s\n", motion_now ? "START" : "end"); + run_hook(motion_now ? "start" : "stop"); + } + if (cfg.md_debug && now - last_dbg >= 1000) { + last_dbg = now; + LOG("md: max %d, cells>thr %d\n", mx, cells); + } + } + return NULL; +} + +/* ------------------------------------------------------------------ writer */ +static void *writer_thread(void *arg) +{ + struct ts_file cont = {0}, mot = {0}; + struct rframe *pre_head = NULL, *pre_tail = NULL; /* pre-roll, starts at a keyframe */ + int want_cont = cfg.mode == MODE_CONT || cfg.mode == MODE_BOTH; + int want_mot = cfg.mode == MODE_MOTION || cfg.mode == MODE_BOTH; + unsigned long long last_clean = 0, retry_at = 0, mot_start = 0; + int mot_active = 0; + (void)arg; + for (;;) { + pthread_mutex_lock(&q_lock); + while (!q_head) pthread_cond_wait(&q_cond, &q_lock); + struct rframe *f = q_head; + q_head = f->next; if (!q_head) q_tail = NULL; + q_bytes -= f->len; + pthread_mutex_unlock(&q_lock); + f->next = NULL; + unsigned long long now = now_ms(); + + /* --- continuous: rotate on the first keyframe after segment_seconds --- */ + if (want_cont) { + if (cont.fp && (cont.err || (f->key && f->ts_ms - cont.start_ms >= cfg.segment_s * 1000ULL))) { + ts_close(&cont); + enforce(cfg.cont_path, cfg.cont_percent, cfg.cont_max_mb, NULL); + } + if (!cont.fp && f->key && now >= retry_at) { + if (ts_open(&cont, cfg.cont_path, "") == 0) { cont.start_ms = f->ts_ms; LOG("-> %s\n", cont.path); } + else retry_at = now + 10000; /* card missing: retry later */ + } + if (cont.fp) ts_frame(&cont, f); + } + + /* --- motion clips --- */ + if (want_mot) { + int active = motion_now; + if (active && !mot_active && now >= retry_at && ((cfg.pre_s > 0 && pre_head) || f->key)) { + if (ts_open(&mot, cfg.motion_path, "") == 0) { + LOG("motion clip -> %s\n", mot.path); + mot_start = now; mot_active = 1; + for (struct rframe *p = pre_head; p; p = p->next) ts_frame(&mot, p); /* pre-roll */ + } else retry_at = now + 10000; + } + if (mot_active) { + ts_frame(&mot, f); + int too_long = now - mot_start >= cfg.clip_max_s * 1000ULL; + if (mot.err || !active || (too_long && f->key)) { + ts_close(&mot); mot_active = 0; + enforce(cfg.motion_path, cfg.motion_percent, cfg.motion_max_mb, NULL); + if (too_long && active) motion_until_ms = now_ms() + cfg.post_s * 1000ULL; + } + } + /* keep pre-roll: drop whole GOPs once the next GOP alone covers pre_s */ + if (cfg.pre_s > 0) { + if (pre_head || f->key) { + if (pre_tail) pre_tail->next = f; else pre_head = f; + pre_tail = f; f = NULL; + } + for (;;) { + struct rframe *g = pre_head ? pre_head->next : NULL; + while (g && !g->key) g = g->next; /* start of the 2nd GOP */ + if (!g || pre_tail->ts_ms - g->ts_ms < cfg.pre_s * 1000ULL) break; + while (pre_head != g) { struct rframe *x = pre_head; pre_head = x->next; free(x); } + } + } + } + free(f); /* NULL if kept as pre-roll */ + + /* periodic cleanup also catches a card that filled up from elsewhere */ + if (now - last_clean > 60000) { + last_clean = now; + if (want_cont) enforce(cfg.cont_path, cfg.cont_percent, cfg.cont_max_mb, cont.fp ? cont.path : NULL); + if (want_mot) enforce(cfg.motion_path, cfg.motion_percent, cfg.motion_max_mb, mot_active ? mot.path : NULL); + } + } + return NULL; +} + +/* ------------------------------------------------------------------ entry */ +int record_start(const char *ini_path) +{ + pthread_t t; + record_load_config(ini_path); + if (cfg.mode == MODE_OFF) { LOG("off ([record] mode = off)\n"); return 0; } + LOG("mode %s, stream %d, segment %ds\n", + cfg.mode == MODE_CONT ? "continuous" : cfg.mode == MODE_MOTION ? "motion" : "both", + cfg.stream, cfg.segment_s); + if (cfg.mode != MODE_MOTION) + LOG("continuous: %s, %s\n", cfg.cont_path, cfg.cont_max_mb > 0 ? "fixed MB quota" : "percent quota"); + if (cfg.mode != MODE_CONT) + LOG("motion: %s, pre %ds, post %ds\n", cfg.motion_path, cfg.pre_s, cfg.post_s); + signal(SIGPIPE, SIG_IGN); + pthread_create(&t, NULL, reader_thread, NULL); pthread_detach(t); + pthread_create(&t, NULL, writer_thread, NULL); pthread_detach(t); + if (cfg.mode != MODE_CONT) { pthread_create(&t, NULL, motion_thread, NULL); pthread_detach(t); } + return 0; +}