pulse_audio_enc.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  1. /*
  2. * Copyright (c) 2013 Lukasz Marek <lukasz.m.luki@gmail.com>
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * FFmpeg is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with FFmpeg; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. #include <math.h>
  21. #include <pulse/pulseaudio.h>
  22. #include <pulse/error.h>
  23. #include "libavformat/avformat.h"
  24. #include "libavformat/internal.h"
  25. #include "libavutil/opt.h"
  26. #include "libavutil/time.h"
  27. #include "libavutil/log.h"
  28. #include "libavutil/attributes.h"
  29. #include "pulse_audio_common.h"
  30. typedef struct PulseData {
  31. AVClass *class;
  32. const char *server;
  33. const char *name;
  34. const char *stream_name;
  35. const char *device;
  36. int64_t timestamp;
  37. int buffer_size; /**< Buffer size in bytes */
  38. int buffer_duration; /**< Buffer size in ms, recalculated to buffer_size */
  39. int prebuf;
  40. int minreq;
  41. int last_result;
  42. pa_threaded_mainloop *mainloop;
  43. pa_context *ctx;
  44. pa_stream *stream;
  45. int nonblocking;
  46. int mute;
  47. pa_volume_t base_volume;
  48. pa_volume_t last_volume;
  49. } PulseData;
  50. static void pulse_audio_sink_device_cb(pa_context *ctx, const pa_sink_info *dev,
  51. int eol, void *userdata)
  52. {
  53. PulseData *s = userdata;
  54. if (s->ctx != ctx)
  55. return;
  56. if (eol) {
  57. pa_threaded_mainloop_signal(s->mainloop, 0);
  58. } else {
  59. if (dev->flags & PA_SINK_FLAT_VOLUME)
  60. s->base_volume = dev->base_volume;
  61. else
  62. s->base_volume = PA_VOLUME_NORM;
  63. av_log(s, AV_LOG_DEBUG, "base volume: %u\n", s->base_volume);
  64. }
  65. }
  66. /* Mainloop must be locked before calling this function as it uses pa_threaded_mainloop_wait. */
  67. static int pulse_update_sink_info(AVFormatContext *h)
  68. {
  69. PulseData *s = h->priv_data;
  70. pa_operation *op;
  71. if (!(op = pa_context_get_sink_info_by_name(s->ctx, s->device,
  72. pulse_audio_sink_device_cb, s))) {
  73. av_log(s, AV_LOG_ERROR, "pa_context_get_sink_info_by_name failed.\n");
  74. return AVERROR_EXTERNAL;
  75. }
  76. while (pa_operation_get_state(op) == PA_OPERATION_RUNNING)
  77. pa_threaded_mainloop_wait(s->mainloop);
  78. pa_operation_unref(op);
  79. return 0;
  80. }
  81. static void pulse_audio_sink_input_cb(pa_context *ctx, const pa_sink_input_info *i,
  82. int eol, void *userdata)
  83. {
  84. AVFormatContext *h = userdata;
  85. PulseData *s = h->priv_data;
  86. if (s->ctx != ctx)
  87. return;
  88. if (!eol) {
  89. double val;
  90. pa_volume_t vol = pa_cvolume_avg(&i->volume);
  91. if (s->mute < 0 || (s->mute && !i->mute) || (!s->mute && i->mute)) {
  92. s->mute = i->mute;
  93. avdevice_dev_to_app_control_message(h, AV_DEV_TO_APP_MUTE_STATE_CHANGED, &s->mute, sizeof(s->mute));
  94. }
  95. vol = pa_sw_volume_divide(vol, s->base_volume);
  96. if (s->last_volume != vol) {
  97. val = (double)vol / PA_VOLUME_NORM;
  98. avdevice_dev_to_app_control_message(h, AV_DEV_TO_APP_VOLUME_LEVEL_CHANGED, &val, sizeof(val));
  99. s->last_volume = vol;
  100. }
  101. }
  102. }
  103. /* This function creates new loop so may be called from PA callbacks.
  104. Mainloop must be locked before calling this function as it operates on streams. */
  105. static int pulse_update_sink_input_info(AVFormatContext *h)
  106. {
  107. PulseData *s = h->priv_data;
  108. pa_operation *op;
  109. enum pa_operation_state op_state;
  110. pa_mainloop *ml = NULL;
  111. pa_context *ctx = NULL;
  112. int ret = 0;
  113. if ((ret = ff_pulse_audio_connect_context(&ml, &ctx, s->server, "Update sink input information")) < 0)
  114. return ret;
  115. if (!(op = pa_context_get_sink_input_info(ctx, pa_stream_get_index(s->stream),
  116. pulse_audio_sink_input_cb, h))) {
  117. ret = AVERROR_EXTERNAL;
  118. goto fail;
  119. }
  120. while ((op_state = pa_operation_get_state(op)) == PA_OPERATION_RUNNING)
  121. pa_mainloop_iterate(ml, 1, NULL);
  122. pa_operation_unref(op);
  123. if (op_state != PA_OPERATION_DONE) {
  124. ret = AVERROR_EXTERNAL;
  125. goto fail;
  126. }
  127. fail:
  128. ff_pulse_audio_disconnect_context(&ml, &ctx);
  129. if (ret)
  130. av_log(s, AV_LOG_ERROR, "pa_context_get_sink_input_info failed.\n");
  131. return ret;
  132. }
  133. static void pulse_event(pa_context *ctx, pa_subscription_event_type_t t,
  134. uint32_t idx, void *userdata)
  135. {
  136. AVFormatContext *h = userdata;
  137. PulseData *s = h->priv_data;
  138. if (s->ctx != ctx)
  139. return;
  140. if ((t & PA_SUBSCRIPTION_EVENT_FACILITY_MASK) == PA_SUBSCRIPTION_EVENT_SINK_INPUT) {
  141. if ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_CHANGE)
  142. // Calling from mainloop callback. No need to lock mainloop.
  143. pulse_update_sink_input_info(h);
  144. }
  145. }
  146. static void pulse_stream_writable(pa_stream *stream, size_t nbytes, void *userdata)
  147. {
  148. AVFormatContext *h = userdata;
  149. PulseData *s = h->priv_data;
  150. int64_t val = nbytes;
  151. if (stream != s->stream)
  152. return;
  153. avdevice_dev_to_app_control_message(h, AV_DEV_TO_APP_BUFFER_WRITABLE, &val, sizeof(val));
  154. pa_threaded_mainloop_signal(s->mainloop, 0);
  155. }
  156. static void pulse_overflow(pa_stream *stream, void *userdata)
  157. {
  158. AVFormatContext *h = userdata;
  159. avdevice_dev_to_app_control_message(h, AV_DEV_TO_APP_BUFFER_OVERFLOW, NULL, 0);
  160. }
  161. static void pulse_underflow(pa_stream *stream, void *userdata)
  162. {
  163. AVFormatContext *h = userdata;
  164. avdevice_dev_to_app_control_message(h, AV_DEV_TO_APP_BUFFER_UNDERFLOW, NULL, 0);
  165. }
  166. static void pulse_stream_state(pa_stream *stream, void *userdata)
  167. {
  168. PulseData *s = userdata;
  169. if (stream != s->stream)
  170. return;
  171. switch (pa_stream_get_state(s->stream)) {
  172. case PA_STREAM_READY:
  173. case PA_STREAM_FAILED:
  174. case PA_STREAM_TERMINATED:
  175. pa_threaded_mainloop_signal(s->mainloop, 0);
  176. default:
  177. break;
  178. }
  179. }
  180. static int pulse_stream_wait(PulseData *s)
  181. {
  182. pa_stream_state_t state;
  183. while ((state = pa_stream_get_state(s->stream)) != PA_STREAM_READY) {
  184. if (state == PA_STREAM_FAILED || state == PA_STREAM_TERMINATED)
  185. return AVERROR_EXTERNAL;
  186. pa_threaded_mainloop_wait(s->mainloop);
  187. }
  188. return 0;
  189. }
  190. static void pulse_context_state(pa_context *ctx, void *userdata)
  191. {
  192. PulseData *s = userdata;
  193. if (s->ctx != ctx)
  194. return;
  195. switch (pa_context_get_state(ctx)) {
  196. case PA_CONTEXT_READY:
  197. case PA_CONTEXT_FAILED:
  198. case PA_CONTEXT_TERMINATED:
  199. pa_threaded_mainloop_signal(s->mainloop, 0);
  200. default:
  201. break;
  202. }
  203. }
  204. static int pulse_context_wait(PulseData *s)
  205. {
  206. pa_context_state_t state;
  207. while ((state = pa_context_get_state(s->ctx)) != PA_CONTEXT_READY) {
  208. if (state == PA_CONTEXT_FAILED || state == PA_CONTEXT_TERMINATED)
  209. return AVERROR_EXTERNAL;
  210. pa_threaded_mainloop_wait(s->mainloop);
  211. }
  212. return 0;
  213. }
  214. static void pulse_stream_result(pa_stream *stream, int success, void *userdata)
  215. {
  216. PulseData *s = userdata;
  217. if (stream != s->stream)
  218. return;
  219. s->last_result = success ? 0 : AVERROR_EXTERNAL;
  220. pa_threaded_mainloop_signal(s->mainloop, 0);
  221. }
  222. static int pulse_finish_stream_operation(PulseData *s, pa_operation *op, const char *name)
  223. {
  224. if (!op) {
  225. pa_threaded_mainloop_unlock(s->mainloop);
  226. av_log(s, AV_LOG_ERROR, "%s failed.\n", name);
  227. return AVERROR_EXTERNAL;
  228. }
  229. s->last_result = 2;
  230. while (s->last_result == 2)
  231. pa_threaded_mainloop_wait(s->mainloop);
  232. pa_operation_unref(op);
  233. pa_threaded_mainloop_unlock(s->mainloop);
  234. if (s->last_result != 0)
  235. av_log(s, AV_LOG_ERROR, "%s failed.\n", name);
  236. return s->last_result;
  237. }
  238. static int pulse_set_pause(PulseData *s, int pause)
  239. {
  240. pa_operation *op;
  241. pa_threaded_mainloop_lock(s->mainloop);
  242. op = pa_stream_cork(s->stream, pause, pulse_stream_result, s);
  243. return pulse_finish_stream_operation(s, op, "pa_stream_cork");
  244. }
  245. static int pulse_flash_stream(PulseData *s)
  246. {
  247. pa_operation *op;
  248. pa_threaded_mainloop_lock(s->mainloop);
  249. op = pa_stream_flush(s->stream, pulse_stream_result, s);
  250. return pulse_finish_stream_operation(s, op, "pa_stream_flush");
  251. }
  252. static void pulse_context_result(pa_context *ctx, int success, void *userdata)
  253. {
  254. PulseData *s = userdata;
  255. if (s->ctx != ctx)
  256. return;
  257. s->last_result = success ? 0 : AVERROR_EXTERNAL;
  258. pa_threaded_mainloop_signal(s->mainloop, 0);
  259. }
  260. static int pulse_finish_context_operation(PulseData *s, pa_operation *op, const char *name)
  261. {
  262. if (!op) {
  263. pa_threaded_mainloop_unlock(s->mainloop);
  264. av_log(s, AV_LOG_ERROR, "%s failed.\n", name);
  265. return AVERROR_EXTERNAL;
  266. }
  267. s->last_result = 2;
  268. while (s->last_result == 2)
  269. pa_threaded_mainloop_wait(s->mainloop);
  270. pa_operation_unref(op);
  271. pa_threaded_mainloop_unlock(s->mainloop);
  272. if (s->last_result != 0)
  273. av_log(s, AV_LOG_ERROR, "%s failed.\n", name);
  274. return s->last_result;
  275. }
  276. static int pulse_set_mute(PulseData *s)
  277. {
  278. pa_operation *op;
  279. pa_threaded_mainloop_lock(s->mainloop);
  280. op = pa_context_set_sink_input_mute(s->ctx, pa_stream_get_index(s->stream),
  281. s->mute, pulse_context_result, s);
  282. return pulse_finish_context_operation(s, op, "pa_context_set_sink_input_mute");
  283. }
  284. static int pulse_set_volume(PulseData *s, double volume)
  285. {
  286. pa_operation *op;
  287. pa_cvolume cvol;
  288. pa_volume_t vol;
  289. const pa_sample_spec *ss = pa_stream_get_sample_spec(s->stream);
  290. vol = pa_sw_volume_multiply(lround(volume * PA_VOLUME_NORM), s->base_volume);
  291. pa_cvolume_set(&cvol, ss->channels, PA_VOLUME_NORM);
  292. pa_sw_cvolume_multiply_scalar(&cvol, &cvol, vol);
  293. pa_threaded_mainloop_lock(s->mainloop);
  294. op = pa_context_set_sink_input_volume(s->ctx, pa_stream_get_index(s->stream),
  295. &cvol, pulse_context_result, s);
  296. return pulse_finish_context_operation(s, op, "pa_context_set_sink_input_volume");
  297. }
  298. static int pulse_subscribe_events(PulseData *s)
  299. {
  300. pa_operation *op;
  301. pa_threaded_mainloop_lock(s->mainloop);
  302. op = pa_context_subscribe(s->ctx, PA_SUBSCRIPTION_MASK_SINK_INPUT, pulse_context_result, s);
  303. return pulse_finish_context_operation(s, op, "pa_context_subscribe");
  304. }
  305. static void pulse_map_channels_to_pulse(int64_t channel_layout, pa_channel_map *channel_map)
  306. {
  307. channel_map->channels = 0;
  308. if (channel_layout & AV_CH_FRONT_LEFT)
  309. channel_map->map[channel_map->channels++] = PA_CHANNEL_POSITION_FRONT_LEFT;
  310. if (channel_layout & AV_CH_FRONT_RIGHT)
  311. channel_map->map[channel_map->channels++] = PA_CHANNEL_POSITION_FRONT_RIGHT;
  312. if (channel_layout & AV_CH_FRONT_CENTER)
  313. channel_map->map[channel_map->channels++] = PA_CHANNEL_POSITION_FRONT_CENTER;
  314. if (channel_layout & AV_CH_LOW_FREQUENCY)
  315. channel_map->map[channel_map->channels++] = PA_CHANNEL_POSITION_LFE;
  316. if (channel_layout & AV_CH_BACK_LEFT)
  317. channel_map->map[channel_map->channels++] = PA_CHANNEL_POSITION_REAR_LEFT;
  318. if (channel_layout & AV_CH_BACK_RIGHT)
  319. channel_map->map[channel_map->channels++] = PA_CHANNEL_POSITION_REAR_RIGHT;
  320. if (channel_layout & AV_CH_FRONT_LEFT_OF_CENTER)
  321. channel_map->map[channel_map->channels++] = PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER;
  322. if (channel_layout & AV_CH_FRONT_RIGHT_OF_CENTER)
  323. channel_map->map[channel_map->channels++] = PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER;
  324. if (channel_layout & AV_CH_BACK_CENTER)
  325. channel_map->map[channel_map->channels++] = PA_CHANNEL_POSITION_REAR_CENTER;
  326. if (channel_layout & AV_CH_SIDE_LEFT)
  327. channel_map->map[channel_map->channels++] = PA_CHANNEL_POSITION_SIDE_LEFT;
  328. if (channel_layout & AV_CH_SIDE_RIGHT)
  329. channel_map->map[channel_map->channels++] = PA_CHANNEL_POSITION_SIDE_RIGHT;
  330. if (channel_layout & AV_CH_TOP_CENTER)
  331. channel_map->map[channel_map->channels++] = PA_CHANNEL_POSITION_TOP_CENTER;
  332. if (channel_layout & AV_CH_TOP_FRONT_LEFT)
  333. channel_map->map[channel_map->channels++] = PA_CHANNEL_POSITION_TOP_FRONT_LEFT;
  334. if (channel_layout & AV_CH_TOP_FRONT_CENTER)
  335. channel_map->map[channel_map->channels++] = PA_CHANNEL_POSITION_TOP_FRONT_CENTER;
  336. if (channel_layout & AV_CH_TOP_FRONT_RIGHT)
  337. channel_map->map[channel_map->channels++] = PA_CHANNEL_POSITION_TOP_FRONT_RIGHT;
  338. if (channel_layout & AV_CH_TOP_BACK_LEFT)
  339. channel_map->map[channel_map->channels++] = PA_CHANNEL_POSITION_TOP_REAR_LEFT;
  340. if (channel_layout & AV_CH_TOP_BACK_CENTER)
  341. channel_map->map[channel_map->channels++] = PA_CHANNEL_POSITION_TOP_REAR_CENTER;
  342. if (channel_layout & AV_CH_TOP_BACK_RIGHT)
  343. channel_map->map[channel_map->channels++] = PA_CHANNEL_POSITION_TOP_REAR_RIGHT;
  344. if (channel_layout & AV_CH_STEREO_LEFT)
  345. channel_map->map[channel_map->channels++] = PA_CHANNEL_POSITION_FRONT_LEFT;
  346. if (channel_layout & AV_CH_STEREO_RIGHT)
  347. channel_map->map[channel_map->channels++] = PA_CHANNEL_POSITION_FRONT_RIGHT;
  348. if (channel_layout & AV_CH_WIDE_LEFT)
  349. channel_map->map[channel_map->channels++] = PA_CHANNEL_POSITION_AUX0;
  350. if (channel_layout & AV_CH_WIDE_RIGHT)
  351. channel_map->map[channel_map->channels++] = PA_CHANNEL_POSITION_AUX1;
  352. if (channel_layout & AV_CH_SURROUND_DIRECT_LEFT)
  353. channel_map->map[channel_map->channels++] = PA_CHANNEL_POSITION_AUX2;
  354. if (channel_layout & AV_CH_SURROUND_DIRECT_RIGHT)
  355. channel_map->map[channel_map->channels++] = PA_CHANNEL_POSITION_AUX3;
  356. if (channel_layout & AV_CH_LOW_FREQUENCY_2)
  357. channel_map->map[channel_map->channels++] = PA_CHANNEL_POSITION_LFE;
  358. }
  359. static av_cold int pulse_write_trailer(AVFormatContext *h)
  360. {
  361. PulseData *s = h->priv_data;
  362. if (s->mainloop) {
  363. pa_threaded_mainloop_lock(s->mainloop);
  364. if (s->stream) {
  365. pa_stream_disconnect(s->stream);
  366. pa_stream_set_state_callback(s->stream, NULL, NULL);
  367. pa_stream_set_write_callback(s->stream, NULL, NULL);
  368. pa_stream_set_overflow_callback(s->stream, NULL, NULL);
  369. pa_stream_set_underflow_callback(s->stream, NULL, NULL);
  370. pa_stream_unref(s->stream);
  371. s->stream = NULL;
  372. }
  373. if (s->ctx) {
  374. pa_context_disconnect(s->ctx);
  375. pa_context_set_state_callback(s->ctx, NULL, NULL);
  376. pa_context_set_subscribe_callback(s->ctx, NULL, NULL);
  377. pa_context_unref(s->ctx);
  378. s->ctx = NULL;
  379. }
  380. pa_threaded_mainloop_unlock(s->mainloop);
  381. pa_threaded_mainloop_stop(s->mainloop);
  382. pa_threaded_mainloop_free(s->mainloop);
  383. s->mainloop = NULL;
  384. }
  385. return 0;
  386. }
  387. static av_cold int pulse_write_header(AVFormatContext *h)
  388. {
  389. PulseData *s = h->priv_data;
  390. AVStream *st = NULL;
  391. int ret;
  392. pa_sample_spec sample_spec;
  393. pa_buffer_attr buffer_attributes = { -1, -1, -1, -1, -1 };
  394. pa_channel_map channel_map;
  395. pa_mainloop_api *mainloop_api;
  396. const char *stream_name = s->stream_name;
  397. static const pa_stream_flags_t stream_flags = PA_STREAM_INTERPOLATE_TIMING |
  398. PA_STREAM_AUTO_TIMING_UPDATE |
  399. PA_STREAM_NOT_MONOTONIC;
  400. if (h->nb_streams != 1 || h->streams[0]->codec->codec_type != AVMEDIA_TYPE_AUDIO) {
  401. av_log(s, AV_LOG_ERROR, "Only a single audio stream is supported.\n");
  402. return AVERROR(EINVAL);
  403. }
  404. st = h->streams[0];
  405. if (!stream_name) {
  406. if (h->filename[0])
  407. stream_name = h->filename;
  408. else
  409. stream_name = "Playback";
  410. }
  411. s->nonblocking = (h->flags & AVFMT_FLAG_NONBLOCK);
  412. if (s->buffer_duration) {
  413. int64_t bytes = s->buffer_duration;
  414. bytes *= st->codec->channels * st->codec->sample_rate *
  415. av_get_bytes_per_sample(st->codec->sample_fmt);
  416. bytes /= 1000;
  417. buffer_attributes.tlength = FFMAX(s->buffer_size, av_clip64(bytes, 0, UINT32_MAX - 1));
  418. av_log(s, AV_LOG_DEBUG,
  419. "Buffer duration: %ums recalculated into %"PRId64" bytes buffer.\n",
  420. s->buffer_duration, bytes);
  421. av_log(s, AV_LOG_DEBUG, "Real buffer length is %u bytes\n", buffer_attributes.tlength);
  422. } else if (s->buffer_size)
  423. buffer_attributes.tlength = s->buffer_size;
  424. if (s->prebuf)
  425. buffer_attributes.prebuf = s->prebuf;
  426. if (s->minreq)
  427. buffer_attributes.minreq = s->minreq;
  428. sample_spec.format = ff_codec_id_to_pulse_format(st->codec->codec_id);
  429. sample_spec.rate = st->codec->sample_rate;
  430. sample_spec.channels = st->codec->channels;
  431. if (!pa_sample_spec_valid(&sample_spec)) {
  432. av_log(s, AV_LOG_ERROR, "Invalid sample spec.\n");
  433. return AVERROR(EINVAL);
  434. }
  435. if (sample_spec.channels == 1) {
  436. channel_map.channels = 1;
  437. channel_map.map[0] = PA_CHANNEL_POSITION_MONO;
  438. } else if (st->codec->channel_layout) {
  439. if (av_get_channel_layout_nb_channels(st->codec->channel_layout) != st->codec->channels)
  440. return AVERROR(EINVAL);
  441. pulse_map_channels_to_pulse(st->codec->channel_layout, &channel_map);
  442. /* Unknown channel is present in channel_layout, let PulseAudio use its default. */
  443. if (channel_map.channels != sample_spec.channels) {
  444. av_log(s, AV_LOG_WARNING, "Unknown channel. Using defaul channel map.\n");
  445. channel_map.channels = 0;
  446. }
  447. } else
  448. channel_map.channels = 0;
  449. if (!channel_map.channels)
  450. av_log(s, AV_LOG_WARNING, "Using PulseAudio's default channel map.\n");
  451. else if (!pa_channel_map_valid(&channel_map)) {
  452. av_log(s, AV_LOG_ERROR, "Invalid channel map.\n");
  453. return AVERROR(EINVAL);
  454. }
  455. /* start main loop */
  456. s->mainloop = pa_threaded_mainloop_new();
  457. if (!s->mainloop) {
  458. av_log(s, AV_LOG_ERROR, "Cannot create threaded mainloop.\n");
  459. return AVERROR(ENOMEM);
  460. }
  461. if ((ret = pa_threaded_mainloop_start(s->mainloop)) < 0) {
  462. av_log(s, AV_LOG_ERROR, "Cannot start threaded mainloop: %s.\n", pa_strerror(ret));
  463. pa_threaded_mainloop_free(s->mainloop);
  464. s->mainloop = NULL;
  465. return AVERROR_EXTERNAL;
  466. }
  467. pa_threaded_mainloop_lock(s->mainloop);
  468. mainloop_api = pa_threaded_mainloop_get_api(s->mainloop);
  469. if (!mainloop_api) {
  470. av_log(s, AV_LOG_ERROR, "Cannot get mainloop API.\n");
  471. ret = AVERROR_EXTERNAL;
  472. goto fail;
  473. }
  474. s->ctx = pa_context_new(mainloop_api, s->name);
  475. if (!s->ctx) {
  476. av_log(s, AV_LOG_ERROR, "Cannot create context.\n");
  477. ret = AVERROR(ENOMEM);
  478. goto fail;
  479. }
  480. pa_context_set_state_callback(s->ctx, pulse_context_state, s);
  481. pa_context_set_subscribe_callback(s->ctx, pulse_event, h);
  482. if ((ret = pa_context_connect(s->ctx, s->server, 0, NULL)) < 0) {
  483. av_log(s, AV_LOG_ERROR, "Cannot connect context: %s.\n", pa_strerror(ret));
  484. ret = AVERROR_EXTERNAL;
  485. goto fail;
  486. }
  487. if ((ret = pulse_context_wait(s)) < 0) {
  488. av_log(s, AV_LOG_ERROR, "Context failed.\n");
  489. goto fail;
  490. }
  491. s->stream = pa_stream_new(s->ctx, stream_name, &sample_spec,
  492. channel_map.channels ? &channel_map : NULL);
  493. if ((ret = pulse_update_sink_info(h)) < 0) {
  494. av_log(s, AV_LOG_ERROR, "Updating sink info failed.\n");
  495. goto fail;
  496. }
  497. if (!s->stream) {
  498. av_log(s, AV_LOG_ERROR, "Cannot create stream.\n");
  499. ret = AVERROR(ENOMEM);
  500. goto fail;
  501. }
  502. pa_stream_set_state_callback(s->stream, pulse_stream_state, s);
  503. pa_stream_set_write_callback(s->stream, pulse_stream_writable, h);
  504. pa_stream_set_overflow_callback(s->stream, pulse_overflow, h);
  505. pa_stream_set_underflow_callback(s->stream, pulse_underflow, h);
  506. if ((ret = pa_stream_connect_playback(s->stream, s->device, &buffer_attributes,
  507. stream_flags, NULL, NULL)) < 0) {
  508. av_log(s, AV_LOG_ERROR, "pa_stream_connect_playback failed: %s.\n", pa_strerror(ret));
  509. ret = AVERROR_EXTERNAL;
  510. goto fail;
  511. }
  512. if ((ret = pulse_stream_wait(s)) < 0) {
  513. av_log(s, AV_LOG_ERROR, "Stream failed.\n");
  514. goto fail;
  515. }
  516. /* read back buffer attributes for future use */
  517. buffer_attributes = *pa_stream_get_buffer_attr(s->stream);
  518. s->buffer_size = buffer_attributes.tlength;
  519. s->prebuf = buffer_attributes.prebuf;
  520. s->minreq = buffer_attributes.minreq;
  521. av_log(s, AV_LOG_DEBUG, "Real buffer attributes: size: %d, prebuf: %d, minreq: %d\n",
  522. s->buffer_size, s->prebuf, s->minreq);
  523. pa_threaded_mainloop_unlock(s->mainloop);
  524. if ((ret = pulse_subscribe_events(s)) < 0) {
  525. av_log(s, AV_LOG_ERROR, "Event subscription failed.\n");
  526. /* a bit ugly but the simplest to lock here*/
  527. pa_threaded_mainloop_lock(s->mainloop);
  528. goto fail;
  529. }
  530. /* force control messages */
  531. s->mute = -1;
  532. s->last_volume = PA_VOLUME_INVALID;
  533. pa_threaded_mainloop_lock(s->mainloop);
  534. if ((ret = pulse_update_sink_input_info(h)) < 0) {
  535. av_log(s, AV_LOG_ERROR, "Updating sink input info failed.\n");
  536. goto fail;
  537. }
  538. pa_threaded_mainloop_unlock(s->mainloop);
  539. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  540. return 0;
  541. fail:
  542. pa_threaded_mainloop_unlock(s->mainloop);
  543. pulse_write_trailer(h);
  544. return ret;
  545. }
  546. static int pulse_write_packet(AVFormatContext *h, AVPacket *pkt)
  547. {
  548. PulseData *s = h->priv_data;
  549. int ret;
  550. int64_t writable_size;
  551. if (!pkt)
  552. return pulse_flash_stream(s);
  553. if (pkt->dts != AV_NOPTS_VALUE)
  554. s->timestamp = pkt->dts;
  555. if (pkt->duration) {
  556. s->timestamp += pkt->duration;
  557. } else {
  558. AVStream *st = h->streams[0];
  559. AVCodecContext *codec_ctx = st->codec;
  560. AVRational r = { 1, codec_ctx->sample_rate };
  561. int64_t samples = pkt->size / (av_get_bytes_per_sample(codec_ctx->sample_fmt) * codec_ctx->channels);
  562. s->timestamp += av_rescale_q(samples, r, st->time_base);
  563. }
  564. pa_threaded_mainloop_lock(s->mainloop);
  565. if (!PA_STREAM_IS_GOOD(pa_stream_get_state(s->stream))) {
  566. av_log(s, AV_LOG_ERROR, "PulseAudio stream is in invalid state.\n");
  567. goto fail;
  568. }
  569. while (pa_stream_writable_size(s->stream) < s->minreq) {
  570. if (s->nonblocking) {
  571. pa_threaded_mainloop_unlock(s->mainloop);
  572. return AVERROR(EAGAIN);
  573. } else
  574. pa_threaded_mainloop_wait(s->mainloop);
  575. }
  576. if ((ret = pa_stream_write(s->stream, pkt->data, pkt->size, NULL, 0, PA_SEEK_RELATIVE)) < 0) {
  577. av_log(s, AV_LOG_ERROR, "pa_stream_write failed: %s\n", pa_strerror(ret));
  578. goto fail;
  579. }
  580. if ((writable_size = pa_stream_writable_size(s->stream)) >= s->minreq)
  581. avdevice_dev_to_app_control_message(h, AV_DEV_TO_APP_BUFFER_WRITABLE, &writable_size, sizeof(writable_size));
  582. pa_threaded_mainloop_unlock(s->mainloop);
  583. return 0;
  584. fail:
  585. pa_threaded_mainloop_unlock(s->mainloop);
  586. return AVERROR_EXTERNAL;
  587. }
  588. static int pulse_write_frame(AVFormatContext *h, int stream_index,
  589. AVFrame **frame, unsigned flags)
  590. {
  591. AVPacket pkt;
  592. /* Planar formats are not supported yet. */
  593. if (flags & AV_WRITE_UNCODED_FRAME_QUERY)
  594. return av_sample_fmt_is_planar(h->streams[stream_index]->codec->sample_fmt) ?
  595. AVERROR(EINVAL) : 0;
  596. pkt.data = (*frame)->data[0];
  597. pkt.size = (*frame)->nb_samples * av_get_bytes_per_sample((*frame)->format) * av_frame_get_channels(*frame);
  598. pkt.dts = (*frame)->pkt_dts;
  599. pkt.duration = av_frame_get_pkt_duration(*frame);
  600. return pulse_write_packet(h, &pkt);
  601. }
  602. static void pulse_get_output_timestamp(AVFormatContext *h, int stream, int64_t *dts, int64_t *wall)
  603. {
  604. PulseData *s = h->priv_data;
  605. pa_usec_t latency;
  606. int neg;
  607. pa_threaded_mainloop_lock(s->mainloop);
  608. pa_stream_get_latency(s->stream, &latency, &neg);
  609. pa_threaded_mainloop_unlock(s->mainloop);
  610. if (wall)
  611. *wall = av_gettime();
  612. if (dts)
  613. *dts = s->timestamp - (neg ? -latency : latency);
  614. }
  615. static int pulse_get_device_list(AVFormatContext *h, AVDeviceInfoList *device_list)
  616. {
  617. PulseData *s = h->priv_data;
  618. return ff_pulse_audio_get_devices(device_list, s->server, 1);
  619. }
  620. static int pulse_control_message(AVFormatContext *h, int type,
  621. void *data, size_t data_size)
  622. {
  623. PulseData *s = h->priv_data;
  624. int ret;
  625. switch(type) {
  626. case AV_APP_TO_DEV_PAUSE:
  627. return pulse_set_pause(s, 1);
  628. case AV_APP_TO_DEV_PLAY:
  629. return pulse_set_pause(s, 0);
  630. case AV_APP_TO_DEV_TOGGLE_PAUSE:
  631. return pulse_set_pause(s, !pa_stream_is_corked(s->stream));
  632. case AV_APP_TO_DEV_MUTE:
  633. if (!s->mute) {
  634. s->mute = 1;
  635. return pulse_set_mute(s);
  636. }
  637. return 0;
  638. case AV_APP_TO_DEV_UNMUTE:
  639. if (s->mute) {
  640. s->mute = 0;
  641. return pulse_set_mute(s);
  642. }
  643. return 0;
  644. case AV_APP_TO_DEV_TOGGLE_MUTE:
  645. s->mute = !s->mute;
  646. return pulse_set_mute(s);
  647. case AV_APP_TO_DEV_SET_VOLUME:
  648. return pulse_set_volume(s, *(double *)data);
  649. case AV_APP_TO_DEV_GET_VOLUME:
  650. s->last_volume = PA_VOLUME_INVALID;
  651. pa_threaded_mainloop_lock(s->mainloop);
  652. ret = pulse_update_sink_input_info(h);
  653. pa_threaded_mainloop_unlock(s->mainloop);
  654. return ret;
  655. case AV_APP_TO_DEV_GET_MUTE:
  656. s->mute = -1;
  657. pa_threaded_mainloop_lock(s->mainloop);
  658. ret = pulse_update_sink_input_info(h);
  659. pa_threaded_mainloop_unlock(s->mainloop);
  660. return ret;
  661. default:
  662. break;
  663. }
  664. return AVERROR(ENOSYS);
  665. }
  666. #define OFFSET(a) offsetof(PulseData, a)
  667. #define E AV_OPT_FLAG_ENCODING_PARAM
  668. static const AVOption options[] = {
  669. { "server", "set PulseAudio server", OFFSET(server), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  670. { "name", "set application name", OFFSET(name), AV_OPT_TYPE_STRING, {.str = LIBAVFORMAT_IDENT}, 0, 0, E },
  671. { "stream_name", "set stream description", OFFSET(stream_name), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  672. { "device", "set device name", OFFSET(device), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  673. { "buffer_size", "set buffer size in bytes", OFFSET(buffer_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
  674. { "buffer_duration", "set buffer duration in millisecs", OFFSET(buffer_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
  675. { "prebuf", "set pre-buffering size", OFFSET(prebuf), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
  676. { "minreq", "set minimum request size", OFFSET(minreq), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
  677. { NULL }
  678. };
  679. static const AVClass pulse_muxer_class = {
  680. .class_name = "PulseAudio muxer",
  681. .item_name = av_default_item_name,
  682. .option = options,
  683. .version = LIBAVUTIL_VERSION_INT,
  684. .category = AV_CLASS_CATEGORY_DEVICE_AUDIO_OUTPUT,
  685. };
  686. AVOutputFormat ff_pulse_muxer = {
  687. .name = "pulse",
  688. .long_name = NULL_IF_CONFIG_SMALL("Pulse audio output"),
  689. .priv_data_size = sizeof(PulseData),
  690. .audio_codec = AV_NE(AV_CODEC_ID_PCM_S16BE, AV_CODEC_ID_PCM_S16LE),
  691. .video_codec = AV_CODEC_ID_NONE,
  692. .write_header = pulse_write_header,
  693. .write_packet = pulse_write_packet,
  694. .write_uncoded_frame = pulse_write_frame,
  695. .write_trailer = pulse_write_trailer,
  696. .get_output_timestamp = pulse_get_output_timestamp,
  697. .get_device_list = pulse_get_device_list,
  698. .control_message = pulse_control_message,
  699. .flags = AVFMT_NOFILE | AVFMT_ALLOW_FLUSH,
  700. .priv_class = &pulse_muxer_class,
  701. };