-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathhsphfpd.pl
executable file
·2713 lines (2581 loc) · 134 KB
/
hsphfpd.pl
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
#!/usr/bin/perl
# (C) 2019 Pali
use 5.010;
use strict;
use warnings;
# Replace socket() by poll() syscall and put POLLHUP events into exception fd set
# Needed to catch POLLHUP events in Net::DBus::Reactor's add_exception() method
use IO::Poll qw(POLLIN POLLOUT POLLERR POLLHUP);
BEGIN {
*CORE::GLOBAL::select = sub {
return CORE::select() if @_ == 0;
return CORE::select($_[0]) if @_ == 1;
my %masks = (0 => POLLIN, 1 => POLLOUT, 2 => POLLERR|POLLHUP);
my @args;
for (0..2) {
next unless defined $_[$_];
for my $fd (0..8*length $_[$_]) {
push @args, $fd => $masks{$_} if vec $_[$_], $fd, 1;
}
}
my $ret = IO::Poll::_poll((defined $_[3]) ? ($_[3] * 1000) : -1, @args);
do { $_[$_] = "\x00" x length $_[$_] if defined $_[$_] } for 0..2;
while ($ret >= 0 and @args) {
my $fd = shift @args;
my $mask = shift @args;
do { vec($_[$_], $fd, 1) = 1 if $mask & $masks{$_} } for 0..2;
}
return $ret;
};
}
use Net::DBus qw(:typing);
use Net::DBus::Error;
use Net::DBus::Reactor;
use Net::DBus::RemoteService;
use Net::DBus::Service;
BEGIN {
require Net::DBus::Binding::Introspector;
no warnings 'redefine';
my $prev_to_xml = \&Net::DBus::Binding::Introspector::to_xml;
*Net::DBus::Binding::Introspector::to_xml = sub {
my $xml = $prev_to_xml->(@_);
# Fix bug in to_xml(), node subname cannot start with "/"
$xml =~ s{(.<node name=")/([^"])}{$1$2}g;
return $xml;
};
}
BEGIN {
require Net::DBus::BaseObject;
no warnings 'redefine';
*Net::DBus::BaseObject::_get_sub_nodes = sub {
my ($self) = @_;
my %uniq;
my $base = $self->{object_path};
# Fix bug in _get_sub_nodes(), base cannot be "//"
$base .= '/' if $base ne '/';
foreach (keys %{$self->{children}}) {
m/^$base([^\/]+)/;
$uniq{$1} = 1;
}
return sort keys %uniq;
};
*Net::DBus::BaseObject::_dispatch_all_prop_read = sub {
my ($self, $connection, $message) = @_;
my $ins = $self->_introspector;
if (!$ins) {
return $connection->make_error_message($message,
"org.freedesktop.DBus.Error.Failed",
"no introspection data exported for properties"
);
}
# Fix bug in _dispatch_all_prop_read, correct method name is "GetAll", not "Get"
my ($pinterface) = $ins->decode($message, "methods", "GetAll", "params");
my %values = ();
foreach my $pname ($ins->list_properties($pinterface)) {
unless ($ins->is_property_readable($pinterface, $pname)) {
next; # skip write-only properties
}
$values{$pname} = eval {
$self->_dispatch_property($pname);
};
if ($@) {
return $connection->make_error_message($message,
"org.freedesktop.DBus.Error.Failed",
"error reading '$pname' in interface '$pinterface': $@"
);
}
}
my $reply = $connection->make_method_return_message($message);
# Fix bug in _dispatch_all_prop_read, correct method name is "GetAll", not "Get"
$self->_introspector->encode($reply, "methods", "GetAll", "returns", \%values);
return $reply;
};
}
BEGIN {
require Net::DBus::Binding::Iterator;
require Net::DBus::Binding::Message;
no warnings 'redefine';
my $prev_append = \&Net::DBus::Binding::Iterator::append;
*Net::DBus::Binding::Iterator::append = sub {
my ($self, $value, $type) = @_;
# Fix bug in append, it does not support unixfd
if (ref $value eq 'Net::DBus::Binding::Value' and $value->type() == &Net::DBus::Binding::Message::TYPE_UNIX_FD) {
$self->append_unix_fd($value->value());
return;
}
$prev_append->($self, $value, $type);
};
}
BEGIN {
require Net::DBus::Reactor;
no warnings 'redefine';
my $prev_dispatch_fd = \&Net::DBus::Reactor::_dispatch_fd;
*Net::DBus::Reactor::_dispatch_fd = sub {
my ($self, $type, $vec) = @_;
# Fix bug in _dispatch_fd, exception type is marked incorrectly as error
$type = 'exception' if $type eq 'error';
return $prev_dispatch_fd->($self, $type, $vec);
};
}
BEGIN {
# Fix bug in dbus_unix_fd, it push TYPE_UNIX_FD into arrayref which is incorrect
no warnings 'redefine';
*Net::DBus::dbus_unix_fd = sub { Net::DBus::Binding::Value->new(&Net::DBus::Binding::Message::TYPE_UNIX_FD, $_[0]) };
# Fix bug in Net::DBus, it does not export dbus_unix_fd, even when :typing is specified
*dbus_unix_fd = \&Net::DBus::dbus_unix_fd;
}
$| = 1;
$SIG{PIPE} = 'IGNORE';
### Mapping tables ###
my %hf_features_mask;
{
my @hf_features_defines = qw(echo-canceling-and-noise-reduction three-way-calling cli-presentation voice-recognition volume-control enhanced-call-status enhanced-call-control codec-negotiation hf-indicators esco-s4-settings enhanced-voice-recognition-status voice-recognition-text);
my $tmp = 0b1;
%hf_features_mask = map { (($tmp <<= 1) >> 1) => $_ } @hf_features_defines;
}
my %hf_profile_features_mask;
{
my @hf_profile_features_defines = qw(echo-canceling-and-noise-reduction three-way-calling cli-presentation voice-recognition volume-control wide-band-speech enhanced-voice-recognition-status voice-recognition-text);
my $tmp = 0b1;
%hf_profile_features_mask = map { (($tmp <<= 1) >> 1) => $_ } @hf_profile_features_defines;
}
my %hf_codecs_map = (1 => 'CVSD', 2 => 'mSBC');
my %hf_indicators_map = (1 => 'enhanced-security', 2 => 'battery-level');
my $hf_indicator_battery = 2;
my %apple_features_mask;
{
my @apple_features_defines = qw(apple-battery-level apple-dock-state apple-siri-status apple-noise-reduction-status);
my $tmp = 0b10;
%apple_features_mask = map { (($tmp <<= 1) >> 1) => $_ } @apple_features_defines;
}
my %ag_indicators;
my $ag_indicator_battchg;
my $ag_indicator_call;
my $ag_indicator_callsetup;
my $ag_indicator_call_setup;
{
# Seems that Creative Labs headsets require at least "service" and "call" indicators, otherwise they drop HFP connection
my @ag_indicators_defines = (
# Indicators introduced in HF profile, version 0.6
service => '0,1', call => '0,1',
# Indicators introduced in HF profile, version 1.0
callsetup => '0-3',
# Indicators introduced in HF profile, version 1.5
callheld => '0-2', signal => '0-5', roam => '0,1', battchg => '0-5',
# Additional indicators defined in HF profile, version 1.00 Voting Draft
call_setup => '0-3',
# Additional indicators defined in ETS 300 916 - Edition 08
sounder => '0,1', message => '0,1', vox => '0,1', smsfull => '0,1',
);
for (my $i = 0; $i < $#ag_indicators_defines; $i += 2) {
$ag_indicators{$i/2+1} = { name => $ag_indicators_defines[$i], values => $ag_indicators_defines[$i+1] };
$ag_indicator_battchg = $i/2+1 if $ag_indicators_defines[$i] eq 'battchg';
$ag_indicator_call = $i/2+1 if $ag_indicators_defines[$i] eq 'call';
$ag_indicator_callsetup = $i/2+1 if $ag_indicators_defines[$i] eq 'callsetup';
$ag_indicator_call_setup = $i/2+1 if $ag_indicators_defines[$i] eq 'call_setup';
}
}
my %ag_profile_features_mask;
{
my @ag_profile_features_defines = qw(three-way-calling echo-canceling-and-noise-reduction voice-recognition in-band-ring-tone attach-voice-tag wide-band-speech);
my $tmp = 0b1;
%ag_profile_features_mask = map { (($tmp <<= 1) >> 1) => $_ } @ag_profile_features_defines;
}
### Global state ###
my $our_power_source = 'unknown';
my $our_battery_level = -1;
# bluez adapter: /org/bluez/hciX
# bluez device: /org/bluez/hciX/dev_XX_XX_XX_XX_XX_XX
# hsphfpd endpoint: /org/hsphfpd/hciX/dev_XX_XX_XX_XX_XX_XX/XXX_XX
# hsphfpd audio transport: /org/hsphfpd/hciX/dev_XX_XX_XX_XX_XX_XX/audio
# hsphfpd profile path: /org/bluez/profile/XXX_XX
# hsphfpd profile: XXX_XX
# hsphfpd application: {service, path, manager, sig1, sig2, [agents], [audios], [telephonys]}
# hsphfpd audio agent: {type=audio, path, codec}
# hsphfpd telephony agent: {type=telephony, path, role}
my %profiles; # profile => exists
my %adapters; # adapter => {address, devices => {device => exists}, codecs => {air_codec => agent_codec => exists}}
my %devices; # device => {adapter, selected_profile, profiles => {profile => endpoint}}
my %endpoints; # endpoint => {device, audio, profile, object, properties, hs_volume_control, hfp_wide_band_speech, ag_features, ag_indicators, ag_indicators_reporting, ag_call_waiting_notifications, hf_features, csr_features, apple_features, hf_codecs, csr_codecs, selected_codec, socket, rx_volume_control, tx_volume_control, rx_volume_gain, tx_volume_gain, nrec}
my %audios; # audio => {endpoint, socket, object, mtu, air_codec, agent_codec, agent_path, application_service, application_path}
my @applications; # [application]
### Main code ###
my $reactor = Net::DBus::Reactor->main();
my $bus = Net::DBus->system();
my $bus_object = $bus->get_bus_object();
$bus_object->connect_to_signal('NameOwnerChanged', \&bus_name_owner_changed);
my $hsphfpd_service = $bus->export_service('org.hsphfpd');
die "Registering org.hsphfpd on DBus failed, maybe hsphfpd is already running?\n" unless $bus->get_service_owner('org.hsphfpd') eq $bus->get_unique_name();
my $hsphfpd_manager = main::Manager->new($hsphfpd_service, '/');
main::Profile->new($hsphfpd_manager, "org/bluez/profile/$_") foreach qw(hsp_ag hsp_hs hfp_ag hfp_hf);
main::PowerSupply->new($hsphfpd_manager, 'org/hsphfpd/power_supply');
my $bluez_service = Net::DBus::RemoteService->new($bus, ($bus->get_service_owner('org.bluez') // ''), 'org.bluez');
$bus->{services}->{'org.bluez'} = $bluez_service;
my $bluez_profile_manager = $bluez_service->get_object('/org/bluez', 'org.bluez.ProfileManager1');
my $bluez_object_manager = $bluez_service->get_object('/', 'org.freedesktop.DBus.ObjectManager');
$bluez_object_manager->connect_to_signal('InterfacesAdded', \&bluez_interfaces_added);
$bluez_object_manager->connect_to_signal('InterfacesRemoved', \&bluez_interfaces_removed);
print "Creating listening SCO socket\n";
check_for_existing_sco_sockets();
my $sco_listening_socket;
# PF_BLUETOOTH => 31, SOCK_SEQPACKET => 5, BTPROTO_SCO => 2
socket $sco_listening_socket, 31, 5, 2 or die "Opening SCO listening socket failed: $!\n";
# AF_BLUETOOTH => 31, struct sockaddr_sco { sa_family_t sco_family; bdaddr_t sco_bdaddr; }, sa_family_t = uint16_t, bdaddr_t = uint8_t[6] (in reverse order)
bind $sco_listening_socket, pack 'S(H2)6', 31, reverse split /:/, "00:00:00:00:00:00" or die "Binding listening SCO socket to local address failed: $!\n";
listen $sco_listening_socket, 10 or die "Listening on SCO socket failed: $!\n";
$reactor->add_read(fileno $sco_listening_socket, sub { hsphfpd_accept_audio() });
$reactor->add_timeout(10_000, sub { check_for_existing_sco_sockets() });
# SOL_BLUETOOTH => 274, BT_DEFER_SETUP => 7, int
my $kernel_defer_support = defined $sco_listening_socket && defined setsockopt $sco_listening_socket, 274, 7, pack 'i', 1;
# SOL_BLUETOOTH => 274, BT_VOICE => 11, struct bt_voice { uint16_t setting; }
my $kernel_soft_msbc_support = $kernel_defer_support && defined getsockopt $sco_listening_socket, 274, 11;
# NOTE: kernel currently blocks usage of non-whitelisted codecs and does not provide API for using other codecs
my $kernel_anycodec_support = 0;
print "Supported codecs combination on SCO socket by kernel:\n";
if ($kernel_anycodec_support) {
print "Any combination supported by adapter\n";
} else {
print "Air codec CVSD with agent codec PCM_s16le_8kHz\n";
print "Air codec mSBC with agent codec mSBC\n" if $kernel_soft_msbc_support;
}
bluez_enumerate_objects();
$SIG{INT} = $SIG{TERM} = sub {
print "\nReceived signal, exiting...\n";
quit();
};
$reactor->run();
exit 0;
### Subroutines ###
sub quit {
exit 0 unless $reactor->{running};
if (defined $sco_listening_socket) {
print "Closing SCO listening socket\n";
$reactor->remove_read(fileno $sco_listening_socket);
close $sco_listening_socket;
undef $sco_listening_socket;
}
hsphfpd_unregister_application_i($_) foreach reverse 0..$#applications;
bluez_release_profiles();
$reactor->shutdown();
}
sub check_for_existing_sco_sockets {
# Check that there is no other software with SCO socket in listening state which can steal new SCO connections and therefore completely break hsphfpd
my $count = 0;
open my $existing_sco_sockets, '<', '/sys/kernel/debug/bluetooth/sco' or die "Cannot open file /sys/kernel/debug/bluetooth/sco: $!" . ($!{ENOENT} ? ', maybe debugfs is not mounted?' : '') . "\n";
while (<$existing_sco_sockets>) {
chomp $_;
my ($src, $dst, $state) = split /\s+/, $_;
# BT_LISTEN => 4
$count++ if $state == 4;
}
close $existing_sco_sockets;
if (defined $sco_listening_socket) {
return unless $count > 1;
print "Some other application opened listening SCO socket, exiting... maybe broken ofono was started?\n";
quit();
} else {
return unless $count > 0;
die "Listening SCO socket is already open by other application, maybe broken ofono is running?\n";
}
}
sub bus_name_owner_changed {
my ($name, $old, $new) = @_;
if ($name eq 'org.bluez') {
if ($old ne '') {
bluez_interfaces_removed($_, [ 'org.bluez.Adapter1' ]) foreach sort keys %adapters;
bluez_interfaces_removed('/org/bluez', [ 'org.bluez.ProfileManager1' ]);
}
if ($new ne '') {
$bluez_service->{owner_name} = $new;
bluez_enumerate_objects();
}
}
foreach (reverse 0..$#applications) {
next unless $applications[$_]->{service} eq $name;
hsphfpd_unregister_application_i($_);
}
}
sub throw_dbus_error {
my ($name, $message) = @_;
print "Returning DBus error $name: $message\n";
die Net::DBus::Error->new(name => $name, message => $message);
}
sub hsphfpd_register_application {
my ($caller, $path) = @_;
throw_dbus_error('org.hsphfpd.Error.InvalidArguments', qq(Invalid object path)) unless defined $path and $path =~ m{^/};
throw_dbus_error('org.hsphfpd.Error.AlreadyExists', qq(Application "$caller" "$path" is already registered)) if grep { $_->{service} eq $caller and $_->{path} eq $path } @applications;
print "Registering application $caller $path\n";
my $application = { service => $caller, path => $path, agents => [], audios => [], telephonys => [] };
my $timer_id; # postpone enumeration after register application callback finish
$timer_id = $reactor->add_timeout(0, sub {
if (not $application->{deleted}) {
$application->{manager} = Net::DBus::RemoteService->new($bus, $caller, $caller)->get_object($path, 'org.freedesktop.DBus.ObjectManager');
$application->{sigid1} = eval { $application->{manager}->connect_to_signal('InterfacesAdded', sub { hsphfpd_application_interfaces_added($application, @_) }) };
if (not defined $application->{sigid1}) {
print "Application $caller $path object manager returned error: $@";
} else {
$application->{sigid2} = eval { $application->{manager}->connect_to_signal('InterfacesRemoved', sub { hsphfpd_application_interfaces_removed($application, @_) }) };
if (not defined $application->{sigid2}) {
print "Application $caller $path object manager returned error: $@";
} else {
my $agents = eval { $application->{manager}->GetManagedObjects() };
if (not defined $agents) {
print "Application $caller $path object manager returned error: $@";
} elsif (ref $agents ne 'HASH') {
print "Application $caller $path object manager returned invalid response\n";
} else {
hsphfpd_application_interfaces_added($application, $_, $agents->{$_}) foreach sort keys %{$agents};
}
}
}
}
$reactor->remove_timeout($timer_id);
});
push @applications, $application;
return;
}
sub hsphfpd_unregister_application_i {
my ($i) = @_;
print "Unregistering application " . $applications[$i]->{service} . " " . $applications[$i]->{path} . " and all it's agents\n";
if (exists $applications[$i]->{manager}) {
eval { $applications[$i]->{manager}->disconnect_from_signal('InterfacesAdded', $applications[$i]->{sigid1}) };
eval { $applications[$i]->{manager}->disconnect_from_signal('InterfacesRemoved', $applications[$i]->{sigid2}) };
delete $applications[$i]->{manager};
}
my @audios = @{$applications[$i]->{audios}};
hsphfpd_disconnect_audio($_) foreach @audios;
my @telephonys = @{$applications[$i]->{telephonys}};
hsphfpd_disconnect_telephony($_) foreach @telephonys;
$applications[$i]->{deleted} = 1;
splice @applications, $i, 1;
if (@telephonys) {
# if we disconnected some telephony connection then estalibsh a new via other telephony agent
my $timer_id; # postpone connecting telephony agent after callback finish
$timer_id = $reactor->add_timeout(0, sub {
hsphfpd_connect_telephony($_) foreach sort keys %endpoints;
$reactor->remove_timeout($timer_id);
});
}
return;
}
sub hsphfpd_unregister_application {
my ($caller, $path) = @_;
throw_dbus_error('org.hsphfpd.Error.InvalidArguments', qq(Invalid object path)) unless defined $path and $path =~ m{^/};
foreach (0..$#applications) {
next unless $applications[$_]->{service} eq $caller and $applications[$_]->{path} eq $path;
hsphfpd_unregister_application_i($_);
return;
}
throw_dbus_error('org.hsphfpd.Error.DoesNotExist', qq(Application "$caller" "$path" is not registered));
}
sub hsphfpd_application_interfaces_added {
my ($application, $path, $interfaces) = @_;
return unless defined $path and defined $interfaces;
return unless ref $path eq '' and ref $interfaces eq 'HASH';
if (exists $interfaces->{'org.hsphfpd.AudioAgent'}) {{
last unless ref $interfaces->{'org.hsphfpd.AudioAgent'} eq 'HASH';
last unless exists $interfaces->{'org.hsphfpd.AudioAgent'}->{AgentCodec};
my $codec = $interfaces->{'org.hsphfpd.AudioAgent'}->{AgentCodec};
last unless ref $codec eq '' and $codec ne '';
last if grep { $_->{path} eq $path } @{$application->{agents}};
print "Registering application's " . $application->{service} . " " . $application->{path} . " audio agent $path for codec $codec\n";
push @{$application->{agents}}, { type => 'audio', path => $path, codec => $codec };
}}
if (exists $interfaces->{'org.hsphfpd.TelephonyAgent'}) {{
last unless ref $interfaces->{'org.hsphfpd.TelephonyAgent'} eq 'HASH';
last unless exists $interfaces->{'org.hsphfpd.TelephonyAgent'}->{Role};
my $role = $interfaces->{'org.hsphfpd.TelephonyAgent'}->{Role};
last unless ref $role eq '' and $role =~ /^(?:gateway|client)$/;
last if grep { $_->{path} eq $path } @{$application->{agents}};
print "Registering application's " . $application->{service} . " " . $application->{path} . " telephony agent $path for role $role\n";
push @{$application->{agents}}, { type => 'telephony', path => $path, role => $role };
my $timer_id; # postpone connecting telephony agent after callback finish
$timer_id = $reactor->add_timeout(0, sub {
hsphfpd_connect_telephony($_) foreach sort keys %endpoints;
$reactor->remove_timeout($timer_id);
});
}}
}
sub hsphfpd_application_interfaces_removed {
my ($application, $path, $interfaces) = @_;
return unless defined $path and defined $interfaces;
return unless ref $path eq '' and ref $interfaces eq 'ARRAY';
foreach (@{$interfaces}) {
next unless ref $_ eq '';
next unless $_ eq 'org.hsphfpd.AudioAgent' or $_ eq 'org.hsphfpd.TelephonyAgent';
foreach (0..$#{$application->{agents}}) {
next unless $application->{agents}->[$_]->{path} eq $path;
print "Unregistering application's " . $application->{service} . " " . $application->{path} . " " . $application->{agents}->[$_]->{type} . " agent $path\n";
splice @{$application->{agents}}, $_, 1;
last;
}
}
}
sub hsphfpd_get_endpoints {
return { map { $_ => { 'org.hsphfpd.Endpoint' => $endpoints{$_}->{properties} } } sort keys %endpoints };
}
sub hsphfpd_our_power_source {
my ($new_source) = @_;
return $our_power_source unless defined $new_source;
throw_dbus_error('org.hsphfpd.Error.InvalidArguments', qq(Invalid value "$new_source", it must be in "battery", "external" or "unknown")) unless $new_source =~ /^(?:battery|external|unknown)$/;
return if $our_power_source eq $new_source;
$our_power_source = $new_source;
print "Sending new power source $our_power_source\n";
foreach my $endpoint (sort keys %endpoints) {
if ($endpoints{$endpoint}->{profile} =~ /_ag$/) {
if (exists $endpoints{$endpoint}->{csr_features}->{'csr-power-source'} and $endpoints{$endpoint}->{csr_features}->{'csr-power-source'}) {
hsphfpd_csr_send_power_source($endpoint);
}
if (exists $endpoints{$endpoint}->{apple_features}->{'apple-battery-level'} and $our_power_source ne 'unknown') {
# We map external power source to docked state and battery power source to undocked state
hsphfpd_socket_write($endpoint, "AT+IPHONEACCEV=1,2," . (($our_power_source eq 'battery') ? 0 : 1));
}
}
}
}
sub hsphfpd_our_battery_level {
my ($new_level) = @_;
return $our_battery_level unless defined $new_level;
throw_dbus_error('org.hsphfpd.Error.InvalidArguments', qq(Invalid value "$new_level", it must be in range 0-100 or -1)) unless $new_level =~ /^(?:-1|[0-9]|[1-9][0-9]|100)$/;
return if $our_battery_level eq $new_level;
$our_battery_level = $new_level;
print "Sending new battery level $our_battery_level\n";
foreach my $endpoint (sort keys %endpoints) {
next unless $endpoints{$endpoint}->{properties}->{Connected}->value();
if ($endpoints{$endpoint}->{profile} =~ /_ag$/) {
if (exists $endpoints{$endpoint}->{csr_features}->{'csr-battery-level'} and $endpoints{$endpoint}->{csr_features}->{'csr-battery-level'}) {
hsphfpd_csr_send_battery_level($endpoint);
}
if (exists $endpoints{$endpoint}->{apple_features}->{'apple-battery-level'} and $our_battery_level != -1) {
hsphfpd_socket_write($endpoint, "AT+IPHONEACCEV=1,1," . int(($our_battery_level-1)/10));
}
if (exists $endpoints{$endpoint}->{hf_indicators}->{'battery-level'} and $our_battery_level != -1) {
hsphfpd_socket_write($endpoint, "AT+BIEV=$hf_indicator_battery,$our_battery_level");
}
} else {
if (exists $endpoints{$endpoint}->{ag_indicators}->{$ag_indicator_battchg} and $our_battery_level != -1) {
hsphfpd_send_ag_battchg($endpoint);
}
}
}
}
sub hsphfpd_connect_telephony {
my ($endpoint) = @_;
return unless $endpoints{$endpoint}->{properties}->{Connected}->value();
return if exists $endpoints{$endpoint}->{telephony};
print "Trying to connect some telephony agent for endpoint $endpoint\n";
my $role = $endpoints{$endpoint}->{properties}->{Role}->value();
my $properties = {
Name => $endpoints{$endpoint}->{properties}->{Name},
LocalAddress => $endpoints{$endpoint}->{properties}->{LocalAddress},
RemoteAddress => $endpoints{$endpoint}->{properties}->{RemoteAddress},
Profile => $endpoints{$endpoint}->{properties}->{Profile},
Version => $endpoints{$endpoint}->{properties}->{Version},
Features => $endpoints{$endpoint}->{properties}->{Features},
(($role eq 'client') ? (Indicators => dbus_array([ map { dbus_string($ag_indicators{$_}->{name}) } sort { $a <=> $b } keys %ag_indicators ])) : ()),
};
my $telephony;
my $connected;
my $error;
foreach (@applications) {
my $path = $_->{path};
my $service = $_->{service};
foreach (@{$_->{agents}}) {
next unless $_->{type} eq 'telephony';
next unless $_->{role} eq $role;
next if exists $_->{skip}->{$endpoint};
print "Creating new telephony socket pair\n";
# PF_UNIX => 1, SOCK_SEQPACKET = 5, PF_UNSPEC => 0, SOCK_NONBLOCK => 2048
socketpair my $socket, my $agent_socket, 1, (5 | 2048), 0 or do {
print "socketpair failed: $!\n";
print "Not trying to contant Telephony agents\n";
return;
};
print "Passing telephony socket to application's $service $path agent $_->{path}\n";
my $agent = Net::DBus::RemoteService->new($bus, $service, $service)->get_object($_->{path}, 'org.hsphfpd.TelephonyAgent');
eval { $agent->NewConnection(dbus_object_path($endpoint), dbus_unix_fd(fileno $agent_socket), $properties); $connected = 1; };
close $agent_socket;
if ($connected) {
select((select($socket), $| = 1)[0]); # enable autoflush
$telephony = { socket => $socket, application_service => $service, application_path => $path, agent_path => $_->{path} };
last;
}
shutdown $socket, 2;
close $socket;
$error = 1;
$_->{skip}->{$endpoint} = 1;
print "Agent $service $_->{path} returned error: $@";
}
push @{$_->{telephonys}}, $endpoint if $connected;
last if $connected;
}
if (not $connected) {
if ($error) {
print "All registered applications rejected telephony socket\n";
} else {
print "There is no application with telephony agent for role $role\n";
}
return;
}
$reactor->add_read(fileno $telephony->{socket}, sub { hsphfpd_telephony_ready_read($endpoint) });
$reactor->add_exception(fileno $telephony->{socket}, sub { print "Socket exception on telephony for endpoint $endpoint\n"; hsphfpd_disconnect_telephony($endpoint) });
$endpoints{$endpoint}->{telephony} = $telephony;
print "Telephony connection for endpoint $endpoint is established\n";
$endpoints{$endpoint}->{properties}->{TelephonyConnected} = dbus_boolean(1);
$endpoints{$endpoint}->{object}->emit_signal('PropertiesChanged', 'org.hsphfpd.Endpoint', { TelephonyConnected => dbus_boolean(1) }, []);
if ($role eq 'client') {
# All indicators except battchg are handled by Telephony agent
hsphfpd_telephony_write($endpoint, 'AT+BIA=' . join ',', map { ($ag_indicator_battchg != $_ and $endpoints{$endpoint}->{ag_indicators}->{$_}) ? 1 : 0 } sort { $a <=> $b } keys %ag_indicators) or return;
hsphfpd_telephony_wait_for_ok_error($endpoint);
if ($endpoints{$endpoint}->{ag_indicators_reporting}) {
hsphfpd_telephony_write($endpoint, 'AT+CMER=3,0,0,1') or return;
hsphfpd_telephony_wait_for_ok_error($endpoint);
}
if ($endpoints{$endpoint}->{ag_call_waiting_notifications}) {
hsphfpd_telephony_write($endpoint, 'AT+CCWA=1') or return;
hsphfpd_telephony_wait_for_ok_error($endpoint);
}
if ($endpoints{$endpoint}->{ag_extended_error_result_codes}) {
hsphfpd_telephony_write($endpoint, 'AT+CMEE=1') or return;
hsphfpd_telephony_wait_for_ok_error($endpoint);
}
} else {
# TODO: implement HFP AG role
}
}
sub hsphfpd_telephony_write {
my ($endpoint, $line, $raw) = @_;
print "Telephony write: endpoint=$endpoint\n";
if (not $raw) {
print "Line: $line\n";
if ($endpoints{$endpoint}->{profile} =~ /_ag$/) {
$line = "\r\n$line\r\n";
} else {
$line .= "\r";
}
}
my $socket = $endpoints{$endpoint}->{telephony}->{socket};
my $success = eval { print $socket $line };
if (not $success) {
my $error = $! ? "$!\n" : $@ ? "$@" : "unknown error\n";
print "Write error: $error";
hsphfpd_disconnect_telephony($endpoint);
}
return $success;
}
sub hsphfpd_telephony_wait_for_ok_error {
my ($endpoint) = @_;
my $fd = fileno $endpoints{$endpoint}->{telephony}->{socket};
# wait maximally 10 seconds and read maximally 20 lines
for (1..20) {
my $rfds = '';
vec($rfds, $fd, 1) = 1;
my $efds = $rfds;
my $nfound = select $rfds, undef, $efds, 10;
return 0 if $nfound <= 0 or vec $efds, $fd, 1;
my $ret = hsphfpd_telephony_ready_read($endpoint, 1);
return $ret if defined $ret;
}
return 0;
}
sub hsphfpd_telephony_ready_read {
my ($endpoint, $ok_error_no_forward) = @_;
print "Telephony ready read: endpoint=$endpoint\n";
my $is_ag = ($endpoints{$endpoint}->{profile} =~ /_ag$/ ? 1 : 0);
my $socket = $endpoints{$endpoint}->{telephony}->{socket};
while (1) { # Due to buffered read we need to process all lines before existing this function
my $origline = eval { local $/ = ($is_ag ? "\r" : "\n"); <$socket> };
if (not defined $origline) {
last if $!{EAGAIN};
my $error = $! ? "$!\n" : $@ ? "$@" : "unknown error\n";
print "Read error: $error";
hsphfpd_disconnect_telephony($endpoint);
return;
}
my $line = $origline;
$line =~ s/^\s*//;
$line =~ s/\s*$//;
if (not length $line) {
hsphfpd_socket_write($endpoint, $origline, 1) unless $ok_error_no_forward;
next;
}
print "Line: $line\n";
if ($endpoints{$endpoint}->{profile} =~ /_ag$/) {
hsphfpd_socket_write($endpoint, $origline, 1);
} else {
if ($line =~ /^\+CIND:\s*((?:[0-9]+)(?:,\s*(?1))?)$/) {
my @values = map { int($_) } split /,/, $1;
if (@values >= $ag_indicator_battchg) {
# All indicators except battchg are handled by Telephony agent
$values[$ag_indicator_battchg-1] = ($our_battery_level != -1) ? int(5 * $our_battery_level / 100 + 0.5) : 0;
}
my $new_values = join ',', @values;
hsphfpd_socket_write($endpoint, "+CIND: $new_values");
} elsif ($line =~ /^\+CIEV:\s*0*\Q$ag_indicator_battchg\E,\s*[0-9]+$/) {
# All indicators except battchg are handled by Telephony agent
hsphfpd_send_ag_battchg($endpoint) if exists $endpoints{$endpoint}->{ag_indicators}->{$ag_indicator_battchg} and $our_battery_level != -1;
} else {
if ($ok_error_no_forward) {
return 1 if $line eq 'OK';
return 0 if $line eq 'ERROR';
}
hsphfpd_socket_write($endpoint, $origline, 1);
}
}
}
return;
}
sub hsphfpd_disconnect_telephony {
my ($endpoint) = @_;
return unless exists $endpoints{$endpoint}->{telephony};
print "Disconnecting telephony agent from endpoint $endpoint\n";
my $telephony = $endpoints{$endpoint}->{telephony};
$reactor->remove_read(fileno $telephony->{socket});
$reactor->remove_exception(fileno $telephony->{socket});
shutdown $telephony->{socket}, 2;
close $telephony->{socket};
my $application_service = $telephony->{application_service};
my $application_path = $telephony->{application_path};
foreach (@applications) {
next unless exists $_->{service} and $_->{service} eq $application_service;
next unless exists $_->{path} and $_->{path} eq $application_path;
$_->{telephonys} = [ grep { $_ ne $endpoint } @{$_->{telephonys}} ];
}
delete $endpoints{$endpoint}->{telephony};
$endpoints{$endpoint}->{properties}->{TelephonyConnected} = dbus_boolean(0);
$endpoints{$endpoint}->{object}->emit_signal('PropertiesChanged', 'org.hsphfpd.Endpoint', { TelephonyConnected => dbus_boolean(0) }, []);
}
sub hsphfpd_set_sco_codec {
my ($socket, $air_codec, $agent_codec) = @_;
if ($air_codec eq 'CVSD' and $agent_codec eq 'PCM_s16le_8kHz') {
# SOL_BLUETOOTH => 274, BT_VOICE => 11, struct bt_voice { uint16_t setting; }
setsockopt $socket, 274, 11, pack 'S', 0x0060 or print "Cannot set codec on SCO socket: $!\n"; # Ignore error as CVSD is default codec
} elsif ($air_codec eq 'mSBC' and $agent_codec eq 'mSBC') {
# SOL_BLUETOOTH => 274, BT_VOICE => 11, struct bt_voice { uint16_t setting; }
setsockopt $socket, 274, 11, pack 'S', 0x0003 or return;
} else {
# TODO: add support for setting other SCO codecs via:
# SOL_BLUETOOTH => 274, BT_VOICE_SETUP => 14, ...
# But this is not implemented in kernel yet
$!{EINVAL} = 1;
return;
}
return 1;
}
sub hsphfpd_get_bluetooth_address {
my ($packed_address) = @_;
# AF_BLUETOOTH => 31, struct sockaddr_sco { sa_family_t sco_family; bdaddr_t sco_bdaddr; }, sa_family_t = uint16_t, bdaddr_t = uint8_t[6] (in reverse order)
my ($family, @address) = unpack 'S(H2)6', $packed_address;
return unless defined $family and $family == 31;
return unless @address == 6 and length $packed_address == 8;
return uc join ':', reverse @address;
}
sub hsphfpd_accept_audio {
print "Accepting new audio transport\n";
my $socket;
my $packed_remote_address = accept $socket, $sco_listening_socket;
if (not defined $packed_remote_address) {
print "Accepting new audio transport failed: $!\n";
return;
}
my $local_address = hsphfpd_get_bluetooth_address(getsockname($socket));
if (not defined $local_address) {
print "Audio transport has unknown local address, closing it\n";
shutdown $socket, 2;
close $socket;
return;
}
my $remote_address = hsphfpd_get_bluetooth_address($packed_remote_address);
if (not defined $remote_address) {
print "Audio transport has unknown remote address, closing it\n";
shutdown $socket, 2;
close $socket;
return;
}
print "Local address is $local_address and remote address is $remote_address\n";
my @candidates;
my $device;
foreach (sort keys %endpoints) {
next unless uc $endpoints{$_}->{properties}->{RemoteAddress}->value() eq uc $remote_address;
next unless uc $endpoints{$_}->{properties}->{LocalAddress}->value() eq uc $local_address;
next unless $endpoints{$_}->{properties}->{Connected}->value();
if ($endpoints{$_}->{properties}->{AudioConnected}->value()) {
print "Audio transport for device $remote_address is already in use\n";
shutdown $socket, 2;
close $socket;
return;
}
# Prefer Audio Gateway endpoints
if ($endpoints{$_}->{profile} =~ /_ag$/) {
unshift @candidates, $_;
} else {
push @candidates, $_;
}
$device = $endpoints{$_}->{device} unless defined $device;
}
if (not @candidates) {
print "Device $remote_address does not have any connected endpoint, closing audio transport\n";
shutdown $socket, 2;
close $socket;
return;
}
# Choose candidate which negotiated codec settings recently or connected recently; otherwise fallback to first candidate
my ($endpoint) = grep { $endpoints{$_}->{profile} eq $devices{$device}->{selected_profile} } @candidates;
$endpoint //= $candidates[0];
my $adapter = $devices{$endpoints{$endpoint}->{device}}->{adapter};
my $air_codec = $endpoints{$endpoint}->{selected_codec};
my $agent_codecs = $adapters{$adapter}->{codecs}->{$air_codec};
my $agent_codec;
if (not $kernel_defer_support) {
# Without defer setup, kernel already accepted SCO connection with CVSD air codec and PCM_s16le_8kHz agent codec
if ($air_codec ne 'CVSD') {
print "Selected air codec $air_codec is not supported by kernel\n";
shutdown $socket, 2;
close $socket;
return;
}
if (not grep { $_ eq 'PCM_s16le_8kHz' } map { map { ($_->{type} eq 'audio' and exists $agent_codecs->{$_->{codec}}) ? $_->{codec} : () } @{$_->{agents}} } @applications) {
print "There is no application with audio agent for agent codec PCM_s16le_8kHz\n";
shutdown $socket, 2;
close $socket;
return;
}
print "Choosing agent codec PCM_s16le_8kHz\n";
$agent_codec = 'PCM_s16le_8kHz';
if (not eval { hsphfpd_establish_audio($endpoint, $socket, $agent_codec, @applications); 1 }) {
shutdown $socket, 2;
close $socket;
return;
}
} else {
($agent_codec) = map { map { ($_->{type} eq 'audio' and exists $agent_codecs->{$_->{codec}}) ? $_->{codec} : () } @{$_->{agents}} } @applications;
if (not defined $agent_codec) {
print "There is no application with audio agent and agent codec comapatile with air codec $air_codec\n";
shutdown $socket, 2;
close $socket;
return;
}
print "Choosing agent codec $agent_codec\n";
if (not hsphfpd_set_sco_codec($socket, $air_codec, $agent_codec)) {
print "Cannot set codec on SCO socket: $!\n";
shutdown $socket, 2;
close $socket;
return;
}
# NOTE: In deferred setup, accepted SCO socket is not connected yet.
# Connecting SCO socket is done by reading non-zero buffer from socket.
# Reading from such socket is always non-blocking and always returns zero length buffer.
# When socket is really connected it is indicated by POLLOUT event.
print "Connecting SCO socket for audio transport\n";
my $buffer;
sysread $socket, $buffer, 1;
$reactor->add_exception(fileno $socket, sub {
print "Connecting SCO socket failed\n";
$reactor->remove_write(fileno $socket);
$reactor->remove_exception(fileno $socket);
shutdown $socket, 2;
close $socket;
});
$reactor->add_write(fileno $socket, sub {
print "SCO socket for audio transport is now connected\n";
$reactor->remove_write(fileno $socket);
$reactor->remove_exception(fileno $socket);
if (not eval { hsphfpd_establish_audio($endpoint, $socket, $agent_codec, @applications); 1 }) {
shutdown $socket, 2;
close $socket;
}
});
}
}
sub hsphfpd_connect_audio {
my ($endpoint, $caller, $air_codec, $agent_codec) = @_;
throw_dbus_error('org.hsphfpd.Error.InvalidArguments', qq(Endpoint "$endpoint" does not exist)) unless exists $endpoints{$endpoint};
throw_dbus_error('org.hsphfpd.Error.NotConnected', qq(Endpoint "$endpoint" is not connected yet)) unless $endpoints{$endpoint}->{properties}->{Connected}->value();
throw_dbus_error('org.hsphfpd.Error.AlreadyConnected', qq(Audio transport for endpoint "$endpoint" is already connected)) if $endpoints{$endpoint}->{properties}->{AudioConnected}->value();
throw_dbus_error('org.hsphfpd.Error.InProgress', qq(Establishing connection of audio transport for endpoint "$endpoint" is already in progress)) if exists $endpoints{$endpoint}->{audio};
my $local_address = $endpoints{$endpoint}->{properties}->{LocalAddress}->value();
my $remote_address = $endpoints{$endpoint}->{properties}->{RemoteAddress}->value();
throw_dbus_error('org.hsphfpd.Error.InUse', qq(Audio transport for device "$remote_address" is already in use)) if grep { $_ ne $endpoint and lc $endpoints{$_}->{properties}->{RemoteAddress}->value() eq lc $remote_address and exists $endpoints{$_}->{audio} } keys %endpoints;
my @sorted_applications = sort { ($a->{service} eq $caller) ? ($b->{service} eq $caller ? 0 : -1) : ($b->{service} eq $caller ? 1 : 0) } @applications;
print "Connecting audio transport for endpoint $endpoint with air_codec $air_codec and agent_codec $agent_codec\n";
my $adapter = $devices{$endpoints{$endpoint}->{device}}->{adapter};
my $endpoint_codecs = $endpoints{$endpoint}->{codecs};
my $air_codecs = $adapters{$adapter}->{codecs};
if ($air_codec ne '') {
throw_dbus_error('org.hsphfpd.Error.NotSupported', qq(Air codec "$air_codec" is not supported by endpoint)) unless exists $endpoint_codecs->{$air_codec};
throw_dbus_error('org.hsphfpd.Error.NotSupported', qq(Air codec "$air_codec" is not supported by adapter)) unless exists $air_codecs->{$air_codec};
throw_dbus_error('org.hsphfpd.Error.NotAvailable', qq(There is no application with audio agent)) unless grep { grep { $_->{type} eq 'audio' } @{$_->{agents}} } @sorted_applications;
my $agent_codecs = $air_codecs->{$air_codec};
if ($agent_codec ne '') {
throw_dbus_error('org.hsphfpd.Error.NotSupported', qq(Air codec "$air_codec" with agent codec "$agent_codec" is not supported by adapter)) unless exists $agent_codecs->{$agent_codec};
throw_dbus_error('org.hsphfpd.Error.NotAvailable', qq(There is no application with audio agent for agent codec "$agent_codec")) unless grep { grep { $_->{type} eq 'audio' and $_->{codec} eq $agent_codec } @{$_->{agents}} } @sorted_applications;
} else {
($agent_codec) = map { map { ($_->{type} eq 'audio' and exists $agent_codecs->{$_->{codec}}) ? $_->{codec} : () } @{$_->{agents}} } @sorted_applications;
throw_dbus_error('org.hsphfpd.Error.NotAvailable', qq(There is no application with audio agent and agent codec comapatile with air codec "$air_codec")) unless defined $agent_codec;
print "Choosing agent codec $agent_codec\n";
}
} else {
my %rev_air_codecs;
foreach my $rev (keys %{$air_codecs}) {
$rev_air_codecs{$_}->{$rev} = 1 foreach keys %{$air_codecs->{$rev}};
}
throw_dbus_error('org.hsphfpd.Error.NotSupported', qq(Agent codec "$agent_codec" is not supported by adapter)) unless $agent_codec eq '' or exists $rev_air_codecs{$agent_codec};
throw_dbus_error('org.hsphfpd.Error.NotAvailable', qq(There is no application with audio agent)) unless grep { grep { $_->{type} eq 'audio' } @{$_->{agents}} } @sorted_applications;
my @all_agent_codecs = map { map { ($_->{type} eq 'audio') ? $_->{codec} : () } @{$_->{agents}} } @sorted_applications;
@all_agent_codecs = grep { $_ eq $agent_codec } @all_agent_codecs if $agent_codec ne '';
$air_codec = $endpoints{$endpoint}->{selected_codec};
if ((not exists $adapters{$adapter}->{codecs}->{$air_codec}) or
($agent_codec eq '' and not grep { grep { $_->{type} eq 'audio' and exists $air_codecs->{$air_codec}->{$_->{codec}} } @{$_->{agents}} } @sorted_applications) or
(not exists $air_codecs->{$air_codec}->{$agent_codec} or not grep { grep { $_->{type} eq 'audio' and $_->{codec} eq $agent_codec } @{$_->{agents}} } @sorted_applications)) {
($air_codec) = grep { exists $endpoint_codecs->{$_} } map { exists $rev_air_codecs{$_} ? sort keys %{$rev_air_codecs{$_}} : () } @all_agent_codecs;
throw_dbus_error('org.hsphfpd.Error.NotAvailable', ($agent_codec eq '') ? qq(There is no application with audio agent for agent codec supported by adapter) : qq(There is no application with audio agent for agent codec "$agent_codec")) unless defined $air_codec;
}
print "Choosing air codec $air_codec\n";
if ($agent_codec eq '') {
($agent_codec) = grep { exists $rev_air_codecs{$_} } @all_agent_codecs;
print "Choosing agent codec $agent_codec\n";
}
}
if ($endpoints{$endpoint}->{selected_codec} ne $air_codec) {
my ($hf_codec_id) = grep { $hf_codecs_map{$_} eq $air_codec } keys %hf_codecs_map;
if (defined $hf_codec_id) {
print "Negotiating HF codec $air_codec\n";
hsphfpd_socket_write($endpoint, "+BCS: $hf_codec_id") or throw_dbus_error('org.hsphfpd.Error.Failed', 'Failed');
} else {
print "Negotiating CSR codec $air_codec\n";
my ($codec, $bandwidth);
if ($air_codec =~ /^AuriStream_2bit_/) {
$codec = 0b010;
} elsif ($air_codec =~ /^AuriStream_4bit_/) {
$codec = 0b100;
}
if ($air_codec =~ /_8kHz$/) {
$bandwidth = 0b01;
} elsif ($air_codec =~ /_16kHz$/) {
$bandwidth = 0b10;
}
throw_dbus_error('org.hsphfpd.Error.Failed', "Unknown air codec $air_codec") unless defined $codec and defined $bandwidth;
my $bandwidth_part = $endpoints{$endpoint}->{csr_bandwidths} ? ",(7,$bandwidth)" : '';
hsphfpd_socket_write($endpoint, "+CSRFN: (6,$codec)$bandwidth_part") or throw_dbus_error('org.hsphfpd.Error.Failed', 'Failed');
}
$endpoints{$endpoint}->{codec_negotiation} = 1;
my $success = hsphfpd_socket_wait_for_ok_error($endpoint);
$endpoints{$endpoint}->{codec_negotiation} = 0;
throw_dbus_error('org.hsphfpd.Error.Failed', qq(Codec connection setup for "$air_codec" failed)) unless $success and $endpoints{$endpoint}->{selected_codec} eq $air_codec;
}
if ($endpoints{$endpoint}->{profile} eq 'hfp_ag' and exists $endpoints{$endpoint}->{hf_features}->{'codec-negotiation'}) {
# TODO: implement HFP AG role and establish audio connection via AT+BCC
}
print "Creating SCO socket\n";
my $socket;
# PF_BLUETOOTH => 31, SOCK_SEQPACKET => 5, BTPROTO_SCO => 2
socket $socket, 31, 5, 2 or throw_dbus_error('org.hsphfpd.Error.Failed', qq(Opening SCO socket failed: $!));
# AF_BLUETOOTH => 31, struct sockaddr_sco { sa_family_t sco_family; bdaddr_t sco_bdaddr; }, sa_family_t = uint16_t, bdaddr_t = uint8_t[6] (in reverse order)
bind $socket, pack 'S(H2)6', 31, reverse split /:/, $local_address or throw_dbus_error('org.hsphfpd.Error.Failed', qq(Binding SCO socket to adapter "$local_address" failed: $!));
hsphfpd_set_sco_codec($socket, $air_codec, $agent_codec) or throw_dbus_error('org.hsphfpd.Error.Failed', qq(Setting air codec to "$air_codec" and agent codec to "$agent_codec" on SCO socket failed: $!));
connect $socket, pack 'S(H2)6', 31, reverse split /:/, $remote_address or throw_dbus_error('org.hsphfpd.Error.Failed', qq(Connecting SCO socket to device "$remote_address" failed: $!));
return hsphfpd_establish_audio($endpoint, $socket, $agent_codec, @sorted_applications);
}
sub hsphfpd_establish_audio {
my ($endpoint, $socket, $agent_codec, @sorted_applications) = @_;
my $mtu;
# SOL_SCO => 17, SCO_OPTIONS => 1, struct sco_options { uint16_t mtu; }
my $value = getsockopt $socket, 17, 1;
if (defined $value and length $value >= 2) {
$mtu = unpack 'S', $value;
} else {
print "Reading MTU of SCO socket failed: $!\n";
$mtu = 48;
}
my $air_codec = $endpoints{$endpoint}->{selected_codec};
my $audio = $endpoint;
$audio =~ s{/[^/]*$}{/audio};
my $hsphfpd_manager_path = $hsphfpd_manager->get_object_path();
my $audio_suffix = $audio;
$audio_suffix =~ s/^\Q$hsphfpd_manager_path\E//;
{
local %Net::DBus::Exporter::dbus_introspectors;
$endpoints{$endpoint}->{audio} = $audio;
$audios{$audio} = { endpoint => $endpoint, socket => $socket, mtu => $mtu, air_codec => $air_codec, agent_codec => $agent_codec };
$audios{$audio}->{object} = main::Audio->new($hsphfpd_manager, $audio_suffix);
$audios{$audio}->{object}->_introspector() if $audios{$audio}->{object}->can('_introspector');
delete $audios{$audio}->{object}->{introspector}->{interfaces}->{'org.hsphfpd.AudioTransport'}->{props}->{NREC} unless exists $endpoints{$endpoint}->{nrec};
$reactor->add_exception(fileno $socket, sub { print "Socket exception on audio transport $audio\n"; hsphfpd_disconnect_audio($audio) });
}
print "Audio transport $audio created\n";
my $properties = {
RxVolumeControl => dbus_string($endpoints{$endpoint}->{rx_volume_control}),
($endpoints{$endpoint}->{rx_volume_control} ne 'none') ? (
RxVolumeGain => dbus_uint16($endpoints{$endpoint}->{rx_volume_gain}),
) : (),
TxVolumeControl => dbus_string($endpoints{$endpoint}->{tx_volume_control}),
($endpoints{$endpoint}->{tx_volume_control} ne 'none') ? (
TxVolumeGain => dbus_uint16($endpoints{$endpoint}->{tx_volume_gain}),
) : (),
(exists $endpoints{$endpoint}->{nrec}) ? (
NREC => dbus_boolean($endpoints{$endpoint}->{nrec}),
) : (),
MTU => dbus_uint16($mtu),
Endpoint => dbus_object_path($endpoint),
Name => $endpoints{$endpoint}->{properties}->{Name},
LocalAddress => $endpoints{$endpoint}->{properties}->{LocalAddress},
RemoteAddress => $endpoints{$endpoint}->{properties}->{RemoteAddress},
Profile => $endpoints{$endpoint}->{properties}->{Profile},
Version => $endpoints{$endpoint}->{properties}->{Version},
Role => $endpoints{$endpoint}->{properties}->{Role},
AirCodec => dbus_string($air_codec),
};
my $connected;
my $canceled;
my $error;
foreach (@sorted_applications) {
my $path = $_->{path};
my $service = $_->{service};
foreach (@{$_->{agents}}) {
next unless $_->{type} eq 'audio';
next unless $_->{codec} eq $agent_codec;