summaryrefslogtreecommitdiff
path: root/src/components/media_manager/src/audio/a2dp_source_player_adapter.cc
blob: 91e3c5465dda4be710852d3228125bcf2fe41a9e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
/*
 * Copyright (c) 2014, Ford Motor Company
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following
 * disclaimer in the documentation and/or other materials provided with the
 * distribution.
 *
 * Neither the name of the Ford Motor Company nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
#include <net/if.h>
#include <pulse/simple.h>
#include <pulse/error.h>
#include <string.h>
#include <utility>
#include "utils/threads/thread.h"
#include "media_manager/audio/a2dp_source_player_adapter.h"
#include "utils/lock.h"
#include "utils/logger.h"
#include "connection_handler/connection_handler_impl.h"
#include "protocol_handler/session_observer.h"

namespace media_manager {

CREATE_LOGGERPTR_GLOBAL(logger_, "MediaManager")

const static size_t BUFSIZE = 32;

class A2DPSourcePlayerAdapter::A2DPSourcePlayerThread
    : public threads::ThreadDelegate {
 public:
  explicit A2DPSourcePlayerThread(const std::string& device);

  void threadMain();

  void exitThreadMain();

 private:
  // The Sample format to use
  static const pa_sample_spec sSampleFormat_;

  pa_simple* s_in, *s_out;
  std::string device_;
  bool should_be_stopped_;
  sync_primitives::Lock should_be_stopped_lock_;

  void freeStreams();

  DISALLOW_COPY_AND_ASSIGN(A2DPSourcePlayerThread);
};

A2DPSourcePlayerAdapter::A2DPSourcePlayerAdapter(
    protocol_handler::SessionObserver& session_observer)
    : session_observer_(session_observer) {}

A2DPSourcePlayerAdapter::~A2DPSourcePlayerAdapter() {
  for (SourcesMap::iterator it = sources_.begin(); sources_.end() != it; ++it) {
    Pair pair = it->second;
    pair.first->join();
    delete pair.second;
    threads::DeleteThread(pair.first);
  }
  sources_.clear();
}

void A2DPSourcePlayerAdapter::StartActivity(int32_t application_key) {
  LOG4CXX_INFO(logger_,
               "Starting a2dp playing music for " << application_key
                                                  << " application.");
  if (application_key != current_application_) {
    current_application_ = application_key;

    transport_manager::DeviceHandle device_id = 0;
    session_observer_.GetDataOnSessionKey(application_key, 0, NULL, &device_id);
    std::string mac_address;
    session_observer_.GetDataOnDeviceID(device_id, NULL, NULL, &mac_address);

    // TODO(PK): Convert mac_address to the
    // following format : "bluez_source.XX_XX_XX_XX_XX_XX" if needed
    // before passing to the A2DPSourcePlayerThread constructor

    A2DPSourcePlayerThread* delegate =
        new A2DPSourcePlayerAdapter::A2DPSourcePlayerThread(mac_address);
    threads::Thread* new_activity =
        threads::CreateThread(mac_address.c_str(), delegate);
    sources_[application_key] = Pair(new_activity, delegate);
    new_activity->start();
  }
}

void A2DPSourcePlayerAdapter::StopActivity(int32_t application_key) {
  LOG4CXX_INFO(logger_,
               "Stopping 2dp playing for " << application_key
                                           << " application.");
  if (application_key != current_application_) {
    return;
  }
  SourcesMap::iterator it = sources_.find(application_key);
  if (sources_.end() != it) {
    Pair pair = it->second;
    pair.first->join();
    delete pair.second;
    threads::DeleteThread(pair.first);
    current_application_ = 0;
  }
}

bool A2DPSourcePlayerAdapter::is_app_performing_activity(
    int32_t application_key) const {
  return (application_key == current_application_);
}

const pa_sample_spec
    A2DPSourcePlayerAdapter::A2DPSourcePlayerThread::sSampleFormat_ = {
        /*format*/ PA_SAMPLE_S16LE,
        /*rate*/ 44100,
        /*channels*/ 2};

A2DPSourcePlayerAdapter::A2DPSourcePlayerThread::A2DPSourcePlayerThread(
    const std::string& device)
    : threads::ThreadDelegate(), device_(device) {}

void A2DPSourcePlayerAdapter::A2DPSourcePlayerThread::freeStreams() {
  LOG4CXX_INFO(logger_, "Free streams in A2DPSourcePlayerThread.");
  if (s_in) {
    pa_simple_free(s_in);
  }

  if (s_out) {
    pa_simple_free(s_out);
  }
}

void A2DPSourcePlayerAdapter::A2DPSourcePlayerThread::exitThreadMain() {
  sync_primitives::AutoLock auto_lock(should_be_stopped_lock_);
  should_be_stopped_ = true;
}

void A2DPSourcePlayerAdapter::A2DPSourcePlayerThread::threadMain() {
  LOG4CXX_INFO(logger_, "Main thread of A2DPSourcePlayerThread.");

  {
    sync_primitives::AutoLock auto_lock(should_be_stopped_lock_);
    should_be_stopped_ = false;
  }

  int32_t error;

  const char* a2dpSource = device_.c_str();

  LOG4CXX_DEBUG(logger_, device_);

  LOG4CXX_DEBUG(logger_, "Creating streams");

  /* Create a new playback stream */
  if (!(s_out = pa_simple_new(NULL,
                              "AudioManager",
                              PA_STREAM_PLAYBACK,
                              NULL,
                              "playback",
                              &sSampleFormat_,
                              NULL,
                              NULL,
                              &error))) {
    LOG4CXX_ERROR(logger_, "pa_simple_new() failed: " << pa_strerror(error));
    freeStreams();
    return;
  }

  if (!(s_in = pa_simple_new(NULL,
                             "AudioManager",
                             PA_STREAM_RECORD,
                             a2dpSource,
                             "record",
                             &sSampleFormat_,
                             NULL,
                             NULL,
                             &error))) {
    LOG4CXX_ERROR(logger_, "pa_simple_new() failed: " << pa_strerror(error));
    freeStreams();
    return;
  }

  LOG4CXX_DEBUG(logger_, "Entering main loop");

  for (;;) {
    uint8_t buf[BUFSIZE];

    pa_usec_t latency;

    if ((latency = pa_simple_get_latency(s_in, &error)) == (pa_usec_t)-1) {
      LOG4CXX_ERROR(logger_,
                    "pa_simple_get_latency() failed: " << pa_strerror(error));
      break;
    }

    // LOG4CXX_INFO(logger_, "In: " << static_cast<float>(latency));

    if ((latency = pa_simple_get_latency(s_out, &error)) == (pa_usec_t)-1) {
      LOG4CXX_ERROR(logger_,
                    "pa_simple_get_latency() failed: " << pa_strerror(error));
      break;
    }

    // LOG4CXX_INFO(logger_, "Out: " << static_cast<float>(latency));

    if (pa_simple_read(s_in, buf, sizeof(buf), &error) < 0) {
      LOG4CXX_ERROR(logger_, "read() failed: " << strerror(error));
      break;
    }

    /* ... and play it */
    if (pa_simple_write(s_out, buf, sizeof(buf), &error) < 0) {
      LOG4CXX_ERROR(logger_,
                    "pa_simple_write() failed: " << pa_strerror(error));
      break;
    }

    bool should_be_stopped;
    {
      // FIXME (dchmerev@luxoft.com): Remove these insane blockings
      sync_primitives::AutoLock auto_lock(should_be_stopped_lock_);
      should_be_stopped = should_be_stopped_;
    }

    if (should_be_stopped) {
      break;
    }
  }

  /* Make sure that every single sample was played */
  if (pa_simple_drain(s_out, &error) < 0) {
    LOG4CXX_ERROR(logger_, "pa_simple_drain() failed: " << pa_strerror(error));
    freeStreams();
    return;
  }

  freeStreams();
}

}  // namespace media_manager