forked from abrasive/shairport
-
-
Notifications
You must be signed in to change notification settings - Fork 647
Expand file tree
/
Copy pathplayer.c
More file actions
5305 lines (4782 loc) · 223 KB
/
Copy pathplayer.c
File metadata and controls
5305 lines (4782 loc) · 223 KB
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
/*
* Slave-clocked ALAC stream player. This file is part of Shairport.
* Copyright (c) James Laird 2011, 2013
* All rights reserved.
*
* Modifications for audio synchronisation, AirPlay 2
* and related work, copyright (c) Mike Brady 2014--2025
* 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 <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <limits.h>
#include <math.h>
#include <pthread.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/syslog.h>
#include <sys/types.h>
#include <unistd.h>
#include "config.h"
#ifdef CONFIG_MBEDTLS
#include <mbedtls/aes.h>
#endif
#ifdef CONFIG_POLARSSL
#include <polarssl/aes.h>
#include <polarssl/havege.h>
#endif
#ifdef CONFIG_OPENSSL
#include <openssl/aes.h> // needed for older AES stuff
#include <openssl/bio.h> // needed for BIO_new_mem_buf
#include <openssl/err.h> // needed for ERR_error_string, ERR_get_error
#include <openssl/evp.h> // needed for EVP_PKEY_CTX_new, EVP_PKEY_sign_init, EVP_PKEY_sign
#include <openssl/pem.h> // needed for PEM_read_bio_RSAPrivateKey, EVP_PKEY_CTX_set_rsa_padding
#include <openssl/rsa.h> // needed for EVP_PKEY_CTX_set_rsa_padding
#endif
#ifdef CONFIG_SOXR
#include <soxr.h>
#endif
#ifdef CONFIG_CONVOLUTION
#include <FFTConvolver/convolver.h>
#endif
#ifdef CONFIG_METADATA_HUB
#include "metadata_hub.h"
#endif
#ifdef CONFIG_DACP_CLIENT
#include "dacp.h"
#endif
#include "common.h"
#include "mdns.h"
#include "player.h"
#include "rtp.h"
#include "rtsp.h"
#include "alac.h"
#ifdef CONFIG_APPLE_ALAC
#include "apple_alac.h"
#endif
#ifdef CONFIG_AIRPLAY_2
#include "ptp-utilities.h"
#endif
#ifdef CONFIG_FFMPEG
#include <libavutil/version.h>
#endif
#include "loudness.h"
#include "activity_monitor.h"
const unsigned int silent_channel_index = 65;
const unsigned int front_mono_channel_index = 66;
// default buffer size
// needs to be a power of 2 because of the way BUFIDX(seqno) works
// #define BUFFER_FRAMES 512
// DAC buffer occupancy stuff
#define DAC_BUFFER_QUEUE_MINIMUM_LENGTH 2500
// static abuf_t audio_buffer[BUFFER_FRAMES];
#define BUFIDX(seqno) ((seq_t)(seqno) % BUFFER_FRAMES)
void do_flush(uint32_t timestamp, rtsp_conn_info *conn);
#ifdef CONFIG_FFMPEG
size_t avflush(rtsp_conn_info *conn);
#endif
int free_audio_buffer_payload(abuf_t *abuf) {
int items_freed = 0;
if (abuf) {
if (abuf->data != NULL) {
free(abuf->data);
items_freed++;
abuf->data = NULL;
}
#ifdef CONFIG_FFMPEG
if (abuf->avframe != NULL) {
av_frame_free(&abuf->avframe);
items_freed++;
abuf->avframe = NULL;
abuf->ssrc = SSRC_NONE;
}
#endif
} else {
debug(1, "null buffer pointer!");
}
return items_freed;
}
void ab_resync(rtsp_conn_info *conn) {
int i;
for (i = 0; i < BUFFER_FRAMES; i++) {
free_audio_buffer_payload(&conn->audio_buffer[i]);
conn->audio_buffer[i].ready = 0;
conn->audio_buffer[i].resend_request_number = 0;
conn->audio_buffer[i].resend_time =
0; // this is either zero or the time the last resend was requested.
conn->audio_buffer[i].initialisation_time =
0; // this is either the time the packet was received or the time it was noticed the packet
// was missing.
conn->audio_buffer[i].sequence_number = 0;
}
conn->ab_synced = 0;
conn->last_seqno_valid = 0;
conn->ab_buffering = 1;
}
void reset_input_flow_metrics(rtsp_conn_info *conn) {
conn->play_number_after_flush = 0;
conn->packet_count_since_flush = 0;
conn->input_frame_rate_starting_point_is_valid = 0;
conn->initial_reference_time = 0;
conn->initial_reference_timestamp = 0;
}
void unencrypted_packet_decode(rtsp_conn_info *conn, unsigned char *packet, int length,
short *dest) {
if (conn->stream.type == ast_apple_lossless) {
#ifdef CONFIG_APPLE_ALAC
if (config.decoder_in_use == 1 << decoder_apple_alac) {
int frames_decoded;
apple_alac_decode_frame(packet, length, (unsigned char *)dest, &frames_decoded);
} else
#endif
#ifdef CONFIG_HAMMERTON
if (config.decoder_in_use == 1 << decoder_hammerton) {
int buffer_size = conn->frames_per_packet * conn->input_bytes_per_frame;
alac_decode_frame(conn->decoder_info, packet, (unsigned char *)dest, &buffer_size);
} else
#endif
{
die("No ALAC decoder included!");
}
} else if (conn->stream.type == ast_uncompressed) {
int i;
short *source = (short *)packet;
for (i = 0; i < length / 2; i++) {
// assuming each input sample is 16 bits.
*dest = ntohs(*source);
dest++;
source++;
}
}
}
#ifdef CONFIG_HAMMERTON
static int init_alac_decoder(int32_t fmtp[12], rtsp_conn_info *conn) {
// clang-format off
// 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:
/*
* ALAC Specific Info (24 bytes) (mandatory)
__________________________________________________________________________________________________________________________________
The Apple Lossless codec stores specific information about the encoded stream in the ALACSpecificConfig. This
info is vended by the encoder and is used to setup the decoder for a given encoded bitstream.
When read from and written to a file, the fields of this struct must be in big-endian order.
When vended by the encoder (and received by the decoder) the struct values will be in big-endian order.
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 parameter.
value should be set to 40
field mb uint8_t currently unused tuning parameter.
value should be set to 10
field kb uint8_t currently unused tuning parameter.
value should be set to 14
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
typedef struct ALACSpecificConfig
{
uint32_t frameLength;
uint8_t compatibleVersion;
uint8_t bitDepth;
uint8_t pb;
uint8_t mb;
uint8_t kb;
uint8_t numChannels;
uint16_t maxRun;
uint32_t maxFrameBytes;
uint32_t avgBitRate;
uint32_t sampleRate;
} ALACSpecificConfig;
*/
// We are going to go on that basis
// clang-format on
alac_file *alac;
alac = alac_create(conn->input_bit_depth,
conn->input_num_channels); // no pthread cancellation point in here
if (!alac)
return 1;
conn->decoder_info = alac;
alac->setinfo_max_samples_per_frame = conn->frames_per_packet;
alac->setinfo_7a = fmtp[2];
alac->setinfo_sample_size = conn->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); // no pthread cancellation point in here
return 0;
}
#endif
static void init_buffer(rtsp_conn_info *conn) {
int i;
for (i = 0; i < BUFFER_FRAMES; i++) {
conn->audio_buffer[i].data = NULL;
#ifdef CONFIG_FFMPEG
conn->audio_buffer[i].avframe = NULL;
conn->audio_buffer[i].ssrc = SSRC_NONE;
#endif
}
}
static void free_audio_buffers(rtsp_conn_info *conn) {
int i;
for (i = 0; i < BUFFER_FRAMES; i++) {
free_audio_buffer_payload(&conn->audio_buffer[i]);
}
}
int first_possibly_missing_frame = -1;
void reset_buffer(rtsp_conn_info *conn) {
pthread_cleanup_debug_mutex_lock(&conn->ab_mutex, 30000, 0);
ab_resync(conn);
pthread_cleanup_pop(1);
#if CONFIG_FFMPEG
avflush(conn);
#endif
if (config.output->flush) {
config.output->flush(); // no cancellation points
// debug(1, "reset_buffer: flush output device.");
}
}
// returns the total number of blocks and the number occupied, but not their size,
// because the size is determined by the block size sent
size_t get_audio_buffer_occupancy(rtsp_conn_info *conn) {
size_t response = 0;
pthread_cleanup_debug_mutex_lock(&conn->ab_mutex, 30000, 0);
if (conn->ab_synced) {
int16_t occ =
conn->ab_write - conn->ab_read; // will be zero or positive if read and write are within
// 2^15 of each other and write is at or after read
response = occ;
}
pthread_cleanup_pop(1);
return response;
}
const char *get_category_string(airplay_stream_c cat) {
char *category;
switch (cat) {
case unspecified_stream_category:
category = "unspecified stream";
break;
case ptp_stream:
category = "PTP stream";
break;
case ntp_stream:
category = "NTP stream";
break;
case remote_control_stream:
category = "Remote Control stream";
break;
case classic_airplay_stream:
category = "Classic AirPlay stream";
break;
default:
category = "Unexpected stream code";
break;
}
return category;
}
#ifdef CONFIG_FFMPEG
static void avcodec_alloc_context3_cleanup_handler(void *arg) {
debug(3, "avcodec_alloc_context3_cleanup_handler");
AVCodecContext *codec_context = arg;
av_free(codec_context);
}
static void avcodec_open2_cleanup_handler(__attribute__((unused)) void *arg) {
debug(3, "avcodec_open2_cleanup_handler");
// AVCodecContext *codec_context = arg;
// avcodec_close(codec_context);
}
static void swr_alloc_cleanup_handler(void *arg) {
debug(3, "swr_alloc_cleanup_handler");
SwrContext **swr = arg;
swr_free(swr);
}
static void av_packet_alloc_cleanup_handler(void *arg) {
debug(4, "av_packet_alloc_cleanup_handler");
AVPacket **pkt = arg;
av_packet_free(pkt);
}
/*
static void av_frame_alloc_cleanup_handler(void *arg) {
debug(3, "av_frame_alloc_cleanup_handler");
AVFrame **frame = arg;
av_frame_free(frame);
}
*/
void clear_decoding_chain(rtsp_conn_info *conn) {
if (conn->incoming_ssrc != 0) {
// debug_mutex_lock(&conn->ab_mutex, 30000, 0);
// ab_resync(conn);
// debug_mutex_unlock(&conn->ab_mutex, 0);
pthread_cleanup_push(avcodec_alloc_context3_cleanup_handler, conn->codec_context);
pthread_cleanup_push(malloc_cleanup, &conn->codec_context->extradata);
pthread_cleanup_push(avcodec_open2_cleanup_handler, conn->codec_context);
pthread_cleanup_pop(1); // avcodec_open2_cleanup_handler
pthread_cleanup_pop(1); // deallocate the malloc
pthread_cleanup_pop(1); // avcodec_alloc_context3_cleanup_handler
conn->incoming_ssrc = SSRC_NONE;
}
}
void clear_software_resampler(rtsp_conn_info *conn) {
if (conn->swr != NULL) {
debug(2, "clear_software_resampler");
pthread_cleanup_push(swr_alloc_cleanup_handler, &conn->swr);
pthread_cleanup_pop(1); // deallocate the swr
conn->swr = NULL;
conn->resampler_ssrc = SSRC_NONE;
}
}
int ssrc_is_recognised(ssrc_t ssrc) {
int response = 0;
switch (ssrc) {
case ALAC_44100_S16_2:
case ALAC_48000_S24_2:
case AAC_44100_F24_2:
case AAC_48000_F24_2:
case AAC_48000_F24_5P1:
case AAC_48000_F24_7P1:
response = 1;
break;
default:
break;
}
return response;
}
int ssrc_is_aac(ssrc_t ssrc) {
int response = 0;
switch (ssrc) {
case AAC_44100_F24_2:
case AAC_48000_F24_2:
case AAC_48000_F24_5P1:
case AAC_48000_F24_7P1:
response = 1;
break;
default:
break;
}
return response;
}
char ssrc_name[1024];
const char *get_ssrc_name(ssrc_t ssrc) {
const char *response = NULL;
switch (ssrc) {
case ALAC_44100_S16_2:
response = "ALAC/44100/S16_LE/2";
break;
case ALAC_48000_S24_2:
response = "ALAC/48000/S24_LE/2";
break;
case AAC_44100_F24_2:
response = "AAC/44100/F24/2";
break;
case AAC_48000_F24_2:
response = "AAC/48000/F24/2";
break;
case AAC_48000_F24_5P1:
response = "AAC/48000/F24/5.1";
break;
case AAC_48000_F24_7P1:
response = "AAC/48000/F24/7.1";
break;
case SSRC_NONE:
response = "None (0)";
break;
default: {
snprintf(ssrc_name, sizeof(ssrc_name), "<unknown ssrc> (0x%" PRIx32 ")", ssrc);
response = ssrc_name;
} break;
}
return response;
}
uint32_t get_ssrc_rate(ssrc_t ssrc) {
uint32_t response = 0;
switch (ssrc) {
case ALAC_44100_S16_2:
case AAC_44100_F24_2:
response = 44100;
break;
case ALAC_48000_S24_2:
case AAC_48000_F24_2:
case AAC_48000_F24_5P1:
case AAC_48000_F24_7P1:
response = 48000;
break;
default:
break;
}
return response;
}
size_t get_ssrc_block_length(ssrc_t ssrc) {
size_t response = 0;
switch (ssrc) {
case ALAC_44100_S16_2:
case ALAC_48000_S24_2:
response = 352;
break;
case AAC_44100_F24_2:
case AAC_48000_F24_2:
case AAC_48000_F24_5P1:
case AAC_48000_F24_7P1:
response = 1024;
break;
default:
break;
}
return response;
}
int setup_software_resampler(rtsp_conn_info *conn, ssrc_t ssrc) {
int response = 0;
unsigned int channels;
// the output from the software resampler will be the input to the rest of
// the player chain, so we need to set those parameters according to the SSRC:
// default values...
conn->input_bit_depth = 16;
conn->input_effective_bit_depth = 16;
conn->input_bytes_per_frame = 4;
conn->frames_per_packet = 352;
// most common values first, changed in the switch statement
conn->input_rate = 48000;
channels = 2;
conn->frames_per_packet = 1024;
sps_format_t suggested_output_format = SPS_FORMAT_S32; // this may be ignored
switch (ssrc) {
case ALAC_44100_S16_2:
conn->input_rate = 44100;
conn->frames_per_packet = 352;
suggested_output_format = SPS_FORMAT_S16;
break;
case ALAC_48000_S24_2:
conn->frames_per_packet = 352;
suggested_output_format = SPS_FORMAT_S24;
break;
case AAC_44100_F24_2:
conn->input_rate = 44100;
break;
case AAC_48000_F24_2:
break;
case AAC_48000_F24_5P1:
channels = 6;
break;
case AAC_48000_F24_7P1:
channels = 8;
break;
default:
debug(1, "Can't set rate for %s.", get_ssrc_name(ssrc));
break;
}
// Now we ask the backend for its best format, giving it the channels, rate and format
// default format is S32_LE/48000/2 for AP2, S16_LE/44100/2 otherwise
#ifdef CONFIG_AIRPLAY_2
uint32_t output_configuration = CHANNELS_TO_ENCODED_FORMAT(2) | RATE_TO_ENCODED_FORMAT(48000) |
FORMAT_TO_ENCODED_FORMAT(SPS_FORMAT_S32_LE);
#else
uint32_t output_configuration = CHANNELS_TO_ENCODED_FORMAT(2) | RATE_TO_ENCODED_FORMAT(44100) |
FORMAT_TO_ENCODED_FORMAT(SPS_FORMAT_S16_LE);
#endif
int output_configuration_changed = 0;
if (config.output->get_configuration) {
output_configuration =
config.output->get_configuration(channels, conn->input_rate, suggested_output_format);
}
// if you can set up a configuration...
if (output_configuration != 0) {
if (config.current_output_configuration != output_configuration) {
output_configuration_changed = 1;
debug(2, "Connection %d: outgoing audio switching to: %s.", conn->connection_number,
short_format_description(output_configuration));
}
config.current_output_configuration = output_configuration;
char *output_device_channel_map = NULL;
if (config.output->configure) {
config.output->configure(output_configuration, &output_device_channel_map);
}
// create a software resampler
if (conn->swr != NULL) {
debug(3, "software resampler already set up");
if (swr_is_initialized(conn->swr)) {
debug(3, "software resampler already initialised -- close it...");
swr_close(conn->swr);
}
debug(3, "software resampler free it...");
swr_free(&conn->swr);
if (conn->swr == NULL) {
debug(3, "software resampler released");
}
}
// input channels to the player
conn->input_num_channels = CHANNELS_FROM_ENCODED_FORMAT(output_configuration);
SwrContext *swr = swr_alloc();
conn->swr = swr;
if (swr == NULL) {
die("can not allocate an swr context");
}
// push a deallocator -- av_packet_free(pkt);
pthread_cleanup_push(swr_alloc_cleanup_handler, &conn->swr);
enum AVSampleFormat input_format = AV_SAMPLE_FMT_FLTP; // default
int64_t input_layout = AV_CH_LAYOUT_STEREO; // default
int64_t output_layout = AV_CH_LAYOUT_STEREO; // default
switch (ssrc) {
case ALAC_44100_S16_2:
case ALAC_48000_S24_2: {
// seems as if the codec_context is correctly set up for ALAC but not for AAC-LC
input_format = conn->codec_context->sample_fmt;
} break;
case AAC_44100_F24_2:
case AAC_48000_F24_2: {
// defaults are fine...
} break;
case AAC_48000_F24_5P1: {
input_layout = config.six_channel_layout;
output_layout = config.six_channel_layout; // assume no mixdown
} break;
case AAC_48000_F24_7P1: {
input_layout = config.eight_channel_layout;
output_layout = config.eight_channel_layout; // assume no mixdown
} break;
default:
debug(1, "unexpected SSRC: 0x%0x", ssrc);
break;
}
av_opt_set_sample_fmt(swr, "in_sample_fmt", input_format, 0);
// remember that if mixdown is enabled,
// set the resampler's channel layout either automatically or use the
// setting that has been given
#if LIBAVUTIL_VERSION_MAJOR >= 57
{
AVChannelLayout input_channel_layout;
av_channel_layout_from_mask(&input_channel_layout, input_layout);
av_opt_set_chlayout(swr, "in_chlayout", &input_channel_layout, 0);
av_channel_layout_uninit(&input_channel_layout);
AVChannelLayout output_channel_layout;
if (config.mixdown_enable != 0) {
if (config.mixdown_channel_layout == 0) {
av_channel_layout_default(&output_channel_layout,
CHANNELS_FROM_ENCODED_FORMAT(output_configuration));
} else {
av_channel_layout_from_mask(&output_channel_layout, config.mixdown_channel_layout);
}
} else {
av_channel_layout_from_mask(&output_channel_layout, output_layout);
}
av_opt_set_chlayout(swr, "out_chlayout", &output_channel_layout, 0);
av_channel_layout_uninit(&output_channel_layout);
}
#else
av_opt_set_int(swr, "in_channel_layout", input_layout, 0);
if (config.mixdown_enable != 0) {
if (config.mixdown_channel_layout == 0) {
output_layout =
av_get_default_channel_layout(CHANNELS_FROM_ENCODED_FORMAT(output_configuration));
} else {
output_layout = config.mixdown_channel_layout;
}
}
av_opt_set_int(swr, "out_channel_layout", output_layout, 0); // assume no mixdown
#endif
av_opt_set_int(swr, "in_sample_rate", conn->input_rate, 0);
// now set the resampler's output rate to match the output device's rate
av_opt_set_int(swr, "out_sample_rate", RATE_FROM_ENCODED_FORMAT(output_configuration), 0);
// Ask for S16 output for AAC/S16 input and for S32 output from resampler for F24 and S24.
// This is to avoid FFmpeg unnecessarily transcoding S16 to S32.
// Dither will be added by Shairport Sync itself later, if needed.
if (ssrc == ALAC_44100_S16_2) {
av_opt_set_sample_fmt(swr, "out_sample_fmt", AV_SAMPLE_FMT_S16, 0);
conn->input_bytes_per_frame =
2 * CHANNELS_FROM_ENCODED_FORMAT(
output_configuration); // the output from the decoder will be input to the player
conn->input_bit_depth = 16;
conn->input_effective_bit_depth = 16;
} else {
av_opt_set_sample_fmt(swr, "out_sample_fmt", AV_SAMPLE_FMT_S32, 0);
conn->input_bytes_per_frame =
4 * CHANNELS_FROM_ENCODED_FORMAT(
output_configuration); // the output from the decoder will be input to the player
conn->input_bit_depth = 32;
// this is important when it comes to deciding on dither
// AFAIK 24-bit ALAC comes out in 32-bit format but is actually 24 bit
// so don't dither if it is truncated from 32 to 24 bit
if (ssrc == ALAC_48000_S24_2)
conn->input_effective_bit_depth = 24;
else
conn->input_effective_bit_depth = 32;
}
// now, having set up the resampler, we can initialise it
// disabling this, as the soxr-based resampler seems not to give exactly the right number of
// frames going from 44100 to 48000 and requires stuffing to compensate.
// also, the soxr resampling engine isn't included in the Docker image.
// #ifdef CONFIG_SOXR
// av_opt_set(swr, "resampler", "soxr", 0);
// #endif
int sres = swr_init(swr);
if (sres != 0)
debug(1, "swr_init returned %d with SSRC of 0x%0x and LIBAVUTIL_VERSION_MAJOR of %u.", sres,
ssrc, LIBAVUTIL_VERSION_MAJOR);
typedef struct {
char *name;
int allocated;
} channel_info_t;
char resampler_channel_list[1024] = "";
unsigned int c;
channel_info_t resampler_channels[64]; // can't be more than 64. This will list the channel
// names in the order they appear in the output from
// the software resampler.
for (c = 0; c < sizeof(resampler_channels) / sizeof(channel_info_t); c++) {
resampler_channels[c].name = NULL;
resampler_channels[c].allocated = 0;
}
// get information about the output from the resampler
int64_t resampler_output_format = 0;
int resampler_channels_found = 0;
#if LIBAVUTIL_VERSION_MAJOR >= 57
AVChannelLayout output_channel_layout = {0};
av_opt_get_chlayout(swr, "out_chlayout", 0, &output_channel_layout);
conn->resampler_output_channels = output_channel_layout.nb_channels;
for (c = 0; c < 64; c++) {
enum AVChannel channel = av_channel_layout_channel_from_index(&output_channel_layout, c);
if (channel != AV_CHAN_NONE) {
char buffer[32];
if (av_channel_name(buffer, 32, channel) > 0) {
if (resampler_channels_found == 0) {
strcat(resampler_channel_list, "\"");
} else {
strcat(resampler_channel_list, "\", \"");
}
strcat(resampler_channel_list, buffer);
resampler_channels[resampler_channels_found].name = strdup(buffer);
resampler_channels_found++;
}
}
}
av_channel_layout_uninit(&output_channel_layout);
#else
int64_t resampler_output_channel_layout = 0;
{
int res = av_opt_get_int(swr, "out_channel_layout", 0, &resampler_output_channel_layout);
if (res == 0) {
conn->resampler_output_channels =
(int64_t)av_get_channel_layout_nb_channels((uint64_t)resampler_output_channel_layout);
} else {
debug(1, "Error %d getting resampler output channel layout.", res);
}
}
int64_t mask = 1;
for (c = 0; c < 64; c++) {
if ((resampler_output_channel_layout & mask) != 0) {
if (resampler_channels_found == 0) {
strcat(resampler_channel_list, "\"");
} else {
strcat(resampler_channel_list, "\", \"");
}
strcat(resampler_channel_list, av_get_channel_name(1 << c));
resampler_channels[resampler_channels_found].name = strdup(av_get_channel_name(1 << c));
resampler_channels_found++;
}
mask = mask << 1;
}
#endif
if (resampler_channels_found != 0) {
strcat(resampler_channel_list, "\"");
}
if (strlen(resampler_channel_list) == 0) {
debug(3, "resampler output channel list is empty.");
} else {
debug(3, "resampler output channel list: %s.", resampler_channel_list);
}
if (output_device_channel_map != NULL) {
debug(3, "output device's channel map is: \"%s\".", output_device_channel_map);
// free(output_device_channel_map);
// output_device_channel_map = NULL;
}
int output_channel_map_faulty = 0;
if (resampler_channels_found != 0) {
// now we have the names of the channels produced by the resampler in the order they
// appear in the output from the resampler. We need to map them to the channel ordering
// of the output device.
// create an output channel list. It will be 64 channels long.
// It may not have names for all channels.
// In fact, it will have no names at all if mapping is disabled or set to auto
// with no device channel map. That will be okay, as unallocated resampler
// channels will be assigned to unused output channels at the end anyway
channel_info_t
output_channels[64]; // can't be more than 64. This will list the output channel names
// in the order they appear in the device channel map.
for (c = 0; c < sizeof(output_channels) / sizeof(channel_info_t); c++) {
output_channels[c].name = NULL;
output_channels[c].allocated = 0;
}
// if channel mapping is enabled
if (config.output_channel_mapping_enable != 0) {
// if a channel map is given
if (config.output_channel_map_size != 0) {
for (c = 0; c < config.output_channel_map_size; c++) {
output_channels[c].name = strdup(config.output_channel_map[c]);
}
} else if (output_device_channel_map != NULL) { // if there is a device channel map...
char *device_channels = strdup(output_device_channel_map);
char delim[] = " ";
char *ptr = strtok(device_channels, delim);
c = 0;
while (ptr != NULL) {
output_channels[c].name = strdup(ptr);
if (strcasecmp(ptr, "UNKNOWN") == 0)
output_channel_map_faulty = 1;
ptr = strtok(NULL, delim);
c++;
}
free(device_channels);
}
}
if (output_channel_map_faulty != 0) {
once(inform("The output device's %u-channel map is incomplete or faulty: \"%s\".",
CHANNELS_FROM_ENCODED_FORMAT(config.current_output_configuration),
output_device_channel_map));
}
// at this point, we should have two arrays
// the first is all the resampler channels
// the second is device channel map channels, which may be empty or incomplete
for (c = 0; c < 64; c++)
if (resampler_channels[c].name != NULL)
debug(3, "audio channel %u is \"%s\".", c, resampler_channels[c].name);
for (c = 0; c < 64; c++)
if (output_channels[c].name != NULL)
debug(3, "output device channel %u is \"%s\".", c, output_channels[c].name);
conn->output_channel_map_size =
CHANNELS_FROM_ENCODED_FORMAT(config.current_output_configuration);
// construct a map to match named resampler channels to named output channels
unsigned int cmi;
for (cmi = 0; cmi < conn->output_channel_map_size; cmi++) {
// debug(1,"checking output channel %u, (\"%s\").", cmi, output_channels[cmi].name);
conn->output_channel_to_resampler_channel_map[cmi] =
silent_channel_index; // by default the channel is silent
if ((output_channels[cmi].name != NULL) && (strcmp(output_channels[cmi].name, "--") == 0)) {
conn->output_channel_to_resampler_channel_map[cmi] = silent_channel_index;
output_channels[cmi].allocated = 1;
debug(1, "output device channel %u (\"--\") will be silent.", cmi);
} else {
int resampler_channel_index;
int found = 0;
for (resampler_channel_index = 0;
((resampler_channel_index < resampler_channels_found) && (found == 0));
resampler_channel_index++) {
if ((output_channels[cmi].name != NULL) &&
(resampler_channels[resampler_channel_index].name != NULL) &&
(strcmp(output_channels[cmi].name,
resampler_channels[resampler_channel_index].name) == 0)) {
conn->output_channel_to_resampler_channel_map[cmi] = resampler_channel_index;
output_channels[cmi].allocated = 1;
resampler_channels[resampler_channel_index].allocated = 1;
found = 1;
if ((resampler_channels_found > 2) && (output_configuration_changed != 0)) {
if (output_channel_map_faulty != 0)
debug(3, "%s -> %s/%u.", resampler_channels[resampler_channel_index].name,
output_channels[cmi].name, cmi);
else
debug(3, "%s -> %s/%u.", resampler_channels[resampler_channel_index].name,
output_channels[cmi].name, cmi);
}
}
}
}
}
// now there may be unmapped resampler channels and unallocated output channels
// allocate them on a first-come-first-served basis
for (cmi = 0; cmi < conn->output_channel_map_size; cmi++) {
if (output_channels[cmi].allocated == 0)
debug(3, "output device channel %u (\"%s\") is unallocated.", cmi,
output_channels[cmi].name);
}
for (c = 0; c < 64; c++) {
if ((resampler_channels[c].name != NULL) && (resampler_channels[c].allocated == 0))
debug(3, "audio channel %u (\"%s\") is unmapped.", c, resampler_channels[c].name);
}
c = 0; // for indexing through the unmapped resampler channels
for (cmi = 0; (cmi < conn->output_channel_map_size) && (c < 64); cmi++) {
if (output_channels[cmi].allocated == 0) {
do {
if ((resampler_channels[c].name != NULL) && (resampler_channels[c].allocated == 0)) {
output_channels[cmi].allocated = 1;
resampler_channels[c].allocated = 1;
conn->output_channel_to_resampler_channel_map[cmi] = c;
if (output_channel_map_faulty != 0)
debug(3, "%s -> %s/%u.", resampler_channels[c].name, output_channels[cmi].name,
cmi);
else
debug(3, "%s -> %s/%u.", resampler_channels[c].name, output_channels[cmi].name,
cmi);
} else {
c++;
}
} while ((output_channels[cmi].allocated == 0) && (c < 64));
}
}
if (output_configuration_changed != 0) {
char channel_mapping_list[256] = "";
for (c = 0; c < 8; c++) {
if ((output_channels[c].allocated != 0) &&
(conn->output_channel_to_resampler_channel_map[c] != silent_channel_index)) {
char channel_mapping[32] = "";
if (output_channels[c].name != NULL)
snprintf(channel_mapping, sizeof(channel_mapping) - 1, " %u (\"%s\") <- %s |", c,
output_channels[c].name,
resampler_channels[conn->output_channel_to_resampler_channel_map[c]].name);
else
snprintf(channel_mapping, sizeof(channel_mapping) - 1, " %u <- %s |", c,
resampler_channels[conn->output_channel_to_resampler_channel_map[c]].name);
strncat(channel_mapping_list, channel_mapping,
sizeof(channel_mapping_list) - 1 - strlen(channel_mapping_list));
}
}
debug(1, "Channel Mapping: |%s", channel_mapping_list);
}