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
|
#include <signal.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#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, _IOLBF, BUFSIZ);
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;
}
|