forked from belese/a2dp-alsa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
a2dp-alsa.c
1503 lines (1308 loc) · 47.4 KB
/
a2dp-alsa.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/****************************************
* a2dp-alsa.c
* Enable A2DP sink and source on ALSA devices using bluez DBus API.
* In short - it enables remote devices to send sound to the computer (sink)
* and enables the computer (source) to send sound to bluetooth speakers.
*
* For bluez 4.x.
*
* Copyright (C) James Budiono 2013
* License: GNU GPL Version 3 or later
* Version 1: June 2013
****************************************/
// std includes
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <pthread.h>
#include <fcntl.h>
#include <dbus/dbus.h>
#include <errno.h>
#include <arpa/inet.h>
#include <getopt.h>
#include <poll.h>
#include "uthash.h"
// our own defines
#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
#ifndef BLUEZ_VERSION
#define BLUEZ_VERSION 4
#endif
#if BLUEZ_VERSION == 4
#define ORG_BLUEZ_MEDIA "org.bluez.Media"
#define ORG_BLUEZ_MEDIAENDPOINT "org.bluez.MediaEndpoint"
#define ORG_BLUEZ_MEDIATRANSPORT "org.bluez.MediaTransport"
#define ORG_BLUEZ_AUDIOSOURCE "org.bluez.AudioSource"
#define ORG_BLUEZ_AUDIOSINK "org.bluez.AudioSink"
#define PROPERTYCHANGED "PropertyChanged"
#else
#define ORG_BLUEZ_MEDIA "org.bluez.Media1"
#define ORG_BLUEZ_MEDIAENDPOINT "org.bluez.MediaEndpoint1"
#define ORG_BLUEZ_MEDIATRANSPORT "org.bluez.MediaTransport1"
#define ORG_BLUEZ_AUDIOSOURCE "org.freedesktop.DBus.Properties"
#define ORG_BLUEZ_AUDIOSINK "org.freedesktop.DBus.Properties"
#define PROPERTYCHANGED "PropertiesChanged"
#endif
#include <time.h>
#include <sys/time.h>
const char *get_time() {
static __thread char szTime[64];
struct timeval tv;
gettimeofday(&tv, NULL);
struct tm tim;
localtime_r(&tv.tv_sec, &tim);
sprintf(szTime,"%d/%02d/%02d %02d:%02d:%02d.%03ld",
tim.tm_year+1900,tim.tm_mon+1,tim.tm_mday,
tim.tm_hour,tim.tm_min,tim.tm_sec,(long)tv.tv_usec/1000);
return szTime;
}
//#define DEBUG
#ifdef DEBUG
#define debug_print(format, ...) fprintf(stderr, "[%s][%s:%d]" format "\n", get_time(), __FUNCTION__, __LINE__, ##__VA_ARGS__)
#else
#define debug_print(...)
#endif
#define error_print(format, ...) fprintf(stderr, "[%s][%s:%d]" format "\n", get_time(), __FUNCTION__, __LINE__, ##__VA_ARGS__)
// bluez specific defines & includes
#define FIND_ADAPTER "FindAdapter"
#define DEFAULT_ADAPTER "DefaultAdapter"
#define ACCESS_TYPE "rw"
// sink and source uuid and endpoints
#define A2DP_SINK_UUID "0000110b-0000-1000-8000-00805f9b34fb"
#define A2DP_SINK_ENDPOINT "/MediaEndpoint/A2DPSink" // bt --> alsa (sink for bt)
#define A2DP_SOURCE_UUID "0000110a-0000-1000-8000-00805f9b34fb"
#define A2DP_SOURCE_ENDPOINT "/MediaEndpoint/A2DPSource" // alsa --> bt (source for bt)
#include "a2dp-codecs.h" // from bluez - some sbc constants
#include "ipc.h" // from bluez - some sbc constants
#include "rtp.h" // from bluez - packet headers
// sbc stuff
#include "sbc/sbc.h"
// structs and prototypes
typedef struct {
// sync and command management
pthread_cond_t cond;
pthread_mutex_t mutex;
pthread_t t_handle; //thread handle
volatile enum {
IO_CMD_IDLE = 0,
IO_CMD_RUNNING,
IO_CMD_TERMINATE
} command;
enum {
STATE_DISCONNECTED = 0,
STATE_CONNECTED,
STATE_PLAYING
} prev_state;
// transport_path - required to get fd and mtus
char *transport_path; // also the hash key
char *dev_path; // so that audiosource/sink event can find us
// the actual fd and mtus for streaming
int fd, read_mtu, write_mtu;
int write; //false = read, true - write
// codec stuff
a2dp_sbc_t cap;
sbc_t sbc;
// persistent stuff for encoding purpose
uint16_t seq_num; //cumulative packet number
uint32_t timestamp; //timestamp
//hashtable management
UT_hash_handle hh;
} io_thread_tcb_s; //the I/O thread control block.
void *io_thread_run(void *ptr);
void io_thread_set_command (io_thread_tcb_s *data, int command);
io_thread_tcb_s *create_io_thread();
void destroy_io_thread(DBusConnection *conn, io_thread_tcb_s *p);
int transport_acquire (DBusConnection *conn, char *transport_path, int *fd, int *read_mtu, int *write_mtu);
int transport_release (DBusConnection *conn, char *transport_path);
// globals
int quit=0; // when set to 1, program terminates
int run_once = 0; // only run output once, then exit
//////////////////////////////// DBUS HELPERS ////////////////////////////////
/*****************//**
* Handle dbus error and clear error message block
*
* @param [in] The error object
* @param [in] function where the error happens
* @param [in] line number where the error happens
* @returns TRUE if successful, FALSE otherwise
********************/
int handle_dbus_error (DBusError *err, const char *func, int line) {
if (dbus_error_is_set (err)) {
error_print("DBus error %s at %u: %s", func, line, err->message);
dbus_error_free(err);
return 1;
}
return 0;
}
/*****************//**
* Connect to the system message bus
*
* @param [out] connection object, if function is successful, other wise it is unchanged.
* @returns TRUE if successful, FALSE otherwise
********************/
int get_system_bus(DBusConnection **system_bus) {
DBusError err;
DBusConnection* conn;
dbus_error_init(&err);
conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
handle_dbus_error (&err, __FUNCTION__, __LINE__);
if (NULL == conn) return 0;
*system_bus = conn;
debug_print("Name %s", dbus_bus_get_unique_name (conn));
return 1;
}
/*****************//**
* Get the bluetooth device's path
*
* @param [in] connection to use
* @param [in] adapter to use (hci0, or bluetooth address, or NULL to use default)
* @param [out] the object path, if function is successful, other wise it is unchanged.
* @returns TRUE if successful, FALSE otherwise
********************/
int get_bluetooth_object(DBusConnection* conn, char *device, char **dev_path) {
DBusMessage *msg, *reply;
DBusMessageIter iter;
DBusError err;
char *s, *method = FIND_ADAPTER;
#if BLUEZ_VERSION == 4
dbus_error_init(&err);
debug_print("Getting object path for adapter %s", device);
// create a new method call msg
if (!device) method = DEFAULT_ADAPTER;
msg = dbus_message_new_method_call("org.bluez",
"/", // object to call on
"org.bluez.Manager", // interface to call on
method); // method name
// append arguments
dbus_message_iter_init_append(msg, &iter);
if (device) dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &device);
// send message and wait for reply, -1 means wait forever
reply = dbus_connection_send_with_reply_and_block (conn, msg, -1, &err);
handle_dbus_error (&err, __FUNCTION__, __LINE__);
if (!reply) {
return 0;
}
// read the parameters
if (dbus_message_iter_init(reply, &iter) &&
DBUS_TYPE_OBJECT_PATH == dbus_message_iter_get_arg_type(&iter))
dbus_message_iter_get_basic(&iter, &s);
else return 0;
// free reply and close connection
debug_print("Object path for %s is %s", device, s);
dbus_message_unref(msg);
dbus_message_unref(reply);
*dev_path = strdup (s);
#else
// org.bluez.Manager has been removed; just use hci0
*dev_path = strdup ("/org/bluez/hci0");
#endif
return 1;
}
/*****************//**
* Add a dict entry of a variant of simple types
*
* @param [in] array iter to add to
* @param [in] key
* @param [in] type (must be simple types)
* @param [in] value
********************/
void util_add_dict_variant_entry (DBusMessageIter *iter, char *key, int type, void *value) {
DBusMessageIter dict, variant;
dbus_message_iter_open_container (iter, DBUS_TYPE_DICT_ENTRY, NULL, &dict);
dbus_message_iter_append_basic (&dict, DBUS_TYPE_STRING, &key);
dbus_message_iter_open_container (&dict, DBUS_TYPE_VARIANT, (char *)&type, &variant);
dbus_message_iter_append_basic (&variant, type, &value);
dbus_message_iter_close_container (&dict, &variant);
dbus_message_iter_close_container (iter, &dict);
}
/*****************//**
* Add a dict entry of an array of of simple types
*
* @param [in] array iter to add to
* @param [in] key
* @param [in] type (must be simple types)
* @param [in] pointer to the array
* @param [in] number of elements (not size in bytes!)
********************/
void util_add_dict_array_entry (DBusMessageIter *iter, char *key, int type, void *buf, int elements) {
DBusMessageIter dict, variant, array;
char array_type[5] = "a";
strncat (array_type, (char*)&type, sizeof(array_type));
dbus_message_iter_open_container (iter, DBUS_TYPE_DICT_ENTRY, NULL, &dict);
dbus_message_iter_append_basic (&dict, DBUS_TYPE_STRING, &key);
dbus_message_iter_open_container (&dict, DBUS_TYPE_VARIANT, array_type, &variant);
dbus_message_iter_open_container (&variant, DBUS_TYPE_ARRAY, (char *)&type, &array);
dbus_message_iter_append_fixed_array (&array, type, &buf, elements);
dbus_message_iter_close_container (&variant, &array);
dbus_message_iter_close_container (&dict, &variant);
dbus_message_iter_close_container (iter, &dict);
}
//////////////////////////////// BLUEZ AUDIO/MEDIA HELPERS ////////////////////////////////
/*****************//**
* Register our "endpoint" handler to bluez audio system.
* As part of its job, it returns supported codecs and codec parameters, as well
* as what functions are we doing here (A2DP source, A2DP sink, HFP, etc - for
* this program it will be A2DP sink).
*
* @param [in] system bus connection
* @param [in] bluetooth object to register to
* @returns TRUE means ok, FALSE means something is wrong
********************/
int media_register_endpoint(DBusConnection* conn, char *bt_object, char *endpoint, char *uuid) {
DBusMessage *msg, *reply;
DBusMessageIter iter, iterarray;
DBusError err;
a2dp_sbc_t capabilities;
capabilities.channel_mode = BT_A2DP_CHANNEL_MODE_MONO | BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL |
BT_A2DP_CHANNEL_MODE_STEREO | BT_A2DP_CHANNEL_MODE_JOINT_STEREO;
capabilities.frequency = BT_SBC_SAMPLING_FREQ_16000 | BT_SBC_SAMPLING_FREQ_32000 |
BT_SBC_SAMPLING_FREQ_44100 | BT_SBC_SAMPLING_FREQ_48000;
capabilities.allocation_method = BT_A2DP_ALLOCATION_SNR | BT_A2DP_ALLOCATION_LOUDNESS;
capabilities.subbands = BT_A2DP_SUBBANDS_4 | BT_A2DP_SUBBANDS_8;
capabilities.block_length = BT_A2DP_BLOCK_LENGTH_4 | BT_A2DP_BLOCK_LENGTH_8 |
BT_A2DP_BLOCK_LENGTH_12 | BT_A2DP_BLOCK_LENGTH_16;
capabilities.min_bitpool = MIN_BITPOOL;
capabilities.max_bitpool = MAX_BITPOOL;
dbus_error_init(&err);
msg = dbus_message_new_method_call("org.bluez",
bt_object, // object to call on
ORG_BLUEZ_MEDIA, // interface to call on
"RegisterEndpoint"); // method name
//build the parameters
dbus_message_iter_init_append (msg, &iter);
//first param - object path
dbus_message_iter_append_basic (&iter, DBUS_TYPE_OBJECT_PATH, &endpoint);
//second param - properties
dbus_message_iter_open_container (&iter, DBUS_TYPE_ARRAY, "{sv}", &iterarray);
util_add_dict_variant_entry (&iterarray, "UUID", DBUS_TYPE_STRING, uuid);
util_add_dict_variant_entry (&iterarray, "Codec", DBUS_TYPE_BYTE, A2DP_CODEC_SBC);
util_add_dict_array_entry (&iterarray, "Capabilities", DBUS_TYPE_BYTE, &capabilities, sizeof (capabilities));
dbus_message_iter_close_container (&iter, &iterarray);
//char *buf; int buflen; dbus_message_marshal (msg, &buf, &buflen); write (1, buf, buflen); return 0;
//make the call
reply = dbus_connection_send_with_reply_and_block (conn, msg, -1, &err);
if (dbus_error_is_set (&err) && strcmp(err.message, "Already Exists") != 0) {
handle_dbus_error (&err, __FUNCTION__, __LINE__);
if (!reply) {
return 0;
}
}
dbus_message_unref(msg);
if (reply)
dbus_message_unref(reply);
return 1;
}
/*****************//**
* Unregister our "endpoint" handler from bluez audio system.
*
* @param [in] system bus connection
* @param [in] bluetooth object to unregister from
* @returns TRUE means ok, FALSE means something is wrong
********************/
int media_unregister_endpoint(DBusConnection* conn, char *bt_object, char *endpoint) {
DBusMessage *msg, *reply;
DBusMessageIter iter;
DBusError err;
debug_print("media_unregister_endpoint");
dbus_error_init(&err);
msg = dbus_message_new_method_call("org.bluez",
bt_object, // object to call on
ORG_BLUEZ_MEDIA, // interface to call on
"UnregisterEndpoint"); // method name
//build the parameters
dbus_message_iter_init_append (msg, &iter);
//first param - object path
dbus_message_iter_append_basic (&iter, DBUS_TYPE_OBJECT_PATH, &endpoint);
//make the call
reply = dbus_connection_send_with_reply_and_block (conn, msg, -1, &err);
handle_dbus_error (&err, __FUNCTION__, __LINE__);
if (!reply) {
return 0;
}
dbus_message_unref(msg);
dbus_message_unref(reply);
return 1;
}
/*****************//**
* Get the transport (ie, the actual file descriptor) for streaming (ie, read/write)
* the audio data
*
* @param [in] system bus connection
* @param [in] transport object path (must come from MediaEndpoint.SetConfiguration)
* @param [out] file descriptor
* @param [out] maximum size to read per transaction
* @param [out] maximum size to write per transaction
* @returns TRUE if ok, FALSE means something is wrong
********************/
int transport_acquire (DBusConnection *conn, char *transport_path, int *fd, int *read_mtu, int *write_mtu) {
DBusMessage *msg, *reply;
DBusMessageIter iter;
DBusError err;
char *access_type = ACCESS_TYPE;
debug_print ("acquire %s", transport_path);
dbus_error_init(&err);
msg = dbus_message_new_method_call("org.bluez",
transport_path, // object to call on
ORG_BLUEZ_MEDIATRANSPORT, // interface to call on
"Acquire"); // method name
#if BLUEZ_VERSION == 4
//build the parameters
dbus_message_iter_init_append (msg, &iter);
dbus_message_iter_append_basic (&iter, DBUS_TYPE_STRING, &access_type);
#endif
//make the call
reply = dbus_connection_send_with_reply_and_block (conn, msg, -1, &err);
handle_dbus_error (&err, __FUNCTION__, __LINE__);
if (!reply) {
return 0;
}
//read the reply
if (!dbus_message_get_args(reply, &err,
DBUS_TYPE_UNIX_FD, fd,
DBUS_TYPE_UINT16, read_mtu,
DBUS_TYPE_UINT16, write_mtu,
DBUS_TYPE_INVALID))
{
handle_dbus_error (&err, __FUNCTION__, __LINE__);
return 0;
}
//clean up
dbus_message_unref(msg);
dbus_message_unref(reply);
return 1;
}
/*****************//**
* Release the transport (ie, the file descriptor)
* Note: this doesn't need to be called if transport is closed by
* "MediaEndpoint.ClearConfiguration". It is only needed if the app wishes to
* release control of the fd while the stream is still active (e.g - suspend
* stream, pausing, etc).
*
* @param [in] system bus connection
* @param [in] transport object path (must come from MediaEndpoint.SetConfiguration)
********************/
int transport_release (DBusConnection *conn, char *transport_path) {
DBusMessage *msg, *reply;
DBusMessageIter iter;
DBusError err;
char *access_type = ACCESS_TYPE;
debug_print ("release %s", transport_path);
dbus_error_init(&err);
msg = dbus_message_new_method_call("org.bluez",
transport_path, // object to call on
ORG_BLUEZ_MEDIATRANSPORT, // interface to call on
"Release"); // method name
#if BLUEZ_VERSION == 4
//build the parameters
dbus_message_iter_init_append (msg, &iter);
dbus_message_iter_append_basic (&iter, DBUS_TYPE_STRING, &access_type);
#endif
//make the call
reply = dbus_connection_send_with_reply_and_block (conn, msg, -1, &err);
handle_dbus_error (&err, __FUNCTION__, __LINE__);
if (!reply) {
return 0;
}
//clean up
dbus_message_unref(msg);
dbus_message_unref(reply);
return 1;
}
/*****************//**
* Helper to calculate the optimum bitpool, given the sampling frequency,
* and number of channels.
* Taken verbatim from pulseaudio 2.1
* (which took it from bluez audio - a2dp.c & pcm_bluetooth.c - default_bitpool)
*
* @param [in] frequency
* @param [in] channel mode
* @returns coded SBC bitpool
*********************/
static uint8_t a2dp_default_bitpool(uint8_t freq, uint8_t mode) {
switch (freq) {
case BT_SBC_SAMPLING_FREQ_16000:
case BT_SBC_SAMPLING_FREQ_32000:
return 53;
case BT_SBC_SAMPLING_FREQ_44100:
switch (mode) {
case BT_A2DP_CHANNEL_MODE_MONO:
case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
return 31;
case BT_A2DP_CHANNEL_MODE_STEREO:
case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
return 53;
default:
error_print ("Invalid channel mode %u", mode);
return 53;
}
case BT_SBC_SAMPLING_FREQ_48000:
switch (mode) {
case BT_A2DP_CHANNEL_MODE_MONO:
case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
return 29;
case BT_A2DP_CHANNEL_MODE_STEREO:
case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
return 51;
default:
error_print ("Invalid channel mode %u", mode);
return 51;
}
default:
error_print ("Invalid sampling freq %u", freq);
return 53;
}
}
/*****************//**
* Helper to setup sbc params from a2dp_sbc_t
* Modified from pulseaudio 2.1 (which took it from bluez - pcm_bluetooth.c
* - bluetooth_a2dp_setup)
*
* @param [in] sbc codec configuration
* @param [in] bluez codec capability configuration
*********************/
void setup_sbc(sbc_t *sbc, a2dp_sbc_t *cap) {
switch (cap->frequency) {
case BT_SBC_SAMPLING_FREQ_16000:
sbc->frequency = SBC_FREQ_16000;
break;
case BT_SBC_SAMPLING_FREQ_32000:
sbc->frequency = SBC_FREQ_32000;
break;
case BT_SBC_SAMPLING_FREQ_44100:
sbc->frequency = SBC_FREQ_44100;
break;
case BT_SBC_SAMPLING_FREQ_48000:
sbc->frequency = SBC_FREQ_48000;
break;
default:
error_print ("No supported frequency");
}
switch (cap->channel_mode) {
case BT_A2DP_CHANNEL_MODE_MONO:
sbc->mode = SBC_MODE_MONO;
break;
case BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL:
sbc->mode = SBC_MODE_DUAL_CHANNEL;
break;
case BT_A2DP_CHANNEL_MODE_STEREO:
sbc->mode = SBC_MODE_STEREO;
break;
case BT_A2DP_CHANNEL_MODE_JOINT_STEREO:
sbc->mode = SBC_MODE_JOINT_STEREO;
break;
default:
error_print ("No supported channel_mode");
}
switch (cap->allocation_method) {
case BT_A2DP_ALLOCATION_SNR:
sbc->allocation = SBC_AM_SNR;
break;
case BT_A2DP_ALLOCATION_LOUDNESS:
sbc->allocation = SBC_AM_LOUDNESS;
break;
default:
error_print ("No supported allocation");
}
switch (cap->subbands) {
case BT_A2DP_SUBBANDS_4:
sbc->subbands = SBC_SB_4;
break;
case BT_A2DP_SUBBANDS_8:
sbc->subbands = SBC_SB_8;
break;
default:
error_print ("No supported subbands");
}
switch (cap->block_length) {
case BT_A2DP_BLOCK_LENGTH_4:
sbc->blocks = SBC_BLK_4;
break;
case BT_A2DP_BLOCK_LENGTH_8:
sbc->blocks = SBC_BLK_8;
break;
case BT_A2DP_BLOCK_LENGTH_12:
sbc->blocks = SBC_BLK_12;
break;
case BT_A2DP_BLOCK_LENGTH_16:
sbc->blocks = SBC_BLK_16;
break;
default:
error_print ("No supported block length");
}
sbc->bitpool = cap->max_bitpool;
}
//////////////////////////////// BLUEZ AUDIO CALLBACK HANDLER ////////////////////////////////
/*****************//**
* Implement MediaEndpoint.SelectConfiguration.
* Called by bluez to negotiate which configuration (=codec, codec parameter)
* for audio streaming.
* This function will examine what the requested configuration and returns back
* a reply with the supported / agreed configuration.
*
* Chosen configuration isn't cached because it will be returned with SetConfiguration.
*
* Contains modified code taken from pulseaudio 2.1 (which took it from
* bluez audio, select_sbc_params (a2dp.c)
*
* @param [in] original "call" message from bluez
* @returns reply message (success or failure)
*********************/
DBusMessage* endpoint_select_configuration (DBusMessage *msg) {
a2dp_sbc_t *cap, config;
uint8_t *pconf = (uint8_t *) &config;
int size;
DBusMessage *reply;
DBusError err;
debug_print ("Select configuration");
dbus_error_init(&err);
if (!dbus_message_get_args(msg, &err, DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE, &cap, &size, DBUS_TYPE_INVALID)) {
handle_dbus_error (&err, __FUNCTION__, __LINE__);
goto fail;
}
//taken from pulseaudio with modification
memset(&config, 0, sizeof(config));
config.frequency = BT_SBC_SAMPLING_FREQ_44100;
if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_JOINT_STEREO)
config.channel_mode = BT_A2DP_CHANNEL_MODE_JOINT_STEREO;
else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_STEREO)
config.channel_mode = BT_A2DP_CHANNEL_MODE_STEREO;
else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL)
config.channel_mode = BT_A2DP_CHANNEL_MODE_DUAL_CHANNEL;
else if (cap->channel_mode & BT_A2DP_CHANNEL_MODE_MONO) {
config.channel_mode = BT_A2DP_CHANNEL_MODE_MONO;
} else {
error_print ("No supported channel modes");
goto fail;
}
if (cap->block_length & BT_A2DP_BLOCK_LENGTH_16)
config.block_length = BT_A2DP_BLOCK_LENGTH_16;
else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_12)
config.block_length = BT_A2DP_BLOCK_LENGTH_12;
else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_8)
config.block_length = BT_A2DP_BLOCK_LENGTH_8;
else if (cap->block_length & BT_A2DP_BLOCK_LENGTH_4)
config.block_length = BT_A2DP_BLOCK_LENGTH_4;
else {
error_print ("No supported block lengths");
goto fail;
}
if (cap->subbands & BT_A2DP_SUBBANDS_8)
config.subbands = BT_A2DP_SUBBANDS_8;
else if (cap->subbands & BT_A2DP_SUBBANDS_4)
config.subbands = BT_A2DP_SUBBANDS_4;
else {
error_print ("No supported subbands");
goto fail;
}
if (cap->allocation_method & BT_A2DP_ALLOCATION_LOUDNESS)
config.allocation_method = BT_A2DP_ALLOCATION_LOUDNESS;
else if (cap->allocation_method & BT_A2DP_ALLOCATION_SNR)
config.allocation_method = BT_A2DP_ALLOCATION_SNR;
config.min_bitpool = (uint8_t) MAX(MIN_BITPOOL, cap->min_bitpool);
config.max_bitpool = (uint8_t) MIN(a2dp_default_bitpool(config.frequency, config.channel_mode), cap->max_bitpool);
reply = dbus_message_new_method_return(msg);
dbus_message_append_args (reply,
DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE, &pconf, size,
DBUS_TYPE_INVALID);
return reply;
fail:
return dbus_message_new_error(msg, "org.bluez.MediaEndpoint.Error.InvalidArguments",
"Unable to select configuration");
}
/*****************//**
* Implement MediaEndpoint.SetConfiguration.
* Called by bluez to confirm that this will be the configuration chosen.
* The most important thing here is the "transport object path", which we will
* need to get the actual file-descriptor for streaming later (see transport_acquire).
*
* In theory the transport_acquire could be called from here with some delays,
* in reality it is a lot better to do it after we've received confirmation that
* audio is "connected" (this is done by watching AudioSource.PropertyChange signal)
*
* This function is too complicated for what it does, for our (simple) purpose
* we actually only need the transport_path so we don't have to parse all the parameters,
* but we do anyway.
*
* @param [in] original "call" message from bluez
* @param [in] io thread hashtable
* @returns reply message (success or failure)
*********************/
DBusMessage* endpoint_set_configuration (DBusMessage *msg, io_thread_tcb_s **io_threads_table) {
const char *transport_path, *dev_path = NULL, *uuid = NULL, *cmd_path = NULL;
uint8_t *config = NULL;
int size = 0;
DBusMessageIter iter, iterprop, iterentry, itervalue, iterarray;
io_thread_tcb_s *head = *io_threads_table;
io_thread_tcb_s *io_data = NULL;
dbus_message_iter_init(msg, &iter);
dbus_message_iter_get_basic(&iter, &transport_path);
if (!dbus_message_iter_next(&iter))
goto fail;
dbus_message_iter_recurse(&iter, &iterprop);
if (dbus_message_iter_get_arg_type(&iterprop) != DBUS_TYPE_DICT_ENTRY)
goto fail;
/* Read transport properties */
while (dbus_message_iter_get_arg_type(&iterprop) == DBUS_TYPE_DICT_ENTRY) {
const char *key;
int var;
dbus_message_iter_recurse(&iterprop, &iterentry);
dbus_message_iter_get_basic(&iterentry, &key);
dbus_message_iter_next(&iterentry);
dbus_message_iter_recurse(&iterentry, &itervalue);
var = dbus_message_iter_get_arg_type(&itervalue);
if (strcasecmp(key, "UUID") == 0) {
if (var != DBUS_TYPE_STRING)
goto fail;
dbus_message_iter_get_basic(&itervalue, &uuid);
} else if (strcasecmp(key, "Device") == 0) {
if (var != DBUS_TYPE_OBJECT_PATH)
goto fail;
dbus_message_iter_get_basic(&itervalue, &dev_path);
} else if (strcasecmp(key, "Configuration") == 0) {
if (var != DBUS_TYPE_ARRAY)
goto fail;
dbus_message_iter_recurse(&itervalue, &iterarray);
dbus_message_iter_get_fixed_array(&iterarray, &config, &size);
}
dbus_message_iter_next(&iterprop);
}
debug_print ("Set configuration %s",transport_path);
//capture the transport_path and allocate the transport later, when the audiosource is "connected".
HASH_FIND_STR (head, transport_path, io_data);
if (!io_data) {
io_data = create_io_thread();
io_data->dev_path = strdup (dev_path);
io_data->transport_path = strdup (transport_path);
io_data->cap = *((a2dp_sbc_t*) config);
//read or write
cmd_path = (char *)dbus_message_get_path (msg);
if ( strcasecmp (cmd_path, A2DP_SINK_ENDPOINT) == 0)
io_data->write = 0;
else if ( strcasecmp (cmd_path, A2DP_SOURCE_ENDPOINT) == 0)
io_data->write = 1;
HASH_ADD_KEYPTR (hh, head, io_data->transport_path, strlen(io_data->transport_path), io_data);
*io_threads_table = head;
}
return dbus_message_new_method_return(msg);
fail:
return dbus_message_new_error(msg, "org.bluez.MediaEndpoint.Error.InvalidArguments",
"Unable to select configuration");
}
/*****************//**
* Implement MediaEndpoint.ClearConfiguration.
* Called by bluez to let us know that the audio streaming process has been reset
* for whatever reason, and we should do our own clean-up.
* Here we tell our I/O thread to stop.
*
* It is not necessary to call transport_release here because by the time we got here,
* the 'transport' has already been released.
*
* @param [in] original "call" message from bluez
* @param [in] io thread's data - to command I/O thread to stop.
* @returns reply message (success or failure)
*********************/
DBusMessage* endpoint_clear_configuration (DBusConnection *conn, DBusMessage *msg, io_thread_tcb_s **io_threads_table) {
DBusMessage *reply;
DBusError err;
DBusMessageIter iter;
char *transport_path;
io_thread_tcb_s *head = *io_threads_table;
io_thread_tcb_s *io_data = NULL;
dbus_error_init(&err);
dbus_message_iter_init(msg, &iter);
dbus_message_iter_get_basic(&iter, &transport_path);
debug_print ("Clear configuration %s",transport_path);
// stop stream
HASH_FIND_STR (head, transport_path, io_data);
if (io_data) {
debug_print ("stopping thread %p",io_data);
HASH_DEL (head, io_data);
*io_threads_table = head;
destroy_io_thread (conn, io_data);
}
reply = dbus_message_new_method_return(msg);
return reply;
}
/*****************//**
* Implement MediaEndpoint.Release
* Called by bluez to let us know our registration (see register_endpoint) has been
* cancelled (or 'released'). The next logical action after this, is either:
* a) to exit
* b) to re-register.
*
* There is no need to 'Unregister' because by the time we get here, our endpoint
* has already been de-registered.
*
* @param [in] original "call" message from bluez
* @returns reply message (success or failure)
*********************/
DBusMessage* endpoint_release (DBusMessage *msg) {
debug_print ("Release endpoint");
DBusMessage *reply;
DBusError err;
dbus_error_init(&err);
reply = dbus_message_new_method_return(msg);
return reply;
}
//////////////////////////////// BLUEZ-DBUS SIGNAL HANDLERS ////////////////////////////////
/*****************//**
* Handle AudioSource.PropertyChanged
* Signalled by bluez to let us know that the state of the audio source has changed.
* We use this signal as a trigger for 'delayed' transport_acquire to get the file
* descriptor, as well as to start the I/O thread.
*
* We don't use the corresponding transport_release because for the time being
* we will never willingly release a transport, until it is closed by
* MediaEndpoint.ClearConfiguration (the I/O thread will be stopped there).
*
* Note: The 'source' and 'sink' terms used in bluez is super-confusing because
* they are not consistent - sometimes they view it from the bluez side
* (in this case, it's a 'source' because the bluez is the 'source' of the data,
* sometimes they view it as 'sink' because this application receives and acts as data sink
* for the remote-end.
*
* Note: There is a corresponding signal for AudioSink, which we don't use.
*
* @param [in] connection object to talk to DBus
* @param [in] original "call" message from bluez
* @param [in] write==0 -> audiosink, write==1 --> audiosource
* @param [in] head of I/O thread hashtable
* @returns reply message (success or failure)
*********************/
#define audiosink_property_changed audiosource_property_changed
void audiosource_property_changed (DBusConnection *conn, DBusMessage *msg, int write, io_thread_tcb_s **io_threads_table) {
DBusMessageIter iter, itervariant;
#if BLUEZ_VERSION >= 5
DBusMessageIter iterarray, iterdict;
#endif
char *key;
char *dev_path;
char *state;
io_thread_tcb_s *head = *io_threads_table;
io_thread_tcb_s *io_data;
int new_state, transition, when_to_acquire, when_to_release;
dbus_message_iter_init (msg, &iter);
dbus_message_iter_get_basic (&iter, &key);
#if BLUEZ_VERSION == 4
if (strcasecmp (key, "State") != 0) return; //we are only interested in this.
#else
if (strcasecmp (key, "org.bluez.MediaTransport1") != 0) return; //we are only interested in this.
#endif
if (!dbus_message_iter_next(&iter)) goto fail;
#if BLUEZ_VERSION == 4
dbus_message_iter_recurse(&iter, &itervariant);
#else
dbus_message_iter_recurse(&iter, &iterarray);
dbus_message_iter_recurse(&iterarray, &iterdict);
dbus_message_iter_get_basic(&iterdict, &state);
if(strcasecmp(state, "State") != 0) return;
if(!dbus_message_iter_next(&iterdict)) goto fail;
dbus_message_iter_recurse(&iterdict, &itervariant);
#endif
if (dbus_message_iter_get_arg_type(&itervariant) != DBUS_TYPE_STRING) goto fail;
dbus_message_iter_get_basic (&itervariant, &state);
dev_path = (char *)dbus_message_get_path (msg);
debug_print ("state for %s: %s", dev_path, state);
//look for our thread
if (!head) return;
io_data = head;
do {
#if BLUEZ_VERSION == 4
if (strcasecmp (dev_path, io_data->dev_path) == 0 &&
#else
if (strncasecmp (dev_path, io_data->dev_path, strlen(io_data->dev_path)) == 0 &&
#endif
io_data->write == write)
break;
else io_data = io_data->hh.next;
} while (io_data && io_data != head);
if (!io_data) return;
//decode state & transition
new_state = transition = -1;
#if BLUEZ_VERSION == 4
if ( strcasecmp (state, "connected") == 0 ) new_state = STATE_CONNECTED;
else if ( strcasecmp (state, "playing") == 0 ) new_state = STATE_PLAYING;
#else
if ( strcasecmp (state, "pending") == 0 ) new_state = STATE_CONNECTED;
else if ( strcasecmp (state, "active") == 0 ) new_state = STATE_PLAYING;
#endif
else if ( strcasecmp (state, "disconnected") == 0 ) new_state = STATE_DISCONNECTED;
if (new_state >= 0) {
#if BLUEZ_VERSION == 4
transition = io_data->prev_state << 4 | new_state;
#endif
io_data->prev_state = new_state;
}
#if BLUEZ_VERSION == 4
//our treatment of sink and source is a bit different
switch (write) {
case 0: // bt sink: bt --> alsa
when_to_acquire = STATE_CONNECTED << 4 | STATE_PLAYING;
when_to_release = STATE_PLAYING << 4 | STATE_CONNECTED;
break;
case 1: // bt source: alsa --> bt
when_to_acquire = STATE_DISCONNECTED << 4 | STATE_CONNECTED;
when_to_release = STATE_CONNECTED << 4 | STATE_DISCONNECTED;
break;
}
#else
when_to_acquire = STATE_CONNECTED;
when_to_release = STATE_DISCONNECTED;
#endif
//acquire or release transport depending on the transitions
if (transition == when_to_acquire) {
if (transport_acquire (conn, io_data->transport_path, &io_data->fd, &io_data->read_mtu, &io_data->write_mtu)) {
debug_print ("fd: %d read mtu %d write mtu %d", io_data->fd, io_data->read_mtu, io_data->write_mtu);
io_thread_set_command (io_data, IO_CMD_RUNNING);
}
} else if (transition == when_to_release) {
transport_release (conn, io_data->transport_path);
io_thread_set_command (io_data, IO_CMD_IDLE);
}
return;
fail:
debug_print ("bad signal");
}
//////////////////////////////// IO THREAD HELPERS ////////////////////////////////
/*****************//**