summaryrefslogtreecommitdiff
path: root/video.c
blob: aa033c0a41a9415c0525a8c62d7fddb56c845fd2 (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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
#include "video.h"

#include <stdatomic.h>
#include <threads.h>
#include <SDL.h>
#include <unistd.h>
#include <ogg/ogg.h>
#include <vorbis/vorbisenc.h>
#include <vpx/vp8cx.h>

#include "log.h"
#include "camera.h"

// no real harm in making this bigger, other than increased memory usage.
#define AUDIO_QUEUE_SIZE ((size_t)128 << 10)

struct VideoContext {
	double start_time;
	int audio_frame_samples;
	ogg_stream_state video_stream, audio_stream;
	vorbis_dsp_state vorbis;
	vpx_codec_ctx_t vpx;
	vpx_image_t vpx_image;
	int64_t next_video_pts;
	int64_t video_packetno;
	int framerate;
	SDL_AudioDeviceID audio_device;
	FILE *outfile;
	bool recording;
	// ring buffer of audio data.
	float audio_queue[AUDIO_QUEUE_SIZE];
	atomic_uint_fast32_t audio_head;
	atomic_uint_fast32_t audio_tail;
	char _unused1[128]; // reduce false sharing
};

// NOTE: SDL2 pulseaudio capture is broken on some versions of SDL 2.30: https://github.com/libsdl-org/SDL/issues/9706
static void audio_callback(void *data, Uint8 *stream_u8, int len) {
	VideoContext *ctx = data;
	const float *stream = (const float *)stream_u8;
	// this call already happens-after any earlier writes to audio_tail, so relaxed is fine.
	uint32_t tail = atomic_load_explicit(&ctx->audio_tail, memory_order_relaxed);
	uint32_t head = atomic_load(&ctx->audio_head);
	if ((tail - head + AUDIO_QUEUE_SIZE) % AUDIO_QUEUE_SIZE > AUDIO_QUEUE_SIZE * 3 / 4) {
		static int warned;
		if (warned < 10) {
			log_warning("audio overrun");
			warned++;
		}
	} else {
		const uint32_t nfloats = (uint32_t)len / sizeof(float);
		if (tail + nfloats <= AUDIO_QUEUE_SIZE) {
			// easy case
			memcpy(&ctx->audio_queue[tail], stream, len);
			tail += nfloats;
		} else {
			// "wrap around" case
			memcpy(&ctx->audio_queue[tail], stream, (AUDIO_QUEUE_SIZE - tail) * sizeof(float));
			memcpy(&ctx->audio_queue[0], &stream[AUDIO_QUEUE_SIZE - tail], (tail + nfloats - AUDIO_QUEUE_SIZE) * sizeof(float));
			tail = tail + nfloats - AUDIO_QUEUE_SIZE;
		}
	}
	atomic_store(&ctx->audio_tail, tail);
}


VideoContext *video_init(void) {
	VideoContext *ctx = calloc(1, sizeof(VideoContext));
	if (!ctx) return NULL;
	atomic_init(&ctx->audio_head, 0);
	atomic_init(&ctx->audio_tail, 0);
	SDL_AudioSpec desired = {
		.channels = 2,
		.freq = 44100,
		.format = AUDIO_F32,
		.samples = 2048,
		.callback = audio_callback,
		.userdata = ctx,
	}, obtained = {0};
	ctx->audio_device = SDL_OpenAudioDevice(NULL, 1, &desired, &obtained, SDL_AUDIO_ALLOW_SAMPLES_CHANGE);
	if (!ctx->audio_device) {
		log_error("couldn't create audio device: %s", SDL_GetError());
	}
	return ctx;
}

static bool write_packet_to_stream(VideoContext *ctx, ogg_stream_state *stream, ogg_packet *packet) {
	if (ogg_stream_packetin(stream, packet) != 0) {
		log_error("ogg_stream_packetin failed");
		return false;
	}
	ogg_page page;
	while (ogg_stream_pageout(stream, &page) != 0) {
		fwrite(page.header, 1, page.header_len, ctx->outfile);
		fwrite(page.body, 1, page.body_len, ctx->outfile);
	}
	if (ferror(ctx->outfile)) {
		log_error("error writing video output");
		return false;
	}
	return true;
}

bool video_start(VideoContext *ctx, const char *filename, int32_t width, int32_t height, int fps, int quality) {
	if (!ctx) return false;
	if (ctx->recording) {
		return true;
	}
	video_stop(ctx);
	ctx->framerate = fps;
	ctx->outfile = fopen(filename, "wb");
	if (!ctx->outfile) {
		log_perror("couldn't create %s", filename);
	}
	struct timespec ts = {1, 1};
	clock_gettime(CLOCK_MONOTONIC, &ts);
	int serial_number = (int)((int32_t)ts.tv_nsec + 1000000000 * ((int32_t)ts.tv_sec % 2));
	if (ogg_stream_init(&ctx->video_stream, serial_number) < 0) {
		log_error("ogg_stream_init(video_stream) failed");
		return false;
	}
	vpx_codec_enc_cfg_t cfg = {0};
	// NOTE: vp9 encoder seems to be much slower
	vpx_codec_iface_t *vp8 = vpx_codec_vp8_cx();
	int err = vpx_codec_enc_config_default(vp8, &cfg, 0);
	if (err != 0) {
		log_error("vpx_codec_enc_config_default: %s", vpx_codec_err_to_string(err));
		return false;
	}
	cfg.g_w = width;
	cfg.g_h = height;
	cfg.g_timebase.num = 1;
	cfg.g_timebase.den = fps;
	cfg.rc_target_bitrate = (unsigned)quality * (unsigned)width * (unsigned)height;
	err = vpx_codec_enc_init(&ctx->vpx, vp8, &cfg, 0);
	if (err != 0) {
		log_error("vpx_codec_enc_init: %s", vpx_codec_err_to_string(err));
		return false;
	}
	if (!vpx_img_alloc(&ctx->vpx_image, VPX_IMG_FMT_I420, width, height, 1)) {
		log_error("couldn't allocate VPX image");
		return false;
	}
	// I can't find any documentation of OggVP8
	//  This was pieced together from ogg_build_vp8_headers in
	//   https://github.com/FFmpeg/FFmpeg/blob/master/libavformat/oggenc.c
	typedef struct {
		char magic[5];
		uint8_t stream_type;
		uint8_t version[2];
		// doesn't seem very forwards-thinking to have these be 16-bit. oh well.
		uint16_t width;
		uint16_t height;
		uint8_t sample_aspect_ratio_num[3];
		uint8_t sample_aspect_ratio_den[3];
		// not aligned to 4 bytes ):
		uint16_t framerate_num_hi;
		uint16_t framerate_num_lo;
		uint16_t framerate_den_hi;
		uint16_t framerate_den_lo;
	} OggVP8Header;
	if (width > UINT16_MAX || height > UINT16_MAX) {
		log_error("video resolution too high");
		return false;
	}
	OggVP8Header header = {
		.magic = "OVP80",
		.stream_type = 1,
		.version = {1, 0},
		// big-endian for some reason....
		.width = SDL_SwapBE16((uint16_t)width),
		.height = SDL_SwapBE16((uint16_t)height),
		.sample_aspect_ratio_num = {0, 0, 1},
		.sample_aspect_ratio_den = {0, 0, 1},
		.framerate_num_lo = SDL_SwapBE16((uint16_t)fps),
		.framerate_den_lo = SDL_SwapBE16(1),
	};
	ogg_packet packet = {
		.packet = (uint8_t *)&header,
		.bytes = sizeof header,
		.b_o_s = true,
		.e_o_s = false,
	};
	write_packet_to_stream(ctx, &ctx->video_stream, &packet);
	bool have_audio = false;
	atomic_store(&ctx->audio_head, 0);
	ctx->recording = true;
	ctx->start_time = get_time_double();
	ctx->next_video_pts = 0;
	ctx->video_packetno = 1;
	if (have_audio) {
		// start recording audio
		SDL_PauseAudioDevice(ctx->audio_device, 0);
	}
	return true;
}

// inverse of vp8_gptopts in  https://github.com/FFmpeg/FFmpeg/blob/master/libavformat/oggparsevp8.c
// see also: https://github.com/FFmpeg/FFmpeg/blob/99e2af4e7837ca09b97d93a562dc12947179fc48/libavformat/oggenc.c#L671
static uint64_t vp8_pts_to_gp(int64_t pts, bool is_key_frame) {
	return (uint64_t)pts << 32 | (uint64_t)!is_key_frame << 3;
}

static void write_video_frame(VideoContext *ctx, vpx_image_t *image, int64_t pts) {
	int err = vpx_codec_encode(&ctx->vpx, image, pts, 1, 0, 1000000 / (ctx->framerate * 2));
	if (err != 0) {
		log_error("vpx_codec_encode: %s", vpx_codec_err_to_string(err));
	}
	const vpx_codec_cx_pkt_t *pkt = NULL;
	vpx_codec_iter_t iter = NULL;
	while ((pkt = vpx_codec_get_cx_data(&ctx->vpx, &iter))) {
		if (pkt->kind != VPX_CODEC_CX_FRAME_PKT) continue;
		ogg_packet oggp = {
			.packet = pkt->data.frame.buf,
			.bytes = pkt->data.frame.sz,
			.granulepos = vp8_pts_to_gp(pkt->data.frame.pts, pkt->data.frame.flags & VPX_FRAME_IS_KEY),
			.b_o_s = false,
			.packetno = ctx->video_packetno++,
			.e_o_s = false,
		};
		write_packet_to_stream(ctx, &ctx->video_stream, &oggp);
	}
}


bool video_submit_frame(VideoContext *ctx, Camera *camera) {
	if (!ctx || !camera || !ctx->recording) return false;
	double curr_time = get_time_double();
	double time_since_start = curr_time - ctx->start_time;
	if (ctx->audio_device) {
		// process audio
		// only this thread writes to head, so relaxed is fine.
		uint32_t head = atomic_load_explicit(&ctx->audio_head, memory_order_relaxed);
		uint32_t tail = atomic_load(&ctx->audio_tail);
		while (true) {
			break;(void)tail;
			// TODO
			#if 0
			uint32_t nfloats = (uint32_t)ctx->audio_frame_samples * 2;
			bool frame_ready = false;
			if (head + nfloats < AUDIO_QUEUE_SIZE) {
				// easy case
				frame_ready = head + nfloats <= tail || head > tail /* tail wrapped around */;
				if (frame_ready) {
					for (uint32_t s = 0; s < nfloats; s++) {
						((float *)ctx->audio_frame->data[s % 2])[s / 2] = ctx->audio_queue[head + s];
					}
					head += nfloats;
				}
			} else {
				// "wrap around" case
				frame_ready = head + nfloats - AUDIO_QUEUE_SIZE <= tail && tail < head;
				if (frame_ready) {
					for (uint32_t s = 0; s < AUDIO_QUEUE_SIZE - head; s++) {
						((float *)ctx->audio_frame->data[s % 2])[s / 2] = ctx->audio_queue[head + s];
					}
					for (uint32_t s = 0; s < head + nfloats - AUDIO_QUEUE_SIZE; s++) {
						uint32_t i = AUDIO_QUEUE_SIZE - head + s;
						((float *)ctx->audio_frame->data[i % 2])[i / 2] = ctx->audio_queue[s];
					}
					head = head + nfloats - AUDIO_QUEUE_SIZE;
				}
			}
			if (frame_ready) {
				write_frame(ctx, ctx->audio_encoder, ctx->audio_stream, ctx->audio_frame);
			} else {
				break;
			}
			#endif
		}
		atomic_store(&ctx->audio_head, head);
	}
	// process video
	int64_t pts = (int64_t)(time_since_start * ctx->framerate);
	if (pts >= ctx->next_video_pts) {
		if (camera_copy_to_vpx_image(camera, &ctx->vpx_image)) {
			write_video_frame(ctx, &ctx->vpx_image, pts);
		}
		ctx->next_video_pts = pts + 1;
	}
	return true;
}

bool video_is_recording(VideoContext *ctx) {
	if (!ctx) return false;
	return ctx->recording;
}

void video_stop(VideoContext *ctx) {
	if (!ctx) return;
	if (ctx->recording) {
		SDL_PauseAudioDevice(ctx->audio_device, 1);
		// block until callback finishes.
		SDL_LockAudioDevice(ctx->audio_device);
		SDL_UnlockAudioDevice(ctx->audio_device);
		atomic_store(&ctx->audio_head, 0);
		atomic_store(&ctx->audio_tail, 0);
		ctx->recording = false;
		// flush video encoder
		write_video_frame(ctx, NULL, -1);
		// finish video stream
		ogg_packet oggp = {
			.packet = NULL,
			.bytes = 0,
			.granulepos = vp8_pts_to_gp(ctx->next_video_pts, false),
			.b_o_s = false,
			.packetno = ctx->video_packetno++,
			.e_o_s = true,
		};
		write_packet_to_stream(ctx, &ctx->video_stream, &oggp);
		// TODO: flush audio encoder
	}
	if (ctx->outfile) {
		fclose(ctx->outfile);
		ctx->outfile = NULL;
	}
	if (ctx->vpx.iface) {
		vpx_codec_destroy(&ctx->vpx);
		ctx->vpx.iface = NULL;
	}
	if (ctx->vpx_image.planes[0]) {
		vpx_img_free(&ctx->vpx_image);
		ctx->vpx_image.planes[0] = NULL;
	}
	vorbis_dsp_clear(&ctx->vorbis);
	ogg_stream_clear(&ctx->video_stream);
	ogg_stream_clear(&ctx->audio_stream);
}

void video_quit(VideoContext *ctx) {
	if (!ctx) return;
	video_stop(ctx);
	if (ctx->audio_device) {
		SDL_CloseAudioDevice(ctx->audio_device);
	}
	free(ctx);
}