/* -*- c-file-style: "linux" -*- */
/***
  This file is part of PulseAudio.
  PulseAudio is free software; you can redistribute it and/or modify
  it under the terms of the GNU Lesser General Public License as published
  by the Free Software Foundation; either version 2.1 of the License,
  or (at your option) any later version.
  PulseAudio is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  General Public License for more details.
  You should have received a copy of the GNU Lesser General Public License
  along with PulseAudio; if not, see <http://www.gnu.org/licenses/>.

  * Copyright 2022, 2024 Pavel Machek
***/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <pulse/simple.h>
#include <pulse/error.h>

#include "medianame.h"

/*         gcc xx.c -o xx $(pkg-config --cflags --libs libpulse-simple)
 */

int main(int argc, char*argv[]) {
	int fps = 305;  /* fps * 10 */
	/* 48000 * 2 * 2 bps, we want chunks corresponding to 30 fps */
	const uint32_t bufsize = ((48000 * 2 * 2 * 10) / fps) & ~3;

	if (argc != 2) {
		printf("usage: prog fps*10, run in recording directory\n");
		exit(1);
	}
	fps = atoi(argv[1]);

	/* The sample type to use */
	static const pa_sample_spec ss = {
		.format = PA_SAMPLE_S16LE,
		.rate = 48000,
		.channels = 2
	};
	static pa_buffer_attr attr = {
		.minreq = (uint32_t) -1,
		.prebuf = (uint32_t) -1,
		.tlength = (uint32_t) -1,
	};
	pa_simple *r = NULL;
	int ret = 1;
	int error;
	const pa_buffer_attr *p_attr = &attr;
	int opt = 0; // | PA_STREAM_ADJUST_LATENCY;
	uint8_t *buf = malloc(bufsize);

	attr.fragsize = bufsize;
	attr.maxlength = bufsize;

	/* Create the recording stream */
	if (!(r = pa_simple_new(NULL, argv[0], PA_STREAM_RECORD | opt, NULL, "record", &ss, NULL, p_attr, &error))) {
		fprintf(stderr, __FILE__": pa_simple_new() failed: %s\n", pa_strerror(error));
		goto finish;
	}

	for (;;) {
		char name[1024];
		int fd, res;

		/* Record some data ... */
		if (pa_simple_read(r, buf, bufsize, &error) < 0) {
			fprintf(stderr, __FILE__": pa_simple_read() failed: %s\n", pa_strerror(error));
			goto finish;
		}

		get_name(name, ".", "48000-s16le-stereo.sa");
		fd = open(name, O_WRONLY | O_CREAT | O_EXCL, 0666);
		res = write(fd, buf, bufsize);
		if (res != bufsize) {
			fprintf(stderr, __FILE__": could not write samples: %m\n");
			goto finish;
		}
		close(fd);
	}

finish:
	if (r)
		pa_simple_free(r);
	return ret;
}
