aboutsummaryrefslogtreecommitdiff
path: root/moc_library.c
blob: ca65f2052733493923d369cd314903bc756eff5b (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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>  //Header file for sleep(). man 3 sleep for details.
#include <errno.h>
 
#include <pthread.h>
#include <sys/socket.h>
#include <sys/un.h>

// A normal C function that is executed as a thread
// when its name is specified in pthread_create()
//

char *moc_socket_path = "/home/calvin/.moc/socket2";

/* State of the server. */
#define STATE_PLAY	0x01
#define STATE_STOP	0x02
#define STATE_PAUSE	0x03
#define CMD_GET_STATE	0x13 /* get the state */
#define CMD_GET_CTIME	0x0d /* get the current song time */
#define CMD_GET_TAGS	0x2c /* get tags for the currently played file */
#define CMD_GET_FILE_TAGS	0x2f	/* get tags for the specified file */
#define CMD_GET_SNAME	0x0f /* get the stream file name */
#define MAX_SEND_STRING	4096
#define RANGE(min, val, max) ((val) >= (min) && (val) <= (max))


/* Definition of events sent by server to the client. */
#define EV_STATE	0x01 /* server has changed the state */
#define EV_CTIME	0x02 /* current time of the song has changed */
#define EV_SRV_ERROR	0x04 /* an error occurred */
#define EV_BUSY		0x05 /* another client is connected to the server */
#define EV_DATA		0x06 /* data in response to a request will arrive */
#define EV_BITRATE	0x07 /* the bitrate has changed */
#define EV_RATE		0x08 /* the rate has changed */
#define EV_CHANNELS	0x09 /* the number of channels has changed */
#define EV_EXIT		0x0a /* the server is about to exit */
#define EV_PONG		0x0b /* response for CMD_PING */
#define EV_OPTIONS	0x0c /* the options has changed */
#define EV_SEND_PLIST	0x0d /* request for sending the playlist */
#define EV_TAGS		0x0e /* tags for the current file have changed */
#define EV_STATUS_MSG	0x0f /* followed by a status message */
#define EV_MIXER_CHANGE	0x10 /* the mixer channel was changed */
#define EV_FILE_TAGS	0x11 /* tags in a response for tags request */
#define EV_AVG_BITRATE  0x12 /* average bitrate has changed (new song) */
#define EV_AUDIO_START	0x13 /* playing of audio has started */
#define EV_AUDIO_STOP	0x14 /* playing of audio has stopped */

/* Events caused by a client that wants to modify the playlist (see
 * CMD_CLI_PLIST* commands). */
#define EV_PLIST_ADD	0x50 /* add an item, followed by the file name */
#define EV_PLIST_DEL	0x51 /* delete an item, followed by the file name */
#define EV_PLIST_MOVE	0x52 /* move an item, followed by 2 file names */
#define EV_PLIST_CLEAR	0x53 /* clear the playlist */

/* These events, though similar to the four previous are caused by server
 * which takes care of clients' queue synchronization. */
#define EV_QUEUE_ADD	0x54
#define EV_QUEUE_DEL	0x55
#define EV_QUEUE_MOVE	0x56
#define EV_QUEUE_CLEAR	0x57
/* Flags for the info decoder function. */
enum tags_select
{
  TAGS_COMMENTS	= 0x01, /* artist, title, etc. */
  TAGS_TIME	= 0x02 /* time of the file. */
};

enum moc_state {
  STOPPED,
  PLAYING,
  PAUSED
};

enum moc_status {
  INITIALIZING,
  CONNECTED,
  FAILED_TO_CONNECT,
  ERROR,
  RECONNECTING,
  
};

struct moc { 
  pthread_mutex_t lock;
  enum moc_status status;
  enum moc_state state;

  char *filename;
  char *title;
  char *album;
  char *artist;
  int track;
  int time;
  int filled;
  int length;
};

extern const char * moc_str_status(enum moc_status s) {
    static const char *strings[] = { "INITIALIZING", "CONNECTED", "FAILED_TO_CONNECT", "ERROR", "RECONNECTING" };
    return strings[s];
}

extern const char * moc_str_state(enum moc_state s) {
    static const char *strings[] = { "STOPPED", "PLAYING", "PAUSED"};
    return strings[s];

}

static char *get_curr_file(int sock);
int send_str (int sock, const char *str);
char *get_str (int sock);
int send_int (int sock, int i);
int get_int (int sock, int *i);

  
void reset_data(struct moc *data) {
  data->filename = NULL;
  data->title = NULL;
  data->album = NULL;
  data->artist = NULL;
  data->time = -1;
  data->length = -1;
  data->state = STOPPED;
}

static char *get_curr_file (const int sock) {
  send_int (sock, CMD_GET_SNAME);
  int ev;
  while(ev != EV_DATA) {
    get_int(sock, &ev);
  }
    return get_str(sock);
}


int send_str (int sock, const char *str)
{
  int len;

  len = strlen (str);
  if (!send_int (sock, len))
    return 0;

  if (send (sock, str, len, 0) != len)
    return 0;

  return 1;
}
char *get_str (int sock) {
  int len;
  int res, nread = 0;
  char *str;

  if (!get_int(sock, &len))
    return NULL;

  if (!RANGE(0, len, MAX_SEND_STRING)) {
    printf("Bad string length.");
    return NULL;
  }

  str = (char *)malloc (sizeof(char) * (len + 1));
  while (nread < len) {
    res = recv (sock, str + nread, len - nread, 0);
    if (res == -1) {
      printf("recv() failed when getting string: %s\n",
          strerror(errno));
      free (str);
      return NULL;
    }
    if (res == 0) {
      printf("Unexpected EOF when getting string\n");
      free (str);
      return NULL;
    }
    nread += res;
  }
  str[len] = 0;

  return str;
}
int send_int (int sock, int i)
{
  int res;

  res = send (sock, &i, sizeof(int), 0);
  if (res == -1)
    printf("send() failed: %s", strerror(errno));

  return res == sizeof(int) ? 1 : 0;
}

int get_int (int sock, int *i)
{
  int res;

  res = recv (sock, i, sizeof(int), 0);
  if (res == -1)
    printf("recv() failed when getting int: %s", strerror(errno));

  return res == sizeof(int) ? 1 : 0;
}

static int moc_server_connect ()
{
  struct sockaddr_un sock_name;
  int sock;

  /* Create a socket */
  if ((sock = socket (PF_LOCAL, SOCK_STREAM, 0)) == -1)
    return -1;

  sock_name.sun_family = AF_LOCAL;
  strcpy (sock_name.sun_path, moc_socket_path);

  if (connect(sock, (struct sockaddr *)&sock_name,
        SUN_LEN(&sock_name)) == -1) {
    close (sock);
    fprintf(stderr, "%s at (%s)\n", strerror(errno), sock_name);
    return -1;
  }

  return sock;
}


void update_state(struct moc *data, int state) {
    fprintf(stderr, "moc: state %d, state\n");
    if(state == STATE_PLAY) {
        data->state = PLAYING;
        fprintf(stderr, "moc: playing\n");
    }
    if(state == STATE_PAUSE) {
        data->state = PAUSED;
        fprintf(stderr, "moc: paused\n");
    }
    if(state == STATE_STOP) {
        data->state = STOPPED;
        fprintf(stderr, "moc: state stopped\n");
    }
}

static int moc_reconnect(struct moc *data) {
 int srv_sock = -1;

 while(srv_sock == -1) { 
   fprintf(stderr, "moc: reconnecting\n");
   srv_sock = moc_server_connect();
   sleep(1);
 }

  pthread_mutex_lock(&data->lock);
  data->status = CONNECTED;
  pthread_mutex_unlock(&data->lock);
  return srv_sock;
}

void *moc_loop(void *input) {


  struct moc *data = (struct moc*)input;

  int srv_sock = -1;

  fprintf(stderr, "moc: connecting\n");
  srv_sock = moc_reconnect(data);
  fprintf(stderr, "moc: connected: %d\n", srv_sock);


  int last_cmd = -1;
  int event = -1;

  send_int(srv_sock, CMD_GET_STATE);
  last_cmd = EV_STATE;

  while(1) {
    get_int(srv_sock, &event); 
    switch (event) {
      // handle our data. we MUST know what the last request was otherwise we
      // don't know how to parse it.
      case EV_DATA:
        fprintf(stderr, "moc: EV_DATA\n");
        if(last_cmd == EV_CTIME) {
          get_int(srv_sock, &data->time);
          fprintf(stderr, "moc: update ctime %d\n");
          if(data->state == 0) {
            send_int(srv_sock, CMD_GET_STATE);
            last_cmd = EV_STATE;
          }
        }
        //  on state change, we need to figure out what file we have and what
        //  tags it has.
        else if(last_cmd == EV_STATE) {
          int state;
          get_int(srv_sock, &state);
          pthread_mutex_lock(&data->lock);
          update_state(data, state);

          if(state != STATE_STOP) {
            char *file = get_curr_file(srv_sock);
            fprintf(stderr, "moc: current file %s\n", file);
            // if it's the same file as we had, don't update.
            if(data->filename == NULL || strcmp(file, data->filename) != 0) {
              fprintf(stderr, "moc: new file, asking for tags\n");
              data->filename = file;
              // get tags.
              send_int(srv_sock, CMD_GET_FILE_TAGS);
              send_str(srv_sock, file);
              send_int(srv_sock,TAGS_COMMENTS | TAGS_TIME);
              last_cmd = EV_FILE_TAGS;
            }
          } else {
            reset_data(data);
          }
          pthread_mutex_unlock(&data->lock);
        }
        else {
          fprintf(stderr, "moc: shit i have data IDK what it is\n");
        }
        last_cmd = -1;

        break;
      case EV_BUSY:
        fprintf(stderr, "moc: EV_BUSY\n");
        break;
      case EV_CTIME:
        fprintf(stderr, "moc: EV_CTIME\n");
        last_cmd = EV_CTIME;
        send_int(srv_sock, CMD_GET_CTIME);
        break;
      case EV_STATE:
        fprintf(stderr, "moc: EV_STATE\n");
        last_cmd = EV_STATE;
        send_int(srv_sock, CMD_GET_STATE);
        break;
      case EV_EXIT:
        fprintf(stderr,"moc: EV_EXIT\n");
        data->status = RECONNECTING;
        reset_data(data);
        srv_sock = moc_reconnect(data);
        break;
      case EV_BITRATE:
        fprintf(stderr, "moc: EV_BITRATE\n");
        break;
      case EV_RATE:
        fprintf(stderr, "moc: EV_RATE\n");
        break;
      case EV_CHANNELS:
        printf("moc: EV_CHANNELS\n");
        break;
      case EV_SRV_ERROR:
          get_str(srv_sock);
        break;
      case EV_OPTIONS:
        printf("moc: EV_OPTIONS\n");
        break;
      case EV_SEND_PLIST:
      case EV_PLIST_ADD:
      case EV_PLIST_CLEAR:
      case EV_PLIST_DEL:
      case EV_PLIST_MOVE:
        printf("moc: EV_PLAYLIST\n");
      case EV_TAGS:
        last_cmd = EV_TAGS;
        printf("moc: EV_TAGS\n");
        break;
      case EV_STATUS_MSG:
        printf("moc: EV_STATUS_MSG\n");
        printf("moc: status update: %s\n", get_str(srv_sock));
        break;
      case EV_MIXER_CHANGE:
        printf("moc: EV_MIXER_CHANGE\n");
        break;
      case EV_FILE_TAGS:
        printf("moc: EV_FILE_TAGS\n");

        pthread_mutex_lock(&data->lock);
        if (!(data->filename = get_str(srv_sock))) {
          fprintf(stderr, "Error while receiving filename\n");
        }

        if (!(data->title = get_str(srv_sock))) {
          fprintf(stderr, "Error while receiving title\n");
        }

        if (!(data->artist = get_str(srv_sock))) {
          fprintf(stderr, "Error while receiving artist\n");
        }

        if (!(data->album = get_str(srv_sock))) {
          fprintf(stderr, "Error while receiving album\n");
        }

        if (!get_int(srv_sock, &data->track)) {
          fprintf(stderr, "Error while receiving track\n");
        }

        if (!get_int(srv_sock, &data->length)) {
          fprintf(stderr, "Error while receiving length\n");
        }

        if (!get_int(srv_sock, &data->filled)) {
          fprintf(stderr, "Error while receiving filled\n");
        }
        pthread_mutex_unlock(&data->lock);

        break;
      case EV_AVG_BITRATE:
        printf("moc: EV_AVG_BITRATE\n");
        break;
      case EV_AUDIO_START:
        printf("moc: AUDIO START\n");
        break;
      case EV_AUDIO_STOP:
        printf("moc: AUDIO STOP\n");
        break;
      default:
        fprintf(stderr, "Unknown event: 0x%02x!\n", event);
        break;
    }
  }
  fprintf(stderr, "loop died, you're fucked\n");
}

extern struct moc *moc_init() {

  struct moc *moc = (struct moc*)malloc(sizeof(struct moc));
  reset_data(moc);
  pthread_t thread_id;

  if (pthread_mutex_init(&moc->lock, NULL) != 0) {
    printf("\n mutex init has failed\n");
    return NULL;
  }
  moc->status = INITIALIZING;

  pthread_create(&thread_id, NULL, moc_loop, (void *)moc);
  return moc;
}