pulse_audio_enc.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  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 = av_rescale(s->buffer_duration,
  419. st->codecpar->ch_layout.nb_channels *
  420. (int64_t)st->codecpar->sample_rate *
  421. av_get_bytes_per_sample(st->codecpar->format),
  422. 1000);
  423. buffer_attributes.tlength = FFMAX(s->buffer_size, av_clip64(bytes, 0, UINT32_MAX - 1));
  424. av_log(s, AV_LOG_DEBUG,
  425. "Buffer duration: %ums recalculated into %"PRId64" bytes buffer.\n",
  426. s->buffer_duration, bytes);
  427. av_log(s, AV_LOG_DEBUG, "Real buffer length is %u bytes\n", buffer_attributes.tlength);
  428. } else if (s->buffer_size)
  429. buffer_attributes.tlength = s->buffer_size;
  430. if (s->prebuf)
  431. buffer_attributes.prebuf = s->prebuf;
  432. if (s->minreq)
  433. buffer_attributes.minreq = s->minreq;
  434. sample_spec.format = ff_codec_id_to_pulse_format(st->codecpar->codec_id);
  435. sample_spec.rate = st->codecpar->sample_rate;
  436. sample_spec.channels = st->codecpar->ch_layout.nb_channels;
  437. if (!pa_sample_spec_valid(&sample_spec)) {
  438. av_log(s, AV_LOG_ERROR, "Invalid sample spec.\n");
  439. return AVERROR(EINVAL);
  440. }
  441. if (sample_spec.channels == 1) {
  442. channel_map.channels = 1;
  443. channel_map.map[0] = PA_CHANNEL_POSITION_MONO;
  444. } else if (st->codecpar->ch_layout.order != AV_CHANNEL_ORDER_UNSPEC) {
  445. if (!av_channel_layout_check(&st->codecpar->ch_layout))
  446. return AVERROR(EINVAL);
  447. pulse_map_channels_to_pulse(&st->codecpar->ch_layout, &channel_map);
  448. /* Unknown channel is present in channel_layout, let PulseAudio use its default. */
  449. if (channel_map.channels != sample_spec.channels) {
  450. av_log(s, AV_LOG_WARNING, "Unknown channel. Using default channel map.\n");
  451. channel_map.channels = 0;
  452. }
  453. } else
  454. channel_map.channels = 0;
  455. if (!channel_map.channels)
  456. av_log(s, AV_LOG_WARNING, "Using PulseAudio's default channel map.\n");
  457. else if (!pa_channel_map_valid(&channel_map)) {
  458. av_log(s, AV_LOG_ERROR, "Invalid channel map.\n");
  459. return AVERROR(EINVAL);
  460. }
  461. /* start main loop */
  462. s->mainloop = pa_threaded_mainloop_new();
  463. if (!s->mainloop) {
  464. av_log(s, AV_LOG_ERROR, "Cannot create threaded mainloop.\n");
  465. return AVERROR(ENOMEM);
  466. }
  467. if ((ret = pa_threaded_mainloop_start(s->mainloop)) < 0) {
  468. av_log(s, AV_LOG_ERROR, "Cannot start threaded mainloop: %s.\n", pa_strerror(ret));
  469. pa_threaded_mainloop_free(s->mainloop);
  470. s->mainloop = NULL;
  471. return AVERROR_EXTERNAL;
  472. }
  473. pa_threaded_mainloop_lock(s->mainloop);
  474. mainloop_api = pa_threaded_mainloop_get_api(s->mainloop);
  475. if (!mainloop_api) {
  476. av_log(s, AV_LOG_ERROR, "Cannot get mainloop API.\n");
  477. ret = AVERROR_EXTERNAL;
  478. goto fail;
  479. }
  480. s->ctx = pa_context_new(mainloop_api, s->name);
  481. if (!s->ctx) {
  482. av_log(s, AV_LOG_ERROR, "Cannot create context.\n");
  483. ret = AVERROR(ENOMEM);
  484. goto fail;
  485. }
  486. pa_context_set_state_callback(s->ctx, pulse_context_state, s);
  487. pa_context_set_subscribe_callback(s->ctx, pulse_event, h);
  488. if ((ret = pa_context_connect(s->ctx, s->server, 0, NULL)) < 0) {
  489. av_log(s, AV_LOG_ERROR, "Cannot connect context: %s.\n", pa_strerror(ret));
  490. ret = AVERROR_EXTERNAL;
  491. goto fail;
  492. }
  493. if ((ret = pulse_context_wait(s)) < 0) {
  494. av_log(s, AV_LOG_ERROR, "Context failed.\n");
  495. goto fail;
  496. }
  497. s->stream = pa_stream_new(s->ctx, stream_name, &sample_spec,
  498. channel_map.channels ? &channel_map : NULL);
  499. if ((ret = pulse_update_sink_info(h)) < 0) {
  500. av_log(s, AV_LOG_ERROR, "Updating sink info failed.\n");
  501. goto fail;
  502. }
  503. if (!s->stream) {
  504. av_log(s, AV_LOG_ERROR, "Cannot create stream.\n");
  505. ret = AVERROR(ENOMEM);
  506. goto fail;
  507. }
  508. pa_stream_set_state_callback(s->stream, pulse_stream_state, s);
  509. pa_stream_set_write_callback(s->stream, pulse_stream_writable, h);
  510. pa_stream_set_overflow_callback(s->stream, pulse_overflow, h);
  511. pa_stream_set_underflow_callback(s->stream, pulse_underflow, h);
  512. if ((ret = pa_stream_connect_playback(s->stream, s->device, &buffer_attributes,
  513. stream_flags, NULL, NULL)) < 0) {
  514. av_log(s, AV_LOG_ERROR, "pa_stream_connect_playback failed: %s.\n", pa_strerror(ret));
  515. ret = AVERROR_EXTERNAL;
  516. goto fail;
  517. }
  518. if ((ret = pulse_stream_wait(s)) < 0) {
  519. av_log(s, AV_LOG_ERROR, "Stream failed.\n");
  520. goto fail;
  521. }
  522. /* read back buffer attributes for future use */
  523. buffer_attributes = *pa_stream_get_buffer_attr(s->stream);
  524. s->buffer_size = buffer_attributes.tlength;
  525. s->prebuf = buffer_attributes.prebuf;
  526. s->minreq = buffer_attributes.minreq;
  527. av_log(s, AV_LOG_DEBUG, "Real buffer attributes: size: %d, prebuf: %d, minreq: %d\n",
  528. s->buffer_size, s->prebuf, s->minreq);
  529. pa_threaded_mainloop_unlock(s->mainloop);
  530. if ((ret = pulse_subscribe_events(s)) < 0) {
  531. av_log(s, AV_LOG_ERROR, "Event subscription failed.\n");
  532. /* a bit ugly but the simplest to lock here*/
  533. pa_threaded_mainloop_lock(s->mainloop);
  534. goto fail;
  535. }
  536. /* force control messages */
  537. s->mute = -1;
  538. s->last_volume = PA_VOLUME_INVALID;
  539. pa_threaded_mainloop_lock(s->mainloop);
  540. if ((ret = pulse_update_sink_input_info(h)) < 0) {
  541. av_log(s, AV_LOG_ERROR, "Updating sink input info failed.\n");
  542. goto fail;
  543. }
  544. pa_threaded_mainloop_unlock(s->mainloop);
  545. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  546. return 0;
  547. fail:
  548. pa_threaded_mainloop_unlock(s->mainloop);
  549. pulse_write_trailer(h);
  550. return ret;
  551. }
  552. static int pulse_write_packet(AVFormatContext *h, AVPacket *pkt)
  553. {
  554. PulseData *s = h->priv_data;
  555. int ret;
  556. int64_t writable_size;
  557. if (!pkt)
  558. return pulse_flash_stream(s);
  559. if (pkt->dts != AV_NOPTS_VALUE)
  560. s->timestamp = pkt->dts;
  561. if (pkt->duration) {
  562. s->timestamp += pkt->duration;
  563. } else {
  564. AVStream *st = h->streams[0];
  565. AVRational r = { 1, st->codecpar->sample_rate };
  566. int64_t samples = pkt->size / (av_get_bytes_per_sample(st->codecpar->format) * st->codecpar->ch_layout.nb_channels);
  567. s->timestamp += av_rescale_q(samples, r, st->time_base);
  568. }
  569. pa_threaded_mainloop_lock(s->mainloop);
  570. if (!PA_STREAM_IS_GOOD(pa_stream_get_state(s->stream))) {
  571. av_log(s, AV_LOG_ERROR, "PulseAudio stream is in invalid state.\n");
  572. goto fail;
  573. }
  574. while (pa_stream_writable_size(s->stream) < s->minreq) {
  575. if (s->nonblocking) {
  576. pa_threaded_mainloop_unlock(s->mainloop);
  577. return AVERROR(EAGAIN);
  578. } else
  579. pa_threaded_mainloop_wait(s->mainloop);
  580. }
  581. if ((ret = pa_stream_write(s->stream, pkt->data, pkt->size, NULL, 0, PA_SEEK_RELATIVE)) < 0) {
  582. av_log(s, AV_LOG_ERROR, "pa_stream_write failed: %s\n", pa_strerror(ret));
  583. goto fail;
  584. }
  585. if ((writable_size = pa_stream_writable_size(s->stream)) >= s->minreq)
  586. avdevice_dev_to_app_control_message(h, AV_DEV_TO_APP_BUFFER_WRITABLE, &writable_size, sizeof(writable_size));
  587. pa_threaded_mainloop_unlock(s->mainloop);
  588. return 0;
  589. fail:
  590. pa_threaded_mainloop_unlock(s->mainloop);
  591. return AVERROR_EXTERNAL;
  592. }
  593. static int pulse_write_frame(AVFormatContext *h, int stream_index,
  594. AVFrame **frame, unsigned flags)
  595. {
  596. AVPacket pkt;
  597. /* Planar formats are not supported yet. */
  598. if (flags & AV_WRITE_UNCODED_FRAME_QUERY)
  599. return av_sample_fmt_is_planar(h->streams[stream_index]->codecpar->format) ?
  600. AVERROR(EINVAL) : 0;
  601. pkt.data = (*frame)->data[0];
  602. pkt.size = (*frame)->nb_samples * av_get_bytes_per_sample((*frame)->format) * (*frame)->ch_layout.nb_channels;
  603. pkt.dts = (*frame)->pkt_dts;
  604. pkt.duration = (*frame)->duration;
  605. return pulse_write_packet(h, &pkt);
  606. }
  607. static void pulse_get_output_timestamp(AVFormatContext *h, int stream, int64_t *dts, int64_t *wall)
  608. {
  609. PulseData *s = h->priv_data;
  610. pa_usec_t latency;
  611. int neg;
  612. pa_threaded_mainloop_lock(s->mainloop);
  613. pa_stream_get_latency(s->stream, &latency, &neg);
  614. pa_threaded_mainloop_unlock(s->mainloop);
  615. if (wall)
  616. *wall = av_gettime();
  617. if (dts)
  618. *dts = s->timestamp - (neg ? -latency : latency);
  619. }
  620. static int pulse_get_device_list(AVFormatContext *h, AVDeviceInfoList *device_list)
  621. {
  622. PulseData *s = h->priv_data;
  623. return ff_pulse_audio_get_devices(device_list, s->server, 1);
  624. }
  625. static int pulse_control_message(AVFormatContext *h, int type,
  626. void *data, size_t data_size)
  627. {
  628. PulseData *s = h->priv_data;
  629. int ret;
  630. switch(type) {
  631. case AV_APP_TO_DEV_PAUSE:
  632. return pulse_set_pause(s, 1);
  633. case AV_APP_TO_DEV_PLAY:
  634. return pulse_set_pause(s, 0);
  635. case AV_APP_TO_DEV_TOGGLE_PAUSE:
  636. return pulse_set_pause(s, !pa_stream_is_corked(s->stream));
  637. case AV_APP_TO_DEV_MUTE:
  638. if (!s->mute) {
  639. s->mute = 1;
  640. return pulse_set_mute(s);
  641. }
  642. return 0;
  643. case AV_APP_TO_DEV_UNMUTE:
  644. if (s->mute) {
  645. s->mute = 0;
  646. return pulse_set_mute(s);
  647. }
  648. return 0;
  649. case AV_APP_TO_DEV_TOGGLE_MUTE:
  650. s->mute = !s->mute;
  651. return pulse_set_mute(s);
  652. case AV_APP_TO_DEV_SET_VOLUME:
  653. return pulse_set_volume(s, *(double *)data);
  654. case AV_APP_TO_DEV_GET_VOLUME:
  655. s->last_volume = PA_VOLUME_INVALID;
  656. pa_threaded_mainloop_lock(s->mainloop);
  657. ret = pulse_update_sink_input_info(h);
  658. pa_threaded_mainloop_unlock(s->mainloop);
  659. return ret;
  660. case AV_APP_TO_DEV_GET_MUTE:
  661. s->mute = -1;
  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. default:
  667. break;
  668. }
  669. return AVERROR(ENOSYS);
  670. }
  671. #define OFFSET(a) offsetof(PulseData, a)
  672. #define E AV_OPT_FLAG_ENCODING_PARAM
  673. static const AVOption options[] = {
  674. { "server", "set PulseAudio server", OFFSET(server), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  675. { "name", "set application name", OFFSET(name), AV_OPT_TYPE_STRING, {.str = LIBAVFORMAT_IDENT}, 0, 0, E },
  676. { "stream_name", "set stream description", OFFSET(stream_name), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  677. { "device", "set device name", OFFSET(device), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, E },
  678. { "buffer_size", "set buffer size in bytes", OFFSET(buffer_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
  679. { "buffer_duration", "set buffer duration in millisecs", OFFSET(buffer_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
  680. { "prebuf", "set pre-buffering size", OFFSET(prebuf), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
  681. { "minreq", "set minimum request size", OFFSET(minreq), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, E },
  682. { NULL }
  683. };
  684. static const AVClass pulse_muxer_class = {
  685. .class_name = "PulseAudio outdev",
  686. .item_name = av_default_item_name,
  687. .option = options,
  688. .version = LIBAVUTIL_VERSION_INT,
  689. .category = AV_CLASS_CATEGORY_DEVICE_AUDIO_OUTPUT,
  690. };
  691. const FFOutputFormat ff_pulse_muxer = {
  692. .p.name = "pulse",
  693. .p.long_name = NULL_IF_CONFIG_SMALL("Pulse audio output"),
  694. .priv_data_size = sizeof(PulseData),
  695. .p.audio_codec = AV_NE(AV_CODEC_ID_PCM_S16BE, AV_CODEC_ID_PCM_S16LE),
  696. .p.video_codec = AV_CODEC_ID_NONE,
  697. .write_header = pulse_write_header,
  698. .write_packet = pulse_write_packet,
  699. .write_uncoded_frame = pulse_write_frame,
  700. .write_trailer = pulse_write_trailer,
  701. .get_output_timestamp = pulse_get_output_timestamp,
  702. .get_device_list = pulse_get_device_list,
  703. .control_message = pulse_control_message,
  704. #if FF_API_ALLOW_FLUSH
  705. .p.flags = AVFMT_NOFILE | AVFMT_ALLOW_FLUSH,
  706. #else
  707. .p.flags = AVFMT_NOFILE,
  708. #endif
  709. .p.priv_class = &pulse_muxer_class,
  710. .flags_internal = FF_OFMT_FLAG_ALLOW_FLUSH,
  711. };