a2dp: Handle remote SEP disappearing
[platform/upstream/bluez.git] / profiles / audio / a2dp.c
1 /*
2  *
3  *  BlueZ - Bluetooth protocol stack for Linux
4  *
5  *  Copyright (C) 2006-2010  Nokia Corporation
6  *  Copyright (C) 2004-2010  Marcel Holtmann <marcel@holtmann.org>
7  *  Copyright (C) 2011  BMW Car IT GmbH. All rights reserved.
8  *
9  *
10  *  This program is free software; you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License as published by
12  *  the Free Software Foundation; either version 2 of the License, or
13  *  (at your option) any later version.
14  *
15  *  This program is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *  GNU General Public License for more details.
19  *
20  *  You should have received a copy of the GNU General Public License
21  *  along with this program; if not, write to the Free Software
22  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
23  *
24  */
25
26 #ifdef HAVE_CONFIG_H
27 #include <config.h>
28 #endif
29
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <errno.h>
33
34 #include <dbus/dbus.h>
35 #include <glib.h>
36
37 #include "lib/bluetooth.h"
38 #include "lib/sdp.h"
39 #include "lib/sdp_lib.h"
40 #include "lib/uuid.h"
41
42 #include "gdbus/gdbus.h"
43
44 #include "src/hcid.h"
45 #include "src/plugin.h"
46 #include "src/adapter.h"
47 #include "src/device.h"
48 #include "src/dbus-common.h"
49 #include "src/error.h"
50 #include "src/profile.h"
51 #include "src/service.h"
52 #include "src/log.h"
53 #include "src/sdpd.h"
54 #include "src/shared/queue.h"
55 #include "src/shared/util.h"
56
57 #include "btio/btio.h"
58
59 #include "avdtp.h"
60 #include "sink.h"
61 #include "source.h"
62 #include "a2dp.h"
63 #include "a2dp-codecs.h"
64 #include "media.h"
65
66 /* The duration that streams without users are allowed to stay in
67  * STREAMING state. */
68 #define SUSPEND_TIMEOUT 5
69 #define RECONFIGURE_TIMEOUT 500
70
71 #define AVDTP_PSM 25
72 #define MEDIA_ENDPOINT_INTERFACE "org.bluez.MediaEndpoint1"
73
74 #ifdef TIZEN_FEATURE_BLUEZ_MODIFY
75 #ifdef TIZEN_FEATURE_SSC_ENCODER
76 /* Vendor and Codec ID for Samsung Scalable codec */
77 #define PREFRED_VENDOR_ID       0x00000075
78 #define PREFRED_CODEC_ID        0x0103
79 #endif
80 #endif
81
82 struct a2dp_sep {
83         struct a2dp_server *server;
84         struct a2dp_endpoint *endpoint;
85         uint8_t type;
86         uint8_t codec;
87         struct avdtp_local_sep *lsep;
88         struct avdtp *session;
89         struct avdtp_stream *stream;
90         guint suspend_timer;
91 #ifdef TIZEN_FEATURE_BLUEZ_MODIFY
92         gboolean remote_suspended;
93 #endif
94         gboolean delay_reporting;
95         gboolean locked;
96         gboolean suspending;
97         gboolean starting;
98         void *user_data;
99         GDestroyNotify destroy;
100 };
101
102 struct a2dp_setup_cb {
103         struct a2dp_setup *setup;
104         a2dp_discover_cb_t discover_cb;
105         a2dp_select_cb_t select_cb;
106         a2dp_config_cb_t config_cb;
107         a2dp_stream_cb_t resume_cb;
108         a2dp_stream_cb_t suspend_cb;
109         guint source_id;
110         void *user_data;
111         unsigned int id;
112 };
113
114 struct a2dp_setup {
115         struct a2dp_channel *chan;
116         struct avdtp *session;
117         struct queue *eps;
118         struct a2dp_sep *sep;
119         struct a2dp_remote_sep *rsep;
120         struct avdtp_stream *stream;
121         struct avdtp_error *err;
122         avdtp_set_configuration_cb setconf_cb;
123         GSList *seps;
124         GSList *caps;
125         gboolean reconfigure;
126         gboolean start;
127         GSList *cb;
128         GIOChannel *io;
129         int ref;
130 };
131
132 struct a2dp_server {
133         struct btd_adapter *adapter;
134         GSList *sinks;
135         GSList *sources;
136         uint32_t source_record_id;
137         uint32_t sink_record_id;
138         gboolean sink_enabled;
139         gboolean source_enabled;
140         GIOChannel *io;
141         struct queue *seps;
142         struct queue *channels;
143 };
144
145 struct a2dp_remote_sep {
146         struct a2dp_channel *chan;
147         char *path;
148         struct avdtp_remote_sep *sep;
149 };
150
151 struct a2dp_last_used {
152         struct a2dp_sep *lsep;
153         struct a2dp_remote_sep *rsep;
154 };
155
156 struct a2dp_channel {
157         struct a2dp_server *server;
158         struct btd_device *device;
159         GIOChannel *io;
160         guint io_id;
161         unsigned int state_id;
162         unsigned int auth_id;
163         struct avdtp *session;
164         struct queue *seps;
165         struct a2dp_last_used *last_used;
166 };
167
168 static GSList *servers = NULL;
169 static GSList *setups = NULL;
170 static unsigned int cb_id = 0;
171
172 static struct a2dp_setup *setup_ref(struct a2dp_setup *setup)
173 {
174         setup->ref++;
175
176         DBG("%p: ref=%d", setup, setup->ref);
177
178         return setup;
179 }
180
181 static bool match_by_session(const void *data, const void *user_data)
182 {
183         const struct a2dp_channel *chan = data;
184         const struct avdtp *session = user_data;
185
186         return chan->session == session;
187 }
188
189 static struct a2dp_channel *find_channel(struct avdtp *session)
190 {
191         GSList *l;
192
193         for (l = servers; l; l = g_slist_next(l)) {
194                 struct a2dp_server *server = l->data;
195                 struct a2dp_channel *chan;
196
197                 chan = queue_find(server->channels, match_by_session, session);
198                 if (chan)
199                         return chan;
200         }
201
202         return NULL;
203 }
204
205 static struct a2dp_setup *setup_new(struct avdtp *session)
206 {
207         struct a2dp_setup *setup;
208         struct a2dp_channel *chan;
209
210         chan = find_channel(session);
211         if (!chan)
212                 return NULL;
213
214         setup = g_new0(struct a2dp_setup, 1);
215         setup->session = avdtp_ref(session);
216         setup->chan = find_channel(session);
217         setups = g_slist_append(setups, setup);
218
219         return setup;
220 }
221
222 static void setup_free(struct a2dp_setup *s)
223 {
224         DBG("%p", s);
225
226         if (s->io) {
227                 g_io_channel_shutdown(s->io, TRUE, NULL);
228                 g_io_channel_unref(s->io);
229         }
230
231         queue_destroy(s->eps, NULL);
232
233         setups = g_slist_remove(setups, s);
234         if (s->session)
235                 avdtp_unref(s->session);
236         g_slist_free_full(s->cb, g_free);
237         g_slist_free_full(s->caps, g_free);
238         g_free(s);
239 }
240
241 static void setup_unref(struct a2dp_setup *setup)
242 {
243         setup->ref--;
244
245         DBG("%p: ref=%d", setup, setup->ref);
246
247         if (setup->ref > 0)
248                 return;
249
250         setup_free(setup);
251 }
252
253 static struct a2dp_setup_cb *setup_cb_new(struct a2dp_setup *setup)
254 {
255         struct a2dp_setup_cb *cb;
256
257         cb = g_new0(struct a2dp_setup_cb, 1);
258         cb->setup = setup;
259         cb->id = ++cb_id;
260
261         setup->cb = g_slist_append(setup->cb, cb);
262         return cb;
263 }
264
265 static void setup_cb_free(struct a2dp_setup_cb *cb)
266 {
267         struct a2dp_setup *setup = cb->setup;
268
269         if (cb->source_id)
270                 g_source_remove(cb->source_id);
271
272         setup->cb = g_slist_remove(setup->cb, cb);
273         setup_unref(cb->setup);
274         g_free(cb);
275 }
276
277 static void finalize_setup_errno(struct a2dp_setup *s, int err,
278                                         GSourceFunc cb1, ...)
279 {
280         GSourceFunc finalize;
281         va_list args;
282 #ifdef TIZEN_FEATURE_BLUEZ_MODIFY
283         struct avdtp_error *avdtp_err;
284 #else
285         struct avdtp_error avdtp_err;
286 #endif
287
288         if (err < 0) {
289 #ifdef TIZEN_FEATURE_BLUEZ_MODIFY
290                 avdtp_err = g_new(struct avdtp_error, 1);
291                 avdtp_error_init(avdtp_err, AVDTP_ERRNO, -err);
292                 s->err = avdtp_err;
293 #else
294                 avdtp_error_init(&avdtp_err, AVDTP_ERRNO, -err);
295                 s->err = &avdtp_err;
296 #endif
297         }
298
299         va_start(args, cb1);
300         finalize = cb1;
301         setup_ref(s);
302         while (finalize != NULL) {
303                 finalize(s);
304                 finalize = va_arg(args, GSourceFunc);
305         }
306         setup_unref(s);
307         va_end(args);
308 }
309
310 static int error_to_errno(struct avdtp_error *err)
311 {
312         int perr;
313
314         if (!err)
315                 return 0;
316
317         if (avdtp_error_category(err) != AVDTP_ERRNO)
318                 return -EIO;
319
320         perr = avdtp_error_posix_errno(err);
321         switch (perr) {
322         case EHOSTDOWN:
323         case ECONNABORTED:
324                 return -perr;
325         default:
326                 /*
327                  * An unexpect error has occurred setup may be attempted again.
328                  */
329                 return -EAGAIN;
330         }
331 }
332
333 static gboolean finalize_config(gpointer data)
334 {
335         struct a2dp_setup *s = data;
336         GSList *l;
337         struct avdtp_stream *stream = s->err ? NULL : s->stream;
338
339         for (l = s->cb; l != NULL; ) {
340                 struct a2dp_setup_cb *cb = l->data;
341
342                 l = l->next;
343
344                 if (!cb->config_cb)
345                         continue;
346
347                 cb->config_cb(s->session, s->sep, stream,
348                                 error_to_errno(s->err), cb->user_data);
349                 setup_cb_free(cb);
350         }
351
352         return FALSE;
353 }
354
355 static gboolean finalize_resume(gpointer data)
356 {
357         struct a2dp_setup *s = data;
358         GSList *l;
359
360         for (l = s->cb; l != NULL; ) {
361                 struct a2dp_setup_cb *cb = l->data;
362
363                 l = l->next;
364
365                 if (!cb->resume_cb)
366                         continue;
367
368                 cb->resume_cb(s->session, error_to_errno(s->err),
369                                                         cb->user_data);
370                 setup_cb_free(cb);
371         }
372
373         return FALSE;
374 }
375
376 static gboolean finalize_suspend(gpointer data)
377 {
378         struct a2dp_setup *s = data;
379         GSList *l;
380
381         for (l = s->cb; l != NULL; ) {
382                 struct a2dp_setup_cb *cb = l->data;
383
384                 l = l->next;
385
386                 if (!cb->suspend_cb)
387                         continue;
388
389                 cb->suspend_cb(s->session, error_to_errno(s->err),
390                                                         cb->user_data);
391                 setup_cb_free(cb);
392         }
393
394         return FALSE;
395 }
396
397 static void finalize_select(struct a2dp_setup *s)
398 {
399         GSList *l;
400
401         for (l = s->cb; l != NULL; ) {
402                 struct a2dp_setup_cb *cb = l->data;
403
404                 l = l->next;
405
406                 if (!cb->select_cb)
407                         continue;
408
409                 cb->select_cb(s->session, s->sep, s->caps, cb->user_data);
410                 setup_cb_free(cb);
411         }
412 }
413
414 static void finalize_discover(struct a2dp_setup *s)
415 {
416         GSList *l;
417
418         for (l = s->cb; l != NULL; ) {
419                 struct a2dp_setup_cb *cb = l->data;
420
421                 l = l->next;
422
423                 if (!cb->discover_cb)
424                         continue;
425
426                 cb->discover_cb(s->session, s->seps, error_to_errno(s->err),
427                                                                 cb->user_data);
428                 setup_cb_free(cb);
429         }
430 }
431
432 static struct a2dp_setup *find_setup_by_session(struct avdtp *session)
433 {
434         GSList *l;
435
436         for (l = setups; l != NULL; l = l->next) {
437                 struct a2dp_setup *setup = l->data;
438
439                 if (setup->session == session)
440                         return setup;
441         }
442
443         return NULL;
444 }
445
446 static struct a2dp_setup *a2dp_setup_get(struct avdtp *session)
447 {
448         struct a2dp_setup *setup;
449
450         setup = find_setup_by_session(session);
451         if (!setup) {
452                 setup = setup_new(session);
453                 if (!setup)
454                         return NULL;
455         }
456
457         return setup_ref(setup);
458 }
459
460 static struct a2dp_setup *find_setup_by_stream(struct avdtp_stream *stream)
461 {
462         GSList *l;
463
464         for (l = setups; l != NULL; l = l->next) {
465                 struct a2dp_setup *setup = l->data;
466
467                 if (setup->stream == stream)
468                         return setup;
469         }
470
471         return NULL;
472 }
473
474 static void stream_state_changed(struct avdtp_stream *stream,
475                                         avdtp_state_t old_state,
476                                         avdtp_state_t new_state,
477                                         struct avdtp_error *err,
478                                         void *user_data)
479 {
480         struct a2dp_sep *sep = user_data;
481
482         if (new_state == AVDTP_STATE_OPEN) {
483                 struct a2dp_setup *setup;
484                 int err;
485
486                 setup = find_setup_by_stream(stream);
487                 if (!setup || !setup->start)
488                         return;
489
490                 setup->start = FALSE;
491
492                 err = avdtp_start(setup->session, stream);
493                 if (err < 0 && err != -EINPROGRESS) {
494                         error("avdtp_start: %s (%d)", strerror(-err), -err);
495                         finalize_setup_errno(setup, err, finalize_resume,
496                                                                         NULL);
497                         return;
498                 }
499
500                 sep->starting = TRUE;
501
502                 return;
503         }
504
505 #ifdef TIZEN_FEATURE_BLUEZ_MODIFY
506         if (new_state == AVDTP_STATE_STREAMING && sep->suspend_timer) {
507                 g_source_remove(sep->suspend_timer);
508                 sep->suspend_timer = 0;
509         }
510 #endif
511
512         if (new_state != AVDTP_STATE_IDLE)
513                 return;
514
515         if (sep->suspend_timer) {
516                 g_source_remove(sep->suspend_timer);
517                 sep->suspend_timer = 0;
518         }
519
520         if (sep->session) {
521                 avdtp_unref(sep->session);
522                 sep->session = NULL;
523         }
524
525         sep->stream = NULL;
526
527         if (sep->endpoint && sep->endpoint->clear_configuration)
528                 sep->endpoint->clear_configuration(sep, sep->user_data);
529 }
530
531 static gboolean auto_config(gpointer data)
532 {
533         struct a2dp_setup *setup = data;
534         struct btd_device *dev = NULL;
535         struct btd_service *service;
536
537         /* Check if configuration was aborted */
538         if (setup->sep->stream == NULL)
539                 return FALSE;
540
541         if (setup->err != NULL)
542                 goto done;
543
544         dev = avdtp_get_device(setup->session);
545
546         avdtp_stream_add_cb(setup->session, setup->stream,
547                                 stream_state_changed, setup->sep);
548
549         if (setup->sep->type == AVDTP_SEP_TYPE_SOURCE) {
550                 service = btd_device_get_service(dev, A2DP_SINK_UUID);
551                 sink_new_stream(service, setup->session, setup->stream);
552         } else {
553                 service = btd_device_get_service(dev, A2DP_SOURCE_UUID);
554                 source_new_stream(service, setup->session, setup->stream);
555         }
556
557 done:
558         if (setup->setconf_cb)
559                 setup->setconf_cb(setup->session, setup->stream, setup->err);
560
561         finalize_config(setup);
562
563         if (setup->err) {
564                 g_free(setup->err);
565                 setup->err = NULL;
566         }
567
568         setup_unref(setup);
569
570         return FALSE;
571 }
572
573 static void endpoint_setconf_cb(struct a2dp_setup *setup, gboolean ret)
574 {
575         if (ret == FALSE) {
576                 setup->err = g_new(struct avdtp_error, 1);
577                 avdtp_error_init(setup->err, AVDTP_MEDIA_CODEC,
578                                         AVDTP_UNSUPPORTED_CONFIGURATION);
579         }
580
581         auto_config(setup);
582         setup_unref(setup);
583 }
584
585 #ifdef TIZEN_FEATURE_BLUEZ_MODIFY
586 #ifdef TIZEN_FEATURE_SSC_ENCODER
587 static gboolean endpoint_match_codec_preference(struct avdtp *session,
588                 struct avdtp_media_codec_capability *codec,
589                 void *user_data)
590 {
591         struct a2dp_sep *sep = user_data;
592         uint8_t *capabilities;
593         a2dp_vendor_codec_t *local_codec;
594         size_t length;
595
596         length = sep->endpoint->get_capabilities(sep, &capabilities,
597                         sep->user_data);
598         if (length < sizeof(a2dp_vendor_codec_t))
599                 return FALSE;
600
601         local_codec = (a2dp_vendor_codec_t *) capabilities;
602         DBG("vendor 0x%08x codec 0x%04x", btohl(local_codec->vendor_id),
603                         btohs(local_codec->codec_id));
604         if (btohl(local_codec->vendor_id) == PREFRED_VENDOR_ID &&
605                         btohs(local_codec->codec_id) == PREFRED_CODEC_ID) {
606                 DBG("Samsung Scalable Codec Selected");
607                 return TRUE;
608         }
609         return FALSE;
610 }
611 #endif
612 #endif
613
614 static gboolean endpoint_match_codec_ind(struct avdtp *session,
615                                 struct avdtp_media_codec_capability *codec,
616                                 void *user_data)
617 {
618         struct a2dp_sep *sep = user_data;
619         a2dp_vendor_codec_t *remote_codec;
620         a2dp_vendor_codec_t *local_codec;
621         uint8_t *capabilities;
622         size_t length;
623
624         if (codec->media_codec_type != A2DP_CODEC_VENDOR)
625                 return TRUE;
626
627         if (sep->endpoint == NULL)
628                 return FALSE;
629
630         length = sep->endpoint->get_capabilities(sep, &capabilities,
631                                                         sep->user_data);
632         if (length < sizeof(a2dp_vendor_codec_t))
633                 return FALSE;
634
635         local_codec = (a2dp_vendor_codec_t *) capabilities;
636         remote_codec = (a2dp_vendor_codec_t *) codec->data;
637
638         if (A2DP_GET_VENDOR_ID(*remote_codec) !=
639                         A2DP_GET_VENDOR_ID(*local_codec))
640                 return FALSE;
641
642         if (A2DP_GET_CODEC_ID(*remote_codec) != A2DP_GET_CODEC_ID(*local_codec))
643                 return FALSE;
644
645         DBG("vendor 0x%08x codec 0x%04x", A2DP_GET_VENDOR_ID(*remote_codec),
646                                         A2DP_GET_CODEC_ID(*remote_codec));
647         return TRUE;
648 }
649
650 static void reverse_discover(struct avdtp *session, GSList *seps, int err,
651                                                         void *user_data)
652 {
653         DBG("err %d", err);
654 }
655
656 static gboolean endpoint_setconf_ind(struct avdtp *session,
657                                                 struct avdtp_local_sep *sep,
658                                                 struct avdtp_stream *stream,
659                                                 GSList *caps,
660                                                 avdtp_set_configuration_cb cb,
661                                                 void *user_data)
662 {
663         struct a2dp_sep *a2dp_sep = user_data;
664         struct a2dp_setup *setup;
665
666         if (a2dp_sep->type == AVDTP_SEP_TYPE_SINK)
667                 DBG("Sink %p: Set_Configuration_Ind", sep);
668         else
669                 DBG("Source %p: Set_Configuration_Ind", sep);
670
671         setup = a2dp_setup_get(session);
672         if (!session)
673                 return FALSE;
674
675         a2dp_sep->stream = stream;
676         setup->sep = a2dp_sep;
677         setup->stream = stream;
678         setup->setconf_cb = cb;
679
680         for (; caps != NULL; caps = g_slist_next(caps)) {
681                 struct avdtp_service_capability *cap = caps->data;
682                 struct avdtp_media_codec_capability *codec;
683                 gboolean ret;
684
685                 if (cap->category == AVDTP_DELAY_REPORTING &&
686                                         !a2dp_sep->delay_reporting) {
687                         setup->err = g_new(struct avdtp_error, 1);
688                         avdtp_error_init(setup->err, AVDTP_DELAY_REPORTING,
689                                         AVDTP_UNSUPPORTED_CONFIGURATION);
690                         goto done;
691                 }
692
693                 if (cap->category != AVDTP_MEDIA_CODEC)
694                         continue;
695
696                 codec = (struct avdtp_media_codec_capability *) cap->data;
697
698                 if (codec->media_codec_type != a2dp_sep->codec) {
699                         setup->err = g_new(struct avdtp_error, 1);
700                         avdtp_error_init(setup->err, AVDTP_MEDIA_CODEC,
701                                         AVDTP_UNSUPPORTED_CONFIGURATION);
702                         goto done;
703                 }
704
705                 ret = a2dp_sep->endpoint->set_configuration(a2dp_sep,
706                                                 codec->data,
707                                                 cap->length - sizeof(*codec),
708                                                 setup_ref(setup),
709                                                 endpoint_setconf_cb,
710                                                 a2dp_sep->user_data);
711                 if (ret == 0) {
712                         /* Attempt to reverse discover if there are no remote
713                          * SEPs.
714                          */
715                         if (queue_isempty(setup->chan->seps))
716                                 a2dp_discover(session, reverse_discover, NULL);
717                         return TRUE;
718                 }
719
720                 setup_unref(setup);
721                 setup->err = g_new(struct avdtp_error, 1);
722                 avdtp_error_init(setup->err, AVDTP_MEDIA_CODEC,
723                                         AVDTP_UNSUPPORTED_CONFIGURATION);
724                 break;
725         }
726
727 done:
728         g_idle_add(auto_config, setup);
729         return TRUE;
730 }
731
732 static gboolean endpoint_getcap_ind(struct avdtp *session,
733                                         struct avdtp_local_sep *sep,
734                                         gboolean get_all, GSList **caps,
735                                         uint8_t *err, void *user_data)
736 {
737         struct a2dp_sep *a2dp_sep = user_data;
738         struct avdtp_service_capability *media_transport, *media_codec;
739         struct avdtp_media_codec_capability *codec_caps;
740         uint8_t *capabilities;
741         size_t length;
742
743         if (a2dp_sep->type == AVDTP_SEP_TYPE_SINK)
744                 DBG("Sink %p: Get_Capability_Ind", sep);
745         else
746                 DBG("Source %p: Get_Capability_Ind", sep);
747
748         *caps = NULL;
749
750         media_transport = avdtp_service_cap_new(AVDTP_MEDIA_TRANSPORT,
751                                                 NULL, 0);
752
753         *caps = g_slist_append(*caps, media_transport);
754
755         length = a2dp_sep->endpoint->get_capabilities(a2dp_sep, &capabilities,
756                                                         a2dp_sep->user_data);
757
758         codec_caps = g_malloc0(sizeof(*codec_caps) + length);
759         codec_caps->media_type = AVDTP_MEDIA_TYPE_AUDIO;
760         codec_caps->media_codec_type = a2dp_sep->codec;
761         memcpy(codec_caps->data, capabilities, length);
762
763         media_codec = avdtp_service_cap_new(AVDTP_MEDIA_CODEC, codec_caps,
764                                                 sizeof(*codec_caps) + length);
765
766         *caps = g_slist_append(*caps, media_codec);
767         g_free(codec_caps);
768
769         if (get_all) {
770                 struct avdtp_service_capability *delay_reporting;
771                 delay_reporting = avdtp_service_cap_new(AVDTP_DELAY_REPORTING,
772                                                                 NULL, 0);
773                 *caps = g_slist_append(*caps, delay_reporting);
774         }
775
776         return TRUE;
777 }
778
779 static void endpoint_open_cb(struct a2dp_setup *setup, gboolean ret)
780 {
781         int err;
782
783         if (ret == FALSE) {
784                 setup->stream = NULL;
785                 finalize_setup_errno(setup, -EPERM, finalize_config, NULL);
786                 goto done;
787         }
788
789         err = avdtp_open(setup->session, setup->stream);
790         if (err == 0)
791                 goto done;
792
793         error("avdtp_open %s (%d)", strerror(-err), -err);
794         setup->stream = NULL;
795         finalize_setup_errno(setup, err, finalize_config, NULL);
796 done:
797         setup_unref(setup);
798 }
799
800 static void setconf_cfm(struct avdtp *session, struct avdtp_local_sep *sep,
801                                 struct avdtp_stream *stream,
802                                 struct avdtp_error *err, void *user_data)
803 {
804         struct a2dp_sep *a2dp_sep = user_data;
805         struct a2dp_setup *setup;
806         struct btd_device *dev;
807         struct btd_service *service;
808         int ret;
809
810         if (a2dp_sep->type == AVDTP_SEP_TYPE_SINK)
811                 DBG("Sink %p: Set_Configuration_Cfm", sep);
812         else
813                 DBG("Source %p: Set_Configuration_Cfm", sep);
814
815         setup = find_setup_by_session(session);
816
817         if (err) {
818                 if (setup) {
819                         setup_ref(setup);
820                         setup->err = err;
821                         finalize_config(setup);
822                         setup->err = NULL;
823                         setup_unref(setup);
824                 }
825                 return;
826         }
827
828         avdtp_stream_add_cb(session, stream, stream_state_changed, a2dp_sep);
829         a2dp_sep->stream = stream;
830
831         if (!setup)
832                 return;
833
834         dev = avdtp_get_device(session);
835
836         /* Notify D-Bus interface of the new stream */
837         if (a2dp_sep->type == AVDTP_SEP_TYPE_SOURCE) {
838                 service = btd_device_get_service(dev, A2DP_SINK_UUID);
839                 sink_new_stream(service, session, setup->stream);
840         } else {
841                 service = btd_device_get_service(dev, A2DP_SOURCE_UUID);
842                 source_new_stream(service, session, setup->stream);
843         }
844
845         /* Notify Endpoint */
846         if (a2dp_sep->endpoint) {
847                 struct avdtp_service_capability *service;
848                 struct avdtp_media_codec_capability *codec;
849                 int err;
850
851                 service = avdtp_stream_get_codec(stream);
852                 codec = (struct avdtp_media_codec_capability *) service->data;
853
854                 err = a2dp_sep->endpoint->set_configuration(a2dp_sep,
855                                                 codec->data, service->length -
856                                                 sizeof(*codec),
857                                                 setup_ref(setup),
858                                                 endpoint_open_cb,
859                                                 a2dp_sep->user_data);
860                 if (err == 0)
861                         return;
862
863                 setup->stream = NULL;
864                 finalize_setup_errno(setup, -EPERM, finalize_config, NULL);
865                 setup_unref(setup);
866                 return;
867         }
868
869         ret = avdtp_open(session, stream);
870         if (ret < 0) {
871                 error("avdtp_open %s (%d)", strerror(-ret), -ret);
872                 setup->stream = NULL;
873                 finalize_setup_errno(setup, ret, finalize_config, NULL);
874         }
875 }
876
877 static gboolean getconf_ind(struct avdtp *session, struct avdtp_local_sep *sep,
878                                 uint8_t *err, void *user_data)
879 {
880         struct a2dp_sep *a2dp_sep = user_data;
881
882         if (a2dp_sep->type == AVDTP_SEP_TYPE_SINK)
883                 DBG("Sink %p: Get_Configuration_Ind", sep);
884         else
885                 DBG("Source %p: Get_Configuration_Ind", sep);
886         return TRUE;
887 }
888
889 static void getconf_cfm(struct avdtp *session, struct avdtp_local_sep *sep,
890                         struct avdtp_stream *stream, struct avdtp_error *err,
891                         void *user_data)
892 {
893         struct a2dp_sep *a2dp_sep = user_data;
894
895         if (a2dp_sep->type == AVDTP_SEP_TYPE_SINK)
896                 DBG("Sink %p: Set_Configuration_Cfm", sep);
897         else
898                 DBG("Source %p: Set_Configuration_Cfm", sep);
899 }
900
901 static bool match_remote_sep(const void *data, const void *user_data)
902 {
903         const struct a2dp_remote_sep *sep = data;
904         const struct avdtp_remote_sep *rsep = user_data;
905
906         return sep->sep == rsep;
907 }
908
909 static void store_last_used(struct a2dp_channel *chan, uint8_t lseid,
910                                                         uint8_t rseid)
911 {
912         GKeyFile *key_file;
913         char filename[PATH_MAX];
914         char dst_addr[18];
915         char value[6];
916         char *data;
917         size_t len = 0;
918
919         ba2str(device_get_address(chan->device), dst_addr);
920
921         snprintf(filename, PATH_MAX, STORAGEDIR "/%s/cache/%s",
922                 btd_adapter_get_storage_dir(device_get_adapter(chan->device)),
923                 dst_addr);
924         key_file = g_key_file_new();
925         g_key_file_load_from_file(key_file, filename, 0, NULL);
926
927         sprintf(value, "%02hhx:%02hhx", lseid, rseid);
928
929         g_key_file_set_string(key_file, "Endpoints", "LastUsed", value);
930
931         data = g_key_file_to_data(key_file, &len, NULL);
932         g_file_set_contents(filename, data, len, NULL);
933
934         g_free(data);
935         g_key_file_free(key_file);
936 }
937
938 static void add_last_used(struct a2dp_channel *chan, struct a2dp_sep *lsep,
939                                 struct a2dp_remote_sep *rsep)
940 {
941         if (!chan->last_used)
942                 chan->last_used = new0(struct a2dp_last_used, 1);
943
944         chan->last_used->lsep = lsep;
945         chan->last_used->rsep = rsep;
946 }
947
948 static void update_last_used(struct a2dp_channel *chan, struct a2dp_sep *lsep,
949                                         struct avdtp_stream *stream)
950 {
951         struct avdtp_remote_sep *rsep;
952         struct a2dp_remote_sep *sep;
953
954         rsep = avdtp_stream_get_remote_sep(stream);
955         sep = queue_find(chan->seps, match_remote_sep, rsep);
956         if (!sep) {
957                 error("Unable to find remote SEP");
958                 return;
959         }
960
961         /* Check if already stored then skip */
962         if (chan->last_used && (chan->last_used->lsep == lsep &&
963                                 chan->last_used->rsep == sep))
964                 return;
965
966         add_last_used(chan, lsep, sep);
967
968         store_last_used(chan, avdtp_sep_get_seid(lsep->lsep),
969                                         avdtp_get_seid(rsep));
970 }
971
972 static gboolean open_ind(struct avdtp *session, struct avdtp_local_sep *sep,
973                                 struct avdtp_stream *stream, uint8_t *err,
974                                 void *user_data)
975 {
976         struct a2dp_sep *a2dp_sep = user_data;
977         struct a2dp_setup *setup;
978
979         if (a2dp_sep->type == AVDTP_SEP_TYPE_SINK)
980                 DBG("Sink %p: Open_Ind", sep);
981         else
982                 DBG("Source %p: Open_Ind", sep);
983
984         setup = a2dp_setup_get(session);
985         if (!setup)
986                 return FALSE;
987
988         setup->stream = stream;
989
990         if (!err && setup->chan)
991                 update_last_used(setup->chan, a2dp_sep, stream);
992
993         if (setup->reconfigure)
994                 setup->reconfigure = FALSE;
995
996         finalize_config(setup);
997
998         return TRUE;
999 }
1000
1001 static void open_cfm(struct avdtp *session, struct avdtp_local_sep *sep,
1002                         struct avdtp_stream *stream, struct avdtp_error *err,
1003                         void *user_data)
1004 {
1005         struct a2dp_sep *a2dp_sep = user_data;
1006         struct a2dp_setup *setup;
1007
1008         if (a2dp_sep->type == AVDTP_SEP_TYPE_SINK)
1009                 DBG("Sink %p: Open_Cfm", sep);
1010         else
1011                 DBG("Source %p: Open_Cfm", sep);
1012
1013         setup = find_setup_by_session(session);
1014         if (!setup)
1015                 return;
1016
1017         if (setup->reconfigure)
1018                 setup->reconfigure = FALSE;
1019
1020         if (err) {
1021                 setup->stream = NULL;
1022                 setup->err = err;
1023                 if (setup->start)
1024                         finalize_resume(setup);
1025         } else if (setup->chan)
1026                 update_last_used(setup->chan, a2dp_sep, stream);
1027
1028         finalize_config(setup);
1029
1030         return;
1031 }
1032
1033 static gboolean suspend_timeout(struct a2dp_sep *sep)
1034 {
1035         if (avdtp_suspend(sep->session, sep->stream) == 0)
1036                 sep->suspending = TRUE;
1037
1038         sep->suspend_timer = 0;
1039
1040         avdtp_unref(sep->session);
1041         sep->session = NULL;
1042
1043         return FALSE;
1044 }
1045
1046 static gboolean start_ind(struct avdtp *session, struct avdtp_local_sep *sep,
1047                                 struct avdtp_stream *stream, uint8_t *err,
1048                                 void *user_data)
1049 {
1050         struct a2dp_sep *a2dp_sep = user_data;
1051         struct a2dp_setup *setup;
1052
1053         if (a2dp_sep->type == AVDTP_SEP_TYPE_SINK)
1054                 DBG("Sink %p: Start_Ind", sep);
1055         else
1056                 DBG("Source %p: Start_Ind", sep);
1057
1058 #ifdef TIZEN_FEATURE_BLUEZ_MODIFY
1059         if (!a2dp_sep->locked) {
1060                 if (a2dp_sep->remote_suspended == FALSE) {
1061                         a2dp_sep->session = avdtp_ref(session);
1062                         a2dp_sep->suspend_timer = g_timeout_add_seconds(SUSPEND_TIMEOUT,
1063                                                         (GSourceFunc) suspend_timeout,
1064                                                         a2dp_sep);
1065                 } else
1066                         a2dp_sep->remote_suspended = FALSE;
1067         }
1068 #else
1069
1070         if (!a2dp_sep->locked) {
1071                 a2dp_sep->session = avdtp_ref(session);
1072                 a2dp_sep->suspend_timer = g_timeout_add_seconds(SUSPEND_TIMEOUT,
1073                                                 (GSourceFunc) suspend_timeout,
1074                                                 a2dp_sep);
1075         }
1076 #endif
1077
1078         if (!a2dp_sep->starting)
1079                 return TRUE;
1080
1081         a2dp_sep->starting = FALSE;
1082
1083         setup = find_setup_by_session(session);
1084         if (setup)
1085                 finalize_resume(setup);
1086
1087         return TRUE;
1088 }
1089
1090 static void start_cfm(struct avdtp *session, struct avdtp_local_sep *sep,
1091                         struct avdtp_stream *stream, struct avdtp_error *err,
1092                         void *user_data)
1093 {
1094         struct a2dp_sep *a2dp_sep = user_data;
1095         struct a2dp_setup *setup;
1096
1097         if (a2dp_sep->type == AVDTP_SEP_TYPE_SINK)
1098                 DBG("Sink %p: Start_Cfm", sep);
1099         else
1100                 DBG("Source %p: Start_Cfm", sep);
1101
1102         a2dp_sep->starting = FALSE;
1103
1104         setup = find_setup_by_session(session);
1105         if (!setup)
1106                 return;
1107
1108         if (err) {
1109                 setup->stream = NULL;
1110                 setup->err = err;
1111         }
1112
1113         finalize_resume(setup);
1114 }
1115
1116 static gboolean suspend_ind(struct avdtp *session, struct avdtp_local_sep *sep,
1117                                 struct avdtp_stream *stream, uint8_t *err,
1118                                 void *user_data)
1119 {
1120         struct a2dp_sep *a2dp_sep = user_data;
1121         struct a2dp_setup *setup;
1122         gboolean start;
1123         int start_err;
1124
1125         if (a2dp_sep->type == AVDTP_SEP_TYPE_SINK)
1126                 DBG("Sink %p: Suspend_Ind", sep);
1127         else
1128                 DBG("Source %p: Suspend_Ind", sep);
1129
1130 #ifdef TIZEN_FEATURE_BLUEZ_MODIFY
1131         a2dp_sep->remote_suspended = TRUE;
1132 #endif
1133
1134         if (a2dp_sep->suspend_timer) {
1135                 g_source_remove(a2dp_sep->suspend_timer);
1136                 a2dp_sep->suspend_timer = 0;
1137                 avdtp_unref(a2dp_sep->session);
1138                 a2dp_sep->session = NULL;
1139         }
1140
1141         if (!a2dp_sep->suspending)
1142                 return TRUE;
1143
1144         a2dp_sep->suspending = FALSE;
1145
1146         setup = find_setup_by_session(session);
1147         if (!setup)
1148                 return TRUE;
1149
1150         start = setup->start;
1151         setup->start = FALSE;
1152
1153         finalize_suspend(setup);
1154
1155         if (!start)
1156                 return TRUE;
1157
1158         start_err = avdtp_start(session, a2dp_sep->stream);
1159         if (start_err < 0 && start_err != -EINPROGRESS) {
1160                 error("avdtp_start: %s (%d)", strerror(-start_err),
1161                                                                 -start_err);
1162                 finalize_setup_errno(setup, start_err, finalize_resume, NULL);
1163         }
1164
1165         return TRUE;
1166 }
1167
1168 static void suspend_cfm(struct avdtp *session, struct avdtp_local_sep *sep,
1169                         struct avdtp_stream *stream, struct avdtp_error *err,
1170                         void *user_data)
1171 {
1172         struct a2dp_sep *a2dp_sep = user_data;
1173         struct a2dp_setup *setup;
1174         gboolean start;
1175         int start_err;
1176
1177         if (a2dp_sep->type == AVDTP_SEP_TYPE_SINK)
1178                 DBG("Sink %p: Suspend_Cfm", sep);
1179         else
1180                 DBG("Source %p: Suspend_Cfm", sep);
1181
1182         a2dp_sep->suspending = FALSE;
1183
1184         setup = find_setup_by_session(session);
1185         if (!setup)
1186                 return;
1187
1188         start = setup->start;
1189         setup->start = FALSE;
1190
1191         if (err) {
1192                 setup->stream = NULL;
1193                 setup->err = err;
1194         }
1195
1196         finalize_suspend(setup);
1197
1198         if (!start)
1199                 return;
1200
1201         if (err) {
1202                 finalize_resume(setup);
1203                 return;
1204         }
1205
1206         start_err = avdtp_start(session, a2dp_sep->stream);
1207         if (start_err < 0 && start_err != -EINPROGRESS) {
1208                 error("avdtp_start: %s (%d)", strerror(-start_err), -start_err);
1209                 finalize_setup_errno(setup, start_err, finalize_suspend, NULL);
1210         }
1211 }
1212
1213 static gboolean close_ind(struct avdtp *session, struct avdtp_local_sep *sep,
1214                                 struct avdtp_stream *stream, uint8_t *err,
1215                                 void *user_data)
1216 {
1217         struct a2dp_sep *a2dp_sep = user_data;
1218         struct a2dp_setup *setup;
1219
1220         if (a2dp_sep->type == AVDTP_SEP_TYPE_SINK)
1221                 DBG("Sink %p: Close_Ind", sep);
1222         else
1223                 DBG("Source %p: Close_Ind", sep);
1224
1225         setup = find_setup_by_session(session);
1226         if (!setup)
1227                 return TRUE;
1228
1229         finalize_setup_errno(setup, -ECONNRESET, finalize_suspend,
1230                                                         finalize_resume, NULL);
1231
1232         return TRUE;
1233 }
1234
1235 static struct a2dp_remote_sep *find_remote_sep(struct a2dp_channel *chan,
1236                                                 struct a2dp_sep *sep)
1237 {
1238         struct avdtp_remote_sep *rsep;
1239
1240         rsep = avdtp_find_remote_sep(chan->session, sep->lsep);
1241
1242         return queue_find(chan->seps, match_remote_sep, rsep);
1243 }
1244
1245 static gboolean a2dp_reconfigure(gpointer data)
1246 {
1247         struct a2dp_setup *setup = data;
1248         struct a2dp_sep *sep = setup->sep;
1249         int posix_err;
1250         struct avdtp_media_codec_capability *rsep_codec;
1251         struct avdtp_service_capability *cap;
1252
1253         if (!sep->lsep) {
1254                 error("no valid local SEP");
1255                 posix_err = -EINVAL;
1256                 goto failed;
1257         }
1258
1259         if (setup->rsep) {
1260                 cap = avdtp_get_codec(setup->rsep->sep);
1261                 rsep_codec = (struct avdtp_media_codec_capability *) cap->data;
1262         }
1263
1264         if (!setup->rsep || sep->codec != rsep_codec->media_codec_type)
1265                 setup->rsep = find_remote_sep(setup->chan, sep);
1266
1267         if (!setup->rsep) {
1268                 error("unable to find remote SEP");
1269                 posix_err = -EINVAL;
1270                 goto failed;
1271         }
1272
1273         posix_err = avdtp_set_configuration(setup->session, setup->rsep->sep,
1274                                                 sep->lsep,
1275                                                 setup->caps,
1276                                                 &setup->stream);
1277         if (posix_err < 0) {
1278                 error("avdtp_set_configuration: %s", strerror(-posix_err));
1279                 goto failed;
1280         }
1281
1282         return FALSE;
1283
1284 failed:
1285         finalize_setup_errno(setup, posix_err, finalize_config, NULL);
1286         return FALSE;
1287 }
1288
1289 static struct a2dp_remote_sep *get_remote_sep(struct a2dp_channel *chan,
1290                                                 struct avdtp_stream *stream)
1291 {
1292         struct avdtp_remote_sep *rsep;
1293
1294         rsep = avdtp_stream_get_remote_sep(stream);
1295
1296         return queue_find(chan->seps, match_remote_sep, rsep);
1297 }
1298
1299 static void close_cfm(struct avdtp *session, struct avdtp_local_sep *sep,
1300                         struct avdtp_stream *stream, struct avdtp_error *err,
1301                         void *user_data)
1302 {
1303         struct a2dp_sep *a2dp_sep = user_data;
1304         struct a2dp_setup *setup;
1305
1306         if (a2dp_sep->type == AVDTP_SEP_TYPE_SINK)
1307                 DBG("Sink %p: Close_Cfm", sep);
1308         else
1309                 DBG("Source %p: Close_Cfm", sep);
1310
1311         setup = find_setup_by_session(session);
1312         if (!setup)
1313                 return;
1314
1315         if (err) {
1316                 setup->stream = NULL;
1317                 setup->err = err;
1318                 finalize_config(setup);
1319                 return;
1320         }
1321
1322         if (!setup->rsep)
1323                 setup->rsep = get_remote_sep(setup->chan, stream);
1324
1325         if (setup->reconfigure)
1326                 g_timeout_add(RECONFIGURE_TIMEOUT, a2dp_reconfigure, setup);
1327 }
1328
1329 static void abort_ind(struct avdtp *session, struct avdtp_local_sep *sep,
1330                                 struct avdtp_stream *stream, uint8_t *err,
1331                                 void *user_data)
1332 {
1333         struct a2dp_sep *a2dp_sep = user_data;
1334         struct a2dp_setup *setup;
1335
1336         if (a2dp_sep->type == AVDTP_SEP_TYPE_SINK)
1337                 DBG("Sink %p: Abort_Ind", sep);
1338         else
1339                 DBG("Source %p: Abort_Ind", sep);
1340
1341         a2dp_sep->stream = NULL;
1342
1343         setup = find_setup_by_session(session);
1344         if (!setup)
1345                 return;
1346
1347         finalize_setup_errno(setup, -ECONNRESET, finalize_suspend,
1348                                                         finalize_resume,
1349                                                         finalize_config, NULL);
1350
1351         return;
1352 }
1353
1354 static void abort_cfm(struct avdtp *session, struct avdtp_local_sep *sep,
1355                         struct avdtp_stream *stream, struct avdtp_error *err,
1356                         void *user_data)
1357 {
1358         struct a2dp_sep *a2dp_sep = user_data;
1359         struct a2dp_setup *setup;
1360
1361         if (a2dp_sep->type == AVDTP_SEP_TYPE_SINK)
1362                 DBG("Sink %p: Abort_Cfm", sep);
1363         else
1364                 DBG("Source %p: Abort_Cfm", sep);
1365
1366         setup = find_setup_by_session(session);
1367         if (!setup)
1368                 return;
1369
1370         if (setup->reconfigure) {
1371                 g_timeout_add(RECONFIGURE_TIMEOUT, a2dp_reconfigure, setup);
1372                 return;
1373         }
1374
1375         setup_unref(setup);
1376 }
1377
1378 static gboolean reconf_ind(struct avdtp *session, struct avdtp_local_sep *sep,
1379                                 uint8_t *err, void *user_data)
1380 {
1381         struct a2dp_sep *a2dp_sep = user_data;
1382
1383         if (a2dp_sep->type == AVDTP_SEP_TYPE_SINK)
1384                 DBG("Sink %p: ReConfigure_Ind", sep);
1385         else
1386                 DBG("Source %p: ReConfigure_Ind", sep);
1387
1388         return TRUE;
1389 }
1390
1391 static gboolean endpoint_delayreport_ind(struct avdtp *session,
1392                                                 struct avdtp_local_sep *sep,
1393                                                 uint8_t rseid, uint16_t delay,
1394                                                 uint8_t *err, void *user_data)
1395 {
1396         struct a2dp_sep *a2dp_sep = user_data;
1397
1398         if (a2dp_sep->type == AVDTP_SEP_TYPE_SINK)
1399                 DBG("Sink %p: DelayReport_Ind", sep);
1400         else
1401                 DBG("Source %p: DelayReport_Ind", sep);
1402
1403         if (a2dp_sep->endpoint == NULL ||
1404                                 a2dp_sep->endpoint->set_delay == NULL)
1405                 return FALSE;
1406
1407         a2dp_sep->endpoint->set_delay(a2dp_sep, delay, a2dp_sep->user_data);
1408
1409         return TRUE;
1410 }
1411
1412 static void reconf_cfm(struct avdtp *session, struct avdtp_local_sep *sep,
1413                         struct avdtp_stream *stream, struct avdtp_error *err,
1414                         void *user_data)
1415 {
1416         struct a2dp_sep *a2dp_sep = user_data;
1417         struct a2dp_setup *setup;
1418
1419         if (a2dp_sep->type == AVDTP_SEP_TYPE_SINK)
1420                 DBG("Sink %p: ReConfigure_Cfm", sep);
1421         else
1422                 DBG("Source %p: ReConfigure_Cfm", sep);
1423
1424         setup = find_setup_by_session(session);
1425         if (!setup)
1426                 return;
1427
1428         if (err) {
1429                 setup->stream = NULL;
1430                 setup->err = err;
1431         }
1432
1433         finalize_config(setup);
1434 }
1435
1436 static void delay_report_cfm(struct avdtp *session, struct avdtp_local_sep *sep,
1437                                 struct avdtp_stream *stream,
1438                                 struct avdtp_error *err, void *user_data)
1439 {
1440         struct a2dp_sep *a2dp_sep = user_data;
1441
1442         if (a2dp_sep->type == AVDTP_SEP_TYPE_SINK)
1443                 DBG("Sink %p: DelayReport_Cfm", sep);
1444         else
1445                 DBG("Source %p: DelayReport_Cfm", sep);
1446 }
1447
1448 static struct avdtp_sep_cfm cfm = {
1449         .set_configuration      = setconf_cfm,
1450         .get_configuration      = getconf_cfm,
1451         .open                   = open_cfm,
1452         .start                  = start_cfm,
1453         .suspend                = suspend_cfm,
1454         .close                  = close_cfm,
1455         .abort                  = abort_cfm,
1456         .reconfigure            = reconf_cfm,
1457         .delay_report           = delay_report_cfm,
1458 };
1459
1460 static struct avdtp_sep_ind endpoint_ind = {
1461         .match_codec            = endpoint_match_codec_ind,
1462         .get_capability         = endpoint_getcap_ind,
1463         .set_configuration      = endpoint_setconf_ind,
1464         .get_configuration      = getconf_ind,
1465         .open                   = open_ind,
1466         .start                  = start_ind,
1467         .suspend                = suspend_ind,
1468         .close                  = close_ind,
1469         .abort                  = abort_ind,
1470         .reconfigure            = reconf_ind,
1471         .delayreport            = endpoint_delayreport_ind,
1472 };
1473
1474 #ifdef TIZEN_FEATURE_BLUEZ_MODIFY
1475 static sdp_record_t *a2dp_record(uint8_t type, gboolean sink_enabled)
1476 #else
1477 static sdp_record_t *a2dp_record(uint8_t type)
1478 #endif
1479 {
1480         sdp_list_t *svclass_id, *pfseq, *apseq, *root;
1481         uuid_t root_uuid, l2cap_uuid, avdtp_uuid, a2dp_uuid;
1482         sdp_profile_desc_t profile[1];
1483         sdp_list_t *aproto, *proto[2];
1484         sdp_record_t *record;
1485         sdp_data_t *psm, *version, *features;
1486         uint16_t lp = AVDTP_UUID;
1487 #ifdef TIZEN_FEATURE_BLUEZ_MODIFY
1488         uint16_t a2dp_ver, avdtp_ver, feat;
1489         if (sink_enabled) {
1490                 DBG("A2DP record for Sink role");
1491                 a2dp_ver = 0x0102;
1492                 avdtp_ver = 0x0103;
1493                 feat = 0x0002;
1494         } else {
1495                 DBG("A2DP record for Source role");
1496                 a2dp_ver = 0x0102;
1497                 avdtp_ver = 0x0103;
1498                 feat = 0x0001;
1499         }
1500 #else
1501         uint16_t a2dp_ver = 0x0103, avdtp_ver = 0x0103, feat = 0x000f;
1502 #endif
1503
1504         record = sdp_record_alloc();
1505         if (!record)
1506                 return NULL;
1507
1508         sdp_uuid16_create(&root_uuid, PUBLIC_BROWSE_GROUP);
1509         root = sdp_list_append(0, &root_uuid);
1510         sdp_set_browse_groups(record, root);
1511
1512         if (type == AVDTP_SEP_TYPE_SOURCE)
1513                 sdp_uuid16_create(&a2dp_uuid, AUDIO_SOURCE_SVCLASS_ID);
1514         else
1515                 sdp_uuid16_create(&a2dp_uuid, AUDIO_SINK_SVCLASS_ID);
1516         svclass_id = sdp_list_append(0, &a2dp_uuid);
1517         sdp_set_service_classes(record, svclass_id);
1518
1519         sdp_uuid16_create(&profile[0].uuid, ADVANCED_AUDIO_PROFILE_ID);
1520         profile[0].version = a2dp_ver;
1521         pfseq = sdp_list_append(0, &profile[0]);
1522         sdp_set_profile_descs(record, pfseq);
1523
1524         sdp_uuid16_create(&l2cap_uuid, L2CAP_UUID);
1525         proto[0] = sdp_list_append(0, &l2cap_uuid);
1526         psm = sdp_data_alloc(SDP_UINT16, &lp);
1527         proto[0] = sdp_list_append(proto[0], psm);
1528         apseq = sdp_list_append(0, proto[0]);
1529
1530         sdp_uuid16_create(&avdtp_uuid, AVDTP_UUID);
1531         proto[1] = sdp_list_append(0, &avdtp_uuid);
1532         version = sdp_data_alloc(SDP_UINT16, &avdtp_ver);
1533         proto[1] = sdp_list_append(proto[1], version);
1534         apseq = sdp_list_append(apseq, proto[1]);
1535
1536         aproto = sdp_list_append(0, apseq);
1537         sdp_set_access_protos(record, aproto);
1538
1539         features = sdp_data_alloc(SDP_UINT16, &feat);
1540         sdp_attr_add(record, SDP_ATTR_SUPPORTED_FEATURES, features);
1541
1542         if (type == AVDTP_SEP_TYPE_SOURCE)
1543                 sdp_set_info_attr(record, "Audio Source", 0, 0);
1544         else
1545                 sdp_set_info_attr(record, "Audio Sink", 0, 0);
1546
1547         free(psm);
1548         free(version);
1549         sdp_list_free(proto[0], 0);
1550         sdp_list_free(proto[1], 0);
1551         sdp_list_free(apseq, 0);
1552         sdp_list_free(pfseq, 0);
1553         sdp_list_free(aproto, 0);
1554         sdp_list_free(root, 0);
1555         sdp_list_free(svclass_id, 0);
1556
1557         return record;
1558 }
1559
1560 static struct a2dp_server *find_server(GSList *list, struct btd_adapter *a)
1561 {
1562
1563         for (; list; list = list->next) {
1564                 struct a2dp_server *server = list->data;
1565
1566                 if (server->adapter == a)
1567                         return server;
1568         }
1569
1570         return NULL;
1571 }
1572
1573 static void remote_sep_free(void *data)
1574 {
1575         struct a2dp_remote_sep *sep = data;
1576
1577         avdtp_remote_sep_set_destroy(sep->sep, NULL, NULL);
1578
1579         free(sep->path);
1580         free(sep);
1581 }
1582
1583 static void remove_remote_sep(void *data)
1584 {
1585         struct a2dp_remote_sep *sep = data;
1586
1587         if (!sep->path) {
1588                 remote_sep_free(sep);
1589                 return;
1590         }
1591
1592         g_dbus_unregister_interface(btd_get_dbus_connection(), sep->path,
1593                                                 MEDIA_ENDPOINT_INTERFACE);
1594 }
1595
1596 static void channel_free(void *data)
1597 {
1598         struct a2dp_channel *chan = data;
1599
1600         if (chan->auth_id > 0)
1601                 btd_cancel_authorization(chan->auth_id);
1602
1603         if (chan->io_id > 0)
1604                 g_source_remove(chan->io_id);
1605
1606         if (chan->io) {
1607                 g_io_channel_shutdown(chan->io, TRUE, NULL);
1608                 g_io_channel_unref(chan->io);
1609         }
1610
1611         avdtp_remove_state_cb(chan->state_id);
1612
1613         queue_destroy(chan->seps, remove_remote_sep);
1614         free(chan->last_used);
1615         g_free(chan);
1616 }
1617
1618 static void channel_remove(struct a2dp_channel *chan)
1619 {
1620         struct a2dp_server *server = chan->server;
1621
1622         DBG("chan %p", chan);
1623
1624         queue_remove(server->channels, chan);
1625
1626         channel_free(chan);
1627 }
1628
1629 static gboolean disconnect_cb(GIOChannel *io, GIOCondition cond, gpointer data)
1630 {
1631         struct a2dp_channel *chan = data;
1632
1633         DBG("chan %p", chan);
1634
1635         chan->io_id = 0;
1636
1637         channel_remove(chan);
1638
1639         return FALSE;
1640 }
1641
1642 static void caps_add_codec(GSList **l, uint8_t codec, uint8_t *caps,
1643                                                         size_t size)
1644 {
1645         struct avdtp_service_capability *media_transport, *media_codec;
1646         struct avdtp_media_codec_capability *cap;
1647
1648         media_transport = avdtp_service_cap_new(AVDTP_MEDIA_TRANSPORT,
1649                                                 NULL, 0);
1650
1651         *l = g_slist_append(*l, media_transport);
1652
1653         cap = g_malloc0(sizeof(*cap) + size);
1654         cap->media_type = AVDTP_MEDIA_TYPE_AUDIO;
1655         cap->media_codec_type = codec;
1656         memcpy(cap->data, caps, size);
1657
1658         media_codec = avdtp_service_cap_new(AVDTP_MEDIA_CODEC, cap,
1659                                                 sizeof(*cap) + size);
1660
1661         *l = g_slist_append(*l, media_codec);
1662         g_free(cap);
1663 }
1664
1665 struct client {
1666         const char *sender;
1667         const char *path;
1668 };
1669
1670 static int match_client(const void *data, const void *user_data)
1671 {
1672         struct a2dp_sep *sep = (void *) data;
1673         const struct a2dp_endpoint *endpoint = sep->endpoint;
1674         const struct client *client = user_data;
1675
1676         if (strcmp(client->sender, endpoint->get_name(sep, sep->user_data)))
1677                 return -1;
1678
1679         return strcmp(client->path, endpoint->get_path(sep, sep->user_data));
1680 }
1681
1682 static struct a2dp_sep *find_sep(struct a2dp_server *server, uint8_t type,
1683                                         const char *sender, const char *path)
1684 {
1685         GSList *l;
1686         struct client client = { sender, path };
1687
1688         l = type == AVDTP_SEP_TYPE_SINK ? server->sources : server->sinks;
1689
1690         l = g_slist_find_custom(l, &client, match_client);
1691         if (l)
1692                 return l->data;
1693
1694         return NULL;
1695 }
1696
1697 static int parse_properties(DBusMessageIter *props, uint8_t **caps, int *size)
1698 {
1699         while (dbus_message_iter_get_arg_type(props) == DBUS_TYPE_DICT_ENTRY) {
1700                 const char *key;
1701                 DBusMessageIter value, entry;
1702                 int var;
1703
1704                 dbus_message_iter_recurse(props, &entry);
1705                 dbus_message_iter_get_basic(&entry, &key);
1706
1707                 dbus_message_iter_next(&entry);
1708                 dbus_message_iter_recurse(&entry, &value);
1709
1710                 var = dbus_message_iter_get_arg_type(&value);
1711                 if (strcasecmp(key, "Capabilities") == 0) {
1712                         DBusMessageIter array;
1713
1714                         if (var != DBUS_TYPE_ARRAY)
1715                                 return -EINVAL;
1716
1717                         dbus_message_iter_recurse(&value, &array);
1718                         dbus_message_iter_get_fixed_array(&array, caps, size);
1719                         return 0;
1720                 }
1721
1722                 dbus_message_iter_next(props);
1723         }
1724
1725         return -EINVAL;
1726 }
1727
1728 static void reconfig_cb(struct avdtp *session, struct a2dp_sep *sep,
1729                         struct avdtp_stream *stream, int err, void *user_data)
1730 {
1731         DBusMessage *msg = user_data;
1732
1733         if (err)
1734                 g_dbus_send_message(btd_get_dbus_connection(),
1735                                         btd_error_failed(msg, strerror(-err)));
1736         else
1737                 g_dbus_send_reply(btd_get_dbus_connection(), msg,
1738                                         DBUS_TYPE_INVALID);
1739
1740         dbus_message_unref(msg);
1741 }
1742
1743 static int a2dp_reconfig(struct a2dp_channel *chan, const char *sender,
1744                         struct a2dp_sep *lsep, struct a2dp_remote_sep *rsep,
1745                         uint8_t *caps, int size, void *user_data)
1746 {
1747         struct a2dp_setup *setup;
1748         struct a2dp_setup_cb *cb_data;
1749         GSList *l;
1750         int err;
1751
1752         setup = a2dp_setup_get(chan->session);
1753         if (!setup)
1754                 return -ENOMEM;
1755
1756         cb_data = setup_cb_new(setup);
1757         cb_data->config_cb = reconfig_cb;
1758         cb_data->user_data = user_data;
1759
1760         setup->sep = lsep;
1761         setup->rsep = rsep;
1762
1763         g_slist_free_full(setup->caps, g_free);
1764         setup->caps = NULL;
1765
1766         caps_add_codec(&setup->caps, setup->sep->codec, caps, size);
1767
1768         l = avdtp_get_type(rsep->sep) == AVDTP_SEP_TYPE_SINK ?
1769                                         chan->server->sources :
1770                                         chan->server->sinks;
1771
1772         /* Check for existing stream and close it */
1773         for (; l; l = g_slist_next(l)) {
1774                 struct a2dp_sep *tmp = l->data;
1775
1776                 /* Attempt to reconfigure if a stream already exists */
1777                 if (tmp->stream) {
1778                         /* Only allow switching sep from the same sender */
1779                         if (strcmp(sender, tmp->endpoint->get_name(tmp,
1780                                                         tmp->user_data)))
1781                                 return -EPERM;
1782
1783                         /* Check if stream is for the channel */
1784                         if (!avdtp_has_stream(chan->session, tmp->stream))
1785                                 continue;
1786
1787                         err = avdtp_close(chan->session, tmp->stream, FALSE);
1788                         if (err < 0) {
1789                                 err = avdtp_abort(chan->session, tmp->stream);
1790                                 if (err < 0) {
1791                                         error("avdtp_abort: %s",
1792                                                         strerror(-err));
1793                                         goto fail;
1794                                 }
1795                         }
1796
1797                         setup->reconfigure = TRUE;
1798
1799                         return 0;
1800                 }
1801         }
1802
1803         err = avdtp_set_configuration(setup->session, setup->rsep->sep,
1804                                                 lsep->lsep,
1805                                                 setup->caps,
1806                                                 &setup->stream);
1807         if (err < 0) {
1808                 error("avdtp_set_configuration: %s", strerror(-err));
1809                 goto fail;
1810         }
1811
1812         return 0;
1813
1814 fail:
1815         setup_cb_free(cb_data);
1816         return err;
1817 }
1818
1819 static DBusMessage *set_configuration(DBusConnection *conn, DBusMessage *msg,
1820                                                                 void *data)
1821 {
1822         struct a2dp_remote_sep *rsep = data;
1823         struct a2dp_channel *chan = rsep->chan;
1824         struct a2dp_sep *lsep = NULL;
1825         struct avdtp_service_capability *service;
1826         struct avdtp_media_codec_capability *codec;
1827         DBusMessageIter args, props;
1828         const char *sender, *path;
1829         uint8_t *caps;
1830         int err, size = 0;
1831
1832         sender = dbus_message_get_sender(msg);
1833
1834         dbus_message_iter_init(msg, &args);
1835
1836         dbus_message_iter_get_basic(&args, &path);
1837         dbus_message_iter_next(&args);
1838
1839         lsep = find_sep(chan->server, avdtp_get_type(rsep->sep), sender, path);
1840         if (!lsep)
1841                 return btd_error_invalid_args(msg);
1842
1843         service = avdtp_get_codec(rsep->sep);
1844         codec = (struct avdtp_media_codec_capability *) service->data;
1845
1846         /* Check if codec really matches */
1847         if (!endpoint_match_codec_ind(chan->session, codec, lsep))
1848                 return btd_error_invalid_args(msg);
1849
1850         dbus_message_iter_recurse(&args, &props);
1851         if (dbus_message_iter_get_arg_type(&props) != DBUS_TYPE_DICT_ENTRY)
1852                 return btd_error_invalid_args(msg);
1853
1854         if (parse_properties(&props, &caps, &size) < 0)
1855                 return btd_error_invalid_args(msg);
1856
1857         err = a2dp_reconfig(chan, sender, lsep, rsep, caps, size,
1858                                         dbus_message_ref(msg));
1859         if (err < 0) {
1860                 dbus_message_unref(msg);
1861                 return btd_error_failed(msg, strerror(-err));
1862         }
1863
1864         return NULL;
1865 }
1866
1867 static const GDBusMethodTable sep_methods[] = {
1868         { GDBUS_ASYNC_METHOD("SetConfiguration",
1869                                         GDBUS_ARGS({ "endpoint", "o" },
1870                                                 { "properties", "a{sv}" } ),
1871                                         NULL, set_configuration) },
1872         { },
1873 };
1874
1875 static gboolean get_uuid(const GDBusPropertyTable *property,
1876                                         DBusMessageIter *iter, void *data)
1877 {
1878         struct a2dp_remote_sep *sep = data;
1879         const char *uuid;
1880
1881         switch (avdtp_get_type(sep->sep)) {
1882         case AVDTP_SEP_TYPE_SOURCE:
1883                 uuid = A2DP_SOURCE_UUID;
1884                 break;
1885         case AVDTP_SEP_TYPE_SINK:
1886                 uuid = A2DP_SINK_UUID;
1887                 break;
1888         default:
1889                 uuid = "";
1890         }
1891
1892         dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &uuid);
1893
1894         return TRUE;
1895 }
1896
1897 static gboolean get_codec(const GDBusPropertyTable *property,
1898                                         DBusMessageIter *iter, void *data)
1899 {
1900         struct a2dp_remote_sep *sep = data;
1901         struct avdtp_service_capability *cap = avdtp_get_codec(sep->sep);
1902         struct avdtp_media_codec_capability *codec = (void *) cap->data;
1903
1904         dbus_message_iter_append_basic(iter, DBUS_TYPE_BYTE,
1905                                                 &codec->media_codec_type);
1906
1907         return TRUE;
1908 }
1909
1910 static gboolean get_capabilities(const GDBusPropertyTable *property,
1911                                         DBusMessageIter *iter, void *data)
1912 {
1913         struct a2dp_remote_sep *sep = data;
1914         struct avdtp_service_capability *service = avdtp_get_codec(sep->sep);
1915         struct avdtp_media_codec_capability *codec = (void *) service->data;
1916         uint8_t *caps = codec->data;
1917         DBusMessageIter array;
1918
1919         dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY,
1920                                         DBUS_TYPE_BYTE_AS_STRING, &array);
1921
1922         dbus_message_iter_append_fixed_array(&array, DBUS_TYPE_BYTE, &caps,
1923                                         service->length - sizeof(*codec));
1924
1925         dbus_message_iter_close_container(iter, &array);
1926
1927         return TRUE;
1928 }
1929
1930 static gboolean get_device(const GDBusPropertyTable *property,
1931                                         DBusMessageIter *iter, void *data)
1932 {
1933         struct a2dp_remote_sep *sep = data;
1934         const char *path;
1935
1936         path = device_get_path(sep->chan->device);
1937
1938         dbus_message_iter_append_basic(iter, DBUS_TYPE_OBJECT_PATH, &path);
1939
1940         return TRUE;
1941 }
1942
1943 static gboolean get_delay_reporting(const GDBusPropertyTable *property,
1944                                         DBusMessageIter *iter, void *data)
1945 {
1946         struct a2dp_remote_sep *sep = data;
1947         dbus_bool_t delay_report;
1948
1949         delay_report = avdtp_get_delay_reporting(sep->sep);
1950
1951         dbus_message_iter_append_basic(iter, DBUS_TYPE_BOOLEAN, &delay_report);
1952
1953         return TRUE;
1954 }
1955
1956 static const GDBusPropertyTable sep_properties[] = {
1957         { "UUID", "s", get_uuid, NULL, NULL },
1958         { "Codec", "y", get_codec, NULL, NULL },
1959         { "Capabilities", "ay", get_capabilities, NULL, NULL },
1960         { "Device", "o", get_device, NULL, NULL },
1961         { "DelayReporting", "b", get_delay_reporting, NULL, NULL },
1962         { }
1963 };
1964
1965 static void remote_sep_destroy(void *user_data)
1966 {
1967         struct a2dp_remote_sep *sep = user_data;
1968
1969         if (queue_remove(sep->chan->seps, sep))
1970                 remove_remote_sep(sep);
1971 }
1972
1973 static void register_remote_sep(void *data, void *user_data)
1974 {
1975         struct avdtp_remote_sep *rsep = data;
1976         struct a2dp_channel *chan = user_data;
1977         struct a2dp_remote_sep *sep;
1978
1979         sep = queue_find(chan->seps, match_remote_sep, rsep);
1980         if (sep)
1981                 return;
1982
1983         sep = new0(struct a2dp_remote_sep, 1);
1984         sep->chan = chan;
1985         sep->sep = rsep;
1986
1987         if (asprintf(&sep->path, "%s/sep%d",
1988                                 device_get_path(chan->device),
1989                                 avdtp_get_seid(rsep)) < 0) {
1990                 error("Could not allocate path for remote sep %s/sep%d",
1991                                 device_get_path(chan->device),
1992                                 avdtp_get_seid(rsep));
1993                 sep->path = NULL;
1994                 goto done;
1995         }
1996
1997         if (g_dbus_register_interface(btd_get_dbus_connection(),
1998                                 sep->path, MEDIA_ENDPOINT_INTERFACE,
1999                                 sep_methods, NULL, sep_properties,
2000                                 sep, remote_sep_free) == FALSE) {
2001                 error("Could not register remote sep %s", sep->path);
2002                 free(sep->path);
2003                 sep->path = NULL;
2004                 goto done;
2005         }
2006
2007         DBG("Found remote SEP: %s", sep->path);
2008
2009         avdtp_remote_sep_set_destroy(rsep, sep, remote_sep_destroy);
2010
2011 done:
2012         queue_push_tail(chan->seps, sep);
2013 }
2014
2015 static bool match_seid(const void *data, const void *user_data)
2016 {
2017         const struct a2dp_remote_sep *sep = data;
2018         const uint8_t *seid = user_data;
2019
2020         return avdtp_get_seid(sep->sep) == *seid;
2021 }
2022
2023 static int match_sep(const void *data, const void *user_data)
2024 {
2025         struct a2dp_sep *sep = (void *) data;
2026         const uint8_t *seid = user_data;
2027
2028         return *seid - avdtp_sep_get_seid(sep->lsep);
2029 }
2030
2031 static struct a2dp_sep *find_sep_by_seid(struct a2dp_server *server,
2032                                                         uint8_t seid)
2033 {
2034         GSList *l;
2035
2036         l = g_slist_find_custom(server->sources, &seid, match_sep);
2037         if (l)
2038                 return l->data;
2039
2040         l = g_slist_find_custom(server->sinks, &seid, match_sep);
2041         if (l)
2042                 return l->data;
2043
2044         return NULL;
2045 }
2046
2047 static void load_remote_sep(struct a2dp_channel *chan, GKeyFile *key_file,
2048                                                                 char **seids)
2049 {
2050         struct a2dp_sep *lsep;
2051         struct a2dp_remote_sep *sep;
2052         struct avdtp_remote_sep *rsep;
2053         uint8_t lseid, rseid;
2054         char *value;
2055
2056         if (!seids)
2057                 return;
2058
2059         for (; *seids; seids++) {
2060                 uint8_t type;
2061                 uint8_t codec;
2062                 uint8_t delay_reporting;
2063                 GSList *l = NULL;
2064                 char caps[256];
2065                 uint8_t data[128];
2066                 int i, size;
2067
2068                 if (sscanf(*seids, "%02hhx", &rseid) != 1)
2069                         continue;
2070
2071                 value = g_key_file_get_string(key_file, "Endpoints", *seids,
2072                                                                 NULL);
2073                 if (!value)
2074                         continue;
2075
2076                 /* Try loading with delay_reporting first */
2077                 if (sscanf(value, "%02hhx:%02hhx:%02hhx:%s", &type, &codec,
2078                                         &delay_reporting, caps) != 4) {
2079                         /* Try old format */
2080                         if (sscanf(value, "%02hhx:%02hhx:%s", &type, &codec,
2081                                                                 caps) != 3) {
2082                                 warn("Unable to load Endpoint: seid %u", rseid);
2083                                 g_free(value);
2084                                 continue;
2085                         }
2086                         delay_reporting = false;
2087                 }
2088
2089                 for (i = 0, size = strlen(caps); i < size; i += 2) {
2090                         uint8_t *tmp = data + i / 2;
2091
2092                         if (sscanf(caps + i, "%02hhx", tmp) != 1) {
2093                                 warn("Unable to load Endpoint: seid %u", rseid);
2094                                 break;
2095                         }
2096                 }
2097
2098                 g_free(value);
2099
2100                 if (i != size)
2101                         continue;
2102
2103                 caps_add_codec(&l, codec, data, size / 2);
2104
2105                 rsep = avdtp_register_remote_sep(chan->session, rseid, type, l,
2106                                                         delay_reporting);
2107                 if (!rsep) {
2108                         warn("Unable to register Endpoint: seid %u", rseid);
2109                         continue;
2110                 }
2111
2112                 register_remote_sep(rsep, chan);
2113         }
2114
2115         value = g_key_file_get_string(key_file, "Endpoints", "LastUsed", NULL);
2116         if (!value)
2117                 return;
2118
2119         if (sscanf(value, "%02hhx:%02hhx", &lseid, &rseid) != 2) {
2120                 warn("Unable to load LastUsed");
2121                 g_free(value);
2122                 return;
2123         }
2124
2125         g_free(value);
2126
2127         lsep = find_sep_by_seid(chan->server, lseid);
2128         if (!lsep) {
2129                 warn("Unable to load LastUsed: lseid %u not found", lseid);
2130                 return;
2131         }
2132
2133         sep = queue_find(chan->seps, match_seid, &rseid);
2134         if (!sep) {
2135                 warn("Unable to load LastUsed: rseid %u not found", rseid);
2136                 return;
2137         }
2138
2139         add_last_used(chan, lsep, sep);
2140 }
2141
2142 static void load_remote_seps(struct a2dp_channel *chan)
2143 {
2144         struct btd_device *device = chan->device;
2145         char filename[PATH_MAX];
2146         char dst_addr[18];
2147         char **keys;
2148         GKeyFile *key_file;
2149
2150         ba2str(device_get_address(device), dst_addr);
2151
2152         snprintf(filename, PATH_MAX, STORAGEDIR "/%s/cache/%s",
2153                         btd_adapter_get_storage_dir(device_get_adapter(device)),
2154                         dst_addr);
2155         key_file = g_key_file_new();
2156         g_key_file_load_from_file(key_file, filename, 0, NULL);
2157         keys = g_key_file_get_keys(key_file, "Endpoints", NULL, NULL);
2158
2159         load_remote_sep(chan, key_file, keys);
2160
2161         g_strfreev(keys);
2162         g_key_file_free(key_file);
2163 }
2164
2165 static void avdtp_state_cb(struct btd_device *dev, struct avdtp *session,
2166                                         avdtp_session_state_t old_state,
2167                                         avdtp_session_state_t new_state,
2168                                         void *user_data)
2169 {
2170         struct a2dp_channel *chan = user_data;
2171
2172         switch (new_state) {
2173         case AVDTP_SESSION_STATE_DISCONNECTED:
2174                 if (chan->session == session)
2175                         channel_remove(chan);
2176                 break;
2177         case AVDTP_SESSION_STATE_CONNECTING:
2178                 break;
2179         case AVDTP_SESSION_STATE_CONNECTED:
2180                 if (!chan->session)
2181                         chan->session = session;
2182                 load_remote_seps(chan);
2183                 break;
2184         }
2185 }
2186
2187 static struct a2dp_channel *channel_new(struct a2dp_server *server,
2188                                         struct btd_device *device,
2189                                         GIOChannel *io)
2190 {
2191         struct a2dp_channel *chan;
2192
2193         chan = g_new0(struct a2dp_channel, 1);
2194         chan->server = server;
2195         chan->device = device;
2196         chan->seps = queue_new();
2197         chan->state_id = avdtp_add_state_cb(device, avdtp_state_cb, chan);
2198
2199         if (!queue_push_tail(server->channels, chan)) {
2200                 g_free(chan);
2201                 return NULL;
2202         }
2203
2204         if (!io)
2205                 return chan;
2206
2207         chan->io = g_io_channel_ref(io);
2208         chan->io_id = g_io_add_watch(io, G_IO_ERR | G_IO_HUP | G_IO_NVAL,
2209                                         (GIOFunc) disconnect_cb, chan);
2210
2211         return chan;
2212 }
2213
2214 static bool match_by_device(const void *data, const void *user_data)
2215 {
2216         const struct a2dp_channel *chan = data;
2217         const struct btd_device *device = user_data;
2218
2219         return chan->device == device;
2220 }
2221
2222 struct avdtp *a2dp_avdtp_get(struct btd_device *device)
2223 {
2224         struct a2dp_server *server;
2225         struct a2dp_channel *chan;
2226         const struct queue_entry *entry;
2227
2228         server = find_server(servers, device_get_adapter(device));
2229         if (server == NULL)
2230                 return NULL;
2231
2232         chan = queue_find(server->channels, match_by_device, device);
2233         if (!chan) {
2234                 chan = channel_new(server, device, NULL);
2235                 if (!chan)
2236                         return NULL;
2237         }
2238
2239 #ifdef TIZEN_FEATURE_BLUEZ_MODIFY
2240         if (chan->auth_id) {
2241                 DBG("auth is already going...");
2242                 return NULL;
2243         }
2244 #endif
2245
2246         if (chan->session)
2247                 return avdtp_ref(chan->session);
2248
2249         /* Check if there is any SEP available */
2250         for (entry = queue_get_entries(server->seps); entry;
2251                                         entry = entry->next) {
2252                 struct avdtp_local_sep *sep = entry->data;
2253
2254                 if (avdtp_sep_get_state(sep) == AVDTP_STATE_IDLE)
2255                         goto found;
2256         }
2257
2258         DBG("Unable to find any available SEP");
2259
2260         return NULL;
2261
2262 found:
2263         chan->session = avdtp_new(chan->io, device, server->seps);
2264         if (!chan->session) {
2265                 channel_remove(chan);
2266                 return NULL;
2267         }
2268
2269         return avdtp_ref(chan->session);
2270 }
2271
2272 static void connect_cb(GIOChannel *io, GError *err, gpointer user_data)
2273 {
2274         struct a2dp_channel *chan = user_data;
2275
2276         if (err) {
2277                 error("%s", err->message);
2278                 goto fail;
2279         }
2280
2281         if (!chan->session) {
2282                 chan->session = avdtp_new(chan->io, chan->device,
2283                                                         chan->server->seps);
2284                 if (!chan->session) {
2285                         error("Unable to create AVDTP session");
2286                         goto fail;
2287                 }
2288         }
2289
2290         g_io_channel_unref(chan->io);
2291         chan->io = NULL;
2292
2293         g_source_remove(chan->io_id);
2294         chan->io_id = 0;
2295
2296         return;
2297
2298 fail:
2299         channel_remove(chan);
2300 }
2301
2302 static void auth_cb(DBusError *derr, void *user_data)
2303 {
2304         struct a2dp_channel *chan = user_data;
2305         GError *err = NULL;
2306
2307         chan->auth_id = 0;
2308
2309         if (derr && dbus_error_is_set(derr)) {
2310                 error("Access denied: %s", derr->message);
2311                 goto fail;
2312         }
2313
2314         if (!bt_io_accept(chan->io, connect_cb, chan, NULL, &err)) {
2315                 error("bt_io_accept: %s", err->message);
2316                 g_error_free(err);
2317                 goto fail;
2318         }
2319
2320         return;
2321
2322 fail:
2323         channel_remove(chan);
2324 }
2325
2326 static void transport_cb(GIOChannel *io, GError *err, gpointer user_data)
2327 {
2328         struct a2dp_setup *setup = user_data;
2329         uint16_t omtu, imtu;
2330
2331         if (!g_slist_find(setups, setup)) {
2332                 warn("bt_io_accept: setup %p no longer valid", setup);
2333                 g_io_channel_shutdown(io, TRUE, NULL);
2334                 return;
2335         }
2336
2337         if (err) {
2338                 error("%s", err->message);
2339                 goto drop;
2340         }
2341
2342         bt_io_get(io, &err, BT_IO_OPT_OMTU, &omtu, BT_IO_OPT_IMTU, &imtu,
2343                                                         BT_IO_OPT_INVALID);
2344         if (err) {
2345                 error("%s", err->message);
2346                 g_error_free(err);
2347                 goto drop;
2348         }
2349
2350         if (!avdtp_stream_set_transport(setup->stream,
2351                                         g_io_channel_unix_get_fd(io),
2352                                         imtu, omtu))
2353                 goto drop;
2354
2355         g_io_channel_set_close_on_unref(io, FALSE);
2356
2357         g_io_channel_unref(setup->io);
2358         setup->io = NULL;
2359
2360         setup_unref(setup);
2361
2362         return;
2363
2364 drop:
2365         setup_unref(setup);
2366         g_io_channel_shutdown(io, TRUE, NULL);
2367
2368 }
2369 static void confirm_cb(GIOChannel *io, gpointer data)
2370 {
2371         struct a2dp_server *server = data;
2372         struct a2dp_channel *chan;
2373         char address[18];
2374         bdaddr_t src, dst;
2375         GError *err = NULL;
2376         struct btd_device *device;
2377
2378         bt_io_get(io, &err,
2379                         BT_IO_OPT_SOURCE_BDADDR, &src,
2380                         BT_IO_OPT_DEST_BDADDR, &dst,
2381                         BT_IO_OPT_DEST, address,
2382                         BT_IO_OPT_INVALID);
2383         if (err) {
2384                 error("%s", err->message);
2385                 g_error_free(err);
2386                 goto drop;
2387         }
2388
2389         DBG("AVDTP: incoming connect from %s", address);
2390
2391         device = btd_adapter_find_device(adapter_find(&src), &dst,
2392                                                                 BDADDR_BREDR);
2393         if (!device)
2394                 goto drop;
2395
2396 #ifdef TIZEN_FEATURE_BLUEZ_MODIFY
2397         if (device_is_profile_blocked(device, A2DP_SINK_UUID)) {
2398                 DBG("A2DP is restricted");
2399                 goto drop;
2400         }
2401 #endif
2402
2403         chan = queue_find(server->channels, match_by_device, device);
2404         if (chan) {
2405                 struct a2dp_setup *setup;
2406
2407                 setup = find_setup_by_session(chan->session);
2408                 if (!setup || !setup->stream)
2409                         goto drop;
2410
2411                 if (setup->io) {
2412                         error("transport channel already exists");
2413                         goto drop;
2414                 }
2415
2416                 if (!bt_io_accept(io, transport_cb, setup, NULL, &err)) {
2417                         error("bt_io_accept: %s", err->message);
2418                         g_error_free(err);
2419                         goto drop;
2420                 }
2421
2422                 /*
2423                  * Reference the channel so it can be shutdown properly
2424                  * stopping bt_io_accept from calling the callback with invalid
2425                  * setup pointer.
2426                  */
2427                 setup->io = g_io_channel_ref(io);
2428
2429                 return;
2430         }
2431
2432         chan = channel_new(server, device, io);
2433         if (!chan)
2434                 goto drop;
2435
2436         chan->auth_id = btd_request_authorization(&src, &dst,
2437                                                         ADVANCED_AUDIO_UUID,
2438                                                         auth_cb, chan);
2439         if (chan->auth_id == 0 && !chan->session)
2440                 channel_remove(chan);
2441
2442         return;
2443
2444 drop:
2445         g_io_channel_shutdown(io, TRUE, NULL);
2446 }
2447
2448 static bool a2dp_server_listen(struct a2dp_server *server)
2449 {
2450         GError *err = NULL;
2451         BtIOMode mode;
2452
2453         if (server->io)
2454                 return true;
2455
2456         if (main_opts.mps == MPS_OFF)
2457                 mode = BT_IO_MODE_BASIC;
2458         else
2459                 mode = BT_IO_MODE_STREAMING;
2460
2461 #if defined(TIZEN_FEATURE_BLUEZ_MODIFY)
2462         if (btd_adapter_get_a2dp_role(server->adapter) == BLUETOOTH_A2DP_SINK_ROLE) {
2463                 server->io = bt_io_listen(NULL, confirm_cb, server, NULL, &err,
2464                                 BT_IO_OPT_SOURCE_BDADDR,
2465                                 btd_adapter_get_address(server->adapter),
2466                                 BT_IO_OPT_PSM, AVDTP_PSM,
2467                                 BT_IO_OPT_MODE, mode,
2468                                 BT_IO_OPT_SEC_LEVEL, BT_IO_SEC_MEDIUM,
2469                                 BT_IO_OPT_IMTU, 895,
2470                                 BT_IO_OPT_MASTER, true,
2471                                 BT_IO_OPT_INVALID);
2472         } else {
2473                 server->io = bt_io_listen(NULL, confirm_cb, server, NULL, &err,
2474                                 BT_IO_OPT_SOURCE_BDADDR,
2475                                 btd_adapter_get_address(server->adapter),
2476                                 BT_IO_OPT_PSM, AVDTP_PSM,
2477                                 BT_IO_OPT_MODE, mode,
2478                                 BT_IO_OPT_SEC_LEVEL, BT_IO_SEC_MEDIUM,
2479                                 BT_IO_OPT_MASTER, true,
2480                                 BT_IO_OPT_INVALID);
2481         }
2482 #else
2483         server->io = bt_io_listen(NULL, confirm_cb, server, NULL, &err,
2484                                 BT_IO_OPT_SOURCE_BDADDR,
2485                                 btd_adapter_get_address(server->adapter),
2486                                 BT_IO_OPT_PSM, AVDTP_PSM,
2487                                 BT_IO_OPT_MODE, mode,
2488                                 BT_IO_OPT_SEC_LEVEL, BT_IO_SEC_MEDIUM,
2489                                 BT_IO_OPT_MASTER, true,
2490                                 BT_IO_OPT_INVALID);
2491 #endif
2492         if (server->io)
2493                 return true;
2494
2495         error("%s", err->message);
2496         g_error_free(err);
2497
2498         return false;
2499 }
2500
2501 static struct a2dp_server *a2dp_server_register(struct btd_adapter *adapter)
2502 {
2503         struct a2dp_server *server;
2504
2505         server = g_new0(struct a2dp_server, 1);
2506
2507         server->adapter = btd_adapter_ref(adapter);
2508         server->seps = queue_new();
2509         server->channels = queue_new();
2510
2511         servers = g_slist_append(servers, server);
2512
2513         return server;
2514 }
2515
2516 static void a2dp_unregister_sep(struct a2dp_sep *sep)
2517 {
2518         struct a2dp_server *server = sep->server;
2519
2520         if (sep->destroy) {
2521                 sep->destroy(sep->user_data);
2522                 sep->endpoint = NULL;
2523         }
2524
2525         avdtp_unregister_sep(server->seps, sep->lsep);
2526
2527         g_free(sep);
2528
2529         if (!queue_isempty(server->seps))
2530                 return;
2531
2532         if (server->io) {
2533                 g_io_channel_shutdown(server->io, TRUE, NULL);
2534                 g_io_channel_unref(server->io);
2535                 server->io = NULL;
2536         }
2537 }
2538
2539 static void a2dp_server_unregister(struct a2dp_server *server)
2540 {
2541         servers = g_slist_remove(servers, server);
2542         queue_destroy(server->channels, channel_free);
2543         queue_destroy(server->seps, NULL);
2544
2545         if (server->io) {
2546                 g_io_channel_shutdown(server->io, TRUE, NULL);
2547                 g_io_channel_unref(server->io);
2548         }
2549
2550         btd_adapter_unref(server->adapter);
2551         g_free(server);
2552 }
2553
2554 struct a2dp_sep *a2dp_add_sep(struct btd_adapter *adapter, uint8_t type,
2555                                 uint8_t codec, gboolean delay_reporting,
2556                                 struct a2dp_endpoint *endpoint,
2557                                 void *user_data, GDestroyNotify destroy,
2558                                 int *err)
2559 {
2560         struct a2dp_server *server;
2561         struct a2dp_sep *sep;
2562         GSList **l;
2563         uint32_t *record_id;
2564         sdp_record_t *record;
2565
2566         server = find_server(servers, adapter);
2567         if (server == NULL) {
2568                 if (err)
2569                         *err = -EPROTONOSUPPORT;
2570                 return NULL;
2571         }
2572
2573         if (type == AVDTP_SEP_TYPE_SINK && !server->sink_enabled) {
2574                 if (err)
2575                         *err = -EPROTONOSUPPORT;
2576                 return NULL;
2577         }
2578
2579         if (type == AVDTP_SEP_TYPE_SOURCE && !server->source_enabled) {
2580                 if (err)
2581                         *err = -EPROTONOSUPPORT;
2582                 return NULL;
2583         }
2584
2585         sep = g_new0(struct a2dp_sep, 1);
2586
2587         sep->lsep = avdtp_register_sep(server->seps, type,
2588                                         AVDTP_MEDIA_TYPE_AUDIO, codec,
2589                                         delay_reporting, &endpoint_ind,
2590                                         &cfm, sep);
2591
2592         if (sep->lsep == NULL) {
2593                 g_free(sep);
2594                 if (err)
2595                         *err = -EINVAL;
2596                 return NULL;
2597         }
2598
2599         sep->server = server;
2600         sep->endpoint = endpoint;
2601         sep->codec = codec;
2602         sep->type = type;
2603         sep->delay_reporting = delay_reporting;
2604         sep->user_data = user_data;
2605         sep->destroy = destroy;
2606
2607         if (type == AVDTP_SEP_TYPE_SOURCE) {
2608                 l = &server->sources;
2609                 record_id = &server->source_record_id;
2610         } else {
2611                 l = &server->sinks;
2612                 record_id = &server->sink_record_id;
2613         }
2614
2615         if (*record_id != 0)
2616                 goto add;
2617
2618 #ifdef TIZEN_FEATURE_BLUEZ_MODIFY
2619         if (btd_adapter_get_a2dp_role(adapter) == BLUETOOTH_A2DP_SINK_ROLE)
2620                 record = a2dp_record(type, true);
2621         else
2622                 record = a2dp_record(type, false);
2623 #else
2624         record = a2dp_record(type);
2625 #endif
2626         if (!record) {
2627                 error("Unable to allocate new service record");
2628                 a2dp_unregister_sep(sep);
2629                 if (err)
2630                         *err = -EINVAL;
2631                 return NULL;
2632         }
2633
2634         if (adapter_service_add(server->adapter, record) < 0) {
2635                 error("Unable to register A2DP service record");
2636                 sdp_record_free(record);
2637                 a2dp_unregister_sep(sep);
2638                 if (err)
2639                         *err = -EINVAL;
2640                 return NULL;
2641         }
2642
2643         if (!a2dp_server_listen(server)) {
2644                 sdp_record_free(record);
2645                 a2dp_unregister_sep(sep);
2646                 if (err)
2647                         *err = -EINVAL;
2648                 return NULL;
2649         }
2650
2651         *record_id = record->handle;
2652
2653 add:
2654         *l = g_slist_append(*l, sep);
2655
2656         if (err)
2657                 *err = 0;
2658         return sep;
2659 }
2660
2661 void a2dp_remove_sep(struct a2dp_sep *sep)
2662 {
2663         struct a2dp_server *server = sep->server;
2664
2665         if (sep->type == AVDTP_SEP_TYPE_SOURCE) {
2666                 if (g_slist_find(server->sources, sep) == NULL)
2667                         return;
2668                 server->sources = g_slist_remove(server->sources, sep);
2669                 if (server->sources == NULL && server->source_record_id) {
2670                         adapter_service_remove(server->adapter,
2671                                                 server->source_record_id);
2672                         server->source_record_id = 0;
2673                 }
2674         } else {
2675                 if (g_slist_find(server->sinks, sep) == NULL)
2676                         return;
2677                 server->sinks = g_slist_remove(server->sinks, sep);
2678                 if (server->sinks == NULL && server->sink_record_id) {
2679                         adapter_service_remove(server->adapter,
2680                                                 server->sink_record_id);
2681                         server->sink_record_id = 0;
2682                 }
2683         }
2684
2685         if (sep->locked)
2686                 return;
2687
2688         a2dp_unregister_sep(sep);
2689 }
2690
2691 static void select_cb(struct a2dp_setup *setup, void *ret, int size)
2692 {
2693         struct avdtp_service_capability *service;
2694         struct avdtp_media_codec_capability *codec;
2695         int err;
2696
2697         if (size >= 0) {
2698                 caps_add_codec(&setup->caps, setup->sep->codec, ret, size);
2699                 goto done;
2700         }
2701
2702         setup->sep = queue_pop_head(setup->eps);
2703         if (!setup->sep) {
2704                 error("Unable to select a valid configuration");
2705                 goto done;
2706         }
2707
2708         setup->rsep = find_remote_sep(setup->chan, setup->sep);
2709         service = avdtp_get_codec(setup->rsep->sep);
2710         codec = (struct avdtp_media_codec_capability *) service->data;
2711
2712         err = setup->sep->endpoint->select_configuration(setup->sep,
2713                                         codec->data,
2714                                         service->length - sizeof(*codec),
2715                                         setup,
2716                                         select_cb, setup->sep->user_data);
2717         if (err == 0)
2718                 return;
2719
2720 done:
2721         finalize_select(setup);
2722         setup_unref(setup);
2723 }
2724
2725 static struct queue *a2dp_find_eps(struct avdtp *session, GSList *list,
2726                                         const char *sender)
2727 {
2728 #ifdef TIZEN_FEATURE_BLUEZ_MODIFY
2729         struct queue *selected_sep = NULL;
2730 #endif
2731
2732         struct a2dp_channel *chan = find_channel(session);
2733         struct queue *seps = NULL;
2734
2735         for (; list; list = list->next) {
2736                 struct a2dp_sep *sep = list->data;
2737                 struct avdtp_remote_sep *rsep;
2738 #ifdef TIZEN_FEATURE_BLUEZ_MODIFY
2739                 struct avdtp_media_codec_capability *cap;
2740                 struct avdtp_service_capability *service;
2741 #endif
2742
2743                 /* Use sender's endpoint if available */
2744                 if (sender) {
2745                         const char *name;
2746
2747                         if (sep->endpoint == NULL)
2748                                 continue;
2749
2750                         name = sep->endpoint->get_name(sep, sep->user_data);
2751                         if (g_strcmp0(sender, name) != 0)
2752                                 continue;
2753                 }
2754
2755 #ifdef TIZEN_FEATURE_BLUEZ_MODIFY
2756                 rsep = avdtp_find_remote_sep(session, sep->lsep);
2757                 if (rsep == NULL)
2758                         continue;
2759
2760                 service = avdtp_get_codec(rsep);
2761                 cap = (struct avdtp_media_codec_capability *) service->data;
2762
2763                 if (cap->media_codec_type != A2DP_CODEC_VENDOR) {
2764                         if (!selected_sep)
2765                                 selected_sep = queue_new();
2766                         queue_push_head(selected_sep, sep);
2767                         continue;
2768 #ifdef TIZEN_FEATURE_SSC_ENCODER
2769                 } else {
2770                         /* This is vendor codec */
2771                         queue_push_head(selected_sep, sep);
2772                         if (endpoint_match_codec_preference(session, cap, sep))
2773                                 return selected_sep;
2774                         continue;
2775 #endif
2776                 }
2777 #else
2778                 rsep = avdtp_find_remote_sep(session, sep->lsep);
2779                 if (!rsep)
2780                         continue;
2781
2782                 if (!seps)
2783                         seps = queue_new();
2784 #endif
2785                 /* Prepend last used so it is preferred over others */
2786                 if (chan->last_used && (chan->last_used->lsep == sep &&
2787                                         chan->last_used->rsep->sep == rsep))
2788                         queue_push_head(seps, sep);
2789                 else
2790                         queue_push_tail(seps, sep);     
2791         }
2792
2793 #ifdef TIZEN_FEATURE_BLUEZ_MODIFY
2794         if (selected_sep)
2795                 return selected_sep;
2796         else
2797                 return NULL;
2798 #else
2799         return seps;
2800 #endif
2801 }
2802
2803 static struct queue *a2dp_select_eps(struct avdtp *session, uint8_t type,
2804                                         const char *sender)
2805 {
2806         struct a2dp_server *server;
2807         struct queue *seps;
2808         GSList *l;
2809
2810         server = find_server(servers, avdtp_get_adapter(session));
2811         if (!server)
2812                 return NULL;
2813
2814         l = type == AVDTP_SEP_TYPE_SINK ? server->sources : server->sinks;
2815
2816         /* Check sender's seps first */
2817         seps = a2dp_find_eps(session, l, sender);
2818         if (seps != NULL)
2819                 return seps;
2820
2821         return a2dp_find_eps(session, l, NULL);
2822 }
2823
2824 static void store_remote_sep(void *data, void *user_data)
2825 {
2826         struct a2dp_remote_sep *sep = data;
2827         GKeyFile *key_file = user_data;
2828         char seid[4], value[256];
2829         struct avdtp_service_capability *service = avdtp_get_codec(sep->sep);
2830         struct avdtp_media_codec_capability *codec = (void *) service->data;
2831         unsigned int i;
2832         ssize_t offset;
2833
2834         sprintf(seid, "%02hhx", avdtp_get_seid(sep->sep));
2835
2836         offset = sprintf(value, "%02hhx:%02hhx:%02hhx:",
2837                         avdtp_get_type(sep->sep), codec->media_codec_type,
2838                         avdtp_get_delay_reporting(sep->sep));
2839
2840         for (i = 0; i < service->length - sizeof(*codec); i++)
2841                 offset += sprintf(value + offset, "%02hhx", codec->data[i]);
2842
2843         g_key_file_set_string(key_file, "Endpoints", seid, value);
2844 }
2845
2846 static void store_remote_seps(struct a2dp_channel *chan)
2847 {
2848         struct btd_device *device = chan->device;
2849         char filename[PATH_MAX];
2850         char dst_addr[18];
2851         GKeyFile *key_file;
2852         char *data;
2853         gsize length = 0;
2854
2855         if (queue_isempty(chan->seps))
2856                 return;
2857
2858         ba2str(device_get_address(device), dst_addr);
2859
2860         snprintf(filename, PATH_MAX, STORAGEDIR "/%s/cache/%s",
2861                         btd_adapter_get_storage_dir(device_get_adapter(device)),
2862                         dst_addr);
2863         key_file = g_key_file_new();
2864         g_key_file_load_from_file(key_file, filename, 0, NULL);
2865
2866         data = g_key_file_get_string(key_file, "Endpoints", "LastUsed",
2867                                                                 NULL);
2868
2869         /* Remove current endpoints since it might have changed */
2870         g_key_file_remove_group(key_file, "Endpoints", NULL);
2871
2872         queue_foreach(chan->seps, store_remote_sep, key_file);
2873
2874         if (data) {
2875                 g_key_file_set_string(key_file, "Endpoints", "LastUsed",
2876                                                 data);
2877                 g_free(data);
2878         }
2879
2880         data = g_key_file_to_data(key_file, &length, NULL);
2881         g_file_set_contents(filename, data, length, NULL);
2882
2883         g_free(data);
2884         g_key_file_free(key_file);
2885 }
2886
2887 static void discover_cb(struct avdtp *session, GSList *seps,
2888                                 struct avdtp_error *err, void *user_data)
2889 {
2890         struct a2dp_setup *setup = user_data;
2891         uint16_t version = avdtp_get_version(session);
2892
2893         DBG("version 0x%04x err %p", version, err);
2894
2895 #ifdef TIZEN_FEATURE_BLUEZ_MODIFY
2896         if (!g_slist_find(setups, setup)) {
2897                 warn("setup %p no longer valid", setup);
2898                 return;
2899         }
2900 #endif
2901
2902         setup->seps = seps;
2903         setup->err = err;
2904
2905         if (!err) {
2906                 g_slist_foreach(seps, register_remote_sep, setup->chan);
2907
2908                 /* Only store version has been initialized as features like
2909                  * Delay Reporting may not be queried if the version in
2910                  * unknown.
2911                  */
2912                 if (version)
2913                         store_remote_seps(setup->chan);
2914         }
2915
2916         finalize_discover(setup);
2917 }
2918
2919 unsigned int a2dp_discover(struct avdtp *session, a2dp_discover_cb_t cb,
2920                                                         void *user_data)
2921 {
2922         struct a2dp_setup *setup;
2923         struct a2dp_setup_cb *cb_data;
2924
2925         setup = a2dp_setup_get(session);
2926         if (!setup)
2927                 return 0;
2928
2929         cb_data = setup_cb_new(setup);
2930         cb_data->discover_cb = cb;
2931         cb_data->user_data = user_data;
2932
2933         if (avdtp_discover(session, discover_cb, setup) == 0)
2934                 return cb_data->id;
2935
2936         setup_cb_free(cb_data);
2937         return 0;
2938 }
2939
2940 unsigned int a2dp_select_capabilities(struct avdtp *session,
2941                                         uint8_t type, const char *sender,
2942                                         a2dp_select_cb_t cb,
2943                                         void *user_data)
2944 {
2945         struct a2dp_setup *setup;
2946         struct a2dp_setup_cb *cb_data;
2947         struct queue *eps;
2948         struct avdtp_service_capability *service;
2949         struct avdtp_media_codec_capability *codec;
2950         int err;
2951
2952         eps = a2dp_select_eps(session, type, sender);
2953         if (!eps) {
2954                 error("Unable to select SEP");
2955                 return 0;
2956         }
2957
2958         setup = a2dp_setup_get(session);
2959         if (!setup)
2960                 return 0;
2961
2962         cb_data = setup_cb_new(setup);
2963         cb_data->select_cb = cb;
2964         cb_data->user_data = user_data;
2965
2966         setup->eps = eps;
2967         setup->sep = queue_pop_head(eps);
2968         setup->rsep = find_remote_sep(setup->chan, setup->sep);
2969
2970         if (setup->rsep == NULL) {
2971                 error("Could not find remote sep");
2972                 goto fail;
2973         }
2974
2975         service = avdtp_get_codec(setup->rsep->sep);
2976         codec = (struct avdtp_media_codec_capability *) service->data;
2977
2978         err = setup->sep->endpoint->select_configuration(setup->sep,
2979                                                         codec->data,
2980                                                         service->length -
2981                                                         sizeof(*codec),
2982                                                         setup_ref(setup),
2983                                                         select_cb,
2984                                                         setup->sep->user_data);
2985         if (err == 0)
2986                 return cb_data->id;
2987
2988         setup_unref(setup);
2989
2990 fail:
2991         setup_cb_free(cb_data);
2992         return 0;
2993
2994 }
2995
2996 unsigned int a2dp_config(struct avdtp *session, struct a2dp_sep *sep,
2997                                 a2dp_config_cb_t cb, GSList *caps,
2998                                 void *user_data)
2999 {
3000         struct a2dp_setup_cb *cb_data;
3001         GSList *l;
3002         struct a2dp_server *server;
3003         struct a2dp_setup *setup;
3004         struct a2dp_sep *tmp;
3005         struct avdtp_service_capability *cap;
3006         struct avdtp_media_codec_capability *codec_cap = NULL;
3007         int posix_err;
3008
3009         server = find_server(servers, avdtp_get_adapter(session));
3010         if (!server)
3011                 return 0;
3012
3013         for (l = caps; l != NULL; l = l->next) {
3014                 cap = l->data;
3015
3016                 if (cap->category != AVDTP_MEDIA_CODEC)
3017                         continue;
3018
3019                 codec_cap = (void *) cap->data;
3020                 break;
3021         }
3022
3023         if (!codec_cap)
3024                 return 0;
3025
3026         if (sep->codec != codec_cap->media_codec_type)
3027                 return 0;
3028
3029         DBG("a2dp_config: selected SEP %p", sep->lsep);
3030
3031         setup = a2dp_setup_get(session);
3032         if (!setup)
3033                 return 0;
3034
3035         cb_data = setup_cb_new(setup);
3036         cb_data->config_cb = cb;
3037         cb_data->user_data = user_data;
3038
3039         setup->sep = sep;
3040         setup->stream = sep->stream;
3041
3042         /* Copy given caps if they are different than current caps */
3043         if (setup->caps != caps) {
3044                 g_slist_free_full(setup->caps, g_free);
3045                 setup->caps = g_slist_copy(caps);
3046         }
3047
3048         switch (avdtp_sep_get_state(sep->lsep)) {
3049         case AVDTP_STATE_IDLE:
3050                 if (sep->type == AVDTP_SEP_TYPE_SOURCE)
3051                         l = server->sources;
3052                 else
3053                         l = server->sinks;
3054
3055                 for (; l != NULL; l = l->next) {
3056                         tmp = l->data;
3057                         if (avdtp_has_stream(session, tmp->stream))
3058                                 break;
3059                 }
3060
3061                 if (l != NULL) {
3062                         if (tmp->locked)
3063                                 goto failed;
3064                         setup->reconfigure = TRUE;
3065                         if (avdtp_close(session, tmp->stream, FALSE) < 0) {
3066                                 error("avdtp_close failed");
3067                                 goto failed;
3068                         }
3069                         break;
3070                 }
3071
3072                 setup->rsep = find_remote_sep(setup->chan, sep);
3073                 if (setup->rsep == NULL) {
3074                         error("No matching ACP and INT SEPs found");
3075                         goto failed;
3076                 }
3077
3078                 posix_err = avdtp_set_configuration(session, setup->rsep->sep,
3079                                                         sep->lsep, caps,
3080                                                         &setup->stream);
3081                 if (posix_err < 0) {
3082                         error("avdtp_set_configuration: %s",
3083                                 strerror(-posix_err));
3084                         goto failed;
3085                 }
3086                 break;
3087         case AVDTP_STATE_OPEN:
3088         case AVDTP_STATE_STREAMING:
3089                 if (avdtp_stream_has_capabilities(setup->stream, caps)) {
3090                         DBG("Configuration match: resuming");
3091                         cb_data->source_id = g_idle_add(finalize_config,
3092                                                                 setup);
3093                 } else if (!setup->reconfigure) {
3094                         setup->reconfigure = TRUE;
3095                         if (avdtp_close(session, sep->stream, FALSE) < 0) {
3096                                 error("avdtp_close failed");
3097                                 goto failed;
3098                         }
3099                 }
3100                 break;
3101         case AVDTP_STATE_CONFIGURED:
3102         case AVDTP_STATE_CLOSING:
3103         case AVDTP_STATE_ABORTING:
3104         default:
3105                 error("SEP in bad state for requesting a new stream");
3106                 goto failed;
3107         }
3108
3109         return cb_data->id;
3110
3111 failed:
3112         setup_cb_free(cb_data);
3113         return 0;
3114 }
3115
3116 unsigned int a2dp_resume(struct avdtp *session, struct a2dp_sep *sep,
3117                                 a2dp_stream_cb_t cb, void *user_data)
3118 {
3119         struct a2dp_setup_cb *cb_data;
3120         struct a2dp_setup *setup;
3121
3122         setup = a2dp_setup_get(session);
3123         if (!setup)
3124                 return 0;
3125
3126         cb_data = setup_cb_new(setup);
3127         cb_data->resume_cb = cb;
3128         cb_data->user_data = user_data;
3129
3130         setup->sep = sep;
3131         setup->stream = sep->stream;
3132
3133         switch (avdtp_sep_get_state(sep->lsep)) {
3134         case AVDTP_STATE_IDLE:
3135                 goto failed;
3136                 break;
3137         case AVDTP_STATE_CONFIGURED:
3138                 setup->start = TRUE;
3139                 break;
3140         case AVDTP_STATE_OPEN:
3141                 if (avdtp_start(session, sep->stream) < 0) {
3142                         error("avdtp_start failed");
3143                         goto failed;
3144                 }
3145                 sep->starting = TRUE;
3146                 break;
3147         case AVDTP_STATE_STREAMING:
3148                 if (!sep->suspending && sep->suspend_timer) {
3149                         g_source_remove(sep->suspend_timer);
3150                         sep->suspend_timer = 0;
3151                         avdtp_unref(sep->session);
3152                         sep->session = NULL;
3153                 }
3154                 if (sep->suspending)
3155                         setup->start = TRUE;
3156                 else
3157                         cb_data->source_id = g_idle_add(finalize_resume,
3158                                                                 setup);
3159                 break;
3160         case AVDTP_STATE_CLOSING:
3161         case AVDTP_STATE_ABORTING:
3162         default:
3163                 error("SEP in bad state for resume");
3164                 goto failed;
3165         }
3166
3167         return cb_data->id;
3168
3169 failed:
3170         setup_cb_free(cb_data);
3171         return 0;
3172 }
3173
3174 unsigned int a2dp_suspend(struct avdtp *session, struct a2dp_sep *sep,
3175                                 a2dp_stream_cb_t cb, void *user_data)
3176 {
3177         struct a2dp_setup_cb *cb_data;
3178         struct a2dp_setup *setup;
3179
3180         setup = a2dp_setup_get(session);
3181         if (!setup)
3182                 return 0;
3183
3184         cb_data = setup_cb_new(setup);
3185         cb_data->suspend_cb = cb;
3186         cb_data->user_data = user_data;
3187
3188         setup->sep = sep;
3189         setup->stream = sep->stream;
3190
3191         switch (avdtp_sep_get_state(sep->lsep)) {
3192         case AVDTP_STATE_IDLE:
3193                 error("a2dp_suspend: no stream to suspend");
3194                 goto failed;
3195                 break;
3196         case AVDTP_STATE_OPEN:
3197                 cb_data->source_id = g_idle_add(finalize_suspend, setup);
3198                 break;
3199         case AVDTP_STATE_STREAMING:
3200                 if (avdtp_suspend(session, sep->stream) < 0) {
3201                         error("avdtp_suspend failed");
3202                         goto failed;
3203                 }
3204                 sep->suspending = TRUE;
3205                 break;
3206         case AVDTP_STATE_CONFIGURED:
3207         case AVDTP_STATE_CLOSING:
3208         case AVDTP_STATE_ABORTING:
3209         default:
3210                 error("SEP in bad state for suspend");
3211                 goto failed;
3212         }
3213
3214         return cb_data->id;
3215
3216 failed:
3217         setup_cb_free(cb_data);
3218         return 0;
3219 }
3220
3221 gboolean a2dp_cancel(unsigned int id)
3222 {
3223         GSList *ls;
3224
3225         for (ls = setups; ls != NULL; ls = g_slist_next(ls)) {
3226                 struct a2dp_setup *setup = ls->data;
3227                 GSList *l;
3228                 for (l = setup->cb; l != NULL; l = g_slist_next(l)) {
3229                         struct a2dp_setup_cb *cb = l->data;
3230
3231                         if (cb->id != id)
3232                                 continue;
3233
3234                         setup_ref(setup);
3235                         setup_cb_free(cb);
3236
3237                         if (!setup->cb) {
3238                                 DBG("aborting setup %p", setup);
3239                                 if (!avdtp_abort(setup->session, setup->stream))
3240                                         return TRUE;
3241                         }
3242
3243                         setup_unref(setup);
3244                         return TRUE;
3245                 }
3246         }
3247
3248         return FALSE;
3249 }
3250
3251 gboolean a2dp_sep_lock(struct a2dp_sep *sep, struct avdtp *session)
3252 {
3253         if (sep->locked)
3254                 return FALSE;
3255
3256         DBG("SEP %p locked", sep->lsep);
3257         sep->locked = TRUE;
3258
3259         return TRUE;
3260 }
3261
3262 gboolean a2dp_sep_unlock(struct a2dp_sep *sep, struct avdtp *session)
3263 {
3264         struct a2dp_server *server = sep->server;
3265         avdtp_state_t state;
3266         GSList *l;
3267
3268         state = avdtp_sep_get_state(sep->lsep);
3269
3270         sep->locked = FALSE;
3271
3272         DBG("SEP %p unlocked", sep->lsep);
3273
3274         if (sep->type == AVDTP_SEP_TYPE_SOURCE)
3275                 l = server->sources;
3276         else
3277                 l = server->sinks;
3278
3279         /* Unregister sep if it was removed */
3280         if (g_slist_find(l, sep) == NULL) {
3281                 a2dp_unregister_sep(sep);
3282                 return TRUE;
3283         }
3284
3285         if (!sep->stream || state == AVDTP_STATE_IDLE)
3286                 return TRUE;
3287
3288         switch (state) {
3289         case AVDTP_STATE_OPEN:
3290                 /* Set timer here */
3291                 break;
3292         case AVDTP_STATE_STREAMING:
3293                 if (avdtp_suspend(session, sep->stream) == 0)
3294                         sep->suspending = TRUE;
3295                 break;
3296         case AVDTP_STATE_IDLE:
3297         case AVDTP_STATE_CONFIGURED:
3298         case AVDTP_STATE_CLOSING:
3299         case AVDTP_STATE_ABORTING:
3300         default:
3301                 break;
3302         }
3303
3304         return TRUE;
3305 }
3306
3307 struct avdtp_stream *a2dp_sep_get_stream(struct a2dp_sep *sep)
3308 {
3309         return sep->stream;
3310 }
3311
3312 struct btd_device *a2dp_setup_get_device(struct a2dp_setup *setup)
3313 {
3314         if (setup->session == NULL)
3315                 return NULL;
3316
3317         return avdtp_get_device(setup->session);
3318 }
3319
3320 const char *a2dp_setup_remote_path(struct a2dp_setup *setup)
3321 {
3322         if (setup->rsep) {
3323                 return setup->rsep->path;
3324         }
3325
3326         return NULL;
3327 }
3328
3329 static int a2dp_source_probe(struct btd_service *service)
3330 {
3331         struct btd_device *dev = btd_service_get_device(service);
3332
3333         DBG("path %s", device_get_path(dev));
3334
3335         source_init(service);
3336
3337         return 0;
3338 }
3339
3340 static void a2dp_source_remove(struct btd_service *service)
3341 {
3342         source_unregister(service);
3343 }
3344
3345 static int a2dp_sink_probe(struct btd_service *service)
3346 {
3347         struct btd_device *dev = btd_service_get_device(service);
3348
3349         DBG("path %s", device_get_path(dev));
3350
3351         return sink_init(service);
3352 }
3353
3354 static void a2dp_sink_remove(struct btd_service *service)
3355 {
3356         sink_unregister(service);
3357 }
3358
3359 static int a2dp_source_connect(struct btd_service *service)
3360 {
3361         struct btd_device *dev = btd_service_get_device(service);
3362         struct btd_adapter *adapter = device_get_adapter(dev);
3363         struct a2dp_server *server;
3364         const char *path = device_get_path(dev);
3365
3366         DBG("path %s", path);
3367
3368         server = find_server(servers, adapter);
3369         if (!server || !server->sink_enabled) {
3370                 DBG("Unexpected error: cannot find server");
3371                 return -EPROTONOSUPPORT;
3372         }
3373
3374         /* Return protocol not available if no record/endpoint exists */
3375         if (server->sink_record_id == 0)
3376                 return -ENOPROTOOPT;
3377
3378         return source_connect(service);
3379 }
3380
3381 static int a2dp_source_disconnect(struct btd_service *service)
3382 {
3383         struct btd_device *dev = btd_service_get_device(service);
3384         const char *path = device_get_path(dev);
3385
3386         DBG("path %s", path);
3387
3388         return source_disconnect(service);
3389 }
3390
3391 static int a2dp_sink_connect(struct btd_service *service)
3392 {
3393         struct btd_device *dev = btd_service_get_device(service);
3394         struct btd_adapter *adapter = device_get_adapter(dev);
3395         struct a2dp_server *server;
3396         const char *path = device_get_path(dev);
3397
3398         DBG("path %s", path);
3399
3400         server = find_server(servers, adapter);
3401         if (!server || !server->source_enabled) {
3402                 DBG("Unexpected error: cannot find server");
3403                 return -EPROTONOSUPPORT;
3404         }
3405
3406         /* Return protocol not available if no record/endpoint exists */
3407         if (server->source_record_id == 0)
3408                 return -ENOPROTOOPT;
3409
3410         return sink_connect(service);
3411 }
3412
3413 static int a2dp_sink_disconnect(struct btd_service *service)
3414 {
3415         struct btd_device *dev = btd_service_get_device(service);
3416         const char *path = device_get_path(dev);
3417
3418         DBG("path %s", path);
3419
3420         return sink_disconnect(service);
3421 }
3422
3423 static int a2dp_source_server_probe(struct btd_profile *p,
3424                                                 struct btd_adapter *adapter)
3425 {
3426         struct a2dp_server *server;
3427
3428         DBG("path %s", adapter_get_path(adapter));
3429
3430         server = find_server(servers, adapter);
3431         if (server != NULL)
3432                 goto done;
3433
3434         server = a2dp_server_register(adapter);
3435         if (server == NULL)
3436                 return -EPROTONOSUPPORT;
3437
3438 done:
3439         server->source_enabled = TRUE;
3440
3441         return 0;
3442 }
3443
3444 static void a2dp_source_server_remove(struct btd_profile *p,
3445                                                 struct btd_adapter *adapter)
3446 {
3447         struct a2dp_server *server;
3448
3449         DBG("path %s", adapter_get_path(adapter));
3450
3451         server = find_server(servers, adapter);
3452         if (!server)
3453                 return;
3454
3455         g_slist_free_full(server->sources,
3456                                         (GDestroyNotify) a2dp_unregister_sep);
3457
3458         if (server->source_record_id) {
3459                 adapter_service_remove(server->adapter,
3460                                         server->source_record_id);
3461                 server->source_record_id = 0;
3462         }
3463
3464         if (server->sink_record_id)
3465                 return;
3466
3467         a2dp_server_unregister(server);
3468 }
3469
3470 static int a2dp_sink_server_probe(struct btd_profile *p,
3471                                                 struct btd_adapter *adapter)
3472 {
3473         struct a2dp_server *server;
3474
3475         DBG("path %s", adapter_get_path(adapter));
3476
3477         server = find_server(servers, adapter);
3478         if (server != NULL)
3479                 goto done;
3480
3481         server = a2dp_server_register(adapter);
3482         if (server == NULL)
3483                 return -EPROTONOSUPPORT;
3484
3485 done:
3486         server->sink_enabled = TRUE;
3487
3488         return 0;
3489 }
3490
3491 static void a2dp_sink_server_remove(struct btd_profile *p,
3492                                                 struct btd_adapter *adapter)
3493 {
3494         struct a2dp_server *server;
3495
3496         DBG("path %s", adapter_get_path(adapter));
3497
3498         server = find_server(servers, adapter);
3499         if (!server)
3500                 return;
3501
3502         g_slist_free_full(server->sinks, (GDestroyNotify) a2dp_unregister_sep);
3503
3504         if (server->sink_record_id) {
3505                 adapter_service_remove(server->adapter, server->sink_record_id);
3506                 server->sink_record_id = 0;
3507         }
3508
3509         if (server->source_record_id)
3510                 return;
3511
3512         a2dp_server_unregister(server);
3513 }
3514
3515 static int media_server_probe(struct btd_adapter *adapter)
3516 {
3517         DBG("path %s", adapter_get_path(adapter));
3518
3519         return media_register(adapter);
3520 }
3521
3522 static void media_server_remove(struct btd_adapter *adapter)
3523 {
3524         DBG("path %s", adapter_get_path(adapter));
3525
3526         media_unregister(adapter);
3527 }
3528
3529 static struct btd_profile a2dp_source_profile = {
3530         .name           = "a2dp-source",
3531         .priority       = BTD_PROFILE_PRIORITY_MEDIUM,
3532
3533         .remote_uuid    = A2DP_SOURCE_UUID,
3534         .device_probe   = a2dp_source_probe,
3535         .device_remove  = a2dp_source_remove,
3536
3537         .auto_connect   = true,
3538         .connect        = a2dp_source_connect,
3539         .disconnect     = a2dp_source_disconnect,
3540
3541         .adapter_probe  = a2dp_sink_server_probe,
3542         .adapter_remove = a2dp_sink_server_remove,
3543 };
3544
3545 static struct btd_profile a2dp_sink_profile = {
3546         .name           = "a2dp-sink",
3547         .priority       = BTD_PROFILE_PRIORITY_MEDIUM,
3548
3549         .remote_uuid    = A2DP_SINK_UUID,
3550         .device_probe   = a2dp_sink_probe,
3551         .device_remove  = a2dp_sink_remove,
3552
3553         .auto_connect   = true,
3554         .connect        = a2dp_sink_connect,
3555         .disconnect     = a2dp_sink_disconnect,
3556
3557         .adapter_probe  = a2dp_source_server_probe,
3558         .adapter_remove = a2dp_source_server_remove,
3559 };
3560
3561 static struct btd_adapter_driver media_driver = {
3562         .name           = "media",
3563         .probe          = media_server_probe,
3564         .remove         = media_server_remove,
3565 };
3566
3567 static int a2dp_init(void)
3568 {
3569         btd_register_adapter_driver(&media_driver);
3570         btd_profile_register(&a2dp_source_profile);
3571         btd_profile_register(&a2dp_sink_profile);
3572
3573         return 0;
3574 }
3575
3576 static void a2dp_exit(void)
3577 {
3578         btd_unregister_adapter_driver(&media_driver);
3579         btd_profile_unregister(&a2dp_source_profile);
3580         btd_profile_unregister(&a2dp_sink_profile);
3581 }
3582
3583 BLUETOOTH_PLUGIN_DEFINE(a2dp, VERSION, BLUETOOTH_PLUGIN_PRIORITY_DEFAULT,
3584                 a2dp_init, a2dp_exit)