You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1559 lines
46 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * libjingle
  3. * Copyright 2010, Google Inc.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice,
  9. * this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright notice,
  11. * this list of conditions and the following disclaimer in the documentation
  12. * and/or other materials provided with the distribution.
  13. * 3. The name of the author may not be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
  17. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  18. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  19. * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  20. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  21. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  22. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  23. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  24. * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  25. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include "talk/sound/pulseaudiosoundsystem.h"
  28. #ifdef HAVE_LIBPULSE
  29. #include "talk/base/common.h"
  30. #include "talk/base/fileutils.h" // for GetApplicationName()
  31. #include "talk/base/logging.h"
  32. #include "talk/base/worker.h"
  33. #include "talk/base/timeutils.h"
  34. #include "talk/sound/sounddevicelocator.h"
  35. #include "talk/sound/soundinputstreaminterface.h"
  36. #include "talk/sound/soundoutputstreaminterface.h"
  37. namespace cricket {
  38. // First PulseAudio protocol version that supports PA_STREAM_ADJUST_LATENCY.
  39. static const uint32_t kAdjustLatencyProtocolVersion = 13;
  40. // Lookup table from the cricket format enum in soundsysteminterface.h to
  41. // Pulse's enums.
  42. static const pa_sample_format_t kCricketFormatToPulseFormatTable[] = {
  43. // The order here must match the order in soundsysteminterface.h
  44. PA_SAMPLE_S16LE,
  45. };
  46. // Some timing constants for optimal operation. See
  47. // https://tango.0pointer.de/pipermail/pulseaudio-discuss/2008-January/001170.html
  48. // for a good explanation of some of the factors that go into this.
  49. // Playback.
  50. // For playback, there is a round-trip delay to fill the server-side playback
  51. // buffer, so setting too low of a latency is a buffer underflow risk. We will
  52. // automatically increase the latency if a buffer underflow does occur, but we
  53. // also enforce a sane minimum at start-up time. Anything lower would be
  54. // virtually guaranteed to underflow at least once, so there's no point in
  55. // allowing lower latencies.
  56. static const int kPlaybackLatencyMinimumMsecs = 20;
  57. // Every time a playback stream underflows, we will reconfigure it with target
  58. // latency that is greater by this amount.
  59. static const int kPlaybackLatencyIncrementMsecs = 20;
  60. // We also need to configure a suitable request size. Too small and we'd burn
  61. // CPU from the overhead of transfering small amounts of data at once. Too large
  62. // and the amount of data remaining in the buffer right before refilling it
  63. // would be a buffer underflow risk. We set it to half of the buffer size.
  64. static const int kPlaybackRequestFactor = 2;
  65. // Capture.
  66. // For capture, low latency is not a buffer overflow risk, but it makes us burn
  67. // CPU from the overhead of transfering small amounts of data at once, so we set
  68. // a recommended value that we use for the kLowLatency constant (but if the user
  69. // explicitly requests something lower then we will honour it).
  70. // 1ms takes about 6-7% CPU. 5ms takes about 5%. 10ms takes about 4.x%.
  71. static const int kLowCaptureLatencyMsecs = 10;
  72. // There is a round-trip delay to ack the data to the server, so the
  73. // server-side buffer needs extra space to prevent buffer overflow. 20ms is
  74. // sufficient, but there is no penalty to making it bigger, so we make it huge.
  75. // (750ms is libpulse's default value for the _total_ buffer size in the
  76. // kNoLatencyRequirements case.)
  77. static const int kCaptureBufferExtraMsecs = 750;
  78. static void FillPlaybackBufferAttr(int latency,
  79. pa_buffer_attr *attr) {
  80. attr->maxlength = latency;
  81. attr->tlength = latency;
  82. attr->minreq = latency / kPlaybackRequestFactor;
  83. attr->prebuf = attr->tlength - attr->minreq;
  84. LOG(LS_VERBOSE) << "Configuring latency = " << attr->tlength << ", minreq = "
  85. << attr->minreq << ", minfill = " << attr->prebuf;
  86. }
  87. static pa_volume_t CricketVolumeToPulseVolume(int volume) {
  88. // PA's volume space goes from 0% at PA_VOLUME_MUTED (value 0) to 100% at
  89. // PA_VOLUME_NORM (value 0x10000). It can also go beyond 100% up to
  90. // PA_VOLUME_MAX (value UINT32_MAX-1), but using that is probably unwise.
  91. // We just linearly map the 0-255 scale of SoundSystemInterface onto
  92. // PA_VOLUME_MUTED-PA_VOLUME_NORM. If the programmer exceeds kMaxVolume then
  93. // they can access the over-100% features of PA.
  94. return PA_VOLUME_MUTED + (PA_VOLUME_NORM - PA_VOLUME_MUTED) *
  95. volume / SoundSystemInterface::kMaxVolume;
  96. }
  97. static int PulseVolumeToCricketVolume(pa_volume_t pa_volume) {
  98. return SoundSystemInterface::kMinVolume +
  99. (SoundSystemInterface::kMaxVolume - SoundSystemInterface::kMinVolume) *
  100. pa_volume / PA_VOLUME_NORM;
  101. }
  102. static pa_volume_t MaxChannelVolume(pa_cvolume *channel_volumes) {
  103. pa_volume_t pa_volume = PA_VOLUME_MUTED; // Minimum possible value.
  104. for (int i = 0; i < channel_volumes->channels; ++i) {
  105. if (pa_volume < channel_volumes->values[i]) {
  106. pa_volume = channel_volumes->values[i];
  107. }
  108. }
  109. return pa_volume;
  110. }
  111. class PulseAudioDeviceLocator : public SoundDeviceLocator {
  112. public:
  113. PulseAudioDeviceLocator(const std::string &name,
  114. const std::string &device_name)
  115. : SoundDeviceLocator(name, device_name) {
  116. }
  117. virtual SoundDeviceLocator *Copy() const {
  118. return new PulseAudioDeviceLocator(*this);
  119. }
  120. };
  121. // Functionality that is common to both PulseAudioInputStream and
  122. // PulseAudioOutputStream.
  123. class PulseAudioStream {
  124. public:
  125. PulseAudioStream(PulseAudioSoundSystem *pulse, pa_stream *stream, int flags)
  126. : pulse_(pulse), stream_(stream), flags_(flags) {
  127. }
  128. ~PulseAudioStream() {
  129. // Close() should have been called during the containing class's destructor.
  130. ASSERT(stream_ == NULL);
  131. }
  132. // Must be called with the lock held.
  133. bool Close() {
  134. if (!IsClosed()) {
  135. // Unset this here so that we don't get a TERMINATED callback.
  136. symbol_table()->pa_stream_set_state_callback()(stream_, NULL, NULL);
  137. if (symbol_table()->pa_stream_disconnect()(stream_) != 0) {
  138. LOG(LS_ERROR) << "Can't disconnect stream";
  139. // Continue and return true anyways.
  140. }
  141. symbol_table()->pa_stream_unref()(stream_);
  142. stream_ = NULL;
  143. }
  144. return true;
  145. }
  146. // Must be called with the lock held.
  147. int LatencyUsecs() {
  148. if (!(flags_ & SoundSystemInterface::FLAG_REPORT_LATENCY)) {
  149. return 0;
  150. }
  151. pa_usec_t latency;
  152. int negative;
  153. Lock();
  154. int re = symbol_table()->pa_stream_get_latency()(stream_, &latency,
  155. &negative);
  156. Unlock();
  157. if (re != 0) {
  158. LOG(LS_ERROR) << "Can't query latency";
  159. // We'd rather continue playout/capture with an incorrect delay than stop
  160. // it altogether, so return a valid value.
  161. return 0;
  162. }
  163. if (negative) {
  164. // The delay can be negative for monitoring streams if the captured
  165. // samples haven't been played yet. In such a case, "latency" contains the
  166. // magnitude, so we must negate it to get the real value.
  167. return -latency;
  168. } else {
  169. return latency;
  170. }
  171. }
  172. PulseAudioSoundSystem *pulse() {
  173. return pulse_;
  174. }
  175. PulseAudioSymbolTable *symbol_table() {
  176. return &pulse()->symbol_table_;
  177. }
  178. pa_stream *stream() {
  179. ASSERT(stream_ != NULL);
  180. return stream_;
  181. }
  182. bool IsClosed() {
  183. return stream_ == NULL;
  184. }
  185. void Lock() {
  186. pulse()->Lock();
  187. }
  188. void Unlock() {
  189. pulse()->Unlock();
  190. }
  191. private:
  192. PulseAudioSoundSystem *pulse_;
  193. pa_stream *stream_;
  194. int flags_;
  195. DISALLOW_COPY_AND_ASSIGN(PulseAudioStream);
  196. };
  197. // Implementation of an input stream. See soundinputstreaminterface.h regarding
  198. // thread-safety.
  199. class PulseAudioInputStream :
  200. public SoundInputStreamInterface,
  201. private talk_base::Worker {
  202. struct GetVolumeCallbackData {
  203. PulseAudioInputStream *instance;
  204. pa_cvolume *channel_volumes;
  205. };
  206. struct GetSourceChannelCountCallbackData {
  207. PulseAudioInputStream *instance;
  208. uint8_t *channels;
  209. };
  210. public:
  211. PulseAudioInputStream(PulseAudioSoundSystem *pulse,
  212. pa_stream *stream,
  213. int flags)
  214. : stream_(pulse, stream, flags),
  215. temp_sample_data_(NULL),
  216. temp_sample_data_size_(0) {
  217. // This callback seems to never be issued, but let's set it anyways.
  218. symbol_table()->pa_stream_set_overflow_callback()(stream, &OverflowCallback,
  219. NULL);
  220. }
  221. virtual ~PulseAudioInputStream() {
  222. bool success = Close();
  223. // We need that to live.
  224. VERIFY(success);
  225. }
  226. virtual bool StartReading() {
  227. return StartWork();
  228. }
  229. virtual bool StopReading() {
  230. return StopWork();
  231. }
  232. virtual bool GetVolume(int *volume) {
  233. bool ret = false;
  234. Lock();
  235. // Unlike output streams, input streams have no concept of a stream volume,
  236. // only a device volume. So we have to retrieve the volume of the device
  237. // itself.
  238. pa_cvolume channel_volumes;
  239. GetVolumeCallbackData data;
  240. data.instance = this;
  241. data.channel_volumes = &channel_volumes;
  242. pa_operation *op = symbol_table()->pa_context_get_source_info_by_index()(
  243. stream_.pulse()->context_,
  244. symbol_table()->pa_stream_get_device_index()(stream_.stream()),
  245. &GetVolumeCallbackThunk,
  246. &data);
  247. if (!stream_.pulse()->FinishOperation(op)) {
  248. goto done;
  249. }
  250. if (data.channel_volumes) {
  251. // This pointer was never unset by the callback, so we must have received
  252. // an empty list of infos. This probably never happens, but we code for it
  253. // anyway.
  254. LOG(LS_ERROR) << "Did not receive GetVolumeCallback";
  255. goto done;
  256. }
  257. // We now have the volume for each channel. Each channel could have a
  258. // different volume if, e.g., the user went and changed the volumes in the
  259. // PA UI. To get a single volume for SoundSystemInterface we just take the
  260. // maximum. Ideally we'd do so with pa_cvolume_max, but it doesn't exist in
  261. // Hardy, so we do it manually.
  262. pa_volume_t pa_volume;
  263. pa_volume = MaxChannelVolume(&channel_volumes);
  264. // Now map onto the SoundSystemInterface range.
  265. *volume = PulseVolumeToCricketVolume(pa_volume);
  266. ret = true;
  267. done:
  268. Unlock();
  269. return ret;
  270. }
  271. virtual bool SetVolume(int volume) {
  272. bool ret = false;
  273. pa_volume_t pa_volume = CricketVolumeToPulseVolume(volume);
  274. Lock();
  275. // Unlike output streams, input streams have no concept of a stream volume,
  276. // only a device volume. So we have to change the volume of the device
  277. // itself.
  278. // The device may have a different number of channels than the stream and
  279. // their mapping may be different, so we don't want to use the channel count
  280. // from our sample spec. We could use PA_CHANNELS_MAX to cover our bases,
  281. // and the server allows that even if the device's channel count is lower,
  282. // but some buggy PA clients don't like that (the pavucontrol on Hardy dies
  283. // in an assert if the channel count is different). So instead we look up
  284. // the actual number of channels that the device has.
  285. uint8_t channels;
  286. GetSourceChannelCountCallbackData data;
  287. data.instance = this;
  288. data.channels = &channels;
  289. uint32_t device_index = symbol_table()->pa_stream_get_device_index()(
  290. stream_.stream());
  291. pa_operation *op = symbol_table()->pa_context_get_source_info_by_index()(
  292. stream_.pulse()->context_,
  293. device_index,
  294. &GetSourceChannelCountCallbackThunk,
  295. &data);
  296. if (!stream_.pulse()->FinishOperation(op)) {
  297. goto done;
  298. }
  299. if (data.channels) {
  300. // This pointer was never unset by the callback, so we must have received
  301. // an empty list of infos. This probably never happens, but we code for it
  302. // anyway.
  303. LOG(LS_ERROR) << "Did not receive GetSourceChannelCountCallback";
  304. goto done;
  305. }
  306. pa_cvolume channel_volumes;
  307. symbol_table()->pa_cvolume_set()(&channel_volumes, channels, pa_volume);
  308. op = symbol_table()->pa_context_set_source_volume_by_index()(
  309. stream_.pulse()->context_,
  310. device_index,
  311. &channel_volumes,
  312. // This callback merely logs errors.
  313. &SetVolumeCallback,
  314. NULL);
  315. if (!op) {
  316. LOG(LS_ERROR) << "pa_context_set_source_volume_by_index()";
  317. goto done;
  318. }
  319. // Don't need to wait for this to complete.
  320. symbol_table()->pa_operation_unref()(op);
  321. ret = true;
  322. done:
  323. Unlock();
  324. return ret;
  325. }
  326. virtual bool Close() {
  327. if (!StopReading()) {
  328. return false;
  329. }
  330. bool ret = true;
  331. if (!stream_.IsClosed()) {
  332. Lock();
  333. ret = stream_.Close();
  334. Unlock();
  335. }
  336. return ret;
  337. }
  338. virtual int LatencyUsecs() {
  339. return stream_.LatencyUsecs();
  340. }
  341. private:
  342. void Lock() {
  343. stream_.Lock();
  344. }
  345. void Unlock() {
  346. stream_.Unlock();
  347. }
  348. PulseAudioSymbolTable *symbol_table() {
  349. return stream_.symbol_table();
  350. }
  351. void EnableReadCallback() {
  352. symbol_table()->pa_stream_set_read_callback()(
  353. stream_.stream(),
  354. &ReadCallbackThunk,
  355. this);
  356. }
  357. void DisableReadCallback() {
  358. symbol_table()->pa_stream_set_read_callback()(
  359. stream_.stream(),
  360. NULL,
  361. NULL);
  362. }
  363. static void ReadCallbackThunk(pa_stream *unused1,
  364. size_t unused2,
  365. void *userdata) {
  366. PulseAudioInputStream *instance =
  367. static_cast<PulseAudioInputStream *>(userdata);
  368. instance->OnReadCallback();
  369. }
  370. void OnReadCallback() {
  371. // We get the data pointer and size now in order to save one Lock/Unlock
  372. // on OnMessage.
  373. if (symbol_table()->pa_stream_peek()(stream_.stream(),
  374. &temp_sample_data_,
  375. &temp_sample_data_size_) != 0) {
  376. LOG(LS_ERROR) << "Can't read data!";
  377. return;
  378. }
  379. // Since we consume the data asynchronously on a different thread, we have
  380. // to temporarily disable the read callback or else Pulse will call it
  381. // continuously until we consume the data. We re-enable it below.
  382. DisableReadCallback();
  383. HaveWork();
  384. }
  385. // Inherited from Worker.
  386. virtual void OnStart() {
  387. Lock();
  388. EnableReadCallback();
  389. Unlock();
  390. }
  391. // Inherited from Worker.
  392. virtual void OnHaveWork() {
  393. ASSERT(temp_sample_data_ && temp_sample_data_size_);
  394. SignalSamplesRead(temp_sample_data_,
  395. temp_sample_data_size_,
  396. this);
  397. temp_sample_data_ = NULL;
  398. temp_sample_data_size_ = 0;
  399. Lock();
  400. for (;;) {
  401. // Ack the last thing we read.
  402. if (symbol_table()->pa_stream_drop()(stream_.stream()) != 0) {
  403. LOG(LS_ERROR) << "Can't ack read data";
  404. }
  405. if (symbol_table()->pa_stream_readable_size()(stream_.stream()) <= 0) {
  406. // Then that was all the data.
  407. break;
  408. }
  409. // Else more data.
  410. const void *sample_data;
  411. size_t sample_data_size;
  412. if (symbol_table()->pa_stream_peek()(stream_.stream(),
  413. &sample_data,
  414. &sample_data_size) != 0) {
  415. LOG(LS_ERROR) << "Can't read data!";
  416. break;
  417. }
  418. // Drop lock for sigslot dispatch, which could take a while.
  419. Unlock();
  420. SignalSamplesRead(sample_data, sample_data_size, this);
  421. Lock();
  422. // Return to top of loop for the ack and the check for more data.
  423. }
  424. EnableReadCallback();
  425. Unlock();
  426. }
  427. // Inherited from Worker.
  428. virtual void OnStop() {
  429. Lock();
  430. DisableReadCallback();
  431. Unlock();
  432. }
  433. static void OverflowCallback(pa_stream *stream,
  434. void *userdata) {
  435. LOG(LS_WARNING) << "Buffer overflow on capture stream " << stream;
  436. }
  437. static void GetVolumeCallbackThunk(pa_context *unused,
  438. const pa_source_info *info,
  439. int eol,
  440. void *userdata) {
  441. GetVolumeCallbackData *data =
  442. static_cast<GetVolumeCallbackData *>(userdata);
  443. data->instance->OnGetVolumeCallback(info, eol, &data->channel_volumes);
  444. }
  445. void OnGetVolumeCallback(const pa_source_info *info,
  446. int eol,
  447. pa_cvolume **channel_volumes) {
  448. if (eol) {
  449. // List is over. Wake GetVolume().
  450. stream_.pulse()->Signal();
  451. return;
  452. }
  453. if (*channel_volumes) {
  454. **channel_volumes = info->volume;
  455. // Unset the pointer so that we know that we have have already copied the
  456. // volume.
  457. *channel_volumes = NULL;
  458. } else {
  459. // We have received an additional callback after the first one, which
  460. // doesn't make sense for a single source. This probably never happens,
  461. // but we code for it anyway.
  462. LOG(LS_WARNING) << "Ignoring extra GetVolumeCallback";
  463. }
  464. }
  465. static void GetSourceChannelCountCallbackThunk(pa_context *unused,
  466. const pa_source_info *info,
  467. int eol,
  468. void *userdata) {
  469. GetSourceChannelCountCallbackData *data =
  470. static_cast<GetSourceChannelCountCallbackData *>(userdata);
  471. data->instance->OnGetSourceChannelCountCallback(info, eol, &data->channels);
  472. }
  473. void OnGetSourceChannelCountCallback(const pa_source_info *info,
  474. int eol,
  475. uint8_t **channels) {
  476. if (eol) {
  477. // List is over. Wake SetVolume().
  478. stream_.pulse()->Signal();
  479. return;
  480. }
  481. if (*channels) {
  482. **channels = info->channel_map.channels;
  483. // Unset the pointer so that we know that we have have already copied the
  484. // channel count.
  485. *channels = NULL;
  486. } else {
  487. // We have received an additional callback after the first one, which
  488. // doesn't make sense for a single source. This probably never happens,
  489. // but we code for it anyway.
  490. LOG(LS_WARNING) << "Ignoring extra GetSourceChannelCountCallback";
  491. }
  492. }
  493. static void SetVolumeCallback(pa_context *unused1,
  494. int success,
  495. void *unused2) {
  496. if (!success) {
  497. LOG(LS_ERROR) << "Failed to change capture volume";
  498. }
  499. }
  500. PulseAudioStream stream_;
  501. // Temporary storage for passing data between threads.
  502. const void *temp_sample_data_;
  503. size_t temp_sample_data_size_;
  504. DISALLOW_COPY_AND_ASSIGN(PulseAudioInputStream);
  505. };
  506. // Implementation of an output stream. See soundoutputstreaminterface.h
  507. // regarding thread-safety.
  508. class PulseAudioOutputStream :
  509. public SoundOutputStreamInterface,
  510. private talk_base::Worker {
  511. struct GetVolumeCallbackData {
  512. PulseAudioOutputStream *instance;
  513. pa_cvolume *channel_volumes;
  514. };
  515. public:
  516. PulseAudioOutputStream(PulseAudioSoundSystem *pulse,
  517. pa_stream *stream,
  518. int flags,
  519. int latency)
  520. : stream_(pulse, stream, flags),
  521. configured_latency_(latency),
  522. temp_buffer_space_(0) {
  523. symbol_table()->pa_stream_set_underflow_callback()(stream,
  524. &UnderflowCallbackThunk,
  525. this);
  526. }
  527. virtual ~PulseAudioOutputStream() {
  528. bool success = Close();
  529. // We need that to live.
  530. VERIFY(success);
  531. }
  532. virtual bool EnableBufferMonitoring() {
  533. return StartWork();
  534. }
  535. virtual bool DisableBufferMonitoring() {
  536. return StopWork();
  537. }
  538. virtual bool WriteSamples(const void *sample_data,
  539. size_t size) {
  540. bool ret = true;
  541. Lock();
  542. if (symbol_table()->pa_stream_write()(stream_.stream(),
  543. sample_data,
  544. size,
  545. NULL,
  546. 0,
  547. PA_SEEK_RELATIVE) != 0) {
  548. LOG(LS_ERROR) << "Unable to write";
  549. ret = false;
  550. }
  551. Unlock();
  552. return ret;
  553. }
  554. virtual bool GetVolume(int *volume) {
  555. bool ret = false;
  556. Lock();
  557. pa_cvolume channel_volumes;
  558. GetVolumeCallbackData data;
  559. data.instance = this;
  560. data.channel_volumes = &channel_volumes;
  561. pa_operation *op = symbol_table()->pa_context_get_sink_input_info()(
  562. stream_.pulse()->context_,
  563. symbol_table()->pa_stream_get_index()(stream_.stream()),
  564. &GetVolumeCallbackThunk,
  565. &data);
  566. if (!stream_.pulse()->FinishOperation(op)) {
  567. goto done;
  568. }
  569. if (data.channel_volumes) {
  570. // This pointer was never unset by the callback, so we must have received
  571. // an empty list of infos. This probably never happens, but we code for it
  572. // anyway.
  573. LOG(LS_ERROR) << "Did not receive GetVolumeCallback";
  574. goto done;
  575. }
  576. // We now have the volume for each channel. Each channel could have a
  577. // different volume if, e.g., the user went and changed the volumes in the
  578. // PA UI. To get a single volume for SoundSystemInterface we just take the
  579. // maximum. Ideally we'd do so with pa_cvolume_max, but it doesn't exist in
  580. // Hardy, so we do it manually.
  581. pa_volume_t pa_volume;
  582. pa_volume = MaxChannelVolume(&channel_volumes);
  583. // Now map onto the SoundSystemInterface range.
  584. *volume = PulseVolumeToCricketVolume(pa_volume);
  585. ret = true;
  586. done:
  587. Unlock();
  588. return ret;
  589. }
  590. virtual bool SetVolume(int volume) {
  591. bool ret = false;
  592. pa_volume_t pa_volume = CricketVolumeToPulseVolume(volume);
  593. Lock();
  594. const pa_sample_spec *spec = symbol_table()->pa_stream_get_sample_spec()(
  595. stream_.stream());
  596. if (!spec) {
  597. LOG(LS_ERROR) << "pa_stream_get_sample_spec()";
  598. goto done;
  599. }
  600. pa_cvolume channel_volumes;
  601. symbol_table()->pa_cvolume_set()(&channel_volumes, spec->channels,
  602. pa_volume);
  603. pa_operation *op;
  604. op = symbol_table()->pa_context_set_sink_input_volume()(
  605. stream_.pulse()->context_,
  606. symbol_table()->pa_stream_get_index()(stream_.stream()),
  607. &channel_volumes,
  608. // This callback merely logs errors.
  609. &SetVolumeCallback,
  610. NULL);
  611. if (!op) {
  612. LOG(LS_ERROR) << "pa_context_set_sink_input_volume()";
  613. goto done;
  614. }
  615. // Don't need to wait for this to complete.
  616. symbol_table()->pa_operation_unref()(op);
  617. ret = true;
  618. done:
  619. Unlock();
  620. return ret;
  621. }
  622. virtual bool Close() {
  623. if (!DisableBufferMonitoring()) {
  624. return false;
  625. }
  626. bool ret = true;
  627. if (!stream_.IsClosed()) {
  628. Lock();
  629. symbol_table()->pa_stream_set_underflow_callback()(stream_.stream(),
  630. NULL,
  631. NULL);
  632. ret = stream_.Close();
  633. Unlock();
  634. }
  635. return ret;
  636. }
  637. virtual int LatencyUsecs() {
  638. return stream_.LatencyUsecs();
  639. }
  640. #if 0
  641. // TODO: Versions 0.9.16 and later of Pulse have a new API for
  642. // zero-copy writes, but Hardy is not new enough to have that so we can't
  643. // rely on it. Perhaps auto-detect if it's present or not and use it if we
  644. // can?
  645. virtual bool GetWriteBuffer(void **buffer, size_t *size) {
  646. bool ret = true;
  647. Lock();
  648. if (symbol_table()->pa_stream_begin_write()(stream_.stream(), buffer, size)
  649. != 0) {
  650. LOG(LS_ERROR) << "Can't get write buffer";
  651. ret = false;
  652. }
  653. Unlock();
  654. return ret;
  655. }
  656. // Releases the caller's hold on the write buffer. "written" must be the
  657. // amount of data that was written.
  658. virtual bool ReleaseWriteBuffer(void *buffer, size_t written) {
  659. bool ret = true;
  660. Lock();
  661. if (written == 0) {
  662. if (symbol_table()->pa_stream_cancel_write()(stream_.stream()) != 0) {
  663. LOG(LS_ERROR) << "Can't cancel write";
  664. ret = false;
  665. }
  666. } else {
  667. if (symbol_table()->pa_stream_write()(stream_.stream(),
  668. buffer,
  669. written,
  670. NULL,
  671. 0,
  672. PA_SEEK_RELATIVE) != 0) {
  673. LOG(LS_ERROR) << "Unable to write";
  674. ret = false;
  675. }
  676. }
  677. Unlock();
  678. return ret;
  679. }
  680. #endif
  681. private:
  682. void Lock() {
  683. stream_.Lock();
  684. }
  685. void Unlock() {
  686. stream_.Unlock();
  687. }
  688. PulseAudioSymbolTable *symbol_table() {
  689. return stream_.symbol_table();
  690. }
  691. void EnableWriteCallback() {
  692. pa_stream_state_t state = symbol_table()->pa_stream_get_state()(
  693. stream_.stream());
  694. if (state == PA_STREAM_READY) {
  695. // May already have available space. Must check.
  696. temp_buffer_space_ = symbol_table()->pa_stream_writable_size()(
  697. stream_.stream());
  698. if (temp_buffer_space_ > 0) {
  699. // Yup, there is already space available, so if we register a write
  700. // callback then it will not receive any event. So dispatch one ourself
  701. // instead.
  702. HaveWork();
  703. return;
  704. }
  705. }
  706. symbol_table()->pa_stream_set_write_callback()(
  707. stream_.stream(),
  708. &WriteCallbackThunk,
  709. this);
  710. }
  711. void DisableWriteCallback() {
  712. symbol_table()->pa_stream_set_write_callback()(
  713. stream_.stream(),
  714. NULL,
  715. NULL);
  716. }
  717. static void WriteCallbackThunk(pa_stream *unused,
  718. size_t buffer_space,
  719. void *userdata) {
  720. PulseAudioOutputStream *instance =
  721. static_cast<PulseAudioOutputStream *>(userdata);
  722. instance->OnWriteCallback(buffer_space);
  723. }
  724. void OnWriteCallback(size_t buffer_space) {
  725. temp_buffer_space_ = buffer_space;
  726. // Since we write the data asynchronously on a different thread, we have
  727. // to temporarily disable the write callback or else Pulse will call it
  728. // continuously until we write the data. We re-enable it below.
  729. DisableWriteCallback();
  730. HaveWork();
  731. }
  732. // Inherited from Worker.
  733. virtual void OnStart() {
  734. Lock();
  735. EnableWriteCallback();
  736. Unlock();
  737. }
  738. // Inherited from Worker.
  739. virtual void OnHaveWork() {
  740. ASSERT(temp_buffer_space_ > 0);
  741. SignalBufferSpace(temp_buffer_space_, this);
  742. temp_buffer_space_ = 0;
  743. Lock();
  744. EnableWriteCallback();
  745. Unlock();
  746. }
  747. // Inherited from Worker.
  748. virtual void OnStop() {
  749. Lock();
  750. DisableWriteCallback();
  751. Unlock();
  752. }
  753. static void UnderflowCallbackThunk(pa_stream *unused,
  754. void *userdata) {
  755. PulseAudioOutputStream *instance =
  756. static_cast<PulseAudioOutputStream *>(userdata);
  757. instance->OnUnderflowCallback();
  758. }
  759. void OnUnderflowCallback() {
  760. LOG(LS_WARNING) << "Buffer underflow on playback stream "
  761. << stream_.stream();
  762. if (configured_latency_ == SoundSystemInterface::kNoLatencyRequirements) {
  763. // We didn't configure a pa_buffer_attr before, so switching to one now
  764. // would be questionable.
  765. return;
  766. }
  767. // Otherwise reconfigure the stream with a higher target latency.
  768. const pa_sample_spec *spec = symbol_table()->pa_stream_get_sample_spec()(
  769. stream_.stream());
  770. if (!spec) {
  771. LOG(LS_ERROR) << "pa_stream_get_sample_spec()";
  772. return;
  773. }
  774. size_t bytes_per_sec = symbol_table()->pa_bytes_per_second()(spec);
  775. int new_latency = configured_latency_ +
  776. bytes_per_sec * kPlaybackLatencyIncrementMsecs /
  777. talk_base::kNumMicrosecsPerSec;
  778. pa_buffer_attr new_attr = {0};
  779. FillPlaybackBufferAttr(new_latency, &new_attr);
  780. pa_operation *op = symbol_table()->pa_stream_set_buffer_attr()(
  781. stream_.stream(),
  782. &new_attr,
  783. // No callback.
  784. NULL,
  785. NULL);
  786. if (!op) {
  787. LOG(LS_ERROR) << "pa_stream_set_buffer_attr()";
  788. return;
  789. }
  790. // Don't need to wait for this to complete.
  791. symbol_table()->pa_operation_unref()(op);
  792. // Save the new latency in case we underflow again.
  793. configured_latency_ = new_latency;
  794. }
  795. static void GetVolumeCallbackThunk(pa_context *unused,
  796. const pa_sink_input_info *info,
  797. int eol,
  798. void *userdata) {
  799. GetVolumeCallbackData *data =
  800. static_cast<GetVolumeCallbackData *>(userdata);
  801. data->instance->OnGetVolumeCallback(info, eol, &data->channel_volumes);
  802. }
  803. void OnGetVolumeCallback(const pa_sink_input_info *info,
  804. int eol,
  805. pa_cvolume **channel_volumes) {
  806. if (eol) {
  807. // List is over. Wake GetVolume().
  808. stream_.pulse()->Signal();
  809. return;
  810. }
  811. if (*channel_volumes) {
  812. **channel_volumes = info->volume;
  813. // Unset the pointer so that we know that we have have already copied the
  814. // volume.
  815. *channel_volumes = NULL;
  816. } else {
  817. // We have received an additional callback after the first one, which
  818. // doesn't make sense for a single sink input. This probably never
  819. // happens, but we code for it anyway.
  820. LOG(LS_WARNING) << "Ignoring extra GetVolumeCallback";
  821. }
  822. }
  823. static void SetVolumeCallback(pa_context *unused1,
  824. int success,
  825. void *unused2) {
  826. if (!success) {
  827. LOG(LS_ERROR) << "Failed to change playback volume";
  828. }
  829. }
  830. PulseAudioStream stream_;
  831. int configured_latency_;
  832. // Temporary storage for passing data between threads.
  833. size_t temp_buffer_space_;
  834. DISALLOW_COPY_AND_ASSIGN(PulseAudioOutputStream);
  835. };
  836. PulseAudioSoundSystem::PulseAudioSoundSystem()
  837. : mainloop_(NULL), context_(NULL) {
  838. }
  839. PulseAudioSoundSystem::~PulseAudioSoundSystem() {
  840. Terminate();
  841. }
  842. bool PulseAudioSoundSystem::Init() {
  843. if (IsInitialized()) {
  844. return true;
  845. }
  846. // Load libpulse.
  847. if (!symbol_table_.Load()) {
  848. // Most likely the Pulse library and sound server are not installed on
  849. // this system.
  850. LOG(LS_WARNING) << "Failed to load symbol table";
  851. return false;
  852. }
  853. // Now create and start the Pulse event thread.
  854. mainloop_ = symbol_table_.pa_threaded_mainloop_new()();
  855. if (!mainloop_) {
  856. LOG(LS_ERROR) << "Can't create mainloop";
  857. goto fail0;
  858. }
  859. if (symbol_table_.pa_threaded_mainloop_start()(mainloop_) != 0) {
  860. LOG(LS_ERROR) << "Can't start mainloop";
  861. goto fail1;
  862. }
  863. Lock();
  864. context_ = CreateNewConnection();
  865. Unlock();
  866. if (!context_) {
  867. goto fail2;
  868. }
  869. // Otherwise we're now ready!
  870. return true;
  871. fail2:
  872. symbol_table_.pa_threaded_mainloop_stop()(mainloop_);
  873. fail1:
  874. symbol_table_.pa_threaded_mainloop_free()(mainloop_);
  875. mainloop_ = NULL;
  876. fail0:
  877. return false;
  878. }
  879. void PulseAudioSoundSystem::Terminate() {
  880. if (!IsInitialized()) {
  881. return;
  882. }
  883. Lock();
  884. symbol_table_.pa_context_disconnect()(context_);
  885. symbol_table_.pa_context_unref()(context_);
  886. Unlock();
  887. context_ = NULL;
  888. symbol_table_.pa_threaded_mainloop_stop()(mainloop_);
  889. symbol_table_.pa_threaded_mainloop_free()(mainloop_);
  890. mainloop_ = NULL;
  891. // We do not unload the symbol table because we may need it again soon if
  892. // Init() is called again.
  893. }
  894. bool PulseAudioSoundSystem::EnumeratePlaybackDevices(
  895. SoundDeviceLocatorList *devices) {
  896. return EnumerateDevices<pa_sink_info>(
  897. devices,
  898. symbol_table_.pa_context_get_sink_info_list(),
  899. &EnumeratePlaybackDevicesCallbackThunk);
  900. }
  901. bool PulseAudioSoundSystem::EnumerateCaptureDevices(
  902. SoundDeviceLocatorList *devices) {
  903. return EnumerateDevices<pa_source_info>(
  904. devices,
  905. symbol_table_.pa_context_get_source_info_list(),
  906. &EnumerateCaptureDevicesCallbackThunk);
  907. }
  908. bool PulseAudioSoundSystem::GetDefaultPlaybackDevice(
  909. SoundDeviceLocator **device) {
  910. return GetDefaultDevice<&pa_server_info::default_sink_name>(device);
  911. }
  912. bool PulseAudioSoundSystem::GetDefaultCaptureDevice(
  913. SoundDeviceLocator **device) {
  914. return GetDefaultDevice<&pa_server_info::default_source_name>(device);
  915. }
  916. SoundOutputStreamInterface *PulseAudioSoundSystem::OpenPlaybackDevice(
  917. const SoundDeviceLocator *device,
  918. const OpenParams &params) {
  919. return OpenDevice<SoundOutputStreamInterface>(
  920. device,
  921. params,
  922. "Playback",
  923. &PulseAudioSoundSystem::ConnectOutputStream);
  924. }
  925. SoundInputStreamInterface *PulseAudioSoundSystem::OpenCaptureDevice(
  926. const SoundDeviceLocator *device,
  927. const OpenParams &params) {
  928. return OpenDevice<SoundInputStreamInterface>(
  929. device,
  930. params,
  931. "Capture",
  932. &PulseAudioSoundSystem::ConnectInputStream);
  933. }
  934. const char *PulseAudioSoundSystem::GetName() const {
  935. return "PulseAudio";
  936. }
  937. inline bool PulseAudioSoundSystem::IsInitialized() {
  938. return mainloop_ != NULL;
  939. }
  940. struct ConnectToPulseCallbackData {
  941. PulseAudioSoundSystem *instance;
  942. bool connect_done;
  943. };
  944. void PulseAudioSoundSystem::ConnectToPulseCallbackThunk(
  945. pa_context *context, void *userdata) {
  946. ConnectToPulseCallbackData *data =
  947. static_cast<ConnectToPulseCallbackData *>(userdata);
  948. data->instance->OnConnectToPulseCallback(context, &data->connect_done);
  949. }
  950. void PulseAudioSoundSystem::OnConnectToPulseCallback(
  951. pa_context *context, bool *connect_done) {
  952. pa_context_state_t state = symbol_table_.pa_context_get_state()(context);
  953. if (state == PA_CONTEXT_READY ||
  954. state == PA_CONTEXT_FAILED ||
  955. state == PA_CONTEXT_TERMINATED) {
  956. // Connection process has reached a terminal state. Wake ConnectToPulse().
  957. *connect_done = true;
  958. Signal();
  959. }
  960. }
  961. // Must be called with the lock held.
  962. bool PulseAudioSoundSystem::ConnectToPulse(pa_context *context) {
  963. bool ret = true;
  964. ConnectToPulseCallbackData data;
  965. // Have to put this up here to satisfy the compiler.
  966. pa_context_state_t state;
  967. data.instance = this;
  968. data.connect_done = false;
  969. symbol_table_.pa_context_set_state_callback()(context,
  970. &ConnectToPulseCallbackThunk,
  971. &data);
  972. // Connect to PulseAudio sound server.
  973. if (symbol_table_.pa_context_connect()(
  974. context,
  975. NULL, // Default server
  976. PA_CONTEXT_NOAUTOSPAWN,
  977. NULL) != 0) { // No special fork handling needed
  978. LOG(LS_ERROR) << "Can't start connection to PulseAudio sound server";
  979. ret = false;
  980. goto done;
  981. }
  982. // Wait for the connection state machine to reach a terminal state.
  983. do {
  984. Wait();
  985. } while (!data.connect_done);
  986. // Now check to see what final state we reached.
  987. state = symbol_table_.pa_context_get_state()(context);
  988. if (state != PA_CONTEXT_READY) {
  989. if (state == PA_CONTEXT_FAILED) {
  990. LOG(LS_ERROR) << "Failed to connect to PulseAudio sound server";
  991. } else if (state == PA_CONTEXT_TERMINATED) {
  992. LOG(LS_ERROR) << "PulseAudio connection terminated early";
  993. } else {
  994. // Shouldn't happen, because we only signal on one of those three states.
  995. LOG(LS_ERROR) << "Unknown problem connecting to PulseAudio";
  996. }
  997. ret = false;
  998. }
  999. done:
  1000. // We unset our callback for safety just in case the state might somehow
  1001. // change later, because the pointer to "data" will be invalid after return
  1002. // from this function.
  1003. symbol_table_.pa_context_set_state_callback()(context, NULL, NULL);
  1004. return ret;
  1005. }
  1006. // Must be called with the lock held.
  1007. pa_context *PulseAudioSoundSystem::CreateNewConnection() {
  1008. // Create connection context.
  1009. std::string app_name;
  1010. // TODO: Pulse etiquette says this name should be localized. Do
  1011. // we care?
  1012. talk_base::Filesystem::GetApplicationName(&app_name);
  1013. pa_context *context = symbol_table_.pa_context_new()(
  1014. symbol_table_.pa_threaded_mainloop_get_api()(mainloop_),
  1015. app_name.c_str());
  1016. if (!context) {
  1017. LOG(LS_ERROR) << "Can't create context";
  1018. goto fail0;
  1019. }
  1020. // Now connect.
  1021. if (!ConnectToPulse(context)) {
  1022. goto fail1;
  1023. }
  1024. // Otherwise the connection succeeded and is ready.
  1025. return context;
  1026. fail1:
  1027. symbol_table_.pa_context_unref()(context);
  1028. fail0:
  1029. return NULL;
  1030. }
  1031. struct EnumerateDevicesCallbackData {
  1032. PulseAudioSoundSystem *instance;
  1033. SoundSystemInterface::SoundDeviceLocatorList *devices;
  1034. };
  1035. void PulseAudioSoundSystem::EnumeratePlaybackDevicesCallbackThunk(
  1036. pa_context *unused,
  1037. const pa_sink_info *info,
  1038. int eol,
  1039. void *userdata) {
  1040. EnumerateDevicesCallbackData *data =
  1041. static_cast<EnumerateDevicesCallbackData *>(userdata);
  1042. data->instance->OnEnumeratePlaybackDevicesCallback(data->devices, info, eol);
  1043. }
  1044. void PulseAudioSoundSystem::EnumerateCaptureDevicesCallbackThunk(
  1045. pa_context *unused,
  1046. const pa_source_info *info,
  1047. int eol,
  1048. void *userdata) {
  1049. EnumerateDevicesCallbackData *data =
  1050. static_cast<EnumerateDevicesCallbackData *>(userdata);
  1051. data->instance->OnEnumerateCaptureDevicesCallback(data->devices, info, eol);
  1052. }
  1053. void PulseAudioSoundSystem::OnEnumeratePlaybackDevicesCallback(
  1054. SoundDeviceLocatorList *devices,
  1055. const pa_sink_info *info,
  1056. int eol) {
  1057. if (eol) {
  1058. // List is over. Wake EnumerateDevices().
  1059. Signal();
  1060. return;
  1061. }
  1062. // Else this is the next device.
  1063. devices->push_back(
  1064. new PulseAudioDeviceLocator(info->description, info->name));
  1065. }
  1066. void PulseAudioSoundSystem::OnEnumerateCaptureDevicesCallback(
  1067. SoundDeviceLocatorList *devices,
  1068. const pa_source_info *info,
  1069. int eol) {
  1070. if (eol) {
  1071. // List is over. Wake EnumerateDevices().
  1072. Signal();
  1073. return;
  1074. }
  1075. if (info->monitor_of_sink != PA_INVALID_INDEX) {
  1076. // We don't want to list monitor sources, since they are almost certainly
  1077. // not what the user wants for voice conferencing.
  1078. return;
  1079. }
  1080. // Else this is the next device.
  1081. devices->push_back(
  1082. new PulseAudioDeviceLocator(info->description, info->name));
  1083. }
  1084. template <typename InfoStruct>
  1085. bool PulseAudioSoundSystem::EnumerateDevices(
  1086. SoundDeviceLocatorList *devices,
  1087. pa_operation *(*enumerate_fn)(
  1088. pa_context *c,
  1089. void (*callback_fn)(
  1090. pa_context *c,
  1091. const InfoStruct *i,
  1092. int eol,
  1093. void *userdata),
  1094. void *userdata),
  1095. void (*callback_fn)(
  1096. pa_context *c,
  1097. const InfoStruct *i,
  1098. int eol,
  1099. void *userdata)) {
  1100. ClearSoundDeviceLocatorList(devices);
  1101. if (!IsInitialized()) {
  1102. return false;
  1103. }
  1104. EnumerateDevicesCallbackData data;
  1105. data.instance = this;
  1106. data.devices = devices;
  1107. Lock();
  1108. pa_operation *op = (*enumerate_fn)(
  1109. context_,
  1110. callback_fn,
  1111. &data);
  1112. bool ret = FinishOperation(op);
  1113. Unlock();
  1114. return ret;
  1115. }
  1116. struct GetDefaultDeviceCallbackData {
  1117. PulseAudioSoundSystem *instance;
  1118. SoundDeviceLocator **device;
  1119. };
  1120. template <const char *(pa_server_info::*field)>
  1121. void PulseAudioSoundSystem::GetDefaultDeviceCallbackThunk(
  1122. pa_context *unused,
  1123. const pa_server_info *info,
  1124. void *userdata) {
  1125. GetDefaultDeviceCallbackData *data =
  1126. static_cast<GetDefaultDeviceCallbackData *>(userdata);
  1127. data->instance->OnGetDefaultDeviceCallback<field>(info, data->device);
  1128. }
  1129. template <const char *(pa_server_info::*field)>
  1130. void PulseAudioSoundSystem::OnGetDefaultDeviceCallback(
  1131. const pa_server_info *info,
  1132. SoundDeviceLocator **device) {
  1133. if (info) {
  1134. const char *dev = info->*field;
  1135. if (dev) {
  1136. *device = new PulseAudioDeviceLocator("Default device", dev);
  1137. }
  1138. }
  1139. Signal();
  1140. }
  1141. template <const char *(pa_server_info::*field)>
  1142. bool PulseAudioSoundSystem::GetDefaultDevice(SoundDeviceLocator **device) {
  1143. if (!IsInitialized()) {
  1144. return false;
  1145. }
  1146. bool ret;
  1147. *device = NULL;
  1148. GetDefaultDeviceCallbackData data;
  1149. data.instance = this;
  1150. data.device = device;
  1151. Lock();
  1152. pa_operation *op = symbol_table_.pa_context_get_server_info()(
  1153. context_,
  1154. &GetDefaultDeviceCallbackThunk<field>,
  1155. &data);
  1156. ret = FinishOperation(op);
  1157. Unlock();
  1158. return ret && (*device != NULL);
  1159. }
  1160. void PulseAudioSoundSystem::StreamStateChangedCallbackThunk(
  1161. pa_stream *stream,
  1162. void *userdata) {
  1163. PulseAudioSoundSystem *instance =
  1164. static_cast<PulseAudioSoundSystem *>(userdata);
  1165. instance->OnStreamStateChangedCallback(stream);
  1166. }
  1167. void PulseAudioSoundSystem::OnStreamStateChangedCallback(pa_stream *stream) {
  1168. pa_stream_state_t state = symbol_table_.pa_stream_get_state()(stream);
  1169. if (state == PA_STREAM_READY) {
  1170. LOG(LS_INFO) << "Pulse stream " << stream << " ready";
  1171. } else if (state == PA_STREAM_FAILED ||
  1172. state == PA_STREAM_TERMINATED ||
  1173. state == PA_STREAM_UNCONNECTED) {
  1174. LOG(LS_ERROR) << "Pulse stream " << stream << " failed to connect: "
  1175. << LastError();
  1176. }
  1177. }
  1178. template <typename StreamInterface>
  1179. StreamInterface *PulseAudioSoundSystem::OpenDevice(
  1180. const SoundDeviceLocator *device,
  1181. const OpenParams &params,
  1182. const char *stream_name,
  1183. StreamInterface *(PulseAudioSoundSystem::*connect_fn)(
  1184. pa_stream *stream,
  1185. const char *dev,
  1186. int flags,
  1187. pa_stream_flags_t pa_flags,
  1188. int latency,
  1189. const pa_sample_spec &spec)) {
  1190. if (!IsInitialized()) {
  1191. return NULL;
  1192. }
  1193. const char *dev = static_cast<const PulseAudioDeviceLocator *>(device)->
  1194. device_name().c_str();
  1195. StreamInterface *stream_interface = NULL;
  1196. ASSERT(params.format < ARRAY_SIZE(kCricketFormatToPulseFormatTable));
  1197. pa_sample_spec spec;
  1198. spec.format = kCricketFormatToPulseFormatTable[params.format];
  1199. spec.rate = params.freq;
  1200. spec.channels = params.channels;
  1201. int pa_flags = 0;
  1202. if (params.flags & FLAG_REPORT_LATENCY) {
  1203. pa_flags |= PA_STREAM_INTERPOLATE_TIMING |
  1204. PA_STREAM_AUTO_TIMING_UPDATE;
  1205. }
  1206. if (params.latency != kNoLatencyRequirements) {
  1207. // If configuring a specific latency then we want to specify
  1208. // PA_STREAM_ADJUST_LATENCY to make the server adjust parameters
  1209. // automatically to reach that target latency. However, that flag doesn't
  1210. // exist in Ubuntu 8.04 and many people still use that, so we have to check
  1211. // the protocol version of libpulse.
  1212. if (symbol_table_.pa_context_get_protocol_version()(context_) >=
  1213. kAdjustLatencyProtocolVersion) {
  1214. pa_flags |= PA_STREAM_ADJUST_LATENCY;
  1215. }
  1216. }
  1217. Lock();
  1218. pa_stream *stream = symbol_table_.pa_stream_new()(context_, stream_name,
  1219. &spec, NULL);
  1220. if (!stream) {
  1221. LOG(LS_ERROR) << "Can't create pa_stream";
  1222. goto done;
  1223. }
  1224. // Set a state callback to log errors.
  1225. symbol_table_.pa_stream_set_state_callback()(stream,
  1226. &StreamStateChangedCallbackThunk,
  1227. this);
  1228. stream_interface = (this->*connect_fn)(
  1229. stream,
  1230. dev,
  1231. params.flags,
  1232. static_cast<pa_stream_flags_t>(pa_flags),
  1233. params.latency,
  1234. spec);
  1235. if (!stream_interface) {
  1236. LOG(LS_ERROR) << "Can't connect stream to " << dev;
  1237. symbol_table_.pa_stream_unref()(stream);
  1238. }
  1239. done:
  1240. Unlock();
  1241. return stream_interface;
  1242. }
  1243. // Must be called with the lock held.
  1244. SoundOutputStreamInterface *PulseAudioSoundSystem::ConnectOutputStream(
  1245. pa_stream *stream,
  1246. const char *dev,
  1247. int flags,
  1248. pa_stream_flags_t pa_flags,
  1249. int latency,
  1250. const pa_sample_spec &spec) {
  1251. pa_buffer_attr attr = {0};
  1252. pa_buffer_attr *pattr = NULL;
  1253. if (latency != kNoLatencyRequirements) {
  1254. // kLowLatency is 0, so we treat it the same as a request for zero latency.
  1255. ssize_t bytes_per_sec = symbol_table_.pa_bytes_per_second()(&spec);
  1256. latency = talk_base::_max(
  1257. latency,
  1258. static_cast<int>(
  1259. bytes_per_sec * kPlaybackLatencyMinimumMsecs /
  1260. talk_base::kNumMicrosecsPerSec));
  1261. FillPlaybackBufferAttr(latency, &attr);
  1262. pattr = &attr;
  1263. }
  1264. if (symbol_table_.pa_stream_connect_playback()(
  1265. stream,
  1266. dev,
  1267. pattr,
  1268. pa_flags,
  1269. // Let server choose volume
  1270. NULL,
  1271. // Not synchronized to any other playout
  1272. NULL) != 0) {
  1273. return NULL;
  1274. }
  1275. return new PulseAudioOutputStream(this, stream, flags, latency);
  1276. }
  1277. // Must be called with the lock held.
  1278. SoundInputStreamInterface *PulseAudioSoundSystem::ConnectInputStream(
  1279. pa_stream *stream,
  1280. const char *dev,
  1281. int flags,
  1282. pa_stream_flags_t pa_flags,
  1283. int latency,
  1284. const pa_sample_spec &spec) {
  1285. pa_buffer_attr attr = {0};
  1286. pa_buffer_attr *pattr = NULL;
  1287. if (latency != kNoLatencyRequirements) {
  1288. size_t bytes_per_sec = symbol_table_.pa_bytes_per_second()(&spec);
  1289. if (latency == kLowLatency) {
  1290. latency = bytes_per_sec * kLowCaptureLatencyMsecs /
  1291. talk_base::kNumMicrosecsPerSec;
  1292. }
  1293. // Note: fragsize specifies a maximum transfer size, not a minimum, so it is
  1294. // not possible to force a high latency setting, only a low one.
  1295. attr.fragsize = latency;
  1296. attr.maxlength = latency + bytes_per_sec * kCaptureBufferExtraMsecs /
  1297. talk_base::kNumMicrosecsPerSec;
  1298. LOG(LS_VERBOSE) << "Configuring latency = " << attr.fragsize
  1299. << ", maxlength = " << attr.maxlength;
  1300. pattr = &attr;
  1301. }
  1302. if (symbol_table_.pa_stream_connect_record()(stream,
  1303. dev,
  1304. pattr,
  1305. pa_flags) != 0) {
  1306. return NULL;
  1307. }
  1308. return new PulseAudioInputStream(this, stream, flags);
  1309. }
  1310. // Must be called with the lock held.
  1311. bool PulseAudioSoundSystem::FinishOperation(pa_operation *op) {
  1312. if (!op) {
  1313. LOG(LS_ERROR) << "Failed to start operation";
  1314. return false;
  1315. }
  1316. do {
  1317. Wait();
  1318. } while (symbol_table_.pa_operation_get_state()(op) == PA_OPERATION_RUNNING);
  1319. symbol_table_.pa_operation_unref()(op);
  1320. return true;
  1321. }
  1322. inline void PulseAudioSoundSystem::Lock() {
  1323. symbol_table_.pa_threaded_mainloop_lock()(mainloop_);
  1324. }
  1325. inline void PulseAudioSoundSystem::Unlock() {
  1326. symbol_table_.pa_threaded_mainloop_unlock()(mainloop_);
  1327. }
  1328. // Must be called with the lock held.
  1329. inline void PulseAudioSoundSystem::Wait() {
  1330. symbol_table_.pa_threaded_mainloop_wait()(mainloop_);
  1331. }
  1332. // Must be called with the lock held.
  1333. inline void PulseAudioSoundSystem::Signal() {
  1334. symbol_table_.pa_threaded_mainloop_signal()(mainloop_, 0);
  1335. }
  1336. // Must be called with the lock held.
  1337. const char *PulseAudioSoundSystem::LastError() {
  1338. return symbol_table_.pa_strerror()(symbol_table_.pa_context_errno()(
  1339. context_));
  1340. }
  1341. } // namespace cricket
  1342. #endif // HAVE_LIBPULSE