/src/player.c

http://github.com/PromyLOPh/pianobar · C · 604 lines · 436 code · 75 blank · 93 comment · 99 complexity · 2a3dc10d6da92db26593fb0b43a1344c MD5 · raw file

  1. /*
  2. Copyright (c) 2008-2018
  3. Lars-Dominik Braun <lars@6xq.net>
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. */
  20. /* receive/play audio stream.
  21. *
  22. * There are two threads involved here:
  23. * BarPlayerThread
  24. * Sets up the stream and fetches the data into a ffmpeg buffersrc
  25. * BarAoPlayThread
  26. * Reads data from the filter chain’s sink and hands it over to libao for
  27. * playback.
  28. *
  29. */
  30. #include "config.h"
  31. #include <unistd.h>
  32. #include <string.h>
  33. #include <math.h>
  34. #include <stdint.h>
  35. #include <fcntl.h>
  36. #include <limits.h>
  37. #include <assert.h>
  38. #include <arpa/inet.h>
  39. #include <sys/stat.h>
  40. #include <libavcodec/avcodec.h>
  41. #include <libavutil/avutil.h>
  42. #include <libavfilter/avfilter.h>
  43. #include <libavfilter/buffersink.h>
  44. #include <libavfilter/buffersrc.h>
  45. #ifdef HAVE_LIBAVFILTER_AVCODEC_H
  46. /* required by ffmpeg1.2 for avfilter_copy_buf_props */
  47. #include <libavfilter/avcodec.h>
  48. #endif
  49. #include <libavutil/channel_layout.h>
  50. #include <libavutil/opt.h>
  51. #include <libavutil/frame.h>
  52. #include "player.h"
  53. #include "ui.h"
  54. #include "ui_types.h"
  55. /* default sample format */
  56. const enum AVSampleFormat avformat = AV_SAMPLE_FMT_S16;
  57. static void printError (const BarSettings_t * const settings,
  58. const char * const msg, int ret) {
  59. char avmsg[128];
  60. av_strerror (ret, avmsg, sizeof (avmsg));
  61. BarUiMsg (settings, MSG_ERR, "%s (%s)\n", msg, avmsg);
  62. }
  63. /* global initialization
  64. */
  65. void BarPlayerInit (player_t * const p, const BarSettings_t * const settings) {
  66. ao_initialize ();
  67. av_log_set_level (AV_LOG_FATAL);
  68. #ifdef HAVE_AV_REGISTER_ALL
  69. av_register_all ();
  70. #endif
  71. #ifdef HAVE_AVFILTER_REGISTER_ALL
  72. avfilter_register_all ();
  73. #endif
  74. #ifdef HAVE_AVFORMAT_NETWORK_INIT
  75. avformat_network_init ();
  76. #endif
  77. pthread_mutex_init (&p->lock, NULL);
  78. pthread_cond_init (&p->cond, NULL);
  79. pthread_mutex_init (&p->aoplayLock, NULL);
  80. pthread_cond_init (&p->aoplayCond, NULL);
  81. BarPlayerReset (p);
  82. p->settings = settings;
  83. }
  84. void BarPlayerDestroy (player_t * const p) {
  85. pthread_cond_destroy (&p->cond);
  86. pthread_mutex_destroy (&p->lock);
  87. pthread_cond_destroy (&p->aoplayCond);
  88. pthread_mutex_destroy (&p->aoplayLock);
  89. #ifdef HAVE_AVFORMAT_NETWORK_INIT
  90. avformat_network_deinit ();
  91. #endif
  92. ao_shutdown ();
  93. }
  94. void BarPlayerReset (player_t * const p) {
  95. p->doQuit = false;
  96. p->doPause = false;
  97. p->songDuration = 0;
  98. p->songPlayed = 0;
  99. p->mode = PLAYER_DEAD;
  100. p->fvolume = NULL;
  101. p->fgraph = NULL;
  102. p->fctx = NULL;
  103. p->st = NULL;
  104. p->cctx = NULL;
  105. p->fbufsink = NULL;
  106. p->fabuf = NULL;
  107. p->streamIdx = -1;
  108. p->lastTimestamp = 0;
  109. p->interrupted = 0;
  110. p->aoDev = NULL;
  111. }
  112. /* Update volume filter
  113. */
  114. void BarPlayerSetVolume (player_t * const player) {
  115. assert (player != NULL);
  116. if (player->mode != PLAYER_PLAYING) {
  117. return;
  118. }
  119. int ret;
  120. #ifdef HAVE_AVFILTER_GRAPH_SEND_COMMAND
  121. /* ffmpeg and libav disagree on the type of this option (string vs. double)
  122. * -> print to string and let them parse it again */
  123. char strbuf[16];
  124. snprintf (strbuf, sizeof (strbuf), "%fdB",
  125. player->settings->volume + (player->gain * player->settings->gainMul));
  126. assert (player->fgraph != NULL);
  127. if ((ret = avfilter_graph_send_command (player->fgraph, "volume", "volume",
  128. strbuf, NULL, 0, 0)) < 0) {
  129. #else
  130. /* convert from decibel */
  131. const double volume = pow (10, (player->settings->volume + (player->gain * player->settings->gainMul)) / 20);
  132. /* libav does not provide other means to set this right now. it might not
  133. * even work everywhere. */
  134. assert (player->fvolume != NULL);
  135. if ((ret = av_opt_set_double (player->fvolume->priv, "volume", volume,
  136. 0)) != 0) {
  137. #endif
  138. printError (player->settings, "Cannot set volume", ret);
  139. }
  140. }
  141. #define softfail(msg) \
  142. printError (player->settings, msg, ret); \
  143. return false;
  144. /* ffmpeg callback for blocking functions, returns 1 to abort function
  145. */
  146. static int intCb (void * const data) {
  147. player_t * const player = data;
  148. assert (player != NULL);
  149. if (player->interrupted > 1) {
  150. /* got a sigint multiple times, quit pianobar (handled by main.c). */
  151. pthread_mutex_lock (&player->lock);
  152. player->doQuit = true;
  153. pthread_mutex_unlock (&player->lock);
  154. return 1;
  155. } else if (player->interrupted != 0) {
  156. /* the request is retried with the same player context */
  157. player->interrupted = 0;
  158. return 1;
  159. } else {
  160. return 0;
  161. }
  162. }
  163. static bool openStream (player_t * const player) {
  164. assert (player != NULL);
  165. /* no leak? */
  166. assert (player->fctx == NULL);
  167. int ret;
  168. /* stream setup */
  169. player->fctx = avformat_alloc_context ();
  170. player->fctx->interrupt_callback.callback = intCb;
  171. player->fctx->interrupt_callback.opaque = player;
  172. /* in microseconds */
  173. unsigned long int timeout = player->settings->timeout*1000000;
  174. char timeoutStr[16];
  175. ret = snprintf (timeoutStr, sizeof (timeoutStr), "%lu", timeout);
  176. assert (ret < sizeof (timeoutStr));
  177. AVDictionary *options = NULL;
  178. av_dict_set (&options, "timeout", timeoutStr, 0);
  179. assert (player->url != NULL);
  180. if ((ret = avformat_open_input (&player->fctx, player->url, NULL, &options)) < 0) {
  181. softfail ("Unable to open audio file");
  182. }
  183. if ((ret = avformat_find_stream_info (player->fctx, NULL)) < 0) {
  184. softfail ("find_stream_info");
  185. }
  186. /* ignore all streams, undone for audio stream below */
  187. for (size_t i = 0; i < player->fctx->nb_streams; i++) {
  188. player->fctx->streams[i]->discard = AVDISCARD_ALL;
  189. }
  190. player->streamIdx = av_find_best_stream (player->fctx, AVMEDIA_TYPE_AUDIO,
  191. -1, -1, NULL, 0);
  192. if (player->streamIdx < 0) {
  193. softfail ("find_best_stream");
  194. }
  195. player->st = player->fctx->streams[player->streamIdx];
  196. player->st->discard = AVDISCARD_DEFAULT;
  197. /* decoder setup */
  198. if ((player->cctx = avcodec_alloc_context3 (NULL)) == NULL) {
  199. softfail ("avcodec_alloc_context3");
  200. }
  201. const AVCodecParameters * const cp = player->st->codecpar;
  202. if ((ret = avcodec_parameters_to_context (player->cctx, cp)) < 0) {
  203. softfail ("avcodec_parameters_to_context");
  204. }
  205. AVCodec * const decoder = avcodec_find_decoder (cp->codec_id);
  206. if (decoder == NULL) {
  207. softfail ("find_decoder");
  208. }
  209. if ((ret = avcodec_open2 (player->cctx, decoder, NULL)) < 0) {
  210. softfail ("codec_open2");
  211. }
  212. if (player->lastTimestamp > 0) {
  213. av_seek_frame (player->fctx, player->streamIdx, player->lastTimestamp, 0);
  214. }
  215. const unsigned int songDuration = av_q2d (player->st->time_base) *
  216. (double) player->st->duration;
  217. pthread_mutex_lock (&player->lock);
  218. player->songPlayed = 0;
  219. player->songDuration = songDuration;
  220. pthread_mutex_unlock (&player->lock);
  221. return true;
  222. }
  223. /* Get output sample rate. Default to stream sample rate
  224. */
  225. static int getSampleRate (const player_t * const player) {
  226. AVCodecParameters const * const cp = player->st->codecpar;
  227. return player->settings->sampleRate == 0 ?
  228. cp->sample_rate :
  229. player->settings->sampleRate;
  230. }
  231. /* setup filter chain
  232. */
  233. static bool openFilter (player_t * const player) {
  234. /* filter setup */
  235. char strbuf[256];
  236. int ret = 0;
  237. AVCodecParameters * const cp = player->st->codecpar;
  238. if ((player->fgraph = avfilter_graph_alloc ()) == NULL) {
  239. softfail ("graph_alloc");
  240. }
  241. /* abuffer */
  242. AVRational time_base = player->st->time_base;
  243. snprintf (strbuf, sizeof (strbuf),
  244. "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%"PRIx64,
  245. time_base.num, time_base.den, cp->sample_rate,
  246. av_get_sample_fmt_name (player->cctx->sample_fmt),
  247. cp->channel_layout);
  248. if ((ret = avfilter_graph_create_filter (&player->fabuf,
  249. avfilter_get_by_name ("abuffer"), "source", strbuf, NULL,
  250. player->fgraph)) < 0) {
  251. softfail ("create_filter abuffer");
  252. }
  253. /* volume */
  254. if ((ret = avfilter_graph_create_filter (&player->fvolume,
  255. avfilter_get_by_name ("volume"), "volume", "0dB", NULL,
  256. player->fgraph)) < 0) {
  257. softfail ("create_filter volume");
  258. }
  259. /* aformat: convert float samples into something more usable */
  260. AVFilterContext *fafmt = NULL;
  261. snprintf (strbuf, sizeof (strbuf), "sample_fmts=%s:sample_rates=%d",
  262. av_get_sample_fmt_name (avformat), getSampleRate (player));
  263. if ((ret = avfilter_graph_create_filter (&fafmt,
  264. avfilter_get_by_name ("aformat"), "format", strbuf, NULL,
  265. player->fgraph)) < 0) {
  266. softfail ("create_filter aformat");
  267. }
  268. /* abuffersink */
  269. if ((ret = avfilter_graph_create_filter (&player->fbufsink,
  270. avfilter_get_by_name ("abuffersink"), "sink", NULL, NULL,
  271. player->fgraph)) < 0) {
  272. softfail ("create_filter abuffersink");
  273. }
  274. /* connect filter: abuffer -> volume -> aformat -> abuffersink */
  275. if (avfilter_link (player->fabuf, 0, player->fvolume, 0) != 0 ||
  276. avfilter_link (player->fvolume, 0, fafmt, 0) != 0 ||
  277. avfilter_link (fafmt, 0, player->fbufsink, 0) != 0) {
  278. softfail ("filter_link");
  279. }
  280. if ((ret = avfilter_graph_config (player->fgraph, NULL)) < 0) {
  281. softfail ("graph_config");
  282. }
  283. return true;
  284. }
  285. /* setup libao
  286. */
  287. static bool openDevice (player_t * const player) {
  288. const AVCodecParameters * const cp = player->st->codecpar;
  289. ao_sample_format aoFmt;
  290. memset (&aoFmt, 0, sizeof (aoFmt));
  291. aoFmt.bits = av_get_bytes_per_sample (avformat) * 8;
  292. assert (aoFmt.bits > 0);
  293. aoFmt.channels = cp->channels;
  294. aoFmt.rate = getSampleRate (player);
  295. aoFmt.byte_format = AO_FMT_NATIVE;
  296. int driver = -1;
  297. if (player->settings->audioPipe) {
  298. // using audio pipe
  299. struct stat st;
  300. if (stat (player->settings->audioPipe, &st)) {
  301. BarUiMsg (player->settings, MSG_ERR, "Cannot stat audio pipe file.\n");
  302. return false;
  303. }
  304. if (!S_ISFIFO (st.st_mode)) {
  305. BarUiMsg (player->settings, MSG_ERR, "File is not a pipe, error.\n");
  306. return false;
  307. }
  308. driver = ao_driver_id ("raw");
  309. if ((player->aoDev = ao_open_file(driver, player->settings->audioPipe, 1, &aoFmt, NULL)) == NULL) {
  310. BarUiMsg (player->settings, MSG_ERR, "Cannot open audio pipe file.\n");
  311. return false;
  312. }
  313. } else {
  314. // use driver from libao configuration
  315. driver = ao_default_driver_id ();
  316. if ((player->aoDev = ao_open_live (driver, &aoFmt, NULL)) == NULL) {
  317. BarUiMsg (player->settings, MSG_ERR, "Cannot open audio device.\n");
  318. return false;
  319. }
  320. }
  321. return true;
  322. }
  323. /* Operating on shared variables and must be protected by mutex
  324. */
  325. static bool shouldQuit (player_t * const player) {
  326. pthread_mutex_lock (&player->lock);
  327. const bool ret = player->doQuit;
  328. pthread_mutex_unlock (&player->lock);
  329. return ret;
  330. }
  331. static void changeMode (player_t * const player, unsigned int mode) {
  332. pthread_mutex_lock (&player->lock);
  333. player->mode = mode;
  334. pthread_mutex_unlock (&player->lock);
  335. }
  336. BarPlayerMode BarPlayerGetMode (player_t * const player) {
  337. pthread_mutex_lock (&player->lock);
  338. const BarPlayerMode ret = player->mode;
  339. pthread_mutex_unlock (&player->lock);
  340. return ret;
  341. }
  342. /* decode and play stream. returns 0 or av error code.
  343. */
  344. static int play (player_t * const player) {
  345. assert (player != NULL);
  346. const int64_t minBufferHealth = player->settings->bufferSecs;
  347. AVPacket pkt;
  348. AVCodecContext * const cctx = player->cctx;
  349. av_init_packet (&pkt);
  350. pkt.data = NULL;
  351. pkt.size = 0;
  352. AVFrame *frame = NULL;
  353. frame = av_frame_alloc ();
  354. assert (frame != NULL);
  355. pthread_t aoplaythread;
  356. pthread_create (&aoplaythread, NULL, BarAoPlayThread, player);
  357. enum { FILL, DRAIN, DONE } drainMode = FILL;
  358. int ret = 0;
  359. const double timeBase = av_q2d (player->st->time_base);
  360. while (!shouldQuit (player) && drainMode != DONE) {
  361. if (drainMode == FILL) {
  362. ret = av_read_frame (player->fctx, &pkt);
  363. if (ret == AVERROR_EOF) {
  364. /* enter drain mode */
  365. drainMode = DRAIN;
  366. avcodec_send_packet (cctx, NULL);
  367. } else if (pkt.stream_index != player->streamIdx) {
  368. /* unused packet */
  369. av_packet_unref (&pkt);
  370. continue;
  371. } else if (ret < 0) {
  372. /* error, abort */
  373. /* mark the EOF, so that BarAoPlayThread can quit*/
  374. pthread_mutex_lock (&player->aoplayLock);
  375. const int rt = av_buffersrc_add_frame (player->fabuf, NULL);
  376. assert (rt == 0);
  377. pthread_cond_broadcast (&player->aoplayCond);
  378. pthread_mutex_unlock (&player->aoplayLock);
  379. break;
  380. } else {
  381. /* fill buffer */
  382. avcodec_send_packet (cctx, &pkt);
  383. }
  384. }
  385. while (!shouldQuit (player)) {
  386. ret = avcodec_receive_frame (cctx, frame);
  387. if (ret == AVERROR_EOF) {
  388. /* done draining */
  389. drainMode = DONE;
  390. /* mark the EOF*/
  391. pthread_mutex_lock (&player->aoplayLock);
  392. const int rt = av_buffersrc_add_frame (player->fabuf, NULL);
  393. assert (rt == 0);
  394. pthread_cond_broadcast (&player->aoplayCond);
  395. pthread_mutex_unlock (&player->aoplayLock);
  396. break;
  397. } else if (ret != 0) {
  398. /* no more output */
  399. break;
  400. }
  401. /* XXX: suppresses warning from resample filter */
  402. if (frame->pts == (int64_t) AV_NOPTS_VALUE) {
  403. frame->pts = 0;
  404. }
  405. pthread_mutex_lock (&player->aoplayLock);
  406. ret = av_buffersrc_write_frame (player->fabuf, frame);
  407. assert (ret >= 0);
  408. pthread_mutex_unlock (&player->aoplayLock);
  409. int64_t bufferHealth = 0;
  410. do {
  411. pthread_mutex_lock (&player->aoplayLock);
  412. bufferHealth = timeBase * (double) (frame->pts - player->lastTimestamp);
  413. if (bufferHealth > minBufferHealth) {
  414. /* Buffer get healthy, resume */
  415. pthread_cond_broadcast (&player->aoplayCond);
  416. /* Buffer is healthy enough, wait */
  417. pthread_cond_wait (&player->aoplayCond, &player->aoplayLock);
  418. }
  419. pthread_mutex_unlock (&player->aoplayLock);
  420. } while (bufferHealth > minBufferHealth);
  421. }
  422. av_packet_unref (&pkt);
  423. }
  424. av_frame_free (&frame);
  425. pthread_join (aoplaythread, NULL);
  426. return ret;
  427. }
  428. static void finish (player_t * const player) {
  429. ao_close (player->aoDev);
  430. player->aoDev = NULL;
  431. if (player->fgraph != NULL) {
  432. avfilter_graph_free (&player->fgraph);
  433. player->fgraph = NULL;
  434. }
  435. if (player->cctx != NULL) {
  436. avcodec_close (player->cctx);
  437. player->cctx = NULL;
  438. }
  439. if (player->fctx != NULL) {
  440. avformat_close_input (&player->fctx);
  441. }
  442. }
  443. /* player thread; for every song a new thread is started
  444. * @param audioPlayer structure
  445. * @return PLAYER_RET_*
  446. */
  447. void *BarPlayerThread (void *data) {
  448. assert (data != NULL);
  449. player_t * const player = data;
  450. uintptr_t pret = PLAYER_RET_OK;
  451. bool retry;
  452. do {
  453. retry = false;
  454. if (openStream (player)) {
  455. if (openFilter (player) && openDevice (player)) {
  456. changeMode (player, PLAYER_PLAYING);
  457. BarPlayerSetVolume (player);
  458. retry = play (player) == AVERROR_INVALIDDATA &&
  459. !player->interrupted;
  460. } else {
  461. /* filter missing or audio device busy */
  462. pret = PLAYER_RET_HARDFAIL;
  463. }
  464. } else {
  465. /* stream not found */
  466. pret = PLAYER_RET_SOFTFAIL;
  467. }
  468. changeMode (player, PLAYER_WAITING);
  469. finish (player);
  470. } while (retry);
  471. changeMode (player, PLAYER_FINISHED);
  472. return (void *) pret;
  473. }
  474. void *BarAoPlayThread (void *data) {
  475. assert (data != NULL);
  476. player_t * const player = data;
  477. AVFrame *filteredFrame = NULL;
  478. filteredFrame = av_frame_alloc ();
  479. assert (filteredFrame != NULL);
  480. int ret;
  481. const double timeBase = av_q2d (av_buffersink_get_time_base (player->fbufsink)),
  482. timeBaseSt = av_q2d (player->st->time_base);
  483. while (!shouldQuit(player)) {
  484. pthread_mutex_lock (&player->aoplayLock);
  485. ret = av_buffersink_get_frame (player->fbufsink, filteredFrame);
  486. if (ret == AVERROR_EOF || shouldQuit (player)) {
  487. /* we are done here */
  488. pthread_mutex_unlock (&player->aoplayLock);
  489. break;
  490. } else if (ret < 0) {
  491. /* wait for more frames */
  492. pthread_cond_broadcast (&player->aoplayCond);
  493. pthread_cond_wait (&player->aoplayCond, &player->aoplayLock);
  494. pthread_mutex_unlock (&player->aoplayLock);
  495. continue;
  496. }
  497. pthread_mutex_unlock (&player->aoplayLock);
  498. const int numChannels = av_get_channel_layout_nb_channels (
  499. filteredFrame->channel_layout);
  500. const int bps = av_get_bytes_per_sample (filteredFrame->format);
  501. ao_play (player->aoDev, (char *) filteredFrame->data[0],
  502. filteredFrame->nb_samples * numChannels * bps);
  503. const double timestamp = (double) filteredFrame->pts * timeBase;
  504. const unsigned int songPlayed = timestamp;
  505. pthread_mutex_lock (&player->lock);
  506. player->songPlayed = songPlayed;
  507. /* pausing */
  508. if (player->doPause) {
  509. do {
  510. pthread_cond_wait (&player->cond, &player->lock);
  511. } while (player->doPause);
  512. }
  513. pthread_mutex_unlock (&player->lock);
  514. /* lastTimestamp must be the last pts, but expressed in terms of
  515. * st->time_base, not the sink’s time_base. */
  516. const int64_t lastTimestamp = timestamp/timeBaseSt;
  517. /* notify download thread, we might need more data */
  518. pthread_mutex_lock (&player->aoplayLock);
  519. player->lastTimestamp = lastTimestamp;
  520. pthread_cond_broadcast (&player->aoplayCond);
  521. pthread_mutex_unlock (&player->aoplayLock);
  522. av_frame_unref (filteredFrame);
  523. }
  524. av_frame_free (&filteredFrame);
  525. return (void *) 0;
  526. }