-
Notifications
You must be signed in to change notification settings - Fork 235
/
cast.c
2461 lines (2026 loc) · 68.5 KB
/
cast.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
/*
* Copyright (C) 2015-2019 Espen Jürgensen <espenjurgensen@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <netinet/in.h>
#include <ifaddrs.h>
#include <unistd.h>
#include <fcntl.h>
#include <gnutls/gnutls.h>
#include <event2/event.h>
#include <json.h>
#include "conffile.h"
#include "misc.h"
#include "mdns.h"
#include "transcode.h"
#include "logger.h"
#include "player.h"
#include "rtp_common.h"
#include "outputs.h"
#include "db.h"
#include "artwork.h"
#include "misc.h"
#ifdef HAVE_PROTOBUF_OLD
#include "cast_channel.v0.pb-c.h"
#else
#include "cast_channel.pb-c.h"
#endif
// This implementation of Chromecast uses the same mirroring app that Chromium
// uses. This app supports RTP-streaming, which has the advantage of quick
// startup and similarity with Airplay. However, I have not found much
// documentation for it, so the reference is Chromium itself. Here's how to
// start a Chromium mirroring session with verbose logging:
//
// 1) chromium --user-data-dir=~/chromium --enable-logging --v=1 ~/Music/test.mp3
// 2) right-click, select Cast, select device
// 3) log will now be in ~/chromium/chrome_debug.log
// Number of bytes to request from TLS connection
#define MAX_BUF 4096
// CA file location (not very portable...?)
#define CAFILE "/etc/ssl/certs/ca-certificates.crt"
// Seconds without a heartbeat from the Chromecast before we close the session
//#define HEARTBEAT_TIMEOUT 30
// Seconds to wait for a reply before making the callback requested by caller
#define REPLY_TIMEOUT 5
// ID of the audio mirroring app used by Chrome (Google Home)
#define CAST_APP_ID "85CDB22F"
// Old mirroring app (Chromecast)
#define CAST_APP_ID_OLD "0F5096E8"
// Namespaces
#define NS_CONNECTION "urn:x-cast:com.google.cast.tp.connection"
#define NS_RECEIVER "urn:x-cast:com.google.cast.receiver"
#define NS_HEARTBEAT "urn:x-cast:com.google.cast.tp.heartbeat"
#define NS_MEDIA "urn:x-cast:com.google.cast.media"
#define NS_WEBRTC "urn:x-cast:com.google.cast.webrtc"
#define USE_TRANSPORT_ID (1 << 1)
#define USE_REQUEST_ID (1 << 2)
#define USE_REQUEST_ID_ONLY (1 << 3)
#define CALLBACK_REGISTER_SIZE 32
// Chromium will send OPUS encoded 10 ms packets (48kHz), about 120 bytes. We
// use a 20 ms packet, so 50 pkts/sec, because that's the default for ffmpeg.
// A 20 ms audio packet at 48000 kHz makes this number 48000 * (20 / 1000)
#define CAST_SAMPLES_PER_PACKET 960
#define CAST_QUALITY_SAMPLE_RATE_DEFAULT 48000
#define CAST_QUALITY_BITS_PER_SAMPLE_DEFAULT 16
#define CAST_QUALITY_CHANNELS_DEFAULT 2
// This is an arbitrary value which just needs to be kept in sync with the config
#define CAST_CONFIG_MAX_VOLUME 11
// This makes the rtp session buffer 6 seconds of audio (6 sec * 50 pkts/sec),
// which can be used for delayed transmission (and retransmission)
#define CAST_PACKET_BUFFER_SIZE 300
// Max number of RTP packets for one artwork image
#define CAST_PACKET_ARTWORK_SIZE 200
// Max (absolute) value the user is allowed to set offset_ms in the config file
#define CAST_OFFSET_MAX 1000
// This is just my measurement of how much extra delay is required to start at
// the same time as Airplay. The value was found experimentally.
#define CAST_DEVICE_START_DELAY_MS 100
// See cast_packet_header_make()
#define CAST_HEADER_SIZE 11
// These limits are from components/mirroring/service/session.cc
#define CAST_SSRC_AUDIO_MIN 1
#define CAST_SSRC_AUDIO_MAX 500000
#define CAST_SSRC_VIDEO_MIN 500001
#define CAST_SSRC_VIDEO_MAX 1000000
#define CAST_RTP_PAYLOADTYPE_AUDIO 127
#define CAST_RTP_PAYLOADTYPE_VIDEO 96
/* Notes
* OFFER/ANSWER <-webrtc
* RTCP/RTP
* XR custom receiver report
* Control and data on same UDP connection
* OPUS encoded
*/
//#define DEBUG_CHROMECAST 1
struct cast_session;
struct cast_msg_payload;
static struct encode_ctx *cast_encode_ctx;
static struct evbuffer *cast_encoded_data;
typedef void (*cast_reply_cb)(struct cast_session *cs, struct cast_msg_payload *payload);
// Session is starting up
#define CAST_STATE_F_STARTUP (1 << 13)
// The receiver app is ready
#define CAST_STATE_F_APP_READY (1 << 14)
// Media is playing in the receiver app
#define CAST_STATE_F_STREAMING (1 << 15)
// Beware, the order of this enum has meaning
enum cast_state
{
// Something bad happened during a session
CAST_STATE_FAILED = 0,
// No session allocated
CAST_STATE_NONE = 1,
// Session allocated, but no connection
CAST_STATE_DISCONNECTED = CAST_STATE_F_STARTUP | 0x01,
// TCP connect, TLS handshake, CONNECT and GET_STATUS request
CAST_STATE_CONNECTED = CAST_STATE_F_STARTUP | 0x02,
// Receiver app has been launched
CAST_STATE_APP_LAUNCHED = CAST_STATE_F_STARTUP | 0x03,
// CONNECT, GET_STATUS and OFFER made to receiver app
CAST_STATE_APP_READY = CAST_STATE_F_APP_READY,
// Buffering packets (playback not started yet)
CAST_STATE_BUFFERING = CAST_STATE_F_APP_READY | 0x01,
// Streaming (playback started)
CAST_STATE_STREAMING = CAST_STATE_F_APP_READY | CAST_STATE_F_STREAMING,
};
struct cast_master_session
{
struct evbuffer *evbuf;
int evbuf_samples;
struct rtp_session *rtp_session;
struct media_quality quality;
uint8_t *rawbuf;
size_t rawbuf_size;
int samples_per_packet;
struct rtp_session *rtp_artwork;
};
struct cast_session
{
uint64_t device_id;
int callback_id;
struct cast_master_session *master_session;
// Current state
enum cast_state state;
// Used to register a target state if we are transitioning from one to another
enum cast_state wanted_state;
// Connection fd and session, and listener event
int server_fd;
gnutls_session_t tls_session;
struct event *ev;
char *devname;
char *address;
int family;
unsigned short port;
// ChromeCast uses a float between 0 - 1
float volume;
uint32_t ssrc_id;
// For initial buffering (delay playback to achieve some sort of sync).
struct timespec start_pts;
struct timespec offset_ts;
uint16_t seqnum_next;
uint16_t ack_last;
// Outgoing request which have the USE_REQUEST_ID flag get a new id, and a
// callback is registered. The callback is called when an incoming message
// from the peer with that request id arrives. If nothing arrives within
// REPLY_TIMEOUT we make the callback with a NULL payload pointer.
unsigned int request_id;
cast_reply_cb callback_register[CALLBACK_REGISTER_SIZE];
struct event *reply_timeout;
// This is used to work around a bug where no response is given by the device.
// For certain requests, we will then retry, e.g. by checking status. We
// register our retry so that we on only retry once.
int retry;
// Session info from the Chromecast
char *transport_id;
char *session_id;
unsigned int media_session_id;
int udp_fd;
unsigned short udp_port;
struct event *rtcp_ev;
struct cast_session *next;
};
enum cast_msg_types
{
UNKNOWN,
PING,
PONG,
CONNECT,
CLOSE,
GET_STATUS,
RECEIVER_STATUS,
LAUNCH,
LAUNCH_OLD,
LAUNCH_ERROR,
STOP,
MEDIA_CONNECT,
MEDIA_CLOSE,
OFFER,
ANSWER,
MEDIA_GET_STATUS,
MEDIA_STATUS,
SET_VOLUME,
PRESENTATION,
GET_CAPABILITIES,
CAPABILITIES_RESPONSE,
};
struct cast_msg_basic
{
enum cast_msg_types type;
char *tag; // Used for looking up incoming message type
char *namespace;
char *payload;
int flags;
};
struct cast_msg_payload
{
enum cast_msg_types type;
unsigned int request_id;
const char *app_id;
const char *session_id;
const char *transport_id;
const char *player_state;
const char *result;
unsigned int media_session_id;
unsigned short udp_port;
};
struct cast_rtcp_packet_feedback
{
uint8_t frame_id_last;
uint8_t num_lost_fields;
struct cast_rtcp_lost_fields
{
uint8_t frame_id;
uint16_t packet_id;
uint8_t bitmask;
} lost_fields[32]; // From observation we normally get just 1 or 2 elements, so 32 should be plenty
uint16_t target_delay_ms;
uint8_t count;
uint8_t recv_fields;
};
struct cast_metadata
{
struct evbuffer *artwork;
};
// Array of the cast messages that we use. Must be in sync with cast_msg_types.
struct cast_msg_basic cast_msg[] =
{
{
.type = UNKNOWN,
.namespace = "",
.payload = "",
},
{
.type = PING,
.tag = "PING",
.namespace = NS_HEARTBEAT,
.payload = "{'type':'PING'}",
},
{
.type = PONG,
.tag = "PONG",
.namespace = NS_HEARTBEAT,
.payload = "{'type':'PONG'}",
},
{
.type = CONNECT,
.namespace = NS_CONNECTION,
.payload = "{'type':'CONNECT'}",
// msg.payload_utf8 = "{\"origin\":{},\"userAgent\":\"owntone\",\"type\":\"CONNECT\",\"senderInfo\":{\"browserVersion\":\"44.0.2403.30\",\"version\":\"15.605.1.3\",\"connectionType\":1,\"platform\":4,\"sdkType\":2,\"systemVersion\":\"Macintosh; Intel Mac OS X10_10_3\"}}";
},
{
.type = CLOSE,
.tag = "CLOSE",
.namespace = NS_CONNECTION,
.payload = "{'type':'CLOSE'}",
},
{
.type = GET_STATUS,
.namespace = NS_RECEIVER,
.payload = "{'type':'GET_STATUS','requestId':%u}",
.flags = USE_REQUEST_ID_ONLY,
},
{
.type = RECEIVER_STATUS,
.tag = "RECEIVER_STATUS",
},
{
.type = LAUNCH,
.namespace = NS_RECEIVER,
.payload = "{'type':'LAUNCH','requestId':%u,'appId':'" CAST_APP_ID "'}",
.flags = USE_REQUEST_ID_ONLY,
},
{
.type = LAUNCH_OLD,
.namespace = NS_RECEIVER,
.payload = "{'type':'LAUNCH','requestId':%u,'appId':'" CAST_APP_ID_OLD "'}",
.flags = USE_REQUEST_ID_ONLY,
},
{
.type = LAUNCH_ERROR,
.tag = "LAUNCH_ERROR",
},
{
.type = STOP,
.namespace = NS_RECEIVER,
.payload = "{'type':'STOP','sessionId':'%s','requestId':%u}",
.flags = USE_REQUEST_ID,
},
{
.type = MEDIA_CONNECT,
.namespace = NS_CONNECTION,
.payload = "{'type':'CONNECT'}",
.flags = USE_TRANSPORT_ID,
},
{
.type = MEDIA_CLOSE,
.namespace = NS_CONNECTION,
.payload = "{'type':'CLOSE'}",
.flags = USE_TRANSPORT_ID,
},
{
.type = OFFER,
.namespace = NS_WEBRTC,
// codecName can be aac or opus, ssrc should be random
// We don't set 'aesKey' and 'aesIvMask'
// sampleRate seems to be ignored
// TODO calculate bitrate, result should be 102000, ref. Chromium
// storeTime unknown meaning - perhaps size of buffer?
// targetDelay - should be RTP delay in ms, but doesn't seem to change anything?
// vp8 timebase - see rfc7741
.payload = "{'type':'OFFER','seqNum':%u,'offer':{'castMode':'mirroring','supportedStreams':[{'index':0,'type':'audio_source','codecName':'opus','rtpProfile':'cast','rtpPayloadType':" NTOSTR(CAST_RTP_PAYLOADTYPE_AUDIO) ",'ssrc':%" PRIu32 ",'storeTime':400,'targetDelay':400,'bitRate':128000,'sampleRate':" NTOSTR(CAST_QUALITY_SAMPLE_RATE_DEFAULT) ",'timeBase':'1/" NTOSTR(CAST_QUALITY_SAMPLE_RATE_DEFAULT) "','channels':" NTOSTR(CAST_QUALITY_CHANNELS_DEFAULT) ",'receiverRtcpEventLog':false},{'codecName':'vp8','index':1,'maxBitRate':5000000,'maxFrameRate':'30000/1000','receiverRtcpEventLog':false,'renderMode':'video','resolutions':[{'height':900,'width':1600}],'rtpPayloadType':" NTOSTR(CAST_RTP_PAYLOADTYPE_VIDEO) ",'rtpProfile':'cast','ssrc':999999,'targetDelay':400,'timeBase':'1/90000','type':'video_source'}]}}",
.flags = USE_TRANSPORT_ID | USE_REQUEST_ID,
},
{
.type = ANSWER,
.tag = "ANSWER",
},
{
.type = MEDIA_GET_STATUS,
.namespace = NS_MEDIA,
.payload = "{'type':'GET_STATUS','requestId':%u}",
.flags = USE_TRANSPORT_ID | USE_REQUEST_ID_ONLY,
},
{
.type = MEDIA_STATUS,
.tag = "MEDIA_STATUS",
},
{
.type = SET_VOLUME,
.namespace = NS_RECEIVER,
.payload = "{'type':'SET_VOLUME','volume':{'level':%.2f,'muted':0},'requestId':%u}",
.flags = USE_REQUEST_ID,
},
{
.type = PRESENTATION,
.namespace = NS_WEBRTC,
.payload = "{'type':'PRESENTATION','sessionId':'%s','seqNum':%u,'title':'" PACKAGE_NAME "','icons':[{'url':'http://www.gyfgafguf.dk/images/fugl.jpg'}] }",
.flags = USE_TRANSPORT_ID | USE_REQUEST_ID,
},
{
// This message is useful for diagnostics, since it will return the
// codecs that the device supports, but doesn't work for all devices
.type = GET_CAPABILITIES,
.namespace = NS_WEBRTC,
.payload = "{'type':'GET_CAPABILITIES','seqNum':%u}",
.flags = USE_TRANSPORT_ID | USE_REQUEST_ID_ONLY,
},
{
.type = CAPABILITIES_RESPONSE,
.tag = "CAPABILITIES_RESPONSE",
},
{
.type = 0,
},
};
/* From player.c */
extern struct event_base *evbase_player;
/* Globals */
static gnutls_certificate_credentials_t tls_credentials;
static struct cast_session *cast_sessions;
static struct cast_master_session *cast_master_session;
//static struct timeval heartbeat_timeout = { HEARTBEAT_TIMEOUT, 0 };
static struct timeval reply_timeout = { REPLY_TIMEOUT, 0 };
static struct media_quality cast_quality_default = { CAST_QUALITY_SAMPLE_RATE_DEFAULT, CAST_QUALITY_BITS_PER_SAMPLE_DEFAULT, CAST_QUALITY_CHANNELS_DEFAULT, 0 };
/* ------------------------------- MISC HELPERS ----------------------------- */
static void
cast_disconnect(int fd)
{
/* no more receptions */
shutdown(fd, SHUT_RDWR);
close(fd);
}
/*static void
cast_metadata_free(struct cast_metadata *cmd)
{
if (!cmd)
return;
if (cmd->artwork)
evbuffer_free(cmd->artwork);
free(cmd);
}
*/
static char *
squote_to_dquote(char *buf)
{
char *ptr;
for (ptr = buf; *ptr != '\0'; ptr++)
if (*ptr == '\'')
*ptr = '"';
return buf;
}
/* ----------------------------- SESSION CLEANUP ---------------------------- */
static void
master_session_free(struct cast_master_session *cms)
{
if (!cms)
return;
outputs_quality_unsubscribe(&cms->rtp_session->quality);
rtp_session_free(cms->rtp_session);
rtp_session_free(cms->rtp_artwork);
evbuffer_free(cms->evbuf);
free(cms->rawbuf);
free(cms);
}
static void
master_session_cleanup(struct cast_master_session *cms)
{
struct cast_session *cs;
// First check if any other session is using the master session
for (cs = cast_sessions; cs; cs=cs->next)
{
if (cs->master_session == cms)
return;
}
if (cms == cast_master_session)
cast_master_session = NULL;
master_session_free(cms);
}
static void
cast_session_free(struct cast_session *cs)
{
if (!cs)
return;
master_session_cleanup(cs->master_session);
event_free(cs->reply_timeout);
event_free(cs->ev);
if (cs->server_fd >= 0)
cast_disconnect(cs->server_fd);
if (cs->rtcp_ev)
event_free(cs->rtcp_ev);
if (cs->udp_fd >= 0)
cast_disconnect(cs->udp_fd);
gnutls_deinit(cs->tls_session);
free(cs->address);
free(cs->devname);
free(cs->session_id);
free(cs->transport_id);
free(cs);
}
static void
cast_session_cleanup(struct cast_session *cs)
{
struct cast_session *s;
if (cs == cast_sessions)
cast_sessions = cast_sessions->next;
else
{
for (s = cast_sessions; s && (s->next != cs); s = s->next)
; /* EMPTY */
if (!s)
DPRINTF(E_WARN, L_CAST, "WARNING: struct cast_session not found in list; BUG!\n");
else
s->next = cs->next;
}
outputs_device_session_remove(cs->device_id);
cast_session_free(cs);
}
// Forward
static void
cast_session_shutdown(struct cast_session *cs, enum cast_state wanted_state);
/* --------------------------- CAST MESSAGE HANDLING ------------------------ */
static int
cast_msg_send(struct cast_session *cs, enum cast_msg_types type, cast_reply_cb reply_cb)
{
Extensions__CoreApi__CastChannel__CastMessage msg = EXTENSIONS__CORE_API__CAST_CHANNEL__CAST_MESSAGE__INIT;
char msg_buf[MAX_BUF];
uint8_t buf[MAX_BUF];
uint32_t be;
size_t len;
int ret;
#ifdef DEBUG_CHROMECAST
DPRINTF(E_DBG, L_CAST, "Preparing to send message type %d to '%s'\n", type, cs->devname);
#endif
msg.source_id = "sender-0";
msg.namespace_ = cast_msg[type].namespace;
if ((cast_msg[type].flags & USE_TRANSPORT_ID) && !cs->transport_id)
{
DPRINTF(E_LOG, L_CAST, "Error, didn't get transportId for message (type %d) to '%s'\n", type, cs->devname);
return -1;
}
if (cast_msg[type].flags & USE_TRANSPORT_ID)
msg.destination_id = cs->transport_id;
else
msg.destination_id = "receiver-0";
if (cast_msg[type].flags & (USE_REQUEST_ID | USE_REQUEST_ID_ONLY))
{
cs->request_id++;
if (reply_cb)
{
cs->callback_register[cs->request_id % CALLBACK_REGISTER_SIZE] = reply_cb;
event_add(cs->reply_timeout, &reply_timeout);
}
}
// Special handling of some message types
if (cast_msg[type].flags & USE_REQUEST_ID_ONLY)
snprintf(msg_buf, sizeof(msg_buf), cast_msg[type].payload, cs->request_id);
else if (type == STOP)
snprintf(msg_buf, sizeof(msg_buf), cast_msg[type].payload, cs->session_id, cs->request_id);
else if (type == OFFER)
snprintf(msg_buf, sizeof(msg_buf), cast_msg[type].payload, cs->request_id, cs->ssrc_id);
else if (type == PRESENTATION)
snprintf(msg_buf, sizeof(msg_buf), cast_msg[type].payload, cs->session_id, cs->request_id);
else if (type == SET_VOLUME)
snprintf(msg_buf, sizeof(msg_buf), cast_msg[type].payload, cs->volume, cs->request_id);
else
snprintf(msg_buf, sizeof(msg_buf), "%s", cast_msg[type].payload);
squote_to_dquote(msg_buf);
msg.payload_utf8 = msg_buf;
len = extensions__core_api__cast_channel__cast_message__get_packed_size(&msg);
if (len <= 0 || len >= sizeof(buf) - 4)
{
DPRINTF(E_LOG, L_CAST, "Could not send message (type %d), invalid length: %zu\n", type, len);
return -1;
}
// The message must be prefixed with Big-Endian 32 bit length
be = htobe32(len);
memcpy(buf, &be, 4);
// Now add the packed message and send it
extensions__core_api__cast_channel__cast_message__pack(&msg, buf + 4);
ret = gnutls_record_send(cs->tls_session, buf, len + 4);
if (ret < 0)
{
DPRINTF(E_LOG, L_CAST, "Could not send message, TLS error\n");
return -1;
}
else if (ret != len + 4)
{
DPRINTF(E_LOG, L_CAST, "BUG! Message partially sent, and we are not able to send the rest\n");
return -1;
}
if (type != PONG)
DPRINTF(E_DBG, L_CAST, "TX %zu %s %s %s %s\n", len, msg.source_id, msg.destination_id, msg.namespace_, msg.payload_utf8);
return 0;
}
static void *
cast_msg_parse(struct cast_msg_payload *payload, char *s)
{
json_object *haystack;
json_object *somehay;
json_object *needle;
const char *val;
int i;
haystack = json_tokener_parse(s);
if (!haystack)
{
DPRINTF(E_LOG, L_CAST, "JSON parser returned an error\n");
return NULL;
}
payload->type = UNKNOWN;
if (json_object_object_get_ex(haystack, "type", &needle))
{
val = json_object_get_string(needle);
for (i = 1; cast_msg[i].type; i++)
{
if (cast_msg[i].tag && (strcmp(val, cast_msg[i].tag) == 0))
{
payload->type = cast_msg[i].type;
break;
}
}
}
if (json_object_object_get_ex(haystack, "requestId", &needle))
payload->request_id = json_object_get_int(needle);
else if (json_object_object_get_ex(haystack, "seqNum", &needle))
payload->request_id = json_object_get_int(needle);
if (json_object_object_get_ex(haystack, "answer", &somehay) &&
json_object_object_get_ex(somehay, "udpPort", &needle) &&
json_object_get_type(needle) == json_type_int )
payload->udp_port = json_object_get_int(needle);
if (json_object_object_get_ex(haystack, "result", &needle) &&
json_object_get_type(needle) == json_type_string )
payload->result = json_object_get_string(needle);
// Might be done now
if ((payload->type != RECEIVER_STATUS) && (payload->type != MEDIA_STATUS))
return haystack;
// Isn't this marvelous
if ( json_object_object_get_ex(haystack, "status", &needle) &&
(json_object_get_type(needle) == json_type_array) &&
(somehay = json_object_array_get_idx(needle, 0)) )
{
if ( json_object_object_get_ex(somehay, "mediaSessionId", &needle) &&
(json_object_get_type(needle) == json_type_int) )
payload->media_session_id = json_object_get_int(needle);
if ( json_object_object_get_ex(somehay, "playerState", &needle) &&
(json_object_get_type(needle) == json_type_string) )
payload->player_state = json_object_get_string(needle);
}
if ( json_object_object_get_ex(haystack, "status", &somehay) &&
json_object_object_get_ex(somehay, "applications", &needle) &&
(json_object_get_type(needle) == json_type_array) &&
(somehay = json_object_array_get_idx(needle, 0)) )
{
if ( json_object_object_get_ex(somehay, "appId", &needle) &&
(json_object_get_type(needle) == json_type_string) )
payload->app_id = json_object_get_string(needle);
if ( json_object_object_get_ex(somehay, "sessionId", &needle) &&
(json_object_get_type(needle) == json_type_string) )
payload->session_id = json_object_get_string(needle);
if ( json_object_object_get_ex(somehay, "transportId", &needle) &&
(json_object_get_type(needle) == json_type_string) )
payload->transport_id = json_object_get_string(needle);
}
return haystack;
}
static void
cast_msg_parse_free(void *haystack)
{
#ifdef HAVE_JSON_C_OLD
json_object_put((json_object *)haystack);
#else
if (json_object_put((json_object *)haystack) != 1)
DPRINTF(E_LOG, L_CAST, "Memleak: JSON parser did not free object\n");
#endif
}
static void
cast_msg_process(struct cast_session *cs, const uint8_t *data, size_t len)
{
Extensions__CoreApi__CastChannel__CastMessage *reply;
cast_reply_cb reply_cb;
struct cast_msg_payload payload = { 0 };
void *hdl;
int unknown_session_id;
int i;
#ifdef DEBUG_CHROMECAST
char *b64 = b64_encode(data, len);
if (b64)
{
DPRINTF(E_DBG, L_CAST, "Reply dump (len %zu): %s\n", len, b64);
free(b64);
}
#endif
reply = extensions__core_api__cast_channel__cast_message__unpack(NULL, len, data);
if (!reply)
{
DPRINTF(E_LOG, L_CAST, "Could not unpack message!\n");
return;
}
hdl = cast_msg_parse(&payload, reply->payload_utf8);
if (!hdl)
{
DPRINTF(E_DBG, L_CAST, "Could not parse message: %s\n", reply->payload_utf8);
goto out_free_unpacked;
}
if (payload.type == PING)
{
cast_msg_send(cs, PONG, NULL);
goto out_free_parsed;
}
DPRINTF(E_DBG, L_CAST, "RX %zu %s %s %s %s\n", len, reply->source_id, reply->destination_id, reply->namespace_, reply->payload_utf8);
if (payload.type == UNKNOWN)
goto out_free_parsed;
i = payload.request_id % CALLBACK_REGISTER_SIZE;
if (payload.request_id && cs->callback_register[i])
{
reply_cb = cs->callback_register[i];
cs->callback_register[i] = NULL;
// Cancel the timeout if no pending callbacks
for (i = 0; (i < CALLBACK_REGISTER_SIZE) && (!cs->callback_register[i]); i++);
if (i == CALLBACK_REGISTER_SIZE)
evtimer_del(cs->reply_timeout);
reply_cb(cs, &payload);
goto out_free_parsed;
}
// TODO Should we read volume and playerstate changes from the Chromecast?
if (payload.type == RECEIVER_STATUS && (cs->state & CAST_STATE_F_APP_READY))
{
unknown_session_id = payload.session_id && (strcmp(payload.session_id, cs->session_id) != 0);
if (unknown_session_id)
{
DPRINTF(E_LOG, L_CAST, "Our session '%s' on '%s' was lost to session '%s'\n", cs->session_id, cs->devname, payload.session_id);
// Downgrade state, we don't have the receiver app any more
cs->state = CAST_STATE_CONNECTED;
cast_session_shutdown(cs, CAST_STATE_FAILED);
goto out_free_parsed;
}
}
if (payload.type == CLOSE && (cs->state & CAST_STATE_F_APP_READY))
{
// Downgrade state, we can't write any more
cs->state = CAST_STATE_CONNECTED;
cast_session_shutdown(cs, CAST_STATE_FAILED);
goto out_free_parsed;
}
if (payload.type == MEDIA_STATUS && (cs->state & CAST_STATE_F_STREAMING))
{
if (payload.player_state && (strcmp(payload.player_state, "PAUSED") == 0))
{
DPRINTF(E_WARN, L_CAST, "Something paused our session on '%s'\n", cs->devname);
/* cs->state = CAST_STATE_APP_READY;
// Kill the session, the player will need to restart it
cast_session_shutdown(cs, CAST_STATE_NONE);
goto out_free_parsed;
*/ }
}
out_free_parsed:
cast_msg_parse_free(hdl);
out_free_unpacked:
extensions__core_api__cast_channel__cast_message__free_unpacked(reply, NULL);
}
/* ------------------ PREPARING AND SENDING CAST RTP PACKETS ---------------- */
// Makes a Cast RTP packet (source: Chromium's media/cast/net/rtp/rtp_packetizer.cc)
//
// A Cast RTP packet is made of:
// RTP header (12 bytes)
// Cast header (7 bytes)
// Extension data (4 bytes)
// Packet data
//
// The Cast header + extension (optional?) consists of:
// 0 1 2 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |k|r| n_ext | frame_id | packet id |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | max_packet_id | ref_frame_id | ext_type |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | ext_size | new_playout_delay_ms |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//
// k: Is the frame a key frame?
// r: Is there a reference frame id?
// n_ext: Number of Cast extensions (Chromium uses 1: Adaptive Latency)
// ext_type: 0x04 Adaptive Latency extension
// ext_size: 0x02 -> 2 bytes
// new_playout_delay_ms: ??
// OPUS encodes the rawbuf payload
static int
payload_encode(struct evbuffer *evbuf, uint8_t *rawbuf, size_t rawbuf_size, int nsamples, struct media_quality *quality)
{
transcode_frame *frame;
int len;
frame = transcode_frame_new(rawbuf, rawbuf_size, nsamples, quality);
if (!frame)
{
DPRINTF(E_LOG, L_CAST, "Could not convert raw PCM to frame (bufsize=%zu)\n", rawbuf_size);
return -1;
}
len = transcode_encode(evbuf, cast_encode_ctx, frame, 0);
transcode_frame_free(frame);
if (len < 0)
{
DPRINTF(E_LOG, L_CAST, "Could not Opus encode frame\n");
return -1;
}
return len;
}
static int
packet_prepare(struct rtp_packet *pkt, struct evbuffer *evbuf)
{
// Cast header
memset(pkt->payload, 0, CAST_HEADER_SIZE);
pkt->payload[0] = 0xc1; // k = 1, r = 1 and one extension
// frame_id - this is the value that is returned when the packet is ack'ed
// Chromecasts possibly expect this to start at zero, sinze when we start
// non-zero we get ack's all the way from zero to our value. We don't start at
// zero because we can't do that for devices that join anyway.
pkt->payload[1] = (char)pkt->seqnum;
// packet_id and max_packet_id don't seem to be used, so leave them at 0
pkt->payload[6] = (char)pkt->seqnum;
pkt->payload[7] = 0x04; // kCastRtpExtensionAdaptiveLatency has id (1 << 2)
pkt->payload[8] = 0x02; // Extension will use two bytes
// leave extension values at 0, but Chromium sets them to:
// (frame.new_playout_delay_ms >> 8) and frame.new_playout_delay_ms (normal byte values are 0x03 0x20)
// Copy payload
return evbuffer_remove(evbuf, pkt->payload + CAST_HEADER_SIZE, pkt->payload_len - CAST_HEADER_SIZE);
}
static int
packet_make(struct cast_master_session *cms)
{
struct rtp_packet *pkt;
int len;
int ret;
// Encode payload into cast_encoded_data
len = payload_encode(cast_encoded_data, cms->rawbuf, cms->rawbuf_size, cms->samples_per_packet, &cms->quality);
if (len < 0)
return -1;
// For audio it is always a complete frame, so marker bit is 1 (like Chromium does)
pkt = rtp_packet_next(cms->rtp_session, CAST_HEADER_SIZE + len, cms->samples_per_packet, CAST_RTP_PAYLOADTYPE_AUDIO, 1);
// Creates Cast header + adds payload
ret = packet_prepare(pkt, cast_encoded_data);
if (ret < 0)
return -1;
// Commits packet to retransmit buffer, and prepares the session for the next packet
rtp_packet_commit(cms->rtp_session, pkt);
return 0;
}
static inline int
packets_make(struct cast_master_session *cms, struct output_data *odata)
{
int ret;
int npkts;
// TODO avoid this copy
evbuffer_add(cms->evbuf, odata->buffer, odata->bufsize);
cms->evbuf_samples += odata->samples;
// Make as many packets as we have data for (one packet requires rawbuf_size bytes)
npkts = 0;
while (evbuffer_get_length(cms->evbuf) >= cms->rawbuf_size)
{
evbuffer_remove(cms->evbuf, cms->rawbuf, cms->rawbuf_size);
cms->evbuf_samples -= cms->samples_per_packet;