forked from mikebrady/shairport-sync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rtsp.c
1592 lines (1362 loc) · 48.5 KB
/
rtsp.c
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* RTSP protocol handler. This file is part of Shairport.
* Copyright (c) James Laird 2013
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include <memory.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/select.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <poll.h>
#include "config.h"
#ifdef HAVE_LIBSSL
#include <openssl/md5.h>
#endif
#ifdef HAVE_LIBPOLARSSL
#include <polarssl/md5.h>
#endif
#include "common.h"
#include "player.h"
#include "rtp.h"
#include "mdns.h"
#ifdef AF_INET6
#define INETx_ADDRSTRLEN INET6_ADDRSTRLEN
#else
#define INETx_ADDRSTRLEN INET_ADDRSTRLEN
#endif
enum rtsp_read_request_response {
rtsp_read_request_response_ok,
rtsp_read_request_response_shutdown_requested,
rtsp_read_request_response_bad_packet,
rtsp_read_request_response_error
};
// Mike Brady's part...
static pthread_mutex_t play_lock = PTHREAD_MUTEX_INITIALIZER;
// every time we want to retain or release a reference count, lock it with this
// if a reference count is read as zero, it means the it's being deallocated.
static pthread_mutex_t reference_counter_lock = PTHREAD_MUTEX_INITIALIZER;
// only one thread is allowed to use the player at once.
// it monitors the request variable (at least when interrupted)
static pthread_mutex_t playing_mutex = PTHREAD_MUTEX_INITIALIZER;
static int please_shutdown = 0;
static pthread_t playing_thread = 0;
typedef struct {
int fd;
stream_cfg stream;
SOCKADDR remote;
int running;
pthread_t thread;
} rtsp_conn_info;
#ifdef CONFIG_METADATA
typedef struct {
pthread_mutex_t pc_queue_lock;
pthread_cond_t pc_queue_item_added_signal;
pthread_cond_t pc_queue_item_removed_signal;
size_t item_size; // number of bytes in each item
uint32_t count; // number of items in the queue
uint32_t capacity; // maximum number of items
uint32_t toq; // first item to take
uint32_t eoq; // free space at end of queue
void *items; // a pointer to where the items are actually stored
} pc_queue; // producer-consumer queue
#endif
typedef struct {
uint32_t referenceCount; // we might start using this...
int nheaders;
char *name[16];
char *value[16];
int contentlength;
char *content;
// for requests
char method[16];
// for responses
int respcode;
} rtsp_message;
#ifdef CONFIG_METADATA
typedef struct {
uint32_t type;
uint32_t code;
char *data;
uint32_t length;
rtsp_message* carrier;
} metadata_package;
void pc_queue_init(pc_queue* the_queue, char* items, size_t item_size, uint32_t number_of_items) {
the_queue->item_size = item_size;
the_queue->items = items;
the_queue->count = 0;
the_queue->capacity = number_of_items;
the_queue->toq = 0;
the_queue->eoq = 0;
}
int send_metadata(uint32_t type,uint32_t code,char *data,uint32_t length,rtsp_message* carrier,int block);
int send_ssnc_metadata(uint32_t code,char *data,uint32_t length,int block) {
return send_metadata('ssnc',code,data,length,NULL,block);
}
int pc_queue_add_item(pc_queue* the_queue,const void* the_stuff, int block) {
int rc;
if (the_queue) {
if (block==0) {
rc = pthread_mutex_trylock(&the_queue->pc_queue_lock);
if (rc==EBUSY)
return EBUSY;
} else
rc = pthread_mutex_lock(&the_queue->pc_queue_lock);
if (rc)
debug(1,"Error locking for pc_queue_add_item");
while(the_queue->count==the_queue->capacity) {
rc = pthread_cond_wait(&the_queue->pc_queue_item_removed_signal,&the_queue->pc_queue_lock);
if (rc)
debug(1,"Error waiting for item to be removed");
}
uint32_t i = the_queue->eoq;
void * p = the_queue->items + the_queue->item_size*i;
// void * p = &the_queue->qbase + the_queue->item_size*the_queue->eoq;
memcpy(p,the_stuff,the_queue->item_size);
// update the pointer
i++;
if (i==the_queue->capacity)
// fold pointer if necessary
i=0;
the_queue->eoq = i;
the_queue->count++;
if (the_queue->count==the_queue->capacity)
debug(1,"pc_queue is full!");
rc = pthread_cond_signal(&the_queue->pc_queue_item_added_signal);
if (rc)
debug(1,"Error signalling after pc_queue_add_item");
rc = pthread_mutex_unlock(&the_queue->pc_queue_lock);
if (rc)
debug(1,"Error unlocking for pc_queue_add_item");
} else {
debug(1,"Adding an item to a NULL queue");
}
return 0;
}
int pc_queue_get_item(pc_queue* the_queue,void* the_stuff) {
int rc;
if (the_queue) {
rc = pthread_mutex_lock(&the_queue->pc_queue_lock);
if (rc)
debug(1,"Error locking for pc_queue_get_item");
while(the_queue->count==0) {
rc = pthread_cond_wait(&the_queue->pc_queue_item_added_signal,&the_queue->pc_queue_lock);
if (rc)
debug(1,"Error waiting for item to be added");
}
uint32_t i = the_queue->toq;
// void * p = &the_queue->qbase + the_queue->item_size*the_queue->toq;
void * p = the_queue->items + the_queue->item_size*i;
memcpy(the_stuff,p,the_queue->item_size);
// update the pointer
i++;
if (i==the_queue->capacity)
// fold pointer if necessary
i=0;
the_queue->toq = i;
the_queue->count--;
rc = pthread_cond_signal(&the_queue->pc_queue_item_removed_signal);
if (rc)
debug(1,"Error signalling after pc_queue_removed_item");
rc = pthread_mutex_unlock(&the_queue->pc_queue_lock);
if (rc)
debug(1,"Error unlocking for pc_queue_get_item");
} else {
debug(1,"Removing an item from a NULL queue");
}
return 0;
}
#endif
// determine if we are the currently playing thread
static inline int rtsp_playing(void) {
if (pthread_mutex_trylock(&playing_mutex)) {
return pthread_equal(playing_thread, pthread_self());
} else {
pthread_mutex_unlock(&playing_mutex);
return 0;
}
}
void rtsp_request_shutdown_stream(void) {
please_shutdown = 1;
pthread_kill(playing_thread, SIGUSR1);
}
static void rtsp_take_player(void) {
if (rtsp_playing())
return;
if (pthread_mutex_trylock(&playing_mutex)) {
debug(1, "shutting down playing thread.");
// XXX minor race condition between please_shutdown and signal delivery
please_shutdown = 1;
pthread_kill(playing_thread, SIGUSR1);
pthread_mutex_lock(&playing_mutex);
}
playing_thread = pthread_self(); // make us the currently-playing thread (why?)
}
void rtsp_shutdown_stream(void) {
rtsp_take_player();
pthread_mutex_unlock(&playing_mutex);
}
// keep track of the threads we have spawned so we can join() them
static rtsp_conn_info **conns = NULL;
static int nconns = 0;
static void track_thread(rtsp_conn_info *conn) {
conns = realloc(conns, sizeof(rtsp_conn_info*) * (nconns + 1));
conns[nconns] = conn;
nconns++;
}
static void cleanup_threads(void) {
void *retval;
int i;
debug(2, "culling threads.");
for (i=0; i<nconns; ) {
if (conns[i]->running == 0) {
pthread_join(conns[i]->thread, &retval);
free(conns[i]);
debug(2, "one joined...");
nconns--;
if (nconns)
conns[i] = conns[nconns];
} else {
i++;
}
}
}
// park a null at the line ending, and return the next line pointer
// accept \r, \n, or \r\n
static char *nextline(char *in, int inbuf) {
char *out = NULL;
while (inbuf) {
if (*in == '\r') {
*in++ = 0;
out = in;
}
if (*in == '\n') {
*in++ = 0;
out = in;
}
if (out)
break;
in++;
inbuf--;
}
return out;
}
static void msg_retain(rtsp_message * msg) {
if (msg) {
int rc = pthread_mutex_lock(&reference_counter_lock);
if (rc)
debug(1,"Error %d locking reference counter lock");
msg->referenceCount++;
rc = pthread_mutex_unlock(&reference_counter_lock);
if (rc)
debug(1,"Error %d unlocking reference counter lock");
} else {
debug(1,"null rtsp_message pointer passed to retain");
}
}
static rtsp_message * msg_init(void) {
rtsp_message *msg = malloc(sizeof(rtsp_message));
memset(msg, 0, sizeof(rtsp_message));
msg->referenceCount = 1; // from now on, any access to this must be protected with the lock
return msg;
}
static int msg_add_header(rtsp_message *msg, char *name, char *value) {
if (msg->nheaders >= sizeof(msg->name)/sizeof(char*)) {
warn("too many headers?!");
return 1;
}
msg->name[msg->nheaders] = strdup(name);
msg->value[msg->nheaders] = strdup(value);
msg->nheaders++;
return 0;
}
static char *msg_get_header(rtsp_message *msg, char *name) {
int i;
for (i=0; i<msg->nheaders; i++)
if (!strcasecmp(msg->name[i], name))
return msg->value[i];
return NULL;
}
static void msg_print_debug_headers(rtsp_message *msg) {
int i;
for (i=0; i<msg->nheaders; i++) {
debug(1," Type: \"%s\", content: \"%s\"",msg->name[i],msg->value[i]);
}
}
static void msg_free(rtsp_message *msg) {
if (msg) {
int rc = pthread_mutex_lock(&reference_counter_lock);
if (rc)
debug(1,"Error %d locking reference counter lock during msg_free()",rc);
msg->referenceCount--;
rc = pthread_mutex_unlock(&reference_counter_lock);
if (rc)
debug(1,"Error %d unlocking reference counter lock during msg_free()",rc);
if (msg->referenceCount==0) {
int i;
for (i=0; i<msg->nheaders; i++) {
free(msg->name[i]);
free(msg->value[i]);
}
if (msg->content)
free(msg->content);
free(msg);
} // else {
// debug(1,"rtsp_message reference count non-zero: %d!",msg->referenceCount);
//}
} else {
debug(1,"null rtsp_message pointer passed to msg_free()");
}
}
static int msg_handle_line(rtsp_message **pmsg, char *line) {
rtsp_message *msg = *pmsg;
if (!msg) {
msg = msg_init();
*pmsg = msg;
char *sp, *p;
// debug(1, "received request: %s", line);
p = strtok_r(line, " ", &sp);
if (!p)
goto fail;
strncpy(msg->method, p, sizeof(msg->method)-1);
p = strtok_r(NULL, " ", &sp);
if (!p)
goto fail;
p = strtok_r(NULL, " ", &sp);
if (!p)
goto fail;
if (strcmp(p, "RTSP/1.0"))
goto fail;
return -1;
}
if (strlen(line)) {
char *p;
p = strstr(line, ": ");
if (!p) {
warn("bad header: >>%s<<", line);
goto fail;
}
*p = 0;
p += 2;
msg_add_header(msg, line, p);
debug(2, " %s: %s.", line, p);
return -1;
} else {
char *cl = msg_get_header(msg, "Content-Length");
if (cl)
return atoi(cl);
else
return 0;
}
fail:
*pmsg = NULL;
msg_free(msg);
return 0;
}
static enum rtsp_read_request_response rtsp_read_request(int fd, rtsp_message** the_packet) {
enum rtsp_read_request_response reply=rtsp_read_request_response_ok;
ssize_t buflen = 512;
char *buf = malloc(buflen+1);
rtsp_message *msg = NULL;
ssize_t nread;
ssize_t inbuf = 0;
int msg_size = -1;
while (msg_size < 0) {
if (please_shutdown) {
debug(1, "RTSP shutdown requested.");
reply = rtsp_read_request_response_shutdown_requested;
goto shutdown;
}
nread = read(fd, buf+inbuf, buflen - inbuf);
if (!nread) {
debug(1, "RTSP connection closed.");
reply = rtsp_read_request_response_shutdown_requested;
goto shutdown;
}
if (nread < 0) {
if (errno==EINTR)
continue;
perror("read failure");
reply = rtsp_read_request_response_error;
goto shutdown;
}
inbuf += nread;
char *next;
while (msg_size < 0 && (next = nextline(buf, inbuf))) {
msg_size = msg_handle_line(&msg, buf);
if (!msg) {
warn("no RTSP header received");
reply = rtsp_read_request_response_bad_packet;
goto shutdown;
}
inbuf -= next-buf;
if (inbuf)
memmove(buf, next, inbuf);
}
}
if (msg_size > buflen) {
buf = realloc(buf, msg_size);
if (!buf) {
warn("too much content");
reply = rtsp_read_request_response_error;
goto shutdown;
}
buflen = msg_size;
}
uint64_t threshold_time = get_absolute_time_in_fp() + ((uint64_t)5<<32); // i.e. five seconds from now
int warning_message_sent = 0;
const size_t max_read_chunk = 50000;
while (inbuf < msg_size) {
// we are going to read the stream in chunks and time how long it takes to do so.
// If it's taking too long, (and we find out about it), we will send an error message as metadata
if (warning_message_sent==0) {
uint64_t time_now = get_absolute_time_in_fp();
if (time_now>threshold_time) { // it's taking too long
debug(1,"Error receiving metadata from source -- transmission seems to be stalled.");
#ifdef CONFIG_METADATA
send_ssnc_metadata('stal',NULL,0,1);
#endif
warning_message_sent = 1;
}
}
ssize_t read_chunk = msg_size-inbuf;
if (read_chunk > max_read_chunk)
read_chunk = max_read_chunk;
nread = read(fd, buf+inbuf, read_chunk);
if (!nread) {
reply = rtsp_read_request_response_error;
goto shutdown;
}
if (nread==EINTR)
continue;
if (nread < 0) {
perror("read failure");
reply = rtsp_read_request_response_error;
goto shutdown;
}
inbuf += nread;
}
msg->contentlength = inbuf;
msg->content = buf;
*the_packet = msg;
return reply;
shutdown:
if (msg) {
msg_free(msg); // which will free the content and everything else
}
// in case the message wasn't formed or wasn't fully initialised
if ((msg) && (msg-> content == NULL) || (!msg))
free(buf);
*the_packet = NULL;
return reply;
}
static void msg_write_response(int fd, rtsp_message *resp) {
char pkt[1024];
int pktfree = sizeof(pkt);
char *p = pkt;
int i, n;
n = snprintf(p, pktfree,
"RTSP/1.0 %d %s\r\n", resp->respcode,
resp->respcode==200 ? "OK" : "Error");
// debug(1, "sending response: %s", pkt);
pktfree -= n;
p += n;
for (i=0; i<resp->nheaders; i++) {
debug(2, " %s: %s.", resp->name[i], resp->value[i]);
n = snprintf(p, pktfree, "%s: %s\r\n", resp->name[i], resp->value[i]);
pktfree -= n;
p += n;
if (pktfree <= 0)
die("Attempted to write overlong RTSP packet");
}
if (pktfree < 3)
die("Attempted to write overlong RTSP packet");
strcpy(p, "\r\n");
int ignore = write(fd, pkt, p-pkt+2);
}
static void handle_record(rtsp_conn_info *conn,
rtsp_message *req, rtsp_message *resp) {
resp->respcode = 200;
msg_add_header(resp, "Audio-Latency","88200");
}
static void handle_options(rtsp_conn_info *conn,
rtsp_message *req, rtsp_message *resp) {
resp->respcode = 200;
msg_add_header(resp, "Public",
"ANNOUNCE, SETUP, RECORD, "
"PAUSE, FLUSH, TEARDOWN, "
"OPTIONS, GET_PARAMETER, SET_PARAMETER");
}
static void handle_teardown(rtsp_conn_info *conn,
rtsp_message *req, rtsp_message *resp) {
if (!rtsp_playing())
return;
resp->respcode = 200;
msg_add_header(resp, "Connection", "close");
please_shutdown = 1;
}
static void handle_flush(rtsp_conn_info *conn,
rtsp_message *req, rtsp_message *resp) {
if (!rtsp_playing())
return;
char *p;
uint32_t rtptime=0;
char * hdr = msg_get_header(req,"RTP-Info");
if (hdr) {
// debug(1,"FLUSH message received: \"%s\".",hdr);
// get the rtp timestamp
p = strstr(hdr, "rtptime=");
if (p) {
p = strchr(p, '=') + 1;
if (p)
rtptime = uatoi(p); // unsigned integer -- up to 2^32-1
}
}
// debug(1,"RTSP Flush Requested.");
player_flush(rtptime);
resp->respcode = 200;
}
static void handle_setup(rtsp_conn_info *conn,
rtsp_message *req, rtsp_message *resp) {
int cport, tport;
int lsport,lcport,ltport;
uint32_t active_remote=0;
char * ar = msg_get_header(req,"Active-Remote");
if (ar) {
// debug(1,"Active-Remote string seen: \"%s\".",ar);
// get the active remote
char *p;
active_remote = strtoul(ar,&p,10);
// debug(1,"Active Remote is %u.",active_remote);
}
// select latency
// if iTunes V10 or later is detected, use the iTunes latency setting
// if AirPlay is detected, use the AirPlay latency setting
// for everything else, use the general latency setting, if given, or
// else use the default latency setting
config.latency=88200;
if (config.userSuppliedLatency)
config.latency=config.userSuppliedLatency;
char * ua = msg_get_header(req,"User-Agent");
if (ua==0) {
debug(1,"No User-Agent string found in the SETUP message. Using latency of %d frames.",config.latency);
} else {
if (strstr(ua,"iTunes")==ua) {
int iTunesVersion=0;
// now check it's version 10 or later
char *pp = strchr(ua,'/') + 1;
if (pp)
iTunesVersion=atoi(pp);
else
debug(2,"iTunes Version Number not found.");
if (iTunesVersion>=10) {
debug(2,"User-Agent is iTunes 10 or better, (actual version is %d); selecting the iTunes latency of %d frames.",iTunesVersion,config.iTunesLatency);
config.latency=config.iTunesLatency;
}
} else if (strstr(ua,"AirPlay")==ua) {
debug(2,"User-Agent is AirPlay; selecting the AirPlay latency of %d frames.",config.AirPlayLatency);
config.latency=config.AirPlayLatency;
} else if (strstr(ua,"forked-daapd")==ua) {
debug(2,"User-Agent is forked-daapd; selecting the forked-daapd latency of %d frames.",config.ForkedDaapdLatency);
config.latency=config.ForkedDaapdLatency;
} else {
debug(2,"Unrecognised User-Agent. Using latency of %d frames.",config.latency);
}
}
char *hdr = msg_get_header(req, "Transport");
if (!hdr)
return;
char *p;
p = strstr(hdr, "control_port=");
if (!p)
return;
p = strchr(p, '=') + 1;
cport = atoi(p);
p = strstr(hdr, "timing_port=");
if (!p)
return;
p = strchr(p, '=') + 1;
tport = atoi(p);
rtsp_take_player();
rtp_setup(&conn->remote, cport, tport, active_remote, &lsport,&lcport,<port);
if (!lsport)
return;
char *q;
p = strstr(hdr,"control_port=");
if (p) {
q = strchr(p,';'); // get past the control port entry
*p++=0;
if (q++)
strcat(hdr,q); // should unsplice the control port entry
}
p = strstr(hdr,"timing_port=");
if (p) {
q = strchr(p,';'); // get past the timing port entry
*p++=0;
if (q++)
strcat(hdr,q); // should unsplice the timing port entry
}
player_play(&conn->stream);
char *resphdr = alloca(200);
*resphdr=0;
sprintf(resphdr, "RTP/AVP/UDP;unicast;interleaved=0-1;mode=record;control_port=%d;timing_port=%d;server_port=%d", lcport, ltport, lsport);
msg_add_header(resp, "Transport", resphdr);
msg_add_header(resp, "Session", "1");
resp->respcode = 200;
}
static void handle_ignore(rtsp_conn_info *conn,
rtsp_message *req, rtsp_message *resp) {
resp->respcode = 200;
}
static void handle_set_parameter_parameter(rtsp_conn_info *conn,
rtsp_message *req, rtsp_message *resp) {
char *cp = req->content;
int cp_left = req->contentlength;
char *next;
while (cp_left && cp) {
next = nextline(cp, cp_left);
cp_left -= next-cp;
if (!strncmp(cp, "volume: ", 8)) {
float volume = atof(cp + 8);
debug(2, "volume: %f\n", volume);
player_volume(volume);
} else
#ifdef CONFIG_METADATA
if(!strncmp(cp, "progress: ", 10)) {
char *progress = cp + 10;
debug(2, "progress: \"%s\"\n", progress); // rtpstampstart/rtpstampnow/rtpstampend 44100 per second
send_ssnc_metadata('prgr',strdup(progress),strlen(progress),1);
} else
#endif
{
debug(1, "unrecognised parameter: \"%s\" (%d)\n", cp, strlen(cp));
}
cp = next;
}
}
#ifdef CONFIG_METADATA
// Metadata is not used by shairport-sync.
// Instead we send all metadata to a fifo pipe, so that other apps can listen to the pipe and use the metadata.
// We use two 4-character codes to identify each piece of data and we send the data itself, if any, in base64 form.
// The first 4-character code, called the "type", is either:
// 'core' for all the regular metadadata coming from iTunes, etc., or
// 'ssnc' (for 'shairport-sync') for all metadata coming from Shairport Sync itself, such as start/end delimiters, etc.
// For 'core' metadata, the second 4-character code is the 4-character metadata code coming from iTunes etc.
// For 'ssnc' metadata, the second 4-character code is used to distinguish the messages.
// Cover art is not tagged in the same way as other metadata, it seems, so is sent as an 'ssnc' type metadata message with the code 'PICT'
// Here are the 'ssnc' codes defined so far:
// 'PICT' -- the payload is a picture, either a JPEG or a PNG. Check the first few bytes to see which.
// 'pbeg' -- play stream begin. No arguments
// 'pend' -- play stream end. No arguments
// 'pfls' -- play stream flush. No arguments
// 'prsm' -- play stream resume. No arguments
// 'pvol' -- play volume. The volume is sent as a string -- "airplay_volume,volume,lowest_volume,highest_volume,has_true_mute,is_muted"
// volume, lowest_volume and highest_volume are given in dB
// is_muted is 1 if [true] mute is enabled, 0 otherwise.
// The "airplay_volume" is what's sent to the player, and is from 0.00 down to -30.00, with -144.00 meaning mute.
// This is linear on the volume control slider of iTunes or iOS AirPLay
// 'prgr' -- progress -- this is metadata from AirPlay consisting of RTP timestamps for the start of the current play sequence, the current play point and the end of the play sequence.
// I guess the timestamps wrap at 2^32.
// 'mdst' -- a sequence of metadata is about to start
// 'mden' -- a sequence of metadata has ended
// 'snam' -- the name of the originator -- e.g. "Joe's iPhone" or "iTunes...".
//
// including a simple base64 encoder to minimise malloc/free activity
// From Stack Overflow, with thanks:
// http://stackoverflow.com/questions/342409/how-do-i-base64-encode-decode-in-c
// minor mods to make independent of C99.
// more significant changes make it not malloc memory
// needs to initialise the docoding table first
// add _so to end of name to avoid confusion with polarssl's implementation
static char encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/'};
static int mod_table[] = {0, 2, 1};
// pass in a pointer to the data, its length, a pointer to the output buffer and a pointer to an int containing its maximum length
// the actual length will be returned.
char *base64_encode_so(const unsigned char *data,
size_t input_length,
char *encoded_data,
size_t *output_length) {
size_t calculated_output_length = 4 * ((input_length + 2) / 3);
if (calculated_output_length> *output_length)
return(NULL);
*output_length = calculated_output_length;
int i,j;
for (i = 0, j = 0; i < input_length;) {
uint32_t octet_a = i < input_length ? (unsigned char)data[i++] : 0;
uint32_t octet_b = i < input_length ? (unsigned char)data[i++] : 0;
uint32_t octet_c = i < input_length ? (unsigned char)data[i++] : 0;
uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F];
}
for (i = 0; i < mod_table[input_length % 3]; i++)
encoded_data[*output_length - 1 - i] = '=';
return encoded_data;
}
// with thanks!
//
static int fd = -1;
static int dirty = 0;
pc_queue metadata_queue;
#define metadata_queue_size 500
metadata_package metadata_queue_items[metadata_queue_size];
static pthread_t metadata_thread;
void metadata_create(void) {
if (!config.meta_dir)
return;
const char fn[] = "shairport-sync-metadata";
size_t pl = strlen(config.meta_dir) + 1 + strlen(fn);
char* path = malloc(pl+1);
snprintf(path, pl+1, "%s/%s", config.meta_dir, fn);
if (mkfifo(path, 0644) && errno != EEXIST)
die("Could not create metadata FIFO %s", path);
free(path);
}
void metadata_open(void) {
if (!config.meta_dir)
return;
const char fn[] = "shairport-sync-metadata";
size_t pl = strlen(config.meta_dir) + 1 + strlen(fn);
char* path = malloc(pl+1);
snprintf(path, pl+1, "%s/%s", config.meta_dir, fn);
fd = open(path, O_WRONLY | O_NONBLOCK);
//if (fd < 0)
// debug(1, "Could not open metadata FIFO %s. Will try again later.", path);
free(path);
}
static void metadata_close(void) {
close(fd);
fd = -1;
}
ssize_t non_blocking_write(int fd, const void *buf, size_t count) {
// debug(1,"writing %u to pipe...",count);
// we are assuming that the count is always smaller than the FIFO's buffer
struct pollfd ufds[1];
ssize_t reply;
do {
ufds[0].fd=fd;
ufds[0].events = POLLOUT;
int rv = poll(ufds,1,5000);
if (rv==-1)
debug(1,"error waiting for pipe to unblock...");
if (rv==0)
debug(1,"timeout waiting for pipe to unblock");
reply=write(fd,buf,count);
if ((reply==-1) && ((errno == EAGAIN) || (errno == EWOULDBLOCK)))
debug(1,"writing to pipe will block...");
// else
// debug(1,"writing %u to pipe done...",reply);
} while ((reply==-1) && ((errno == EAGAIN) || (errno == EWOULDBLOCK)));
return reply;
// return write(fd,buf,count);
}
void metadata_process(uint32_t type,uint32_t code,char *data,uint32_t length) {
debug(2,"Process metadata with type %x, code %x and length %u.",type,code,length);
int ret;
// readers may go away and come back
if (fd < 0)
metadata_open();
if (fd < 0)
return;
char thestring[1024];
snprintf(thestring,1024,"<type>%x</type><code>%x</code><length>%u</length>\n",type,code,length);
ret = non_blocking_write(fd, thestring, strlen(thestring));
if (ret < 1)
return;
if ((data!=NULL) && (length>0)) {
snprintf(thestring,1024,"<data encoding=\"base64\">\n");
ret = non_blocking_write(fd, thestring, strlen(thestring));
if (ret < 1) // no reader
return;
// here, we write the data in base64 form using our nice base64 encoder
// but, we break it into lines of 76 output characters, except for the last one.
// thus, we send groups of (76/4)*3 = 57 bytes to the encoder at a time
size_t remaining_count = length;
char *remaining_data = data;
size_t towrite_count;
char outbuf[76];
while ((remaining_count) && (ret>=0)) {
size_t towrite_count = remaining_count;
if (towrite_count>57)
towrite_count = 57;
size_t outbuf_size = 76; // size of output buffer on entry, length of result on exit
if (base64_encode_so(remaining_data, towrite_count, outbuf, &outbuf_size)==NULL)
debug(1,"Error encoding base64 data.");
//debug(1,"Remaining count: %d ret: %d, outbuf_size: %d.",remaining_count,ret,outbuf_size);
ret = non_blocking_write(fd,outbuf,outbuf_size);
if (ret<0)
return;
remaining_data+=towrite_count;
remaining_count-=towrite_count;
// ret = write(fd,"\r\n",2);
// if (ret<0)
// return;
}
snprintf(thestring,1024,"</data>\n");
ret = non_blocking_write(fd, thestring, strlen(thestring));
if (ret < 1) // no reader
return;
}
}
void* metadata_thread_function(void *ignore) {
metadata_create();
metadata_package pack;
while (1) {
pc_queue_get_item(&metadata_queue, &pack);
if (config.meta_dir)
metadata_process(pack.type,pack.code,pack.data,pack.length);
if (pack.carrier)
msg_free(pack.carrier); // release the message
else if (pack.data)
free(pack.data);
}
pthread_exit(NULL);
}
void metadata_init(void) {
// create a pc_queue for passing information to a threaded metadata handler
pc_queue_init(&metadata_queue,(char *)&metadata_queue_items,sizeof(metadata_package),metadata_queue_size);
int ret = pthread_create(&metadata_thread, NULL, metadata_thread_function, NULL);
if (ret)
debug(1,"Failed to create metadata thread!");
}
int send_metadata(uint32_t type,uint32_t code,char *data,uint32_t length, rtsp_message* carrier, int block) {
metadata_package pack;
pack.type = type;