summaryrefslogtreecommitdiff
path: root/thread_mpjpeg.c
blob: 112e1a218b4b22bbbd9f0f839f9c41f50b0f7ab1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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);
}