ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
pipeline.c
Go to the documentation of this file.
1#include <ascii-chat/otel.h>
3#include <ascii-chat/buffer.h>
9
12#include "pipeline.h"
13#include "capture.h"
14#include "display.h"
15#include "render.h"
16#include <libplatform/memory.h>
17#include <libplatform/compiler.h>
18#include <libplatform/system.h>
19#include <libplatform/terminal.h>
20#include <libplatform/keyboard.h>
21#include <libplatform/terminal.h>
22#include <libplatform/wakeup.h>
25#include <ascii-chat/log/log.h>
26#include <options/options.h>
27#include <libplatform/atomic.h>
29#include <string.h>
30
31/* ============================================================================
32 * External Declarations
33 * ============================================================================ */
34
35// Flag set by display thread when first frame is rendered
37
38/* ============================================================================
39 * Frame Type & Queue
40 * ============================================================================ */
41
43
44typedef struct {
45 frame_slot_t *slot; // Exclusive until free_frame publishes the slot back to capture.
46 const uint8_t *pixels; // Immutable owning reference shared by display and encoding
47 int w, h;
49 gotel_context_t telemetry_context;
50 bool fresh;
52 uint64_t captured_ns; // wall-clock timestamp
66
67static bool pipeline_frame_is_stale_visualization(const pipeline_frame_t *frame) {
68 return frame && frame->visualization && !GET_OPTION(waveform) && !GET_OPTION(fft);
69}
70
73 _Atomic bool busy;
74 size_t capacity;
75};
76
77#define PIPELINE_FRAME_SLOTS 3
78
79// Thread-safe bounded queue (ring buffer)
80typedef struct frame_queue_s {
81 void **slots;
84 mutex_t mu;
85 cond_t not_empty;
86 cond_t not_full;
87 const char *name;
89
90static frame_queue_t *frame_queue_create(int capacity, const char *name) {
91 frame_queue_t *q = SAFE_CALLOC(1, sizeof(*q), frame_queue_t *);
92 q->slots = SAFE_CALLOC(capacity, sizeof(void *), void *);
93 q->capacity = capacity;
94 q->head = q->tail = q->count = 0;
95 q->name = name;
96 mutex_init(&q->mu, name);
97 cond_init(&q->not_empty, "queue_not_empty");
98 cond_init(&q->not_full, "queue_not_full");
99 return q;
100}
101
102static void frame_queue_destroy(frame_queue_t *q) {
103 if (!q)
104 return;
105 mutex_destroy(&q->mu);
106 cond_destroy(&q->not_empty);
107 cond_destroy(&q->not_full);
108 SAFE_FREE(q->slots);
109 SAFE_FREE(q);
110}
111
112// Push item, timeout_ns=0 means non-blocking (drops if full)
113static bool frame_queue_push(frame_queue_t *q, void *item, uint64_t timeout_ns) {
114 mutex_lock(&q->mu);
115 while (q->count >= q->capacity) {
116 if (timeout_ns == 0) {
117 // Non-blocking: drop the item
118 mutex_unlock(&q->mu);
119 return false;
120 }
121 if (cond_timedwait(&q->not_full, &q->mu, timeout_ns) != 0) {
122 mutex_unlock(&q->mu);
123 return false; // timeout
124 }
125 }
126 q->slots[q->tail] = item;
127 q->tail = (q->tail + 1) % q->capacity;
128 q->count++;
129 ascii_otel_metric(ASCII_OTEL_METRIC_ENCODE_DEPTH, q->count);
130 cond_signal(&q->not_empty);
131 mutex_unlock(&q->mu);
132 return true;
133}
134
135// Pop item, timeout_ns=0 means blocking forever
136static void *frame_queue_pop(frame_queue_t *q, uint64_t timeout_ns) {
137 mutex_lock(&q->mu);
138 while (q->count == 0) {
139 if (timeout_ns == 0) {
140 // Block forever
141 cond_wait(&q->not_empty, &q->mu);
142 } else {
143 if (cond_timedwait(&q->not_empty, &q->mu, timeout_ns) != 0) {
144 mutex_unlock(&q->mu);
145 return NULL; // timeout
146 }
147 }
148 }
149 void *item = q->slots[q->head];
150 q->head = (q->head + 1) % q->capacity;
151 q->count--;
152 ascii_otel_metric(!strcmp(q->name, "display") ? ASCII_OTEL_METRIC_DISPLAY_DEPTH : ASCII_OTEL_METRIC_ENCODE_DEPTH, q->count);
153 pipeline_frame_t *telemetry_frame = item;
154 double age = (double)(time_get_ns() - telemetry_frame->captured_ns) / 1e9;
155 ascii_otel_metric(!strcmp(q->name, "display") ? ASCII_OTEL_METRIC_DISPLAY_WAIT : ASCII_OTEL_METRIC_ENCODE_WAIT, age);
156 ascii_otel_metric(ASCII_OTEL_METRIC_QUEUE_OLDEST, age);
157 cond_signal(&q->not_full);
158 mutex_unlock(&q->mu);
159 return item;
160}
161
162static int frame_queue_count(frame_queue_t *q) {
163 if (!q)
164 return 0;
165 mutex_lock(&q->mu);
166 int count = q->count;
167 mutex_unlock(&q->mu);
168 return count;
169}
170
171static void frame_queue_flush(frame_queue_t *q, void (*free_fn)(void *)) {
172 if (!q)
173 return;
174 mutex_lock(&q->mu);
175 while (q->count > 0) {
176 void *item = q->slots[q->head];
177 q->head = (q->head + 1) % q->capacity;
178 q->count--;
179 ascii_otel_metric(!strcmp(q->name, "display") ? ASCII_OTEL_METRIC_DISPLAY_DEPTH : ASCII_OTEL_METRIC_ENCODE_DEPTH, q->count);
180 pipeline_frame_t *telemetry_frame = item;
181 double age = (double)(time_get_ns() - telemetry_frame->captured_ns) / 1e9;
182 ascii_otel_metric(!strcmp(q->name, "display") ? ASCII_OTEL_METRIC_DISPLAY_WAIT : ASCII_OTEL_METRIC_ENCODE_WAIT, age);
183 ascii_otel_metric(ASCII_OTEL_METRIC_QUEUE_OLDEST, age);
184 if (item && free_fn)
185 free_fn(item);
186 }
187 mutex_unlock(&q->mu);
188}
189
190/* ============================================================================
191 * Frame Helpers
192 * ============================================================================ */
193
194static pipeline_frame_t *make_frame_copy(const image_t *src, frame_slot_t *slots) {
195 if (src->w <= 0 || src->h <= 0 || (size_t)src->w > SIZE_MAX / sizeof(rgb_pixel_t) / (size_t)src->h) {
196 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid pipeline frame dimensions");
197 return NULL;
198 }
199 size_t bytes = (size_t)src->w * (size_t)src->h * sizeof(rgb_pixel_t);
200 pipeline_frame_t *f = NULL;
201 if (slots) {
202 for (size_t i = 0; i < PIPELINE_FRAME_SLOTS; ++i) {
203 bool expected = false;
204 if (atomic_compare_exchange_strong_explicit(&slots[i].busy, &expected, true, memory_order_acquire, memory_order_relaxed)) {
205 f = &slots[i].frame;
206 f->slot = &slots[i];
207 if (slots[i].capacity < bytes) {
209 f->pixels = NULL;
210 slots[i].capacity = 0;
211 }
212 break;
213 }
214 }
215 }
216 if (!f)
217 f = SAFE_CALLOC(1, sizeof(*f), pipeline_frame_t *);
218 if (!f)
219 return NULL;
220 if (!f->pixels) {
221 f->pixels = buffer_alloc(NULL, bytes);
222 if (!f->pixels) {
223 if (f->slot)
224 atomic_store_explicit(&f->slot->busy, false, memory_order_release);
225 else
226 SAFE_FREE(f);
227 return NULL;
228 }
229 if (f->slot)
230 f->slot->capacity = bytes;
231 }
232 f->w = src->w;
233 f->h = src->h;
234 f->captured_ns = time_get_ns();
235 memcpy((void *)f->pixels, src->pixels, bytes);
236 return f;
237}
238
239static void free_frame(pipeline_frame_t *f) {
240 if (!f)
241 return;
242 if (f->slot) {
243 atomic_store_explicit(&f->slot->busy, false, memory_order_release);
244 return;
245 }
247 SAFE_FREE(f);
248}
249
250static void frame_slots_destroy(frame_slot_t *slots) {
251 for (size_t i = 0; i < PIPELINE_FRAME_SLOTS; ++i) {
252 buffer_release(slots[i].frame.pixels);
253 slots[i].frame.pixels = NULL;
254 slots[i].capacity = 0;
255 }
256}
257
258// Generic wrapper for frame_queue_flush that matches the expected void (*)(void *) signature
259static void free_frame_generic(void *f) {
260 free_frame((pipeline_frame_t *)f);
261}
262
263// Validate frame dimensions to detect corruption
264static bool frame_is_valid(const pipeline_frame_t *f) {
265 if (!f) {
266 log_error("Frame pointer is NULL");
267 return false;
268 }
269 // Reasonable bounds: width/height should be between 1 and 10000
270 if (f->w <= 0 || f->w > 10000 || f->h <= 0 || f->h > 10000) {
271 log_error("Invalid frame dimensions detected: w=%d, h=%d (likely corrupted)", f->w, f->h);
272 return false;
273 }
274 if (!f->pixels) {
275 log_error("Frame pixels pointer is NULL");
276 return false;
277 }
278 return true;
279}
280
281/* ============================================================================
282 * Pipeline Context
283 * ============================================================================ */
284
315
316/* ============================================================================
317 * Capture Thread
318 * ============================================================================ */
319
320static void *pipeline_capture_thread(void *arg) {
321 session_pipeline_t *pipeline = (session_pipeline_t *)arg;
322 log_debug("[PIPELINE_CAPTURE] Starting capture thread");
323
324 bool snapshot_mode = GET_OPTION(snapshot_mode);
325 uint64_t snapshot_frames_captured = 0;
326 uint64_t snapshot_target_frames = 1;
327 media_source_t *capture_source = session_capture_get_media_source(pipeline->capture);
328 media_source_type_t capture_source_type = media_source_get_type(capture_source);
329 bool snapshot_uses_frame_target = (capture_source_type == MEDIA_SOURCE_FILE || capture_source_type == MEDIA_SOURCE_STDIN) && !media_source_uses_webcam(capture_source);
330 if (snapshot_mode) {
331 // Initialize duration estimate BEFORE encoding frames so PTS scaling works from frame 1
333 double snapshot_delay = GET_OPTION(snapshot_delay);
334 g_snapshot_actual_duration_ms = (uint64_t)(snapshot_delay * 1000.0);
335 if (snapshot_delay > 0.0 && snapshot_uses_frame_target) {
336 double target_frames = snapshot_delay * session_capture_get_target_fps(pipeline->capture);
337 snapshot_target_frames = (uint64_t)(target_frames + 0.999999);
338 }
339 log_debug("[PIPELINE_CAPTURE] Snapshot mode: initialized g_snapshot_actual_duration_ms=%llu ms (snapshot_delay=%.2f)", (unsigned long long)g_snapshot_actual_duration_ms, snapshot_delay);
340 }
341
342 uint64_t previous_serial = 0;
343 while (!atomic_load_bool(&pipeline->stop)) {
344 ASCII_OTEL_SCOPE(PIPELINE_CAPTURE);
346 uint64_t acquisition_started_ns = time_get_ns();
347 // Classify the frame using the mode active when capture begins. KEY_3 can
348 // change the option while media_source_read_video() is still blocked.
349 bool visualization = GET_OPTION(waveform) || GET_OPTION(fft);
351
352 if (!img) {
353 if (errno_peek_since(frame_scope, &pipeline->capture_failure))
354 break;
355 if (session_capture_at_end(pipeline->capture)) {
356 log_debug("[PIPELINE_CAPTURE] End of media reached");
357 break;
358 }
359 platform_sleep_ns(1 * NS_PER_MS_INT);
360 continue;
361 }
362
363 // Copy frame
364 pipeline_frame_t *frame = make_frame_copy(img, pipeline->has_render_file ? NULL : pipeline->frame_slots);
365 if (!frame) {
367 continue;
368 }
369 frame->acquisition_started_ns = acquisition_started_ns;
371
374 frame->fresh = frame->frame_serial != previous_serial;
375 frame->visualization = visualization;
376 previous_serial = frame->frame_serial;
377
378 // Record first frame timestamp for snapshot timer
379 uint64_t zero = 0;
380 atomic_cas_u64(&pipeline->first_frame_ns, &zero, frame->captured_ns);
381
382 int telemetry_screen = ui_controller_current_screen();
383 unsigned expected = telemetry_screen == UI_SCREEN_PROMPT || telemetry_screen == UI_SCREEN_LOGS ? 0 : 1;
384 ascii_otel_pipeline_progress(0, expected | (pipeline->has_render_file ? 2 : 0));
385 // Fan out: display queue (fast, can drop), encode queue (slow, keep all)
386 pipeline_frame_t *display_copy = frame;
387 if (pipeline->has_render_file) {
388 display_copy = SAFE_MALLOC(sizeof(*display_copy), pipeline_frame_t *);
389 memcpy(display_copy, frame, sizeof(*display_copy));
390 display_copy->pixels = buffer_share(frame->pixels);
391 }
392 pipeline_frame_t *retired = atomic_ptr_exchange(&pipeline->display_pending, display_copy);
393 ascii_otel_metric(ASCII_OTEL_METRIC_DISPLAY_DEPTH, 1);
394 platform_wakeup_signal(pipeline->display_ready);
395 if (retired)
396 ascii_otel_metric(ASCII_OTEL_METRIC_DROP_DISPLAY, 1);
397 if (retired) {
400 free_frame(retired);
401 }
403
404 if (pipeline->has_render_file) {
405 // Encode all captured frames, including frames before display rendering starts
406 // The encoder will use them with correct timestamps regardless of display timing
407 bool queued = frame_queue_push(pipeline->encode_queue, frame, 500 * NS_PER_MS_INT);
408 while (!queued && snapshot_uses_frame_target && !atomic_load_bool(&pipeline->stop))
409 queued = frame_queue_push(pipeline->encode_queue, frame, 100 * NS_PER_MS_INT);
410 if (!queued) {
411 ascii_otel_metric(ASCII_OTEL_METRIC_DROP_ENCODE, 1);
414 // Non-blocking: drop if queue full after 500ms
415 log_warn_every(US_PER_SEC_INT, "[PIPELINE_CAPTURE] Encode queue blocked, dropping frame");
416 free_frame(frame);
417 } else {
419 pipeline->frames_accepted++;
420 log_debug_every(60 * US_PER_SEC_INT, "[PIPELINE_CAPTURE] Enqueued frame to encode_queue");
421 }
422 }
423
424 // Publish the acquired image before pacing the next acquisition. Sleeping
425 // with an already captured frame adds a full interval to live latency.
427
428 // Check snapshot mode elapsed time AFTER queueing frame (ensure at least 1 frame is queued)
429 if (snapshot_mode) {
430 snapshot_frames_captured++;
431 uint64_t now_ns = time_get_ns();
432
433 // Set first capture timestamp on first frame (only once)
436 log_debug("[SNAPSHOT_CAPTURE] First frame captured at %llu ns", (unsigned long long)now_ns);
437 }
438
439 // Calculate elapsed time from first capture
440 double elapsed = (double)(now_ns - g_snapshot_first_capture_ns) / NS_PER_SEC_INT;
441 double snapshot_delay = GET_OPTION(snapshot_delay);
442 bool snapshot_complete = snapshot_uses_frame_target ? snapshot_frames_captured >= snapshot_target_frames : elapsed >= snapshot_delay;
443
444 if (snapshot_complete) {
445 log_debug("[PIPELINE_CAPTURE] Snapshot video elapsed=%.3f reached delay=%.2f - stopping capture but waiting for "
446 "encode queue to drain",
447 elapsed, snapshot_delay);
448
449 // Update with actual measured duration so encoder can scale frames accurately
452 uint64_t actual_ms = snapshot_uses_frame_target ? (uint64_t)(snapshot_delay * 1000.0) : (uint64_t)(elapsed * 1000.0);
454 uint64_t last_frame_elapsed_ns = now_ns - g_snapshot_first_capture_ns;
455 g_snapshot_last_capture_elapsed_ns = last_frame_elapsed_ns;
456 log_debug("[PIPELINE_CAPTURE] g_snapshot_actual_duration_ms=%llu, last_capture_elapsed_ns=%llu", (unsigned long long)actual_ms, (unsigned long long)last_frame_elapsed_ns);
457
458 break;
459 }
460 }
461 }
462
463 atomic_store_bool(&pipeline->capture_finished, true);
464 platform_wakeup_signal(pipeline->display_ready);
465 log_debug("[PIPELINE_CAPTURE] Capture thread exiting");
466 return NULL;
467}
468
469/* ============================================================================
470 * Encode Thread
471 * ============================================================================ */
472
473static void *pipeline_encode_thread(void *arg) {
474 session_pipeline_t *pipeline = (session_pipeline_t *)arg;
475 log_debug("[PIPELINE_ENCODE] Starting encode thread");
476
477 uint64_t frames_processed = 0;
478 uint64_t recording_epoch = UINT64_MAX;
479 while (true) {
480 // Drain queued frames before exiting, even when capture was interrupted.
481 pipeline_frame_t *frame = (pipeline_frame_t *)frame_queue_pop(pipeline->encode_queue, 100 * NS_PER_MS_INT);
482
483 if (!frame) {
484 // An empty queue is final only after the producer has exited.
485 if (atomic_load_bool(&pipeline->capture_finished) && frame_queue_count(pipeline->encode_queue) == 0)
486 break; // No producer remains and the queue has drained.
487 log_debug_every(1 * US_PER_SEC_INT, "[PIPELINE_ENCODE] Waiting for frames (processed=%llu)", (unsigned long long)frames_processed);
488 continue; // timeout, keep waiting
489 }
490
491 ASCII_OTEL_SCOPE_PARENT(PIPELINE_ENCODE, &frame->telemetry_context);
492 // Validate frame before processing (catch memory corruption)
493 if (!frame_is_valid(frame)) {
494 ascii_otel_metric(ASCII_OTEL_METRIC_DROP_INVALID, 1);
495 log_error("Skipping frame with corrupted dimensions in encode thread");
496 free_frame(frame);
497 continue;
498 }
499
500 if (frames_processed == 0 || frames_processed % 30 == 0) {
501 log_debug_every(US_PER_SEC_INT, "[PIPELINE_ENCODE] Processing frame %llu: %dx%d", (unsigned long long)frames_processed, frame->w, frame->h);
502 }
503
504 if (recording_epoch != frame->source_epoch) {
506 recording_epoch = frame->source_epoch;
507 }
508
509 // Encode frame (convert_to_ascii is called internally by encode_frame)
510 // Avoid double-conversion that was causing state desynchronization between display/encode threads
511 image_t raw_image = {.w = frame->w, .h = frame->h, .pixels = (rgb_pixel_t *)frame->pixels};
512 pipeline->encode_error = session_display_encode_frame(pipeline->display, &raw_image, frame->captured_ns);
513 if (pipeline->encode_error == ASCIICHAT_OK) {
515 ascii_otel_metric(ASCII_OTEL_METRIC_ENCODE_LATENCY, (double)(time_get_ns() - frame->acquisition_started_ns) / 1e9);
516 }
517 if (pipeline->encode_error != ASCIICHAT_OK) {
518 atomic_store_bool(&pipeline->stop, true);
520 free_frame(frame);
521 break;
522 }
523 frames_processed++;
524
525 free_frame(frame);
526 }
527
528 log_debug("[PIPELINE_ENCODE] Encode thread exiting (total frames encoded=%llu)", (unsigned long long)frames_processed);
529 return NULL;
530}
531
532/* ============================================================================
533 * Public API
534 * ============================================================================ */
535
537 if (!capture || !display || !out) {
538 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL argument");
539 }
540
542 for (size_t i = 0; i < PIPELINE_FRAME_SLOTS; ++i)
543 atomic_init(&p->frame_slots[i].busy, false);
544 p->capture = capture;
545 p->display = display;
546 if (platform_wakeup_create(&p->display_ready) != ASCIICHAT_OK) {
547 SAFE_FREE(p);
548 return SET_ERRNO(ERROR_INIT, "failed to create display wakeup");
549 }
551 NAMED_REGISTER_ATOMIC_PTR(&p->display_pending, "display.pending_frame", p);
552 p->encode_queue = frame_queue_create(256, "encode"); // Large buffer for slow encoding
553
554 // Check if display has render_file configured (will be checked in encode thread)
555 // We store a flag to know whether to enqueue frames for encoding
556 double render_fps = session_display_get_render_fps(display);
557 bool has_file = session_display_has_render_file(display);
559 // Synthetic/visualization sessions can switch sources too. Their recording
560 // clock must remain elapsed session time across gaps and source FPS changes.
563
564 // Playback FPS also has a default when no recording was requested. It must
565 // not enable the encoder's lossless queue for a live-only session.
566 p->has_render_file = has_file;
567 log_debug("[PIPELINE_CREATE] render_fps=%.1f, has_file=%d, has_render_file=%d", render_fps, has_file ? 1 : 0, p->has_render_file ? 1 : 0);
568
569 atomic_store_bool(&p->stop, false);
571 NAMED_REGISTER_ATOMIC(&p->capture_finished, "pipeline_capture_finished", p);
573
574 // Start capture thread
575 if (platform_thread_create(&p->capture_tid, "pipeline_capture", pipeline_capture_thread, p) != 0) {
576 free_frame(atomic_ptr_exchange(&p->display_pending, NULL));
577 platform_wakeup_destroy(p->display_ready);
579 frame_queue_destroy(p->encode_queue);
581 SAFE_FREE(p);
582 return SET_ERRNO(ERROR_INIT, "failed to start capture thread");
583 }
584
585 // Start encode thread only if render_file is active
586 if (p->has_render_file) {
587 if (platform_thread_create(&p->encode_tid, "pipeline_encode", pipeline_encode_thread, p) != 0) {
588 atomic_store_bool(&p->stop, true);
589 thread_join(&p->capture_tid, NULL);
590 free_frame(atomic_ptr_exchange(&p->display_pending, NULL));
591 frame_slots_destroy(p->frame_slots);
592 platform_wakeup_destroy(p->display_ready);
594 frame_queue_destroy(p->encode_queue);
596 SAFE_FREE(p);
597 return SET_ERRNO(ERROR_INIT, "failed to start encode thread");
598 }
599 }
600
601 *out = p;
602 return ASCIICHAT_OK;
603}
604
605// Input has its own bounded poll cadence; ASCII conversion and terminal output
606// must never determine when an interactive command is consumed.
607static void *pipeline_input_thread(void *data) {
608 session_pipeline_t *pipeline = data;
609 asciichat_error_t result = keyboard_init();
610 atomic_store(&pipeline->input_start_status, result == ASCIICHAT_OK ? 1 : -1);
611 if (result != ASCIICHAT_OK)
612 return NULL;
613 while (!atomic_load_bool(&pipeline->stop) && !pipeline->should_exit(pipeline->input_data)) {
614 keyboard_key_t key = ui_input_read_key(UI_SCREEN_MEDIA);
615 if (key != KEY_NONE) {
616 // Ctrl-C must wake the render loop immediately. The global exit flag
617 // is also set by the handler, but stopping the pipeline here prevents a
618 // frame wait or terminal read from extending shutdown.
619 if ((int)key == 3)
620 atomic_store_bool(&pipeline->stop, true);
621 pipeline->keyboard_handler(pipeline->capture, (int)key, pipeline->input_data);
622 } else
623 platform_sleep_ms(10);
624 }
625 return NULL;
626}
627
629 if (!pipeline || !should_exit) {
630 return SET_ERRNO(ERROR_INVALID_PARAM, "NULL argument");
631 }
632
633 log_debug("[PIPELINE_MAIN] Starting main thread loop");
634 uint64_t display_epoch = UINT64_MAX;
635 if (keyboard_handler && !GET_OPTION(snapshot_mode) && !(pipeline->has_render_file && !terminal_is_interactive())) {
636 pipeline->keyboard_handler = keyboard_handler;
637 pipeline->should_exit = should_exit;
638 pipeline->input_data = user_data;
639 atomic_store(&pipeline->input_start_status, 0);
640 if (platform_thread_create(&pipeline->input_tid, "pipeline_input", pipeline_input_thread, pipeline) != ASCIICHAT_OK)
641 return SET_ERRNO(ERROR_THREAD, "Cannot start responsive session input");
642 while (atomic_load(&pipeline->input_start_status) == 0)
643 platform_sleep_ms(1);
644 if (atomic_load(&pipeline->input_start_status) < 0) {
645 thread_join(&pipeline->input_tid, NULL);
646 return SET_ERRNO(ERROR_INIT, "Cannot initialize session keyboard input");
647 }
648 }
649
650 // Snapshot duration is owned by the capture thread. It records the first
651 // captured frame and marks capture_finished at its duration limit.
652 // The display thread waits for producer completion instead of using
653 // a second timer based on terminal rendering speed; large terminals can make
654 // ASCII conversion and render-file encoding substantially slower than capture.
655 while (!should_exit(user_data) && !atomic_load_bool(&pipeline->stop)) {
656 bool exit_check = should_exit(user_data);
657 log_debug_every(US_PER_SEC_INT, "[PIPELINE_DEBUG] should_exit=%d, stop=%d", exit_check, atomic_load_bool(&pipeline->stop));
658
659 platform_wakeup_wait(pipeline->display_ready, 100 * NS_PER_MS_INT);
660 pipeline_frame_t *frame = atomic_ptr_exchange(&pipeline->display_pending, NULL);
661
662 if (!frame) {
664 break;
665 continue;
666 }
667
668 ascii_otel_metric(ASCII_OTEL_METRIC_DISPLAY_DEPTH, 0);
669 double queue_age = (double)(time_get_ns() - frame->captured_ns) / 1e9;
670 ascii_otel_metric(ASCII_OTEL_METRIC_DISPLAY_WAIT, queue_age);
671 ascii_otel_metric(ASCII_OTEL_METRIC_QUEUE_OLDEST, queue_age);
672 ASCII_OTEL_SCOPE_PARENT(PIPELINE_DISPLAY, &frame->telemetry_context);
673 ascii_otel_scope_int(&otel_scope, "ascii_chat.queue.wait_ns", (int64_t)(time_get_ns() - frame->captured_ns));
674 // Validate frame structure exists before accessing fields
675 if (!frame_is_valid(frame)) {
676 ascii_otel_metric(ASCII_OTEL_METRIC_DROP_INVALID, 1);
677 log_error("Received invalid frame: corrupted or NULL");
678 free_frame(frame);
679 frame = NULL;
680 continue;
681 }
682
683 // A visualization frame may already be pending when the keyboard handler
684 // disables FFT/waveform. Do not let that stale synthetic frame flash before
685 // the first frame captured from the underlying webcam is displayed.
686 if (pipeline_frame_is_stale_visualization(frame)) {
687 ascii_otel_metric(ASCII_OTEL_METRIC_DROP_DISPLAY, 1);
688 free_frame(frame);
689 frame = NULL;
690 continue;
691 }
692
693 /* Visualization presentation replaces the captured image. Avoid running
694 * that image through the expensive glyph renderer only to discard it. */
695 if (frame->visualization) {
696 const bool fresh = frame->fresh;
697 const uint64_t epoch = frame->source_epoch;
698 const uint64_t acquisition_started_ns = frame->acquisition_started_ns;
699 free_frame(frame);
700 frame = NULL;
701 if (epoch == session_capture_source_epoch(pipeline->capture) && (GET_OPTION(waveform) || GET_OPTION(fft))) {
702 ui_controller_frame_acquired_at(acquisition_started_ns);
703 session_display_write_ascii_frame(pipeline->display, " ", fresh);
705 session_capture_complete_open(pipeline->capture, epoch);
706 }
707 continue;
708 }
709
710 // Check if help screen is active - if so, don't render ASCII frames
712 // Snapshot mode has no interactive prompt/log overlay. Do not discard its
713 // only captured frame because startup UI state is still settling.
714 bool help_is_active = !GET_OPTION(snapshot_mode) && (screen == UI_SCREEN_PROMPT || screen == UI_SCREEN_LOGS);
715
716 if (!help_is_active) {
717 // Convert to ASCII
718 if (display_epoch != frame->source_epoch) {
720 display_epoch = frame->source_epoch;
721 }
722 image_t tmp = {.w = frame->w, .h = frame->h, .pixels = (rgb_pixel_t *)frame->pixels};
723 uint64_t conversion_started_ns = time_get_ns();
724 char *ascii = session_display_convert_to_ascii_reuse(pipeline->display, &tmp);
725 uint64_t converted_ns = time_get_ns();
726 double read_ms = (double)(frame->captured_ns - frame->acquisition_started_ns) / NS_PER_MS_INT;
727 double queue_ms = (double)(conversion_started_ns - frame->captured_ns) / NS_PER_MS_INT;
728 double convert_ms = (double)(converted_ns - conversion_started_ns) / NS_PER_MS_INT;
729 uint64_t epoch = frame->source_epoch;
730 bool fresh = frame->fresh;
731 bool frame_visualization = frame->visualization;
732 uint64_t acquisition_started_ns = frame->acquisition_started_ns;
733 free_frame(frame);
734 frame = NULL;
735
736 if (ascii) {
737 // The option can change while conversion runs. Do not publish a
738 // synthetic visualization frame after KEY_3 has disabled it.
739 if (frame_visualization && !GET_OPTION(waveform) && !GET_OPTION(fft)) {
740 session_display_release_ascii(pipeline->display, ascii);
741 continue;
742 }
743 if (epoch == session_capture_source_epoch(pipeline->capture)) {
744 ui_controller_frame_acquired_at(acquisition_started_ns);
745 session_display_write_ascii_frame(pipeline->display, ascii, fresh);
747 uint64_t published_ns = time_get_ns();
748 ascii_otel_metric(ASCII_OTEL_METRIC_FRAME_DISPLAYED, 1);
750 ascii_otel_metric(ASCII_OTEL_METRIC_FRAME_LATENCY, (double)(published_ns - acquisition_started_ns) / 1e9);
751 session_capture_complete_open(pipeline->capture, epoch);
753 "LIVE_FRAME: capture_to_publish_ms=%.2f fresh=%d read_ms=%.2f queue_ms=%.2f convert_ms=%.2f "
754 "publish_ms=%.2f",
755 (double)(published_ns - acquisition_started_ns) / NS_PER_MS_INT, fresh, read_ms, queue_ms, convert_ms, (double)(published_ns - converted_ns) / NS_PER_MS_INT);
756 }
757 session_display_release_ascii(pipeline->display, ascii);
758 } else {
759 ascii_otel_metric(ASCII_OTEL_METRIC_DROP_CONVERT, 1);
760 log_error_every(US_PER_SEC_INT, "Failed to convert captured frame to ASCII; skipping display frame");
761 }
762 } else {
763 ascii_otel_metric(ASCII_OTEL_METRIC_DROP_SCREEN, 1);
764 free_frame(frame);
765 frame = NULL;
766 }
767 }
768
769 log_debug("[PIPELINE_MAIN] Main loop exiting, signaling threads to stop");
770 atomic_store_bool(&pipeline->stop, true);
772 if (thread_is_initialized(&pipeline->input_tid) && thread_join(&pipeline->input_tid, NULL) != ASCIICHAT_OK)
773 return SET_ERRNO(ERROR_THREAD, "Cannot join session input thread");
774 return ASCIICHAT_OK;
775}
776
778 if (!pipeline)
779 return ASCIICHAT_OK;
780
781 log_debug("[PIPELINE] Destroying pipeline, waiting for threads...");
782
783 // Signal threads to stop (may already be stopped)
784 atomic_store_bool(&pipeline->stop, true);
786
787 // Wake up any threads blocked on condition variable waits
788 // so they can check the stop flag and exit immediately
789 // instead of waiting for timeouts (e.g., 100ms frame_queue_pop timeout)
790 platform_wakeup_signal(pipeline->display_ready);
791 if (pipeline->encode_queue) {
792 mutex_lock(&pipeline->encode_queue->mu);
793 cond_broadcast(&pipeline->encode_queue->not_empty);
794 cond_broadcast(&pipeline->encode_queue->not_full);
795 mutex_unlock(&pipeline->encode_queue->mu);
796 }
797
798 if (thread_is_initialized(&pipeline->input_tid) && thread_join(&pipeline->input_tid, NULL) != ASCIICHAT_OK)
799 return SET_ERRNO(ERROR_THREAD, "Cannot join session input thread during shutdown");
800 // During Ctrl-C the presentation thread may be inside terminal output. Its
801 // drain handshake waits for that output to complete and can deadlock the
802 // shutdown path. The pending frame is still released below; normal exits
803 // retain the full display drain.
805 session_display_begin_drain(pipeline->display, 0, false);
806
807 // A timeout must never let the owner free memory still referenced by a worker.
808 // Capture observes stop; encode drains its queue and exits once capture is done.
809 if (thread_is_initialized(&pipeline->capture_tid)) {
810 if (thread_join(&pipeline->capture_tid, NULL) != 0)
811 return SET_ERRNO(ERROR_THREAD, "Cannot join pipeline capture thread");
812 }
814 session_display_begin_drain(pipeline->display, pipeline->frames_accepted, true);
815 if (thread_is_initialized(&pipeline->encode_tid)) {
816 if (thread_join(&pipeline->encode_tid, NULL) != 0)
817 return SET_ERRNO(ERROR_THREAD, "Cannot join pipeline encode thread");
818 }
819
820 // Flush queues to free any remaining frames
821 free_frame(atomic_ptr_exchange(&pipeline->display_pending, NULL));
822 frame_queue_flush(pipeline->encode_queue, free_frame_generic);
823
824 frame_slots_destroy(pipeline->frame_slots);
825 platform_wakeup_destroy(pipeline->display_ready);
827 frame_queue_destroy(pipeline->encode_queue);
830 if (pipeline->capture_failure.code != ASCIICHAT_OK)
831 LOG_ERRNO_IF_SET("Media capture failed");
832 SAFE_FREE(pipeline);
833
834 log_debug("[PIPELINE] Pipeline destroyed");
835 return err;
836}
bool errno_peek_since(asciichat_errno_scope_t scope, asciichat_error_context_t *out)
asciichat_errno_scope_t errno_checkpoint(void)
asciichat_error_t errno_import(const asciichat_error_context_t *cause)
#define SET_ERRNO(code,...)
#define LOG_ERRNO_IF_SET(message)
bool atomic_cas_u64(atomic_t *a, uint64_t *expected, uint64_t new_value)
Atomically compare-and-swap a uint64_t.
void * atomic_ptr_exchange(atomic_ptr_t *a, void *new_value)
Atomically exchange a pointer and return the old value.
void atomic_store_bool(atomic_t *a, bool value)
Atomically store a boolean value.
void atomic_ptr_store(atomic_ptr_t *a, void *value)
Atomically store a pointer.
bool atomic_load_bool(atomic_t *a)
Atomic pointer wrapper.
void * atomic_ptr_load(atomic_ptr_t *a)
Atomically load a pointer.
void atomic_store_u64(atomic_t *a, uint64_t value)
Atomically store a uint64_t value.
void * buffer_alloc(buffer_domain_t *domain, size_t size)
Definition buffer.c:294
const void * buffer_share(const void *data)
Definition buffer.c:322
#define buffer_release(data)
Definition buffer.h:108
uint64_t session_capture_frame_serial(session_capture_ctx_t *ctx)
void session_capture_complete_open(session_capture_ctx_t *ctx, uint64_t epoch)
uint64_t session_capture_source_epoch(session_capture_ctx_t *ctx)
📹 Unified media capture abstraction for session-based video sources
Named object registry for debugging — log identifiable resource names.
audio_visualization_source_t source
Definition fft.c:25
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
#define SAFE_CALLOC(count, size, cast)
unsigned long long uint64_t
unsigned char uint8_t
#define NAMED_REGISTER_ATOMIC(a, name, parent_ptr)
Register an atomic_t with automatic format specifier.
#define NAMED_REGISTER_ATOMIC_PTR(a, name, parent_ptr)
Register an _Atomic(void *) with automatic format specifier.
#define NAMED_UNREGISTER(ptr)
Unregister a pointer.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INIT
Definition error_codes.h:60
@ ERROR_INVALID_PARAM
@ ERROR_THREAD
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
media_source_type_t
Media source type enumeration.
Definition source.h:102
media_source_type_t media_source_get_type(media_source_t *source)
Get media source type.
Definition source.c:1099
@ MEDIA_SOURCE_STDIN
Piped or redirected input.
Definition source.h:105
@ MEDIA_SOURCE_FILE
Media file (video/audio).
Definition source.h:104
#define NS_PER_SEC_INT
Definition time.h:173
#define NS_PER_MS_INT
Definition time.h:172
#define US_PER_SEC_INT
Definition time.h:177
#define GET_OPTION(field)
Definition options.h:1339
bool(* session_should_exit_fn)(void *user_data)
Exit condition callback type.
void(* session_keyboard_handler_fn)(session_capture_ctx_t *capture, int key, void *user_data)
Keyboard input handler callback type.
struct session_display_ctx session_display_ctx_t
session display config is intentionally a small, concrete record. Fields such as snapshot_mode,...
void session_display_begin_drain(session_display_ctx_t *ctx, uint64_t total, bool total_known)
asciichat_error_t session_display_encode_frame(session_display_ctx_t *ctx, const image_t *image, uint64_t captured_ns)
Encode frame to render-file (FFmpeg only, no terminal output).
bool session_capture_at_end(session_capture_ctx_t *ctx)
Check if capture source has reached end of stream.
struct session_capture_ctx session_capture_ctx_t
session capture config keeps the values that move through the subsystem: type, path,...
image_t * session_capture_read_frame(session_capture_ctx_t *ctx)
Read the next video frame from the capture source.
bool session_display_has_render_file(session_display_ctx_t *ctx)
Check if display has render-file configured.
uint32_t session_capture_get_target_fps(session_capture_ctx_t *ctx)
Get the target FPS configured for this capture context.
void * session_capture_get_media_source(session_capture_ctx_t *ctx)
Get the underlying media source from capture context.
void session_capture_sleep_for_fps(session_capture_ctx_t *ctx)
Sleep to maintain target frame rate.
uint32_t session_display_get_render_fps(session_display_ctx_t *ctx)
Get the render FPS configured for file output.
bool shutdown_is_requested(void)
Check if shutdown has been requested.
Definition common.c:87
🆘 Interactive keyboard help overlay for session keyboard shortcuts
void stats_counter_add(stats_scope_t *scope, stats_counter_id_t id, uint64_t amount)
📝 Logging API with multiple log levels and terminal output control
#define log_debug_every(interval_us, fmt,...)
Rate-limited DEBUG logging.
Definition log/log.h:719
#define log_error_every(interval_us, fmt,...)
Rate-limited ERROR logging.
Definition log/log.h:728
#define log_warn_every(interval_us, fmt,...)
Rate-limited WARN logging.
Definition log/log.h:725
bool should_exit(void)
Definition main.c:260
⚙️ Unified options parsing system for ascii-chat with builder pattern and lock-free access
gotel_context_t ascii_otel_context(void)
Definition otel.c:870
void ascii_otel_pipeline_progress(unsigned stage, unsigned expected)
Definition otel.c:298
void ascii_otel_scope_int(ascii_otel_scope_t *s, const char *key, int64_t value)
Definition otel.c:871
void ascii_otel_metric(ascii_otel_metric_t metric, double value)
Definition otel.c:175
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:102
#define ASCII_OTEL_SCOPE_PARENT(id, parent)
Definition otel.h:98
asciichat_error_t session_pipeline_run_main(session_pipeline_t *pipeline, session_should_exit_fn should_exit, session_keyboard_handler_fn keyboard_handler, void *user_data)
Definition pipeline.c:628
struct frame_slot_s frame_slot_t
Definition pipeline.c:42
struct frame_queue_s frame_queue_t
#define PIPELINE_FRAME_SLOTS
Definition pipeline.c:77
asciichat_error_t session_pipeline_create(session_capture_ctx_t *capture, session_display_ctx_t *display, session_pipeline_t **out)
Definition pipeline.c:536
bool g_snapshot_first_frame_rendered
asciichat_error_t session_pipeline_destroy(session_pipeline_t *pipeline)
Definition pipeline.c:777
Three-thread render pipeline: capture → display/encode.
struct session_pipeline_s session_pipeline_t
Definition pipeline.h:22
static bool size_t gotel_query_t * out
Definition queries.h:10
stats_scope_t * stats_runtime_scope(void)
Definition runtime.c:88
bool media_source_uses_webcam(media_source_t *source)
Definition source.c:647
void session_display_release_ascii(session_display_ctx_t *ctx, char *ascii)
void session_display_reset_stabilizer(session_display_ctx_t *ctx, bool recording)
char * session_display_convert_to_ascii_reuse(session_display_ctx_t *ctx, const image_t *image)
void session_display_set_render_live_timing(session_display_ctx_t *ctx)
void session_display_write_ascii_frame(session_display_ctx_t *ctx, const char *ascii, bool fresh)
🖥️ Unified terminal display abstraction for session-based rendering
uint64_t g_snapshot_last_capture_elapsed_ns
uint64_t g_snapshot_first_capture_ns
uint64_t g_snapshot_actual_duration_ms
Centralized render loop abstraction for all display modes.
bool terminal_is_interactive(void)
🔤 String Manipulation and Shell Escaping Utilities
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...
Atomic value wrapper for integral/boolean types.
Definition atomic.h:114
Atomic value wrapper for integral/boolean types.
Definition atomic.h:80
void ** slots
Definition pipeline.c:81
const char * name
Definition pipeline.c:87
cond_t not_empty
Definition pipeline.c:85
cond_t not_full
Definition pipeline.c:86
mutex_t mu
Definition pipeline.c:84
_Atomic bool busy
Definition pipeline.c:73
size_t capacity
Definition pipeline.c:74
pipeline_frame_t frame
Definition pipeline.c:72
int h
Image height in pixels (must be > 0).
rgb_pixel_t * pixels
Pixel data array (width * height RGB pixels, row-major order).
int w
Image width in pixels (must be > 0).
Media source for video and audio capture.
Definition source.c:48
uint64_t acquisition_started_ns
Definition pipeline.c:53
uint64_t source_epoch
Definition pipeline.c:48
frame_slot_t * slot
Definition pipeline.c:45
uint64_t captured_ns
Definition pipeline.c:52
gotel_context_t telemetry_context
Definition pipeline.c:49
const uint8_t * pixels
Definition pipeline.c:46
uint64_t frame_serial
Definition pipeline.c:48
For session pipeline, this is the live record that ties capture_tid, encode_tid, input_tid,...
Definition pipeline.c:290
frame_slot_t frame_slots[3]
Definition pipeline.c:299
platform_thread_t encode_tid
Definition pipeline.c:292
atomic_t capture_finished
Definition pipeline.c:308
platform_wakeup_t * display_ready
Definition pipeline.c:301
platform_thread_t capture_tid
Definition pipeline.c:291
atomic_ptr_t display_pending
Definition pipeline.c:300
session_should_exit_fn should_exit
Definition pipeline.c:296
atomic_int input_start_status
Definition pipeline.c:294
asciichat_error_t encode_error
Definition pipeline.c:311
session_display_ctx_t * display
Definition pipeline.c:305
session_keyboard_handler_fn keyboard_handler
Definition pipeline.c:295
atomic_t first_frame_ns
Definition pipeline.c:309
frame_queue_t * encode_queue
Definition pipeline.c:302
session_capture_ctx_t * capture
Definition pipeline.c:304
uint64_t frames_accepted
Definition pipeline.c:312
platform_thread_t input_tid
Definition pipeline.c:293
asciichat_error_context_t capture_failure
Definition pipeline.c:310
⏱️ High-precision timing utilities using sokol_time.h and uthash
void ui_controller_frame_acquired_at(uint64_t started_ns)
int ui_controller_current_screen(void)
@ UI_SCREEN_PROMPT
@ UI_SCREEN_LOGS
@ UI_SCREEN_MEDIA
keyboard_key_t ui_input_read_key(ui_screen_t screen)
Definition tui/input.c:374