pulse_audio_enc.c 30 KB

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