summaryrefslogtreecommitdiff
path: root/thread_mpjpeg.c
diff options
context:
space:
mode:
Diffstat (limited to 'thread_mpjpeg.c')
-rw-r--r--thread_mpjpeg.c90
1 files changed, 90 insertions, 0 deletions
diff --git a/thread_mpjpeg.c b/thread_mpjpeg.c
new file mode 100644
index 0000000..112e1a2
--- /dev/null
+++ b/thread_mpjpeg.c
@@ -0,0 +1,90 @@
+/* Copyright 2016 Luke Shumaker */
+
+#include <pthread.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "main.h"
+
+static
+char *add_nl(const char *old) {
+ size_t len = strlen(old);
+ char *new = xrealloc(NULL, len+2);
+ strcpy(new, old);
+ new[len+0] = '\n';
+ new[len+1] = '\0';
+ return new;
+}
+
+#define STARTS_WITH(str, prefix) strncmp(str, prefix, sizeof(prefix)-1)
+
+void thread_mpjpeg_reader(struct mpjpeg_stream *s, int fd, const char *boundary) {
+ FILE *stream = fdopen(fd, "r");
+ boundary = add_nl(boundary);
+
+ char *line_buf = NULL;
+ size_t line_cap = 0;
+
+ while (1) {
+ s->back->len = -1;
+ /* read the frame header (MIME headers) */
+ getline(&line_buf, &line_cap, stream);
+ if (strcmp(line_buf, boundary) != 0)
+ return;
+ ssize_t framelen = -1;
+ while (strcmp(line_buf, "\r\n") != 0) {
+ if (STARTS_WITH(line_buf, "Content-Type:")) {
+ s->back->len = atoi(&line_buf[sizeof("Content-Type:")-1]);
+ }
+ }
+ if (s->back->len < 0)
+ return;
+
+ /* read the frame contents (JPEG) */
+ if (s->back->cap < (size_t)s->back->len)
+ s->back->data = xrealloc(s->back->data, s->back->cap = s->back->len);
+ if (fread(line_buf, framelen, 1, stream) != 1)
+ return;
+
+ /* swap the frames */
+ pthread_mutex_lock(&s->frontlock);
+ struct frame *tmp = s->front;
+ s->front = s->back;
+ s->back = tmp;
+ pthread_mutex_unlock(&s->frontlock);
+ }
+
+}
+
+void thread_mpjpeg_writer(struct mpjpeg_stream *s, int fd, const char *boundary) {
+ struct frame myframe = { 0 };
+ struct frame *lastframe = NULL;
+ while(1) {
+ /* get the most recent frame (copy front to myframe) */
+ pthread_mutex_lock(&s->frontlock);
+ if (s->front == lastframe) { /* TODO: use a pthread_cond_t instead of a busy loop */
+ pthread_mutex_unlock(&s->frontlock);
+ continue;
+ }
+ if (myframe.cap < (size_t)s->front->len)
+ myframe.data = xrealloc(myframe.data, myframe.cap = s->front->len);
+ memcpy(myframe.data, s->front->data, myframe.len = s->front->len);
+ lastframe = s->front;
+ pthread_mutex_unlock(&s->frontlock);
+ /* send the frame to the client */
+ if (dprintf(fd, "%s\r\nContent-Type: image/jpeg\r\nContent-Length: %zd\r\n\r\n", boundary, myframe.len) < 0)
+ return;
+ if (write(fd, myframe.data, myframe.len) < myframe.len)
+ return;
+ }
+}
+
+void init_mpjpeg_stream(struct mpjpeg_stream *s) {
+ ZERO(s->a);
+ ZERO(s->b);
+ s->front = &s->a;
+ s->back = &s->b;
+ pthread_mutex_init(&s->frontlock, NULL);
+}