From 459e2685158f1dc5a9cd3da1c3125889bc02f9d6 Mon Sep 17 00:00:00 2001 From: gayot_o Date: Tue, 19 Nov 2013 02:43:27 +0000 Subject: mplayer_server: first version of the server --- main.c | 92 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 main.c (limited to 'main.c') diff --git a/main.c b/main.c new file mode 100644 index 0000000..bb74011 --- /dev/null +++ b/main.c @@ -0,0 +1,92 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "mplayer_server.h" +#include "request.h" + +FILE *stream_g; + +static request_t buffer_g; + +void *get_assoc_cb(int opcode); + +/* returns a socket listing to port or -1 if something failed */ +static int bind_socket(uint16_t port) +{ + int sock = socket(AF_INET, SOCK_STREAM, 0); + struct sockaddr_in sin; + + if (sock < 0) { + perror("socket"); + return -1; + } + + sin.sin_addr.s_addr = htonl(INADDR_ANY); + sin.sin_family = AF_INET; + sin.sin_port = htons(port); + setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (int []){1}, sizeof(int)); + + if (bind(sock, (struct sockaddr *)&sin, sizeof(sin)) < 0) { + perror("bind"); + return -1; + } + + if (listen(sock, 10) < 0) { + perror("listen"); + return -1; + } + + return sock; +} + +/* TODO allow multiple clients to send queries */ +static int event_loop(int sock) +{ + for (;;) { + int csock = accept(sock, NULL, NULL); + + int size = read(csock, &buffer_g, sizeof(buffer_g)); + + _log("received: [%.*s]\n", size - (int)sizeof(buffer_g.opcode), buffer_g.data); + + if (size >= (int)sizeof(buffer_g.opcode)) { + int (*cb)(const byte *, int) = get_assoc_cb(buffer_g.opcode); + + if (cb != NULL) { + (*cb)(buffer_g.data, size - (int)sizeof(buffer_g.opcode)); + } + } + + close(csock); + } + + return 0; +} + +int main(int argc, char *argv[]) +{ + stream_g = popen("/usr/bin/mplayer -quiet -slave -idle", "w"); + + if (stream_g == NULL) { + fprintf(stderr, "cannot run mplayer: %m\n"); + return -1; + } + + setvbuf(stream_g, NULL, _IONBF, 0); + + int sock = bind_socket((argc < 2) ? 4333 : atoi(argv[1])); + + if (sock >= 0) { + signal(SIGPIPE, SIG_IGN); + + event_loop(sock); + } + + pclose(stream_g); + return 0; +} -- cgit v1.2.3