forked from libretro/RetroArch
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathlibrsound.c
1636 lines (1364 loc) · 43.7 KB
/
librsound.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
/* RetroArch - A frontend for libretro.
* Copyright (C) 2010-2014 - Hans-Kristian Arntzen
* Copyright (C) 2011-2017 - Daniel De Matteis
*
* RetroArch 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 Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* RetroArch 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 RetroArch.
* If not, see <http://www.gnu.org/licenses/>.
*/
/* RSound - A PCM audio client/server
* Copyright (C) 2010 - Hans-Kristian Arntzen
*
* RSound 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 Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* RSound 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 RSound.
* If not, see <http://www.gnu.org/licenses/>.
*/
#include "drivers/rsound.h"
#ifdef __PS3__
#ifdef __PSL1GHT__
#include <sysmodule/sysmodule.h>
#include <sys/systime.h>
#include <net/net.h>
#else
#include <cell/sysmodule.h>
#include <sys/timer.h>
#include <sys/sys_time.h>
#include <netex/net.h>
#include <netex/errno.h>
#endif
#endif
#if defined(GEKKO)
#include <network.h>
#else
#define NETWORK_COMPAT_HEADERS 1
#endif
#ifdef NETWORK_COMPAT_HEADERS
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#ifdef __PS3__
#ifdef __PSL1GHT__
#include <net/poll.h>
#else
#include <sys/poll.h>
#endif
#else
#include <poll.h>
#endif
#endif
#include <fcntl.h>
#ifdef _WIN32
#include <direct.h>
#else
#include <unistd.h>
#endif
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <time.h>
#include <errno.h>
#include <compat/strl.h>
#include <retro_inline.h>
#include <retro_miscellaneous.h>
#include <retro_timers.h>
/*
****************************************************************************
Naming convention. Functions for use in API are called rsd_*(), *
internal function are called rsnd_*() *
****************************************************************************
*/
/* Internal enumerations */
enum rsd_logtype
{
RSD_LOG_DEBUG = 0,
RSD_LOG_WARN,
RSD_LOG_ERR
};
enum rsd_conn_type
{
RSD_CONN_TCP = 0x0000,
RSD_CONN_UNIX = 0x0001,
RSD_CONN_DECNET = 0x0002,
RSD_CONN_PROTO = 0x100
};
/* Some logging macros. */
#define RSD_WARN(fmt, args...)
#define RSD_ERR(fmt, args...)
#define RSD_DEBUG(fmt, args...)
#if defined(__PS3__)
static int init_count = 0;
#define pollfd_fd(x) x.fd
#define net_send(a,b,c,d) send(a,b,c,d)
#define net_socket(a,b,c) socket(a,b,c)
#define net_connect(a,b,c) connect(a,b,c)
#define net_shutdown(a,b) shutdown(a,b)
#define net_socketclose(x) socketclose(x)
#define net_recv(a,b,c,d) recv(a,b,c,d)
#elif defined(GEKKO)
#define SHUT_RD 0
#define socketpoll(x, y, z) net_poll(x, y, z)
#define pollfd pollsd
#define pollfd_fd(x) x.socket
#define gethostbyname net_gethostbyname
#define getsockopt net_getsockopt
#define setsockopt net_setsockopt
#define net_send(a,b,c,d) net_send(a,b,c,d)
#define net_socket(a,b,c) net_socket(a,b,c)
#define net_connect(a,b,c) net_connect(a,b,c)
#define net_shutdown(a,b) net_shutdown(a,b)
#define net_socketclose(x) net_close(x)
#define net_recv(a,b,c,d) net_recv(a,b,c,d)
#else
#define pollfd_fd(x) x.fd
#define net_socket(a,b,c) socket(a,b,c)
#define socketpoll(x, y, z) poll(x, y, z)
#define net_send(a,b,c,d) send(a,b,c,d)
#define net_connect(a,b,c) connect(a,b,c)
#define net_shutdown(a,b) shutdown(a,b)
#define net_socketclose(x) close(x)
#define net_recv(a,b,c,d) recv(a,b,c,d)
#endif
static ssize_t rsnd_send_chunk(int socket, const void *buf, size_t size, int blocking);
static ssize_t rsnd_recv_chunk(int socket, void *buf, size_t size, int blocking);
static int rsnd_start_thread(rsound_t *rd);
static int rsnd_stop_thread(rsound_t *rd);
static size_t rsnd_get_delay(rsound_t *rd);
static size_t rsnd_get_ptr(rsound_t *rd);
static int rsnd_reset(rsound_t *rd);
/* Protocol functions */
static int rsnd_send_identity_info(rsound_t *rd);
static int rsnd_close_ctl(rsound_t *rd);
static int rsnd_send_info_query(rsound_t *rd);
static int rsnd_update_server_info(rsound_t *rd);
static int rsnd_poll(struct pollfd *fd, int numfd, int timeout);
static void rsnd_cb_thread(void *thread_data);
static void rsnd_thread(void *thread_data);
/* Determine whether we're running big- or little endian */
static INLINE int rsnd_is_little_endian(void)
{
uint16_t i = 1;
return *((uint8_t*)&i);
}
/* Simple functions for swapping bytes */
static INLINE void rsnd_swap_endian_16 ( uint16_t * x )
{
*x = (*x>>8) | (*x<<8);
}
static INLINE void rsnd_swap_endian_32 ( uint32_t * x )
{
*x = (*x >> 24 ) |
((*x<<8) & 0x00FF0000) |
((*x>>8) & 0x0000FF00) |
(*x << 24);
}
static INLINE int rsnd_format_to_samplesize ( uint16_t fmt )
{
switch(fmt)
{
case RSD_S32_LE:
case RSD_S32_BE:
case RSD_S32_NE:
case RSD_U32_LE:
case RSD_U32_BE:
case RSD_U32_NE:
return 4;
case RSD_S16_LE:
case RSD_U16_LE:
case RSD_S16_BE:
case RSD_U16_BE:
case RSD_S16_NE:
case RSD_U16_NE:
return 2;
case RSD_U8:
case RSD_S8:
case RSD_ALAW:
case RSD_MULAW:
return 1;
default:
return -1;
}
}
int rsd_samplesize( rsound_t *rd )
{
return rd->samplesize;
}
/* Creates sockets and attempts to connect to the server. Returns -1 when failed, and 0 when success. */
static int rsnd_connect_server( rsound_t *rd )
{
struct sockaddr_in addr;
struct pollfd fd;
int i = 1;
(void)i;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(atoi(rd->port));
if (!isdigit(rd->host[0]))
{
struct hostent *host = gethostbyname(rd->host);
if (!host)
return -1;
addr.sin_addr.s_addr = inet_addr(host->h_addr_list[0]);
}
else
addr.sin_addr.s_addr = inet_addr(rd->host);
rd->conn_type = RSD_CONN_TCP;
rd->conn.socket = net_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if ( rd->conn.socket < 0 )
goto error;
rd->conn.ctl_socket = net_socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if ( rd->conn.ctl_socket < 0 )
goto error;
/* Uses non-blocking IO since it performed more deterministic with poll()/send() */
#ifdef __PS3__
setsockopt(rd->conn.socket, SOL_SOCKET, SO_NBIO, &i, sizeof(int));
setsockopt(rd->conn.ctl_socket, SOL_SOCKET, SO_NBIO, &i, sizeof(int));
#else
fcntl(rd->conn.socket, F_SETFL, O_NONBLOCK);
fcntl(rd->conn.ctl_socket, F_SETFL, O_NONBLOCK);
#endif
/* Nonblocking connect with 3 second timeout */
net_connect(rd->conn.socket, (struct sockaddr*)&addr, sizeof(addr));
pollfd_fd(fd) = rd->conn.socket;
fd.events = POLLOUT;
rsnd_poll(&fd, 1, 3000);
if (!(fd.revents & POLLOUT))
goto error;
net_connect(rd->conn.ctl_socket, (struct sockaddr*)&addr, sizeof(addr));
pollfd_fd(fd) = rd->conn.ctl_socket;
rsnd_poll(&fd, 1, 3000);
if (!(fd.revents & POLLOUT))
goto error;
return 0;
/* Cleanup for errors. */
error:
RSD_ERR("[RSound] Connecting to server failed. \"%s\"", rd->host);
return -1;
}
/* Conjures a WAV-header and sends this to server. Returns -1 when failed, and 0 when success. */
static int rsnd_send_header_info(rsound_t *rd)
{
/* Defines the size of a wave header */
#define HEADER_SIZE 44
char *header = calloc(1, HEADER_SIZE);
if (!header)
{
RSD_ERR("[RSound] Could not allocate memory.");
return -1;
}
uint16_t temp16;
uint32_t temp32;
/* These magic numbers represent the position of the elements in the wave header.
We can't simply send a wave struct over the network since the compiler is allowed to
pad our structs as they like, so sizeof(waveheader) might not be similar on two different
systems. */
#define RATE 24
#define CHANNEL 22
#define FRAMESIZE 34
#define FORMAT 42
uint32_t temp_rate = rd->rate;
uint16_t temp_channels = rd->channels;
uint16_t temp_bits = 8 * rsnd_format_to_samplesize(rd->format);
uint16_t temp_format = rd->format;
/* Checks the format for native endian which will need to be set properly. */
switch ( temp_format )
{
case RSD_S16_NE:
if ( rsnd_is_little_endian() )
temp_format = RSD_S16_LE;
else
temp_format = RSD_S16_BE;
break;
case RSD_U16_NE:
if ( rsnd_is_little_endian() )
temp_format = RSD_U16_LE;
else
temp_format = RSD_U16_BE;
break;
case RSD_S32_NE:
if ( rsnd_is_little_endian() )
temp_format = RSD_S32_LE;
else
temp_format = RSD_S32_BE;
break;
case RSD_U32_NE:
if ( rsnd_is_little_endian() )
temp_format = RSD_U32_LE;
else
temp_format = RSD_U32_BE;
break;
default:
break;
}
/* Since the values in the wave header we are interested in, are little endian (>_<), we need
to determine whether we're running it or not, so we can byte swap accordingly.
Could determine this compile time, but it was simpler to do it this way. */
/* Fancy macros for embedding little endian values into the header. */
#define SET32(buf,offset,x) (*((uint32_t*)(buf+offset)) = x)
#define SET16(buf,offset,x) (*((uint16_t*)(buf+offset)) = x)
#define LSB16(x) if ( !rsnd_is_little_endian() ) { rsnd_swap_endian_16(&(x)); }
#define LSB32(x) if ( !rsnd_is_little_endian() ) { rsnd_swap_endian_32(&(x)); }
/* Here we embed in the rest of the WAV header for it to be somewhat valid */
strlcpy(header, "RIFF", sizeof(header));
SET32(header, 4, 0);
strlcpy(header+8, "WAVE", sizeof(header));
strlcpy(header+12, "fmt ", sizeof(header));
temp32 = 16;
LSB32(temp32);
SET32(header, 16, temp32);
temp16 = 0; /* PCM data */
switch( rd->format )
{
case RSD_S16_LE:
case RSD_U8:
temp16 = 1;
break;
case RSD_ALAW:
temp16 = 6;
break;
case RSD_MULAW:
temp16 = 7;
break;
}
LSB16(temp16);
SET16(header, 20, temp16);
/* Channels here */
LSB16(temp_channels);
SET16(header, CHANNEL, temp_channels);
/* Samples per sec */
LSB32(temp_rate);
SET32(header, RATE, temp_rate);
temp32 = rd->rate * rd->channels * rsnd_format_to_samplesize(rd->format);
LSB32(temp32);
SET32(header, 28, temp32);
temp16 = rd->channels * rsnd_format_to_samplesize(rd->format);
LSB16(temp16);
SET16(header, 32, temp16);
/* Bits per sample */
LSB16(temp_bits);
SET16(header, FRAMESIZE, temp_bits);
strlcpy(header+36, "data", sizeof(header));
/* Do not care about cksize here (impossible to know beforehand).
* It is used by the server for format. */
LSB16(temp_format);
SET16(header, FORMAT, temp_format);
/* End static header */
if ( rsnd_send_chunk(rd->conn.socket, header, HEADER_SIZE, 1) != HEADER_SIZE )
{
free(header);
return -1;
}
free(header);
return 0;
}
/* Receives backend info from server that is of interest to the client. (This mini-protocol might be extended later on.) */
static int rsnd_get_backend_info ( rsound_t *rd )
{
#define RSND_HEADER_SIZE 8
#define LATENCY 0
#define CHUNKSIZE 1
/* Header is 2 uint32_t's. = 8 bytes. */
uint32_t rsnd_header[2] = {0};
if ( rsnd_recv_chunk(rd->conn.socket, rsnd_header, RSND_HEADER_SIZE, 1) != RSND_HEADER_SIZE )
{
RSD_ERR("[RSound] Couldn't receive chunk.\n");
return -1;
}
/* Again, we can't be 100% certain that sizeof(backend_info_t) is equal on every system */
if ( rsnd_is_little_endian() )
{
rsnd_swap_endian_32(&rsnd_header[LATENCY]);
rsnd_swap_endian_32(&rsnd_header[CHUNKSIZE]);
}
rd->backend_info.latency = rsnd_header[LATENCY];
rd->backend_info.chunk_size = rsnd_header[CHUNKSIZE];
#define MAX_CHUNK_SIZE 1024 /* We do not want larger chunk sizes than this. */
if ( rd->backend_info.chunk_size > MAX_CHUNK_SIZE || rd->backend_info.chunk_size <= 0 )
rd->backend_info.chunk_size = MAX_CHUNK_SIZE;
/* Assumes a default buffer size should it cause problems of being too small */
if ( rd->buffer_size == 0 || rd->buffer_size < rd->backend_info.chunk_size * 2 )
rd->buffer_size = rd->backend_info.chunk_size * 32;
if ( rd->fifo_buffer != NULL )
fifo_free(rd->fifo_buffer);
rd->fifo_buffer = fifo_new (rd->buffer_size);
if (!rd->fifo_buffer)
{
RSD_ERR("[RSound] Failed to create FIFO buffer.\n");
return -1;
}
/* Only bother with setting network buffer size if we're doing TCP. */
if ( rd->conn_type & RSD_CONN_TCP )
{
#define MAX_TCP_BUFSIZE (1 << 14)
int bufsiz = rd->buffer_size;
if (bufsiz > MAX_TCP_BUFSIZE)
bufsiz = MAX_TCP_BUFSIZE;
setsockopt(rd->conn.socket, SOL_SOCKET, SO_SNDBUF, &bufsiz, sizeof(int));
bufsiz = rd->buffer_size;
setsockopt(rd->conn.ctl_socket, SOL_SOCKET, SO_SNDBUF, &bufsiz, sizeof(int));
bufsiz = rd->buffer_size;
setsockopt(rd->conn.ctl_socket, SOL_SOCKET, SO_RCVBUF, &bufsiz, sizeof(int));
int flag = 1;
setsockopt(rd->conn.socket, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(int));
flag = 1;
setsockopt(rd->conn.ctl_socket, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(int));
}
/* Can we read the last 8 bytes so we can use the protocol interface? */
/* This is non-blocking. */
if ( rsnd_recv_chunk(rd->conn.socket, rsnd_header, RSND_HEADER_SIZE, 0) == RSND_HEADER_SIZE )
rd->conn_type |= RSD_CONN_PROTO;
else
{ RSD_DEBUG("[RSound] Failed to get new proto.\n"); }
/* We no longer want to read from this socket. */
#ifdef _WIN32
net_shutdown(rd->conn.socket, SD_RECEIVE);
#elif !defined(__APPLE__) /* OSX doesn't seem to like shutdown() */
net_shutdown(rd->conn.socket, SHUT_RD);
#endif
return 0;
}
/* Makes sure that we're connected and done with wave header handshaking. Returns -1 on error, and 0 on success.
This goes for all other functions in use. */
static int rsnd_create_connection(rsound_t *rd)
{
int rc;
/* Are we connected to the server? If not, these values have been set to <0, so we make sure that we connect */
if ( rd->conn.socket <= 0 && rd->conn.ctl_socket <= 0 )
{
rc = rsnd_connect_server(rd);
if (rc < 0)
{
RSD_ERR("[RSound] connect server failed.\n");
rsd_stop(rd);
return -1;
}
/* After connecting, makes really sure that we have a working connection. */
struct pollfd fd;
pollfd_fd(fd) = rd->conn.socket;
fd.events = POLLOUT;
if ( rsnd_poll(&fd, 1, 2000) < 0 )
{
RSD_ERR("[RSound] rsnd_poll failed.\n");
rsd_stop(rd);
return -1;
}
if ( !(fd.revents & POLLOUT) )
{
RSD_ERR("[RSound] Poll didn't return what we wanted.\n");
rsd_stop(rd);
return -1;
}
}
/* Is the server ready for data? The first thing it expects is the wave header */
if ( !rd->ready_for_data )
{
/* Part of the uber simple protocol.
1. Send wave header.
2. Receive backend info like latency and preferred packet size.
3. Starts the playback thread. */
rc = rsnd_send_header_info(rd);
if (rc < 0)
{
RSD_ERR("[RSound] Send header failed.\n");
rsd_stop(rd);
return -1;
}
rc = rsnd_get_backend_info(rd);
if (rc < 0)
{
RSD_ERR("[RSound] Get backend info failed.\n");
rsd_stop(rd);
return -1;
}
rc = rsnd_start_thread(rd);
if (rc < 0)
{
RSD_ERR("[RSound] Starting thread failed.\n");
rsd_stop(rd);
return -1;
}
if ( (rd->conn_type & RSD_CONN_PROTO) && strlen(rd->identity) > 0 )
{
rsnd_send_identity_info(rd);
}
rd->ready_for_data = 1;
}
return 0;
}
/* Sends a chunk over the network. Makes sure that everything is sent if blocking. Returns -1 if connection is lost, non-negative if success.
* If blocking, and not enough data is received, it will return -1. */
static ssize_t rsnd_send_chunk(int socket, const void* buf, size_t size, int blocking)
{
ssize_t rc = 0;
size_t wrote = 0;
ssize_t send_size = 0;
struct pollfd fd;
pollfd_fd(fd) = socket;
fd.events = POLLOUT;
int sleep_time = (blocking) ? 10000 : 0;
#define MAX_PACKET_SIZE 1024
while ( wrote < size )
{
if ( rsnd_poll(&fd, 1, sleep_time) < 0 )
return -1;
if ( fd.revents & POLLHUP )
{
RSD_WARN("*** Remote side hung up! ***");
return -1;
}
if ( fd.revents & POLLOUT )
{
/* We try to limit ourselves to 1KiB packet sizes. */
send_size = (size - wrote) > MAX_PACKET_SIZE ? MAX_PACKET_SIZE : size - wrote;
rc = net_send(socket, (const char*)buf + wrote, send_size, 0);
if ( rc < 0 )
{
RSD_ERR("[RSound] Error sending chunk, %s.\n", strerror(errno));
return rc;
}
wrote += rc;
}
else
{
/* If server hasn't stopped blocking after 10 secs, then we should probably shut down the stream. */
if ( blocking )
return -1;
else
return wrote;
}
}
return (ssize_t)wrote;
}
/* Received chunk. Makes sure that everything is received if blocking. Returns -1 if connection is lost, non-negative if success.
* If blocking, and not enough data is received, it will return -1. */
static ssize_t rsnd_recv_chunk(int socket, void *buf, size_t size, int blocking)
{
ssize_t rc = 0;
size_t has_read = 0;
ssize_t read_size = 0;
struct pollfd fd;
pollfd_fd(fd) = socket;
fd.events = POLLIN;
int sleep_time = (blocking) ? 5000 : 0;
while ( has_read < size )
{
if ( rsnd_poll(&fd, 1, sleep_time) < 0 )
{
RSD_ERR("[RSound] Poll failed.\n");
return -1;
}
if ( fd.revents & POLLHUP )
{
RSD_ERR("[RSound] Server hung up.\n");
return -1;
}
if ( fd.revents & POLLIN )
{
read_size = (size - has_read) > MAX_PACKET_SIZE ? MAX_PACKET_SIZE : size - has_read;
rc = net_recv(socket, (char*)buf + has_read, read_size, 0);
if ( rc <= 0 )
{
RSD_ERR("[RSound] Error receiving chunk, %s.\n", strerror(errno));
return rc;
}
has_read += rc;
}
else
{
if ( blocking )
{
RSD_ERR("[RSound] Block fail.\n");
return -1;
}
else
return has_read;
}
}
return (ssize_t)has_read;
}
static int rsnd_poll(struct pollfd *fd, int numfd, int timeout)
{
for (;;)
{
if (socketpoll(fd, numfd, timeout) < 0)
{
if (errno == EINTR)
continue;
perror("poll");
return -1;
}
return 0;
}
}
static int64_t rsnd_get_time_usec(void)
{
#if defined(_WIN32)
static LARGE_INTEGER freq;
if (!freq.QuadPart && !QueryPerformanceFrequency(&freq)) /* Frequency is guaranteed to not change. */
return 0;
LARGE_INTEGER count;
if (!QueryPerformanceCounter(&count))
return 0;
return count.QuadPart * 1000000 / freq.QuadPart;
#elif defined(__PS3__)
return sysGetSystemTime();
#elif defined(GEKKO)
return ticks_to_microsecs(gettime());
#elif defined(__MACH__) /* OSX doesn't have clock_gettime ... */
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
return mts.tv_sec * INT64_C(1000000) + (mts.tv_nsec + 500) / 1000;
#elif defined(_POSIX_MONOTONIC_CLOCK) || defined(__QNX__) || defined(ANDROID)
struct timespec tv;
if (clock_gettime(CLOCK_MONOTONIC, &tv) < 0)
return 0;
return tv.tv_sec * INT64_C(1000000) + (tv.tv_nsec + 500) / 1000;
#elif defined(EMSCRIPTEN)
return emscripten_get_now() * 1000;
#else
#error "Your platform does not have a timer function implemented in rsnd_get_time_usec(). Cannot continue."
#endif
}
/* Calculates how many bytes there are in total in the virtual buffer. This is calculated client side.
It should be accurate enough unless we have big problems with buffer underruns.
This function is called by rsd_delay() to determine the latency.
This function might be changed in the future to correctly determine latency from server. */
static void rsnd_drain(rsound_t *rd)
{
/* If the audio playback has started on the server we need to use timers. */
if ( rd->has_written )
{
/* Calculates the amount of bytes that the server has consumed. */
int64_t time = rsnd_get_time_usec();
int64_t delta = time - rd->start_time;
delta *= rd->rate * rd->channels * rd->samplesize;
delta /= 1000000;
/* Calculates the amount of data we have in our virtual buffer. Only used to calculate delay. */
slock_lock(rd->thread.mutex);
rd->bytes_in_buffer = (int)((int64_t)rd->total_written + (int64_t)FIFO_READ_AVAIL(rd->fifo_buffer) - delta);
slock_unlock(rd->thread.mutex);
}
else
{
slock_lock(rd->thread.mutex);
rd->bytes_in_buffer = FIFO_READ_AVAIL(rd->fifo_buffer);
slock_unlock(rd->thread.mutex);
}
}
/* Tries to fill the buffer. Uses signals to determine when the buffer is ready to be filled. Should the thread not be active
it will treat this as an error. Crude implementation of a blocking FIFO. */
static size_t rsnd_fill_buffer(rsound_t *rd, const char *buf, size_t size)
{
/* Wait until we have a ready buffer */
for (;;)
{
/* Should the thread be shut down while we're running, return with error */
if ( !rd->thread_active )
return 0;
slock_lock(rd->thread.mutex);
if (FIFO_WRITE_AVAIL(rd->fifo_buffer) >= size)
{
slock_unlock(rd->thread.mutex);
break;
}
slock_unlock(rd->thread.mutex);
/* Sleeps until we can write to the FIFO. */
slock_lock(rd->thread.cond_mutex);
scond_signal(rd->thread.cond);
RSD_DEBUG("[RSound] rsnd_fill_buffer: Going to sleep.\n");
scond_wait(rd->thread.cond, rd->thread.cond_mutex);
RSD_DEBUG("[RSound] rsnd_fill_buffer: Woke up.\n");
slock_unlock(rd->thread.cond_mutex);
}
slock_lock(rd->thread.mutex);
fifo_write(rd->fifo_buffer, buf, size);
slock_unlock(rd->thread.mutex);
#if 0
RSD_DEBUG("[RSound] fill_buffer: Wrote to buffer.\n");
#endif
/* Send signal to thread that buffer has been updated */
#if 0
RSD_DEBUG("[RSound] fill_buffer: Waking up thread.\n");
#endif
scond_signal(rd->thread.cond);
return size;
}
static int rsnd_start_thread(rsound_t *rd)
{
if ( !rd->thread_active )
{
rd->thread_active = 1;
rd->thread.thread = (sthread_t*)sthread_create(rd->audio_callback ? rsnd_cb_thread : rsnd_thread, rd);
if ( !rd->thread.thread )
{
rd->thread_active = 0;
RSD_ERR("[RSound] Failed to create thread.");
return -1;
}
return 0;
}
else
return 0;
}
/* Makes sure that the playback thread has been correctly shut down */
static int rsnd_stop_thread(rsound_t *rd)
{
if ( rd->thread_active )
{
RSD_DEBUG("[RSound] Shutting down thread.\n");
slock_lock(rd->thread.cond_mutex);
rd->thread_active = 0;
scond_signal(rd->thread.cond);
slock_unlock(rd->thread.cond_mutex);
sthread_join(rd->thread.thread);
RSD_DEBUG("[RSound] Thread joined successfully.\n");
return 0;
}
else
{
RSD_DEBUG("Thread is already shut down.\n");
return 0;
}
}
/* Calculates audio delay in bytes */
static size_t rsnd_get_delay(rsound_t *rd)
{
int ptr;
rsnd_drain(rd);
ptr = rd->bytes_in_buffer;
/* Adds the backend latency to the calculated latency. */
ptr += (int)rd->backend_info.latency;
slock_lock(rd->thread.mutex);
ptr += rd->delay_offset;
RSD_DEBUG("Offset: %d.\n", rd->delay_offset);
slock_unlock(rd->thread.mutex);
if ( ptr < 0 )
ptr = 0;
return (size_t)ptr;
}
static size_t rsnd_get_ptr(rsound_t *rd)
{
int ptr;
slock_lock(rd->thread.mutex);
ptr = FIFO_READ_AVAIL(rd->fifo_buffer);
slock_unlock(rd->thread.mutex);
return ptr;
}
static int rsnd_send_identity_info(rsound_t *rd)
{
#define RSD_PROTO_MAXSIZE 256
#define RSD_PROTO_CHUNKSIZE 8
char tmpbuf[RSD_PROTO_MAXSIZE];
char sendbuf[RSD_PROTO_MAXSIZE];
snprintf(tmpbuf, RSD_PROTO_MAXSIZE - 1, " IDENTITY %s", rd->identity);
tmpbuf[RSD_PROTO_MAXSIZE - 1] = '\0';
snprintf(sendbuf, RSD_PROTO_MAXSIZE - 1, "RSD%5d%s", (int)strlen(tmpbuf), tmpbuf);
sendbuf[RSD_PROTO_MAXSIZE - 1] = '\0';
if ( rsnd_send_chunk(rd->conn.ctl_socket, sendbuf, strlen(sendbuf), 0) != (ssize_t)strlen(sendbuf) )
return -1;
return 0;
}
static int rsnd_close_ctl(rsound_t *rd)
{
if ( !(rd->conn_type & RSD_CONN_PROTO) )
return -1;
struct pollfd fd;
pollfd_fd(fd) = rd->conn.ctl_socket;
fd.events = POLLOUT;
if ( rsnd_poll(&fd, 1, 0) < 0 )
return -1;
if ( fd.revents & POLLOUT )
{
const char *sendbuf = "RSD 9 CLOSECTL";
if (net_send(rd->conn.ctl_socket, sendbuf, strlen(sendbuf), 0) < 0 )
return -1;
}
else if ( fd.revents & POLLHUP )
return 0;
/* Let's wait for reply (or POLLHUP) */
fd.events = POLLIN;
int index = 0;
char buf[RSD_PROTO_MAXSIZE*2] = {0};
for (;;)
{
if (rsnd_poll(&fd, 1, 2000) < 0)
return -1;
if (fd.revents & POLLHUP)
break;
if (fd.revents & POLLIN)
{
const char *subchar;
/* We just read everything in large chunks until we find
* what we're looking for */
int rc = net_recv(rd->conn.ctl_socket, buf + index, RSD_PROTO_MAXSIZE*2 - 1 - index, 0);
if (rc <= 0 )
return -1;
/* Can we find it directly? */
if ( strstr(buf, "RSD 12 CLOSECTL OK") != NULL )
break;
else if ( strstr(buf, "RSD 15 CLOSECTL ERROR") != NULL )
return -1;
subchar = strrchr(buf, 'R');
if (!subchar)
index = 0;
else
{
memmove(buf, subchar, strlen(subchar) + 1);
index = strlen(buf);
}
}
else
return -1;
}
net_socketclose(rd->conn.ctl_socket);
return 0;
}
/* Sends delay info request to server on the ctl socket.
* This code section isn't critical, and will work if it works.
* It will never block. */
static int rsnd_send_info_query(rsound_t *rd)
{
char tmpbuf[RSD_PROTO_MAXSIZE];
char sendbuf[RSD_PROTO_MAXSIZE];