summaryrefslogtreecommitdiff
path: root/player.c
blob: 7edc2b3bba1c553ea3e7e69f7295e3b23479eb58 (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
/*
 * Slave-clocked ALAC stream player. This file is part of Shairport.
 * Copyright (c) James Laird 2011, 2013
 * All rights reserved.
 *
 * Modifications for audio synchronisation
 * and related work, copyright (c) Mike Brady 2014
 * 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 <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <pthread.h>
#include <math.h>
#include <sys/stat.h>
#include <signal.h>
#include <sys/syslog.h>
#include <assert.h>
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <inttypes.h>

#include "config.h"

#ifdef HAVE_LIBPOLARSSL
#include <polarssl/aes.h>
#include <polarssl/havege.h>
#endif

#ifdef HAVE_LIBSSL
#include <openssl/aes.h>
#endif

#ifdef HAVE_LIBSOXR
#include <soxr.h>
#endif

#include "common.h"
#include "player.h"
#include "rtp.h"
#include "rtsp.h"

#include "alac.h"

#include "apple_alac.h"

// parameters from the source
static unsigned char *aesiv;
#ifdef HAVE_LIBSSL
static AES_KEY aes;
#endif
static int input_sample_rate, input_bit_depth, input_num_channels, max_frames_per_packet;

static uint32_t timestamp_epoch, last_timestamp, maximum_timestamp_interval;// timestamp_epoch of zero means not initialised, could start at 2 or 1.



static int input_bytes_per_frame = 4;
static int output_bytes_per_frame;
static int output_sample_ratio;
static int output_sample_rate;


// The maximum frame size change there can be is +/- 1;
static int max_frame_size_change;
// #define FRAME_BYTES(max_frames_per_packet) (4 * max_frames_per_packet)
// maximal resampling shift - conservative
//#define OUTFRAME_BYTES(max_frames_per_packet) (4 * (max_frames_per_packet + 3))

#ifdef HAVE_LIBPOLARSSL
static aes_context dctx;
#endif

//static pthread_t player_thread = NULL;
static int please_stop;
static int encrypted; // Normally the audio is encrypted, but it may not be

static int connection_state_to_output; // if true, then play incoming stuff; if false drop everything

static alac_file *decoder_info;

// debug variables
static int late_packet_message_sent;
static uint64_t packet_count = 0;
static int32_t last_seqno_read;
static int decoder_in_use = 0;

// interthread variables
static int fix_volume = 0x10000;
static pthread_mutex_t vol_mutex = PTHREAD_MUTEX_INITIALIZER;

// default buffer size
// needs to be a power of 2 because of the way BUFIDX(seqno) works
#define BUFFER_FRAMES 512
#define MAX_PACKET 2048

// DAC buffer occupancy stuff
#define DAC_BUFFER_QUEUE_MINIMUM_LENGTH 600

typedef struct audio_buffer_entry { // decoded audio packets
  int ready;
  int64_t timestamp;
  seq_t sequence_number;
  signed short *data;
  int length; // the length of the decoded data
} abuf_t;
static abuf_t audio_buffer[BUFFER_FRAMES];
#define BUFIDX(seqno) ((seq_t)(seqno) % BUFFER_FRAMES)

// mutex-protected variables
static seq_t ab_read, ab_write;
static int ab_buffering = 1, ab_synced = 0;
static int64_t first_packet_timestamp = 0;
static int flush_requested = 0;
static int64_t flush_rtp_timestamp;
static uint64_t time_of_last_audio_packet;
static int shutdown_requested;

// mutexes and condition variables
static pthread_mutex_t ab_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t flush_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t flowcontrol;

static int64_t first_packet_time_to_play, time_since_play_started; // nanoseconds

static audio_parameters audio_information;

// stats
static uint64_t missing_packets, late_packets, too_late_packets, resend_requests;

// make timestamps and seqnos definitely monotonic

// add an epoch to the timestamp. The monotonic timestamp guaranteed to start between 2^32 and 2^33 frames and continue up to 2^63-1 frames
// if should never get into the negative range
// which is about 2*10^8 * 1,000 seconds at 384,000 frames per second -- about 2 trillion seconds or over 50,000 years.
// also, it won't reach zero until then, if ever, so we can safely say that a null monotonic timestamp can mean something special
int64_t monotonic_timestamp(uint32_t timestamp) {
  int64_t previous_value;
  int64_t return_value;
  if (timestamp_epoch==0) {
    if (timestamp>maximum_timestamp_interval)
      timestamp_epoch=1;
    else
      timestamp_epoch=2;
    previous_value = timestamp_epoch;
    previous_value<<=32;
    previous_value+=timestamp;
  } else {
    previous_value = timestamp_epoch;
    previous_value<<=32;
    previous_value+=last_timestamp;  
    if (timestamp<last_timestamp) {
      // the incoming timestamp is less than the last one.
      // if the difference is more than a minute, assume it's really from the next epoch
      if ((last_timestamp-timestamp)>maximum_timestamp_interval)
        timestamp_epoch++;      
    } else {
      // the incoming timestamp is greater than the last one.
      // if the difference is more than a minute, assume it's really from the previous epoch
      if ((timestamp-last_timestamp)>maximum_timestamp_interval)
        timestamp_epoch--;
    }
  }
  last_timestamp=timestamp;
  return_value = timestamp_epoch;
  return_value<<=32;
  return_value+=timestamp;
  if (previous_value>return_value) {
   if ((previous_value-return_value)>maximum_timestamp_interval)
    debug(1,"interval between successive rtptimes greater than allowed!");
  } else {
    if ((return_value-previous_value)>maximum_timestamp_interval)
    debug(1,"interval between successive rtptimes greater than allowed!");
  }
  if (return_value<0)
  	debug(1,"monotonic rtptime is negative!");
  return return_value*output_sample_ratio;
}

// add an epoch to the seq_no. Uses the accompanying timestamp to determine the correct epoch
uint64_t monotonic_seqno(uint16_t seq_no) { 
}

static void ab_resync(void) {
  int i;
  for (i = 0; i < BUFFER_FRAMES; i++) {
    audio_buffer[i].ready = 0;
    audio_buffer[i].sequence_number = 0;
  }
  ab_synced = 0;
  last_seqno_read = -1;
  ab_buffering = 1;
}

// the sequence number is a 16-bit unsigned number which wraps pretty often
// to work out if one seqno is 'after' another therefore depends whether wrap has occurred
// this function works out the actual ordinate of the seqno, i.e. the distance up from
// the zeroth element, at ab_read, taking due account of wrap.

static inline seq_t SUCCESSOR(seq_t x) {
  uint32_t p = x & 0xffff;
  p += 1;
  p = p & 0xffff;
  return p;
}

static inline seq_t PREDECESSOR(seq_t x) {
  uint32_t p = (x & 0xffff) + 0x10000;
  p -= 1;
  p = p & 0xffff;
  return p;
}

// anything with ORDINATE in it must be proctected by the ab_mutex
static inline int32_t ORDINATE(seq_t x) {
  int32_t p = x; // int32_t from seq_t, i.e. uint16_t, so okay
  int32_t q = ab_read; // int32_t from seq_t, i.e. uint16_t, so okay
  int32_t t = (p + 0x10000 - q) & 0xffff;
  // we definitely will get a positive number in t at this point, but it might be a
  // positive alias of a negative number, i.e. x might actually be "before" ab_read
  // So, if the result is greater than 32767, we will assume its an
  // alias and subtract 65536 from it
  if (t >= 32767) {
    // debug(1,"OOB: %u, ab_r: %u, ab_w: %u",x,ab_read,ab_write);
    t -= 65536;
  }
  return t;
}

// wrapped number between two seq_t.
int32_t seq_diff(seq_t a, seq_t b) {
  int32_t diff = ORDINATE(b) - ORDINATE(a);
  return diff;
}

// the sequence numbers will wrap pretty often.
// this returns true if the second arg is after the first
static inline int seq_order(seq_t a, seq_t b) {
  int32_t d = ORDINATE(b) - ORDINATE(a);
  return d > 0;
}

static inline seq_t seq_sum(seq_t a, seq_t b) {
  uint32_t p = a & 0xffff;
  uint32_t q = b & 0x0ffff;
  uint32_t r = (a + b) & 0xffff;
  return r;
}

// now for 32-bit wrapping in timestamps

// this returns true if the second arg is strictly after the first
// on the assumption that the gap between them is never greater than (2^31)-1
// Represent a and b in 64 bits
static inline int seq32_order(uint32_t a, uint32_t b) {
  if (a == b)
    return 0;
  int64_t A = a & 0xffffffff;
  int64_t B = b & 0xffffffff;
  int64_t C = B - A;
  // if bit 31 is set, it means either b is before (i.e. less than) a or
  // b is (2^31)-1 ahead of a.

  // If we assume the gap between b and a should never reach 2 billion, then
  // bit 31 == 0 means b is strictly after a
  return (C & 0x80000000) == 0;
}

static int alac_decode(short *dest, int *destlen, uint8_t *buf, int len) {
  // parameters: where the decoded stuff goes, its length in samples,
  // the incoming packet, the length of the incoming packet in bytes
  // destlen should contain the allowed max number of samples on entry
  
  if (len>MAX_PACKET) {
    warn("Incoming audio packet size is too large at %d; it should not exceed %d.",len,MAX_PACKET);
    return -1;
  }
  unsigned char packet[MAX_PACKET];
  unsigned char packetp[MAX_PACKET];
  assert(len <= MAX_PACKET);
  int reply = 0; //everything okay
  int outsize=input_bytes_per_frame*(*destlen); // the size the output should be, in bytes
  int toutsize = outsize;

  if (encrypted) {
    unsigned char iv[16];
    int aeslen = len & ~0xf;
    memcpy(iv, aesiv, sizeof(iv));
#ifdef HAVE_LIBPOLARSSL
    aes_crypt_cbc(&dctx, AES_DECRYPT, aeslen, iv, buf, packet);
#endif
#ifdef HAVE_LIBSSL
    AES_cbc_encrypt(buf, packet, aeslen, &aes, iv, AES_DECRYPT);
#endif
    memcpy(packet + aeslen, buf + aeslen, len - aeslen);
#ifdef HAVE_APPLE_ALAC
    if (config.use_apple_decoder) {
      if (decoder_in_use!=1<<decoder_apple_alac) {
        debug(1,"Apple ALAC Decoder used on encrypted audio.");
        decoder_in_use=1<<decoder_apple_alac;
      }
      apple_alac_decode_frame(packet, len, (unsigned char *) dest, &outsize);
      outsize=outsize*4; // bring the size to bytes
    } else
#endif
    {
      if (decoder_in_use!=1<<decoder_hammerton) {
        debug(1,"Hammerton Decoder used on encrypted audio.");
        decoder_in_use=1<<decoder_hammerton;
      }
      alac_decode_frame(decoder_info, packet, (unsigned char *) dest, &outsize);
    }
  } else {
    // not encrypted
#ifdef HAVE_APPLE_ALAC
    if (config.use_apple_decoder) {
      if (decoder_in_use!=1<<decoder_apple_alac) {
        debug(1,"Apple ALAC Decoder used on unencrypted audio.");
        decoder_in_use=1<<decoder_apple_alac;
      }
      apple_alac_decode_frame(buf, len, (unsigned char *) dest, &outsize);
      outsize=outsize*4; // bring the size to bytes
    } else
#endif
    {
      if (decoder_in_use!=1<<decoder_hammerton) {
        debug(1,"Hammerton Decoder used on unencrypted audio.");
        decoder_in_use=1<<decoder_hammerton;
      }
      alac_decode_frame(decoder_info, buf, dest, &outsize);
    }
  }

  if(outsize>toutsize) {
    debug(2,"Output from alac_decode larger (%d bytes, not frames) than expected (%d bytes) -- truncated, but buffer overflow possible! Encrypted = %d.",outsize, toutsize, encrypted);
    reply = -1; // output packet is the wrong size
  }

  *destlen = outsize / input_bytes_per_frame;
  if ((outsize % input_bytes_per_frame)!=0)
    debug(1,"Number of audio frames (%d) does not correspond exactly to the number of bytes (%d) and the audio frame size (%d).",*destlen,outsize,input_bytes_per_frame);
  return reply;
}

static int init_decoder(int32_t fmtp[12]) {

// This is a guess, but the format of the fmtp looks identical to the format of an ALACSpecificCOnfig
// which is detailed in the file ALACMagicCookieDescription.txt in the Apple ALAC sample implementation
// Here it is:

/*
    struct	ALACSpecificConfig (defined in ALACAudioTypes.h)
    abstract   	This struct is used to describe codec provided information about the encoded Apple Lossless bitstream. 
		It must accompany the encoded stream in the containing audio file and be provided to the decoder.

    field      	frameLength 		uint32_t	indicating the frames per packet when no explicit frames per packet setting is 
							  present in the packet header. The encoder frames per packet can be explicitly set 
							  but for maximum compatibility, the default encoder setting of 4096 should be used.

    field      	compatibleVersion 	uint8_t 	indicating compatible version, 
							  value must be set to 0

    field      	bitDepth 		uint8_t 	describes the bit depth of the source PCM data (maximum value = 32)

    field      	pb 			uint8_t 	currently unused tuning parametetbugr. 
						 	  value should be set to 40

    field      	mb 			uint8_t 	currently unused tuning parameter. 
						 	  value should be set to 14

    field      	kb			uint8_t 	currently unused tuning parameter. 
						 	  value should be set to 10

    field      	numChannels 		uint8_t 	describes the channel count (1 = mono, 2 = stereo, etc...)
							  when channel layout info is not provided in the 'magic cookie', a channel count > 2
							  describes a set of discreet channels with no specific ordering

    field      	maxRun			uint16_t 	currently unused. 
   						  value should be set to 255

    field      	maxFrameBytes 		uint32_t 	the maximum size of an Apple Lossless packet within the encoded stream. 
						  	value of 0 indicates unknown

    field      	avgBitRate 		uint32_t 	the average bit rate in bits per second of the Apple Lossless stream. 
						  	value of 0 indicates unknown

    field      	sampleRate 		uint32_t 	sample rate of the encoded stream
 */

// We are going to go on that basis



  alac_file *alac;

  max_frames_per_packet = fmtp[1]; // number of audio frames per packet.

  input_sample_rate = fmtp[11];
  input_num_channels = fmtp[7];
  input_bit_depth = fmtp[3];
  
  input_bytes_per_frame = input_num_channels*((input_bit_depth+7)/8);

  alac = alac_create(input_bit_depth, input_num_channels);
  if (!alac)
    return 1;
  decoder_info = alac;

  alac->setinfo_max_samples_per_frame = max_frames_per_packet;
  alac->setinfo_7a = fmtp[2];
  alac->setinfo_sample_size = input_bit_depth;
  alac->setinfo_rice_historymult = fmtp[4];
  alac->setinfo_rice_initialhistory = fmtp[5];
  alac->setinfo_rice_kmodifier = fmtp[6];
  alac->setinfo_7f = fmtp[7];
  alac->setinfo_80 = fmtp[8];
  alac->setinfo_82 = fmtp[9];
  alac->setinfo_86 = fmtp[10];
  alac->setinfo_8a_rate = fmtp[11];
  alac_allocate_buffers(alac);

#ifdef HAVE_APPLE_ALAC
  apple_alac_init(fmtp);
#endif

  return 0;
}

static void terminate_decoders(void) {
  alac_free(decoder_info);
#ifdef HAVE_APPLE_ALAC
  apple_alac_terminate();
#endif
}

static void init_buffer(void) {
  int i;
  for (i = 0; i < BUFFER_FRAMES; i++)
    audio_buffer[i].data = malloc(input_bytes_per_frame*(max_frames_per_packet+max_frame_size_change));
  ab_resync();
}

static void free_buffer(void) {
  int i;
  for (i = 0; i < BUFFER_FRAMES; i++)
    free(audio_buffer[i].data);
}

void player_put_packet(seq_t seqno, int64_t timestamp, uint8_t *data, int len) {

  // ignore a request to flush that has been made before the first packet...
  if (packet_count==0) {
    pthread_mutex_lock(&flush_mutex);
    flush_requested = 0;
    flush_rtp_timestamp = 0;
    pthread_mutex_unlock(&flush_mutex);
  }
  
  pthread_mutex_lock(&ab_mutex);
  packet_count++;
  time_of_last_audio_packet = get_absolute_time_in_fp();
  if (connection_state_to_output) { // if we are supposed to be processing these packets

//    if (flush_rtp_timestamp != 0)
//    	debug(1,"Flush_rtp_timestamp is %u",flush_rtp_timestamp);

    if ((flush_rtp_timestamp != 0) &&
        (timestamp <= flush_rtp_timestamp)) {
      debug(3, "Dropping flushed packet in player_put_packet, seqno %u, timestamp %lld, flushing to "
               "timestamp: %lld.",
            seqno, timestamp, flush_rtp_timestamp);
    } else {
      if ((flush_rtp_timestamp != 0x0) &&
          (timestamp>flush_rtp_timestamp)) // if we have gone past the flush boundary time
        flush_rtp_timestamp = 0x0;

      abuf_t *abuf = 0;

      if (!ab_synced) {
        debug(2, "syncing to seqno %u.", seqno);
        ab_write = seqno;
        ab_read = seqno;
        ab_synced = 1;
      }
      if (ab_write == seqno) { // expected packet
        abuf = audio_buffer + BUFIDX(seqno);
        ab_write = SUCCESSOR(seqno);
      } else if (seq_order(ab_write, seqno)) { // newer than expected
        // if (ORDINATE(seqno)>(BUFFER_FRAMES*7)/8)
        // debug(1,"An interval of %u frames has opened, with ab_read: %u, ab_write: %u and seqno:
        // %u.",seq_diff(ab_read,seqno),ab_read,ab_write,seqno);
        int32_t gap = seq_diff(ab_write, seqno);
        if (gap <= 0)
          debug(1, "Unexpected gap size: %d.", gap);
        int i;
        for (i = 0; i < gap; i++) {
          abuf = audio_buffer + BUFIDX(seq_sum(ab_write, i));
          abuf->ready = 0; // to be sure, to be sure
          abuf->timestamp = 0;
          abuf->sequence_number = 0;
        }
        // debug(1,"N %d s %u.",seq_diff(ab_write,PREDECESSOR(seqno))+1,ab_write);
        abuf = audio_buffer + BUFIDX(seqno);
//        rtp_request_resend(ab_write, gap);
//        resend_requests++;
        ab_write = SUCCESSOR(seqno);
      } else if (seq_order(ab_read, seqno)) { // late but not yet played
        late_packets++;
        abuf = audio_buffer + BUFIDX(seqno);
      } else { // too late.
        too_late_packets++;
        /*
        if (!late_packet_message_sent) {
                debug(1, "too-late packet received: %u; ab_read: %u; ab_write: %u.", seqno, ab_read,
        ab_write);
                late_packet_message_sent=1;
        }
        */
      }
      // pthread_mutex_unlock(&ab_mutex);

      if (abuf) {
        int datalen = max_frames_per_packet;
        if (alac_decode(abuf->data, &datalen, data, len)==0) {
					abuf->ready = 1;
					abuf->length = datalen;
					abuf->timestamp = timestamp;
					abuf->sequence_number = seqno;
        } else {
        	debug(1,"Bad audio packet detected and discarded.");
					abuf->ready = 0;
					abuf->timestamp = 0;
					abuf->sequence_number = 0;        
        }
      }

      // pthread_mutex_lock(&ab_mutex);
    }
    int rc = pthread_cond_signal(&flowcontrol);
    if (rc)
      debug(1, "Error signalling flowcontrol.");
  }
  pthread_mutex_unlock(&ab_mutex);
}

int32_t rand_in_range(int32_t exclusive_range_limit) {
  static uint32_t lcg_prev = 12345;
	// returns a pseudo random integer in the range 0 to (exclusive_range_limit-1) inclusive
	int64_t sp = lcg_prev;
	int64_t rl = exclusive_range_limit;
	lcg_prev = lcg_prev * 69069 + 3; // crappy psrg
	sp = sp*rl; // 64 bit calculation. INtersting part if above the 32 rightmost bits;
	return sp >> 32;  
}

static inline short dithered_vol(short sample) {
  long out;

  out = (long)sample * fix_volume;
  if (fix_volume < 0x10000) {
  
  	// add a TPDF dither -- see http://www.users.qwest.net/%7Evolt42/cadenzarecording/DitherExplained.pdf
  	// and the discussion around https://www.hydrogenaud.io/forums/index.php?showtopic=16963&st=25
  	
  	// I think, for a 32 --> 16 bits, the range of
  	// random numbers needs to be from -2^16 to 2^16, i.e. from -65536 to 65536 inclusive, not from -32768 to +32767
  	
  	// See the original paper at http://www.ece.rochester.edu/courses/ECE472/resources/Papers/Lipshitz_1992.pdf
  	// by Lipshitz, Wannamaker and Vanderkooy, 1992.
  	
  	long tpdf = rand_in_range(65536+1) - rand_in_range(65536+1);
  	// Check there's no clipping -- if there is, 
  	if (tpdf>=0) {
  		if (LONG_MAX-tpdf>=out)
    		out += tpdf;
    	else
    		out = LONG_MAX;
    } else {
    	if (LONG_MIN-tpdf<=out)
    		out += tpdf;
    	else
    		out = LONG_MIN;
    }
  }
  return out >> 16;
}

// get the next frame, when available. return 0 if underrun/stream reset.
static abuf_t *buffer_get_frame(void) {
  int16_t buf_fill;
  uint64_t local_time_now;
  // struct timespec tn;
  abuf_t *abuf = 0;
  int i;
  abuf_t *curframe;
  int notified_buffer_empty = 0; // diagnostic only

  pthread_mutex_lock(&ab_mutex);
  int wait;
  long dac_delay = 0; // long because alsa returns a long 
  do {
    // get the time
    local_time_now = get_absolute_time_in_fp(); // type okay

    // if config.timeout (default 120) seconds have elapsed since the last audio packet was
    // received, then we should stop.
    // config.timeout of zero means don't check..., but iTunes may be confused by a long gap
    // followed by a resumption...

    if ((time_of_last_audio_packet != 0) && (shutdown_requested == 0) &&
        (config.dont_check_timeout == 0)) {
      uint64_t ct = config.timeout; // go from int to 64-bit int
      if ((local_time_now > time_of_last_audio_packet) &&
          (local_time_now - time_of_last_audio_packet >= ct << 32)) {
        debug(1, "As Yeats almost said, \"Too long a silence / can make a stone of the heart\"");
        rtsp_request_shutdown_stream();
        shutdown_requested = 1;
      }
    }
    int rco = get_requested_connection_state_to_output();

    if (connection_state_to_output != rco) {
      connection_state_to_output = rco;
      // change happening
      if (connection_state_to_output == 0) { // going off
        pthread_mutex_lock(&flush_mutex);
        flush_requested = 1;
        pthread_mutex_unlock(&flush_mutex);
      }
    }

    pthread_mutex_lock(&flush_mutex);
    if (flush_requested == 1) {
      if (config.output->flush)
        config.output->flush();
      ab_resync();
      first_packet_timestamp = 0;
      first_packet_time_to_play = 0;
      time_since_play_started = 0;
      flush_requested = 0;
    }
    pthread_mutex_unlock(&flush_mutex);
    uint32_t flush_limit = 0;
    if (ab_synced) {
      do {
        curframe = audio_buffer + BUFIDX(ab_read);
        if ((ab_read!=ab_write) && (curframe->ready)) { // it could be synced and empty, under exceptional circumstances, with the frame unused, thus apparently ready

          if (curframe->sequence_number != ab_read) {
            // some kind of sync problem has occurred.
            if (BUFIDX(curframe->sequence_number) == BUFIDX(ab_read)) {
              // it looks like some kind of aliasing has happened
              if (seq_order(ab_read, curframe->sequence_number)) {
                ab_read = curframe->sequence_number;
                debug(1, "Aliasing of buffer index -- reset.");
              }
            } else {
              debug(1, "Inconsistent sequence numbers detected");
            }
          }

          if ((flush_rtp_timestamp != 0) &&
              (curframe->timestamp <= flush_rtp_timestamp)) {
            debug(1, "Dropping flushed packet seqno %u, timestamp %lld", curframe->sequence_number,
                  curframe->timestamp);
            curframe->ready = 0;
            flush_limit++;
            ab_read = SUCCESSOR(ab_read);
          }
          if (curframe->timestamp>flush_rtp_timestamp) 
            flush_rtp_timestamp = 0;
        }
      } while ((flush_rtp_timestamp != 0) && (flush_limit <= 8820) && (curframe->ready == 0));

      if (flush_limit == 8820) {
        debug(1, "Flush hit the 8820 frame limit!");
        flush_limit = 0;
      }

      curframe = audio_buffer + BUFIDX(ab_read);

      if (curframe->ready) {
        notified_buffer_empty=0; // at least one buffer now -- diagnostic only.
        if (ab_buffering) { // if we are getting packets but not yet forwarding them to the player
          int have_sent_prefiller_silence; // set true when we have sent some silent frames to the DAC
          int64_t reference_timestamp;
          uint64_t reference_timestamp_time,remote_reference_timestamp_time;
          get_reference_timestamp_stuff(&reference_timestamp, &reference_timestamp_time, &remote_reference_timestamp_time);
          if (first_packet_timestamp == 0) { // if this is the very first packet
            // debug(1,"First frame seen, time %u, with %d
            // frames...",curframe->timestamp,seq_diff(ab_read, ab_write));
            if (reference_timestamp) { // if we have a reference time
              // debug(1,"First frame seen with timestamp...");
              first_packet_timestamp = curframe->timestamp; // we will keep buffering until we are
                                                            // supposed to start playing this
              have_sent_prefiller_silence = 0;

              // Here, calculate when we should start playing. We need to know when to allow the
              // packets to be sent to the player.
              // We will send packets of silence from now until that time and then we will send the
              // first packet, which will be followed by the subsequent packets.

              // we will get a fix every second or so, which will be stored as a pair consisting of
              // the time when the packet with a particular timestamp should be played, neglecting
              // latencies, etc.

              // It probably won't  be the timestamp of our first packet, however, so we might have
              // to do some calculations.

              // To calculate when the first packet will be played, we figure out the exact time the
              // packet should be played according to its timestamp and the reference time.
              // We then need to add the desired latency, typically 88200 frames.

              // Then we need to offset this by the backend latency offset. For example, if we knew
              // that the audio back end has a latency of 100 ms, we would
              // ask for the first packet to be emitted 100 ms earlier than it should, i.e. -4410
              // frames, so that when it got through the audio back end,
              // if would be in sync. To do this, we would give it a latency offset of -100 ms, i.e.
              // -4410 frames.

              int64_t delta = (first_packet_timestamp - reference_timestamp)+config.latency+config.audio_backend_latency_offset*output_sample_rate;
              
              if (delta>=0) {
                int64_t delta_fp_sec = (delta << 32) / output_sample_rate; // int64_t which is positive
                first_packet_time_to_play=reference_timestamp_time+delta_fp_sec;
              } else {
                int64_t abs_delta = -delta;
                int64_t delta_fp_sec = (abs_delta << 32) / output_sample_rate; // int64_t which is positive
                first_packet_time_to_play=reference_timestamp_time-delta_fp_sec;              
              }

              if (local_time_now >= first_packet_time_to_play) {
                debug(
                    1,
                    "First packet is late! It should have played before now. Flushing 0.1 seconds");
                player_flush(first_packet_timestamp + 4410);
              }
            }
          }

          if (first_packet_time_to_play != 0) {
            // recalculate first_packet_time_to_play -- the latency might change
            int64_t delta = (first_packet_timestamp - reference_timestamp)+config.latency+config.audio_backend_latency_offset*output_sample_rate;
            
            if (delta>=0) {
              int64_t delta_fp_sec = (delta << 32) / output_sample_rate; // int64_t which is positive
              first_packet_time_to_play=reference_timestamp_time+delta_fp_sec;
            } else {
              int64_t abs_delta = -delta;
              int64_t delta_fp_sec = (abs_delta << 32) / output_sample_rate; // int64_t which is positive
              first_packet_time_to_play=reference_timestamp_time-delta_fp_sec;              
            }

            int64_t max_dac_delay = output_sample_rate/10;
            int64_t filler_size = max_dac_delay; // 0.1 second -- the maximum we'll add to the DAC

            if (local_time_now >= first_packet_time_to_play) {
              // we've gone past the time...
              // debug(1,"Run past the exact start time by %llu frames, with time now of %llx, fpttp
              // of %llx and dac_delay of %d and %d packets;
              // flush.",(((tn-first_packet_time_to_play)*output_sample_rate)>>32)+dac_delay,tn,first_packet_time_to_play,dac_delay,seq_diff(ab_read,
              // ab_write));

              if (config.output->flush)
                config.output->flush();
              ab_resync();
              first_packet_timestamp = 0;
              first_packet_time_to_play = 0;
              time_since_play_started = 0;
            } else {
              // first_packet_time_to_play is definitely later than local_time_now
              if ((config.output->delay) && (have_sent_prefiller_silence != 0)) {
          			int resp = config.output->delay(&dac_delay);
                if (resp != 0) {
                  debug(1, "Error %d getting dac_delay in buffer_get_frame.",resp);
                  dac_delay = 0;
                }              
              } else
                dac_delay = 0;
              int64_t gross_frame_gap =
                  ((first_packet_time_to_play - local_time_now) * output_sample_rate) >> 32;
              int64_t exact_frame_gap = gross_frame_gap - dac_delay;
              if (exact_frame_gap < 0) {
                // we've gone past the time...
                // debug(1,"Run a bit past the exact start time by %lld frames, with time now of
                // %llx, fpttp of %llx and dac_delay of %d and %d packets;
                // flush.",-exact_frame_gap,tn,first_packet_time_to_play,dac_delay,seq_diff(ab_read,
                // ab_write));
                if (config.output->flush)
                  config.output->flush();
                ab_resync();
                first_packet_timestamp = 0;
                first_packet_time_to_play = 0;
              } else {
                int64_t fs = filler_size;
                if (fs > (max_dac_delay - dac_delay))
                  fs = max_dac_delay - dac_delay;
                if (fs<0) {
                  debug(2,"frame size (fs) < 0 with max_dac_delay of %lld and dac_delay of %ld",max_dac_delay, dac_delay);
                  fs=0;
                }
                if ((exact_frame_gap <= fs) || (exact_frame_gap <= max_frames_per_packet * 2)) {
                  fs = exact_frame_gap;
                  // debug(1,"Exact frame gap is %llu; play %d frames of silence. Dac_delay is %d,
                  // with %d packets, ab_read is %04x, ab_write is
                  // %04x.",exact_frame_gap,fs,dac_delay,seq_diff(ab_read,
                  // ab_write),ab_read,ab_write);
                  ab_buffering = 0;
                }
                signed short *silence;
                //if (fs==0)
                //  debug(2,"Zero length silence buffer needed with gross_frame_gap of %lld and dac_delay of %lld.",gross_frame_gap,dac_delay);
                // the fs (number of frames of silence to play) can be zero in the DAC doesn't start ouotputting frames for a while -- it could get loaded up but not start responding for many milliseconds.
                if (fs!=0) {
                  silence = malloc(input_bytes_per_frame*fs);
                  if (silence==NULL)
                    debug(1,"Failed to allocate %d byte silence buffer.",fs);
                  else {
                    memset(silence, 0, input_bytes_per_frame*fs);
                    // debug(1,"Exact frame gap is %llu; play %d frames of silence. Dac_delay is %d,
                    // with %d packets.",exact_frame_gap,fs,dac_delay,seq_diff(ab_read, ab_write));
                    config.output->play(silence, fs);
                    free(silence);
                    have_sent_prefiller_silence = 1;
                  }
                }
              }
            }
          }
          if (ab_buffering == 0) {
            // not the time of the playing of the first frame
            uint64_t reference_timestamp_time; // don't need this...
            get_reference_timestamp_stuff(&play_segment_reference_frame, &reference_timestamp_time, &play_segment_reference_frame_remote_time);
#ifdef CONFIG_METADATA
            send_ssnc_metadata('prsm', NULL, 0, 0); // "resume", but don't wait if the queue is locked
#endif
          }              
        }
      }
    }

    // Here, we work out whether to release a packet or wait
    // We release a buffer when the time is right.

    // To work out when the time is right, we need to take account of (1) the actual time the packet
    // should be released,
    // (2) the latency requested, (3) the audio backend latency offset and (4) the desired length of
    // the audio backend's buffer

    // The time is right if the current time is later or the same as
    // The packet time + (latency + latency offset - backend_buffer_length).
    // Note: the last three items are expressed in frames and must be converted to time.

    int do_wait = 0; // don't wait unless we can really prove we must
    if ((ab_synced) && (curframe) && (curframe->ready) && (curframe->timestamp)) {
    	do_wait = 1; // if the current frame exists and is ready, then wait unless it's time to let it go...
      int64_t reference_timestamp;
      uint64_t reference_timestamp_time,remote_reference_timestamp_time;
      get_reference_timestamp_stuff(&reference_timestamp, &reference_timestamp_time, &remote_reference_timestamp_time); // all types okay
      if (reference_timestamp) { // if we have a reference time
        int64_t packet_timestamp = curframe->timestamp; // types okay
        int64_t delta = packet_timestamp - reference_timestamp;
        int64_t offset = config.latency + config.audio_backend_latency_offset*output_sample_rate -
                         config.audio_backend_buffer_desired_length*output_sample_rate; // all arguments are int32_t, so expression promotion okay
        int64_t net_offset = delta + offset; // okay
        uint64_t time_to_play = reference_timestamp_time; // type okay
        if (net_offset >= 0) {
          uint64_t net_offset_fp_sec = (net_offset << 32) / output_sample_rate; // int64_t which is positive
          time_to_play += net_offset_fp_sec; // using the latency requested...
          // debug(2,"Net Offset: %lld, adjusted: %lld.",net_offset,net_offset_fp_sec);
        } else {
          int64_t abs_net_offset = -net_offset;
          uint64_t net_offset_fp_sec = (abs_net_offset << 32) / output_sample_rate; // int64_t which is positive
          time_to_play -= net_offset_fp_sec;
          // debug(2,"Net Offset: %lld, adjusted: -%lld.",net_offset,net_offset_fp_sec);
        }

        if (local_time_now >= time_to_play) {
          do_wait = 0;
        }
      }
    }
    if (do_wait==0)
      if ((ab_synced!=0) && (ab_read==ab_write)) { // the buffer is empty!
        if (notified_buffer_empty==0) {
          debug(1,"Buffers exhausted.");
          notified_buffer_empty=1;
        }
        do_wait=1;
      }
    wait = (ab_buffering || (do_wait != 0) || (!ab_synced)) && (!please_stop);

    if (wait) {
      uint64_t time_to_wait_for_wakeup_fp =
          ((uint64_t)1 << 32) / input_sample_rate;       // this is time period of one frame
      time_to_wait_for_wakeup_fp *= 4 * 352; // four full 352-frame packets
      time_to_wait_for_wakeup_fp /= 3; // four thirds of a packet time

#ifdef COMPILE_FOR_LINUX_AND_FREEBSD_AND_CYGWIN
      uint64_t time_of_wakeup_fp = local_time_now + time_to_wait_for_wakeup_fp;
      uint64_t sec = time_of_wakeup_fp >> 32;
      uint64_t nsec = ((time_of_wakeup_fp & 0xffffffff) * 1000000000) >> 32;

      struct timespec time_of_wakeup;
      time_of_wakeup.tv_sec = sec;
      time_of_wakeup.tv_nsec = nsec;

      pthread_cond_timedwait(&flowcontrol, &ab_mutex, &time_of_wakeup);
// int rc = pthread_cond_timedwait(&flowcontrol,&ab_mutex,&time_of_wakeup);
// if (rc!=0)
//  debug(1,"pthread_cond_timedwait returned error code %d.",rc);
#endif
#ifdef COMPILE_FOR_OSX
      uint64_t sec = time_to_wait_for_wakeup_fp >> 32;
      uint64_t nsec = ((time_to_wait_for_wakeup_fp & 0xffffffff) * 1000000000) >> 32;
      struct timespec time_to_wait;
      time_to_wait.tv_sec = sec;
      time_to_wait.tv_nsec = nsec;
      pthread_cond_timedwait_relative_np(&flowcontrol, &ab_mutex, &time_to_wait);
#endif
    }
  } while (wait);

  if (please_stop) {
    pthread_mutex_unlock(&ab_mutex);
    return 0;
  }

  seq_t read = ab_read;

  // check if t+8, t+16, t+32, t+64, t+128, ... (buffer_start_fill / 2)
  // packets have arrived... last-chance resend

  if (!ab_buffering) {
    for (i = 8; i < (seq_diff(ab_read, ab_write) / 2); i = (i * 2)) {
      seq_t next = seq_sum(ab_read, i);
      abuf = audio_buffer + BUFIDX(next);
      if (!abuf->ready) {
        rtp_request_resend(next, 1);
        // debug(1,"Resend %u.",next);
        resend_requests++;
      }
    }
  }


  if (!curframe->ready) {
    // debug(1, "Supplying a silent frame for frame %u", read);
    missing_packets++;
    memset(curframe->data, 0, input_bytes_per_frame*max_frames_per_packet);
    curframe->timestamp = 0;
  }
  curframe->ready = 0;
  ab_read = SUCCESSOR(ab_read);
  pthread_mutex_unlock(&ab_mutex);
  return curframe;
}

static inline short shortmean(short a, short b) {
  long al = (long)a;
  long bl = (long)b;
  long longmean = (al + bl) / 2;
  short r = (short)longmean;
  if (r != longmean)
    debug(1, "Error calculating average of two shorts");
  return r;
}

// stuff: 1 means add 1; 0 means do nothing; -1 means remove 1
static int stuff_buffer_basic(short *inptr, int length, short *outptr, int stuff) {
  int tstuff = stuff;
  if ((stuff > 1) || (stuff < -1) || (length <100)) {
    // debug(1, "Stuff argument to stuff_buffer must be from -1 to +1 and length >100.");
    tstuff = 0; // if any of these conditions hold, don't stuff anything/
  }
  int i;
  int stuffsamp = length;
  if (tstuff)
    //      stuffsamp = rand() % (length - 1);
    stuffsamp =
        (rand() % (length - 2)) + 1; // ensure there's always a sample before and after the item

  pthread_mutex_lock(&vol_mutex);
  for (i = 0; i < stuffsamp; i++) { // the whole frame, if no stuffing
    *outptr++ = dithered_vol(*inptr++);
    *outptr++ = dithered_vol(*inptr++);
  };
  if (tstuff) {
    if (tstuff == 1) {
      // debug(3, "+++++++++");
      // interpolate one sample
      //*outptr++ = dithered_vol(((long)inptr[-2] + (long)inptr[0]) >> 1);
      //*outptr++ = dithered_vol(((long)inptr[-1] + (long)inptr[1]) >> 1);
      *outptr++ = dithered_vol(shortmean(inptr[-2], inptr[0]));
      *outptr++ = dithered_vol(shortmean(inptr[-1], inptr[1]));
    } else if (stuff == -1) {
      // debug(3, "---------");
      inptr++;
      inptr++;
    }
    
    // if you're removing, i.e. stuff < 0, copy that much less over. If you're adding, do all the rest.
    int remainder = length;
    if (tstuff<0)
      remainder = remainder+tstuff; // don't run over the correct end of the output buffer

    for (i = stuffsamp; i < remainder; i++) {
      *outptr++ = dithered_vol(*inptr++);
      *outptr++ = dithered_vol(*inptr++);
    }
  }
  pthread_mutex_unlock(&vol_mutex);

  return length + tstuff;
}

#ifdef HAVE_LIBSOXR
// stuff: 1 means add 1; 0 means do nothing; -1 means remove 1
static int stuff_buffer_soxr(short *inptr, int length, short *outptr, int stuff) {
  int tstuff = stuff;
  if ((stuff > 1) || (stuff < -1) || (length <100)) {
    // debug(1, "Stuff argument to stuff_buffer must be from -1 to +1 and length >100.");
    tstuff = 0; // if any of these conditions hold, don't stuff anything/
  }
  int i;
  short *ip, *op;
  ip = inptr;
  op = outptr;

  if (tstuff) {
    // debug(1,"Stuff %d.",stuff);
    soxr_io_spec_t io_spec;
    io_spec.itype = SOXR_INT16_I;
    io_spec.otype = SOXR_INT16_I;
    io_spec.scale = 1.0; // this seems to crash if not = 1.0
    io_spec.e = NULL;
    io_spec.flags = 0;

    size_t odone;

    soxr_error_t error = soxr_oneshot(length, length + tstuff, 2, /* Rates and # of chans. */
                                      inptr, length, NULL,           /* Input. */
                                      outptr, length + tstuff, &odone, /* Output. */
                                      &io_spec,    /* Input, output and transfer spec. */
                                      NULL, NULL); /* Default configuration.*/

    if (error)
      die("soxr error: %s\n", "error: %s\n", soxr_strerror(error));

    if (odone > length + 1)
      die("odone = %d!\n", odone);

    const int gpm = 5;

    // keep the first (dpm) samples, to mitigate the Gibbs phenomenon
    for (i = 0; i < gpm; i++) {
      *op++ = *ip++;
      *op++ = *ip++;
    }

    // keep the last (dpm) samples, to mitigate the Gibbs phenomenon
    op = outptr + (length + tstuff - gpm) * sizeof(short);
    ip = inptr + (length - gpm) * sizeof(short);
    for (i = 0; i < gpm; i++) {
      *op++ = *ip++;
      *op++ = *ip++;
    }

    // finally, adjust the volume, if necessary
    if (fix_volume != 65536.0) {
      // pthread_mutex_lock(&vol_mutex);
      op = outptr;
      for (i = 0; i < length + tstuff; i++) {
        *op = dithered_vol(*op);
        op++;
        *op = dithered_vol(*op);
        op++;
      };
      // pthread_mutex_unlock(&vol_mutex);
    }

  } else { // the whole frame, if no stuffing

    // pthread_mutex_lock(&vol_mutex);
    for (i = 0; i < length; i++) {
      *op++ = dithered_vol(*ip++);
      *op++ = dithered_vol(*ip++);
    };
    // pthread_mutex_unlock(&vol_mutex);
  }
  return length + tstuff;
}
#endif

typedef struct stats { // statistics for running averages
  int64_t sync_error, correction, drift;
} stats_t;

static void *player_thread_func(void *arg) {
	struct inter_threads_record itr;
	itr.please_stop = 0;
	timestamp_epoch = 0; // indicate that the next timestamp will be the first one.
	maximum_timestamp_interval = input_sample_rate * 60; // actually there shouldn't be more than about 13v seconds of a gap between successive rtptimes, at worst

	output_sample_rate = input_sample_rate;

	if (config.output_rate!=0)
	  output_sample_rate = config.output_rate;
	  
	output_sample_ratio = output_sample_rate/input_sample_rate;

	debug(1,"Output sample ratio is %d.",output_sample_ratio);
	
	max_frame_size_change = 1*output_sample_ratio; // we add or subtract one frame at the nominal rate, multiply it by the frame ratio.

	output_bytes_per_frame = 4;	
	switch (config.output_format) {
		case SPS_FORMAT_S24_LE:
			output_bytes_per_frame=8;
			break;
		case SPS_FORMAT_S32_LE:
			output_bytes_per_frame=8;
			break;		
	}

	// create and start the timing, control and audio receiver threads
	pthread_t rtp_audio_thread, rtp_control_thread, rtp_timing_thread;
	pthread_create(&rtp_audio_thread, NULL, &rtp_audio_receiver, (void *)&itr);
  pthread_create(&rtp_control_thread, NULL, &rtp_control_receiver, (void *)&itr);
  pthread_create(&rtp_timing_thread, NULL, &rtp_timing_receiver, (void *)&itr);

	session_corrections = 0;
	play_segment_reference_frame = 0; // zero signals that we are not in a play segment


	// check that there are enough buffers to accommodate the desired latency and the latency offset
	
	int maximum_latency = config.latency+config.audio_backend_latency_offset*output_sample_rate;
	if ((maximum_latency+(352-1))/352 + 10 > BUFFER_FRAMES)
		die("Not enough buffers available for a total latency of %d frames. A maximum of %d 352-frame packets may be accommodated.",maximum_latency,BUFFER_FRAMES);
  connection_state_to_output = get_requested_connection_state_to_output();
// this is about half a minute
#define trend_interval 3758
  stats_t statistics[trend_interval];
  int number_of_statistics, oldest_statistic, newest_statistic;
  int at_least_one_frame_seen = 0;
  int64_t tsum_of_sync_errors, tsum_of_corrections, tsum_of_insertions_and_deletions,
      tsum_of_drifts;
  int64_t previous_sync_error, previous_correction;
  int64_t minimum_dac_queue_size = INT64_MAX;
  int32_t minimum_buffer_occupancy = INT32_MAX;
  int32_t maximum_buffer_occupancy = INT32_MIN;

  time_t playstart = time(NULL);

  buffer_occupancy = 0;

  int play_samples;
  int64_t current_delay;
  int play_number = 0;
  time_of_last_audio_packet = 0;
  shutdown_requested = 0;
  number_of_statistics = oldest_statistic = newest_statistic = 0;
  tsum_of_sync_errors = tsum_of_corrections = tsum_of_insertions_and_deletions = tsum_of_drifts = 0;

  const int print_interval = trend_interval; // don't ask...
  // I think it's useful to keep this prime to prevent it from falling into a pattern with some
  // other process.

  char rnstate[256];
  initstate(time(NULL), rnstate, 256);

  signed short *inbuf, *outbuf, *tbuf, *silence;
  int inbuflength;
  
  int output_bit_depth = 16; // default;
  
  switch (config.output_format) {
    case SPS_FORMAT_S16_LE:
      output_bit_depth = 16;
      break;
    case SPS_FORMAT_S24_LE:
      output_bit_depth = 24;
      break;
    case SPS_FORMAT_S32_LE:
      output_bit_depth = 32;
      break;
  }
  
  
  // if we are changing any of the parameters of the input, like sample rate or sample depth, then we
  // need an intermediate "transition" buffer
  
//  if ((config.output_rate!=0 && (input_sample_rate!=config.output_rate)) || (input_bit_depth!=output_bit_depth)) {
    tbuf = malloc(output_bytes_per_frame*(max_frames_per_packet*output_sample_ratio+max_frame_size_change));
    if (tbuf==NULL)
      debug(1,"Failed to allocate memory for the transition buffer.");
//  } else {
//    tbuf = 0;
//  }  
  
  // We might need an output buffer and a buffer of silence.
  // The size of these dependents on the number of frames, the size of each frame and the maximum size change
  outbuf = malloc(output_bytes_per_frame*(max_frames_per_packet*output_sample_ratio+max_frame_size_change));
  if (outbuf==NULL)
    debug(1,"Failed to allocate memory for an output buffer.");
  silence = malloc(output_bytes_per_frame*max_frames_per_packet*output_sample_ratio);
  if (silence==NULL)
    debug(1,"Failed to allocate memory for a silence buffer.");
  memset(silence, 0, output_bytes_per_frame*max_frames_per_packet*output_sample_ratio);
  late_packet_message_sent = 0;
  first_packet_timestamp = 0;
  missing_packets = late_packets = too_late_packets = resend_requests = 0;
  flush_rtp_timestamp = 0; // it seems this number has a special significance -- it seems to be used
                           // as a null operand, so we'll use it like that too
  int sync_error_out_of_bounds = 0; // number of times in a row that there's been a serious sync error

  if (config.statistics_requested) {
    if ((config.output->delay)) {
      if (config.no_sync==0) {
        inform("sync error in milliseconds, "
               "net correction in ppm, "
               "corrections in ppm, "
               "total packets, "
               "missing packets, "
               "late packets, "
               "too late packets, "
               "resend requests, "
               "min DAC queue size, "
               "min buffer occupancy, "
               "max buffer occupancy");
      } else {
        inform("sync error in milliseconds, "
               "total packets, "
               "missing packets, "
               "late packets, "
               "too late packets, "
               "resend requests, "
               "min DAC queue size, "
               "min buffer occupancy, "
               "max buffer occupancy");
      }
    } else {
      inform("sync error in milliseconds, "
             "total packets, "
             "missing packets, "
             "late packets, "
             "too late packets, "
             "resend requests, "
             "min buffer occupancy, "
             "max buffer occupancy");
    }
  }

  uint64_t tens_of_seconds = 0;
  while (!please_stop) {
    abuf_t *inframe = buffer_get_frame();
    if (inframe) {
      inbuf = inframe->data;
      inbuflength = inframe->length;
      if (inbuf) {
        play_number++;
        // if it's a supplied silent frame, let us know...
        if (inframe->timestamp == 0) {
          // debug(1,"Player has a supplied silent frame.");
          last_seqno_read =
              (SUCCESSOR(last_seqno_read) & 0xffff); // manage the packet out of sequence minder
          if (inbuf==NULL)
            debug(1,"NULL inbuf to play -- skipping it.");
          else {
            if (inbuflength==0)
              debug(1,"empty frame to play -- skipping it (1).");
            else
              config.output->play(inbuf, inbuflength);
          }
        } else {
          // here, let's transform the frame of data, if necessary
          
          if (tbuf!=NULL) { //this will be null if no changes are needed
            switch (input_bit_depth) {
              case 16: {
                  int i,j;
                  int16_t ls,rs;
                  int16_t *inps=inbuf;
                  int16_t *outps=tbuf;
                  int32_t *outpl=(int32_t*)tbuf;
                  for (i=0;i<inbuflength;i++) {
                    ls=*inps++;
                    rs=*inps++;
                    
                    // here, do the mode stuff -- mono / reverse stereo / leftonly / rightonly
                    
                    switch (config.playback_mode) {
                      case ST_mono: {
                        int both = ls+rs;
                        // Note -- this is assuming 16 bit signed.
                        if (both > INT16_MAX) {
                          both = INT16_MAX;
                        } else if (both < INT16_MIN) {
                          both = INT16_MIN;
                        }
                        uint16_t sboth = (uint16_t)both;
                        ls = sboth;
                        rs = sboth;
                        } break;
                      case ST_reverse_stereo: {
                        uint16_t t = ls;
                        ls = rs;
                        rs = t;
                        } break;
                      case ST_left_only:
                        rs = ls;
                        break;
                      case ST_right_only:
                        ls = rs;
                        break;
                    }
                    
                    // here, replicate the samples if you're upsampling
                    for (j=0;j<output_sample_ratio;j++) {
                      switch (output_bit_depth) {
                        case 16:
                          *outps++=ls;
                          *outps++=rs;
                          break;
                        case 24: {
                          uint32_t t = ls<<8;
                          *outpl++=t;
                          uint32_t u = rs<<8;
                          *outpl++=u;
                          } break;
                        case 32: {
                          uint32_t t = ls<<16;
                          *outpl++=t;
                          uint32_t u = rs<<16;
                          *outpl++=u;
                          } break;
                      }
                    }
                  }

                }
                break;
              default:
                die("Shairport Sync only supports 16 bit input");
            }
            
            inbuf = tbuf;
            inbuflength*=output_sample_ratio;
          }
          
          // We have a frame of data. We need to see if we want to add or remove a frame from it to
          // keep in sync.
          // So we calculate the timing error for the first frame in the DAC.
          // If it's ahead of time, we add one audio frame to this frame to delay a subsequent frame
          // If it's late, we remove an audio frame from this frame to bring a subsequent frame
          // forward in time

          at_least_one_frame_seen = 1;

          int64_t reference_timestamp;
          uint64_t reference_timestamp_time,remote_reference_timestamp_time;
          get_reference_timestamp_stuff(&reference_timestamp, &reference_timestamp_time, &remote_reference_timestamp_time); // types okay

          int64_t rt, nt;
          rt = reference_timestamp; // uint32_t to int64_t
          nt = inframe->timestamp; // uint32_t to int64_t

          uint64_t local_time_now = get_absolute_time_in_fp(); // types okay
          // struct timespec tn;
          // clock_gettime(CLOCK_MONOTONIC,&tn);
          // uint64_t
          // local_time_now=((uint64_t)tn.tv_sec<<32)+((uint64_t)tn.tv_nsec<<32)/1000000000;

          int64_t td = 0;
          int64_t td_in_frames = 0;
          if (local_time_now >= reference_timestamp_time) {
          // debug(1,"td is %lld.",td);
             td = local_time_now - reference_timestamp_time; // this is the positive value. Conversion is positive uint64_t to int64_t, thus okay
            td_in_frames = (td * output_sample_rate) >> 32;
          } else {
            td = reference_timestamp_time - local_time_now; // this is the absolute value, which should be negated. Conversion is positive uint64_t to int64_t, thus okay.
            td_in_frames = (td * output_sample_rate) >> 32; //use the absolute td value for the present. Types okay
            td_in_frames = -td_in_frames;
            td = -td; // should be okay, as the range of values should be very small w.r.t 64 bits
          }

          // This is the timing error for the next audio frame in the DAC, if applicable
          int64_t sync_error = 0;

          int amount_to_stuff = 0;

          // check sequencing
          if (last_seqno_read == -1)
            last_seqno_read = inframe->sequence_number; //int32_t from seq_t, i.e. uint16_t, so okay.
          else {
            last_seqno_read = SUCCESSOR(last_seqno_read); // int32_t from seq_t, i.e. uint16_t, so okay.
            if (inframe->sequence_number != last_seqno_read) { //seq_t, ei.e. uint16_t and int32_t, so okay
              debug(
                  1,
                  "Player: packets out of sequence: expected: %u, got: %u, with ab_read: %u and ab_write: %u.",
                  last_seqno_read, inframe->sequence_number,ab_read,ab_write);
              last_seqno_read = inframe->sequence_number; // reset warning...
            }
          }

					buffer_occupancy = seq_diff(ab_read, ab_write); // int32_t from int32

					if (buffer_occupancy < minimum_buffer_occupancy)
						minimum_buffer_occupancy = buffer_occupancy;

					if (buffer_occupancy > maximum_buffer_occupancy)
						maximum_buffer_occupancy = buffer_occupancy;

          // here, we want to check (a) if we are meant to do synchronisation,
          // (b) if we have a delay procedure, (c) if we can get the delay.

          // If any of these are false, we don't do any synchronisation stuff

					int resp = -1; // use this as a flag -- if negative, we can't rely on a real known delay
          current_delay = -1; // use this as a failure flag
 
					if (config.output->delay) {
						long l_delay; 
						resp = config.output->delay(&l_delay);
						current_delay = l_delay;
						if (resp==0) { // no error
							if (current_delay<0) {
								debug(1,"Underrun of %d frames reported, but ignored.",current_delay);
								current_delay=0; // could get a negative value if there was underrun, but ignore it.
							}
							if (current_delay < minimum_dac_queue_size) {
								minimum_dac_queue_size = current_delay; // update for display later
							}
						} else { 
							debug(2, "Delay error %d when checking running latency.",resp);
						}
					}

          if (resp >= 0) {

            // this is the actual delay, including the latency we actually want, which will
            // fluctuate a good bit about a potentially rising or falling trend.
            int64_t delay = td_in_frames + rt - (nt - current_delay); // all int64_t
            

            // This is the timing error for the next audio frame in the DAC.
            sync_error = delay - config.latency; // int64_t from int64_t - int32_t, so okay

            // if (llabs(sync_error)>352*512)
            //  debug(1,"Very large sync error: %lld",sync_error);

            // before we finally commit to this frame, check its sequencing and timing

            // require a certain error before bothering to fix it...
            if (sync_error > config.tolerance*output_sample_rate) { // int64_t > int, okay
              amount_to_stuff = -1;
            }
            if (sync_error < -config.tolerance*output_sample_rate) {
              amount_to_stuff = 1;
            }

            // only allow stuffing if there is enough time to do it -- check DAC buffer...
            if (current_delay < DAC_BUFFER_QUEUE_MINIMUM_LENGTH) {
              // debug(1,"DAC buffer too short to allow stuffing.");
              amount_to_stuff = 0;
            }

            // try to keep the corrections definitely below 1 in 1000 audio frames
            
            // calculate the time elapsed since the play session started.
            
            if (amount_to_stuff) {
              if ((local_time_now) && (first_packet_time_to_play) && (local_time_now >= first_packet_time_to_play)) {

                int64_t tp = (local_time_now - first_packet_time_to_play)>>32; // seconds int64_t from uint64_t which is always positive, so ok
                
                if (tp<5)
                  amount_to_stuff = 0; // wait at least five seconds
                else if (tp<30) {
                  if ((random() % 1000) > 352) // keep it to about 1:1000 for the first thirty seconds
                    amount_to_stuff = 0;
                }
              }
            }
            
            if (config.no_sync!=0)
              amount_to_stuff = 0 ; // no stuffing if it's been disabled
                        
            if ((amount_to_stuff == 0) && (fix_volume == 0x10000) && ((config.output_rate==0) || (config.output_rate==44100)) && ((config.output_format==0) || (config.output_format==SPS_FORMAT_S16_LE))) {
              // if no stuffing needed and no volume adjustment, then
              // don't send to stuff_buffer_* and don't copy to outbuf; just send directly to the
              // output device...
              if (inbuf==NULL)
                debug(1,"NULL inframe->data to play -- skipping it.");
              else {
                if (inbuflength==0)
                  debug(1,"empty frame to play -- skipping it (2).");
                else
                  config.output->play(inbuf, inbuflength);
              }
            } else {


#ifdef HAVE_LIBSOXR
              switch (config.packet_stuffing) {
              case ST_basic:
                //                if (amount_to_stuff) debug(1,"Basic stuff...");
                play_samples = stuff_buffer_basic(inbuf, inbuflength, outbuf, amount_to_stuff);
                break;
              case ST_soxr:
                //                if (amount_to_stuff) debug(1,"Soxr stuff...");
                play_samples = stuff_buffer_soxr(inbuf, inbuflength, outbuf, amount_to_stuff);
                break;
              }
#else
              //          if (amount_to_stuff) debug(1,"Standard stuff...");
              play_samples = stuff_buffer_basic(inbuf, inbuflength, outbuf, amount_to_stuff);
#endif

              /*
              {
                int co;
                int is_silent=1;
                short *p = outbuf;
                for (co=0;co<play_samples;co++) {
                  if (*p!=0)
                    is_silent=0;
                  p++;
                }
                if (is_silent)
                  debug(1,"Silence!");
              }
              */
              
              
              if (outbuf==NULL)
                debug(1,"NULL outbuf to play -- skipping it.");
              else {
                if (play_samples==0)
                  debug(1,"play_samples==0 skipping it (1).");
                else
                  config.output->play(outbuf, play_samples);
              }
            }

            // check for loss of sync
            // timestamp of zero means an inserted silent frame in place of a missing frame
            
            // not too sure if abs() is implemented for int64_t, so we'll do it manually
            int64_t abs_sync_error = sync_error;
            if (abs_sync_error<0)
              abs_sync_error = -abs_sync_error;
            
            if ((config.no_sync==0) && (inframe->timestamp != 0) && (!please_stop) && (config.resyncthreshold > 0.0) &&
                (abs_sync_error > config.resyncthreshold*output_sample_rate)) {
              sync_error_out_of_bounds++;
              // debug(1,"Sync error out of bounds: Error: %lld; previous error: %lld; DAC: %lld;
              // timestamp: %llx, time now
              // %llx",sync_error,previous_sync_error,current_delay,inframe->timestamp,local_time_now);
              if (sync_error_out_of_bounds > 3) {
                debug(1, "Lost sync with source for %d consecutive packets -- flushing and "
                         "resyncing. Error: %lld.",
                      sync_error_out_of_bounds, sync_error);
                sync_error_out_of_bounds = 0;
                player_flush(nt);
              }
            } else {
              sync_error_out_of_bounds = 0;
            }
          } else {
            // if there is no delay procedure, or it's not working or not allowed, there can be no synchronising
            
            if (fix_volume == 0x10000)
            
              if (inbuf==NULL)
                debug(1,"NULL inbuf to play -- skipping it.");
              else {
                if (inbuflength==0)
                  debug(1,"empty frame to play -- skipping it (3).");
                else
                  config.output->play(inbuf, inbuflength);
              }
            else {
              play_samples = stuff_buffer_basic(inbuf, inbuflength, outbuf, 0); // no stuffing, but volume adjustment

              if (outbuf==NULL)
                debug(1,"NULL outbuf to play -- skipping it.");
              else {
                if (inbuf==0)
                  debug(1,"empty frame to play -- skipping it (4).");
                else
                  config.output->play(outbuf, play_samples);
              }
            }
          }

          // mark the frame as finished
          inframe->timestamp = 0;
          inframe->sequence_number = 0;

          // debug(1,"Sync error %lld frames. Amount to stuff %d." ,sync_error,amount_to_stuff);

          // new stats calculation. We want a running average of sync error, drift, adjustment,
          // number of additions+subtractions
          
          // this is a misleading hack -- the statistics should include some data on the number of valid samples and the number of times sync wasn't checked due to non availability of a delay figure.
          // for the present, stats are only updated when sync has been checked
          if (sync_error!=-1) {
            if (number_of_statistics == trend_interval) {
              // here we remove the oldest statistical data and take it from the summaries as well
              tsum_of_sync_errors -= statistics[oldest_statistic].sync_error;
              tsum_of_drifts -= statistics[oldest_statistic].drift;
              if (statistics[oldest_statistic].correction > 0)
                tsum_of_insertions_and_deletions -= statistics[oldest_statistic].correction;
              else
                tsum_of_insertions_and_deletions += statistics[oldest_statistic].correction;
              tsum_of_corrections -= statistics[oldest_statistic].correction;
              oldest_statistic = (oldest_statistic + 1) % trend_interval;
              number_of_statistics--;
            }

            statistics[newest_statistic].sync_error = sync_error;
            statistics[newest_statistic].correction = amount_to_stuff;

            if (number_of_statistics == 0)
              statistics[newest_statistic].drift = 0;
            else
              statistics[newest_statistic].drift =
                  sync_error - previous_sync_error - previous_correction;

            previous_sync_error = sync_error;
            previous_correction = amount_to_stuff;

            tsum_of_sync_errors += sync_error;
            tsum_of_drifts += statistics[newest_statistic].drift;
            if (amount_to_stuff > 0) {
              tsum_of_insertions_and_deletions += amount_to_stuff;
            } else {
              tsum_of_insertions_and_deletions -= amount_to_stuff;
            }
            tsum_of_corrections += amount_to_stuff;
            session_corrections += amount_to_stuff;


            newest_statistic = (newest_statistic + 1) % trend_interval;
            number_of_statistics++;
            }
        }
        if (play_number % print_interval == 0) {
          // we can now calculate running averages for sync error (frames), corrections (ppm),
          // insertions plus deletions (ppm), drift (ppm)
          double moving_average_sync_error = (1.0 * tsum_of_sync_errors) / number_of_statistics;
          double moving_average_correction = (1.0 * tsum_of_corrections) / number_of_statistics;
          double moving_average_insertions_plus_deletions =
              (1.0 * tsum_of_insertions_and_deletions) / number_of_statistics;
          double moving_average_drift = (1.0 * tsum_of_drifts) / number_of_statistics;
          // if ((play_number/print_interval)%20==0)
          if (config.statistics_requested) {
            if (at_least_one_frame_seen) {
            	if ((config.output->delay)) {
                if (config.no_sync==0) {
                  inform("%*.1f,"  /* Sync error in milliseconds */
                         "%*.1f,"  /* net correction in ppm */
                         "%*.1f,"  /* corrections in ppm */
                         "%*d,"    /* total packets */
                         "%*llu,"  /* missing packets */
                         "%*llu,"  /* late packets */
                         "%*llu,"  /* too late packets */
                         "%*llu,"  /* resend requests */
                         "%*lli,"  /* min DAC queue size */
                         "%*d,"    /* min buffer occupancy */
                         "%*d",    /* max buffer occupancy */
                         10, 1000*moving_average_sync_error/output_sample_rate,
                         10, moving_average_correction * 1000000 / (352*output_sample_ratio),
                         10, moving_average_insertions_plus_deletions * 1000000 / (352*output_sample_ratio),
                         12, play_number,
                         7, missing_packets,
                         7, late_packets,
                         7, too_late_packets,
                         7, resend_requests,
                         7, minimum_dac_queue_size,
                         5, minimum_buffer_occupancy,
                         5, maximum_buffer_occupancy);
                } else {
                  inform("%*.1f,"  /* Sync error in milliseconds */
                         "%*d,"    /* total packets */
                         "%*llu,"  /* missing packets */
                         "%*llu,"  /* late packets */
                         "%*llu,"  /* too late packets */
                         "%*llu,"  /* resend requests */
                         "%*lli,"  /* min DAC queue size */
                         "%*d,"    /* min buffer occupancy */
                         "%*d",    /* max buffer occupancy */
                         10, 1000*moving_average_sync_error/output_sample_rate,
                         12, play_number,
                         7, missing_packets,
                         7, late_packets,
                         7, too_late_packets,
                         7, resend_requests,
                         7, minimum_dac_queue_size,
                         5, minimum_buffer_occupancy,
                         5, maximum_buffer_occupancy);
                } 
              } else {
                inform("%*.1f,"  /* Sync error in milliseconds */
                       "%*d,"    /* total packets */
                       "%*llu,"  /* missing packets */
                       "%*llu,"  /* late packets */
                       "%*llu,"  /* too late packets */
                       "%*llu,"  /* resend requests */
                       "%*d,"    /* min buffer occupancy */
                       "%*d",    /* max buffer occupancy */
                       10, 1000*moving_average_sync_error/output_sample_rate,
                       12, play_number,
                       7, missing_packets,
                       7, late_packets,
                       7, too_late_packets,
                       7, resend_requests,
                       5, minimum_buffer_occupancy,
                       5, maximum_buffer_occupancy);
              }
            } else {
              inform("No frames received in the last sampling interval.");
            }
          }
          minimum_dac_queue_size = INT64_MAX;   // hack reset
          maximum_buffer_occupancy = INT32_MIN; // can't be less than this
          minimum_buffer_occupancy = INT32_MAX; // can't be more than this
          at_least_one_frame_seen = 0;
        }
      }
    }
  }

  if (config.statistics_requested) {
     int rawSeconds = (int) difftime( time( NULL ), playstart );
     int elapsedHours = rawSeconds / 3600;
     int elapsedMin = (rawSeconds / 60) % 60;
     int elapsedSec = rawSeconds % 60;
     inform( "Playback Stopped. Total playing time %02d:%02d:%02d\n", elapsedHours, elapsedMin, elapsedSec );
  }

  if (config.output->stop)
  	config.output->stop();
  usleep(100000); // allow this time to (?) allow the alsa subsystem to finish cleaning up after itself. 50 ms seems too short
  free(outbuf);
  free(silence);
  debug(1,"Shut down audio, control and timing threads");
  itr.please_stop = 1;
  pthread_kill(rtp_audio_thread, SIGUSR1);
  pthread_kill(rtp_control_thread, SIGUSR1);
  pthread_kill(rtp_timing_thread, SIGUSR1);
  pthread_join(rtp_timing_thread, NULL);
  debug(1,"timing thread joined");
  pthread_join(rtp_audio_thread, NULL);
  debug(1,"audio thread joined");
  pthread_join(rtp_control_thread, NULL);
  debug(1,"control thread joined");
  debug(1,"Player thread exit");
  return 0;
}

// takes the volume as specified by the airplay protocol
void player_volume(double airplay_volume) {

  // The volume ranges -144.0 (mute) or -30 -- 0. See
  // http://git.zx2c4.com/Airtunes2/about/#setting-volume
  // By examination, the -30 -- 0 range is linear on the slider; i.e. the slider is calibrated in 30
  // equal increments. Since the human ear's response is roughly logarithmic, we imagine these to
  // be power dB, i.e. from -30dB to 0dB.
    
  // We may have a hardware mixer, and if so, we will give it priority.
  // If a desired volume range is given, then we will try to accommodate it from
  // the top of the hardware mixer's range downwards.
  
  // If no desired volume range is given, we will use the native resolution of the hardware mixer, if any,
  // or failing that, the software mixer. The software mixer has a range of from -96.3 dB up to 0 dB,
  // corresponding to a multiplier of 1 to 65535.
 
  // Otherwise, we will accommodate the desired volume range in the combination of the software and hardware mixer
  // Intuitively (!), it seems best to give the hardware mixer as big a role as possible, so
  // we will use its full range and then accommodate the rest of the attenuation in software.
  // A problem is that we don't know whether the lowest hardware volume actually mutes the output
  // so we must assume that it does, and for this reason, the volume control goes at the "bottom" of the adjustment range
    
  // The dB range of a value from 1 to 65536 is about 96.3 dB (log10 of 65536 is 4.8164).
  // Since the levels correspond with amplitude, they correspond to voltage, hence voltage dB,
  // or 20 times the log of the ratio. Then multiplied by 100 for convenience.
  // Thus, we ask our vol2attn function for an appropriate dB between -96.3 and 0 dB and translate
  // it back to a number.
  
  int32_t hw_min_db, hw_max_db, hw_range_db, range_to_use, min_db, max_db; // hw_range_db is a flag; if 0 means no mixer
  
  int32_t sw_min_db = -9630;
  int32_t sw_max_db = 0;
  int32_t sw_range_db = sw_max_db - sw_min_db;
  int32_t desired_range_db; // this is used as a flag; if 0 means no desired range
  
  if (config.volume_range_db)
    desired_range_db = (int32_t)trunc(config.volume_range_db*100);
  else
    desired_range_db = 0;
  
  if (config.output->parameters) {
    // have a hardware mixer
    config.output->parameters(&audio_information);
    hw_max_db = audio_information.maximum_volume_dB;
    hw_min_db = audio_information.minimum_volume_dB;
    hw_range_db = hw_max_db-hw_min_db;
  } else {
    // don't have a hardware mixer
    hw_max_db = hw_min_db = hw_range_db = 0;
  }
  
  if (desired_range_db) {
    // debug(1,"An attenuation range of %d is requested.",desired_range_db);
    // we have a desired volume range.
    if (hw_range_db) {
    // we have a hardware mixer
      if (hw_range_db>=desired_range_db) {
        // the hardware mixer can accommodate the desired range
        max_db = hw_max_db;
        min_db = max_db - desired_range_db;
      } else {
        if ((hw_range_db+sw_range_db)<desired_range_db) {
          inform("The volume attenuation range %f is greater than can be accommodated by the hardware and software -- set to %f.",config.volume_range_db,hw_range_db+sw_range_db);
          desired_range_db=hw_range_db+sw_range_db;
        }
        min_db = hw_min_db;
        max_db = min_db + desired_range_db;
      }
    } else {
      // we have a desired volume range and no hardware mixer
      if (sw_range_db<desired_range_db) {
        inform("The volume attenuation range %f is greater than can be accommodated by the software -- set to %f.",config.volume_range_db,sw_range_db);
        desired_range_db=sw_range_db;      
      }
      max_db = sw_max_db;
      min_db = max_db - desired_range_db;
    }
  } else {
    // we do not have a desired volume range, so use the mixer's volume range, if there is one.
    // debug(1,"No attenuation range requested.");
    if (hw_range_db) {
      min_db = hw_min_db;
      max_db = hw_max_db;
    } else {
      min_db = sw_min_db;
      max_db = sw_max_db;
    }
  }
  
  double hardware_attenuation, software_attenuation;
  double scaled_attenuation = hw_min_db+sw_min_db;
    
  // now, we can map the input to the desired output volume
  if (airplay_volume==-144.0) {    
    // do a mute   
    // needed even with hardware mute, as when sound is unmuted it might otherwise be very loud.
  	hardware_attenuation = hw_min_db;
  	software_attenuation = sw_min_db;
  	if (config.output->mute)
  		config.output->mute(1); // use real mute if it's there
    
  } else {
  	if (config.output->mute)
  		config.output->mute(0); // unmute mute if it's there  
    scaled_attenuation = vol2attn(airplay_volume, max_db, min_db);
    if (hw_range_db) {
      // if there is a hardware mixer
      if (scaled_attenuation<=hw_max_db) {
        // the attenuation is so low that's it's in the hardware mixer's range
        // debug(1,"Attenuation all taken care of by the hardware mixer.");
        hardware_attenuation = scaled_attenuation;
        software_attenuation = sw_max_db - (max_db-hw_max_db); // e.g. if the hw_max_db  is +4 and the max is +40, this will be -36 (all by 100, of course)
      } else {
        // debug(1,"Attenuation taken care of by hardware and software mixer.");
        hardware_attenuation = hw_max_db; // the hardware mixer is turned up full
        software_attenuation = sw_max_db - (max_db-scaled_attenuation);
      }
    } else {
      // if there is no hardware mixer, the scaled_volume is the software volume
      // debug(1,"Attenuation all taken care of by the software mixer.");
      software_attenuation = scaled_attenuation;
    }
  }
  
  if ((config.output->volume) && (hw_range_db)) {
	  config.output->volume(hardware_attenuation); // otherwise set the output to the lowest value
	  //debug(1,"Hardware attenuation set to %f for airplay volume of %f.",hardware_attenuation,airplay_volume);
  }
  double temp_fix_volume = 65536.0 * pow(10, software_attenuation / 2000);
 	// debug(1,"Software attenuation set to %f, i.e %f out of 65,536, for airplay volume of %f",software_attenuation,temp_fix_volume,airplay_volume);
  
  pthread_mutex_lock(&vol_mutex);
  fix_volume = temp_fix_volume;
  pthread_mutex_unlock(&vol_mutex);

#ifdef CONFIG_METADATA
  char *dv = malloc(128); // will be freed in the metadata thread
  if (dv) {
    memset(dv, 0, 128);
    snprintf(dv, 127, "%.2f,%.2f,%.2f,%.2f", airplay_volume,
             scaled_attenuation / 100.0,
             min_db / 100.0,
             max_db / 100.0);
    send_ssnc_metadata('pvol', dv, strlen(dv), 1);
  }
#endif
}

void player_flush(int64_t timestamp) {
  debug(3,"Flush requested up to %u. It seems as if 0 is special.",timestamp);
  pthread_mutex_lock(&flush_mutex);
  flush_requested = 1;
  // if (timestamp!=0)
  flush_rtp_timestamp = timestamp; // flush all packets up to (and including?) this
  pthread_mutex_unlock(&flush_mutex);
  play_segment_reference_frame = 0;
#ifdef CONFIG_METADATA
  send_ssnc_metadata('pfls', NULL, 0, 1);
#endif
}

int player_play(stream_cfg *stream, pthread_t *player_thread) {
	//if (*player_thread!=NULL)
	//	die("Trying to create a second player thread for this RTSP session");
  packet_count = 0;
  encrypted = stream->encrypted;
  if (config.buffer_start_fill > BUFFER_FRAMES)
    die("specified buffer starting fill %d > buffer size %d", config.buffer_start_fill,
        BUFFER_FRAMES);
  if (encrypted) {
#ifdef HAVE_LIBPOLARSSL
    memset(&dctx, 0, sizeof(aes_context));
    aes_setkey_dec(&dctx, stream->aeskey, 128);
#endif

#ifdef HAVE_LIBSSL
    AES_set_decrypt_key(stream->aeskey, 128, &aes);
#endif
    aesiv = stream->aesiv;
  }
  init_decoder(stream->fmtp); // this sets up incoming rate, bit depth, channels
  // must be after decoder init
  init_buffer();
  please_stop = 0;
  command_start();
#ifdef CONFIG_METADATA
  send_ssnc_metadata('pbeg', NULL, 0, 1);
#endif

// set the flowcontrol condition variable to wait on a monotonic clock
#ifdef COMPILE_FOR_LINUX_AND_FREEBSD_AND_CYGWIN
  pthread_condattr_t attr;
  pthread_condattr_init(&attr);
  pthread_condattr_setclock(&attr, CLOCK_MONOTONIC); // can't do this in OS X, and don't need it.
  int rc = pthread_cond_init(&flowcontrol, &attr);
#endif
#ifdef COMPILE_FOR_OSX
  int rc = pthread_cond_init(&flowcontrol, NULL);
#endif
  if (rc)
    debug(1, "Error initialising condition variable.");
  config.output->start(config.output_rate,config.output_format);
  size_t size = (PTHREAD_STACK_MIN + 256 * 1024);
  pthread_attr_t tattr;
  pthread_attr_init(&tattr);
  rc = pthread_attr_setstacksize(&tattr, size);
  if (rc)
    debug(1, "Error setting stack size for player_thread: %s", strerror(errno));
  pthread_create(player_thread, &tattr, player_thread_func, NULL);
  pthread_attr_destroy(&tattr);
  return 0;
}

void player_stop(pthread_t *player_thread) {
	//if (*thread==NULL)
	//	debug(1,"Trying to stop a non-existent player thread");
	// else {
		please_stop = 1;
		pthread_cond_signal(&flowcontrol); // tell it to give up
		pthread_join(*player_thread, NULL);
	#ifdef CONFIG_METADATA
		send_ssnc_metadata('pend', NULL, 0, 1);
	#endif
		command_stop();
		free_buffer();
		terminate_decoders();
		int rc = pthread_cond_destroy(&flowcontrol);
		if (rc)
			debug(1, "Error destroying condition variable.");
	//	}
}