Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ad_ffmpeg.c 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. /**
  2. Copyright (C) 2011-2013 Robin Gareus <robin@gareus.org>
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU Lesser Public License as published by
  5. the Free Software Foundation; either version 2.1, or (at your option)
  6. any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Lesser Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public
  12. License along with this library; if not, write to the Free Software
  13. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  14. */
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #include <unistd.h>
  19. #include <math.h>
  20. #include "audio_decoder/ad_plugin.h"
  21. #ifdef HAVE_FFMPEG
  22. #include "ffcompat.h"
  23. #ifndef MIN
  24. #define MIN(a,b) ( ( (a) < (b) )? (a) : (b) )
  25. #endif
  26. typedef struct {
  27. AVFormatContext* formatContext;
  28. AVCodecContext* codecContext;
  29. AVCodec* codec;
  30. AVPacket packet;
  31. int audioStream;
  32. int pkt_len;
  33. uint8_t* pkt_ptr;
  34. int16_t m_tmpBuffer[AVCODEC_MAX_AUDIO_FRAME_SIZE];
  35. int16_t* m_tmpBufferStart;
  36. unsigned long m_tmpBufferLen;
  37. int64_t decoder_clock;
  38. int64_t output_clock;
  39. int64_t seek_frame;
  40. unsigned int samplerate;
  41. unsigned int channels;
  42. int64_t length;
  43. } ffmpeg_audio_decoder;
  44. static int ad_info_ffmpeg(void *sf, struct adinfo *nfo) {
  45. ffmpeg_audio_decoder *priv = (ffmpeg_audio_decoder*) sf;
  46. if (!priv) return -1;
  47. if (nfo) {
  48. nfo->sample_rate = priv->samplerate;
  49. nfo->channels = priv->channels;
  50. nfo->frames = priv->length;
  51. if (nfo->sample_rate==0) return -1;
  52. nfo->length = (nfo->frames * 1000) / nfo->sample_rate;
  53. nfo->bit_rate = priv->formatContext->bit_rate;
  54. nfo->bit_depth = 0;
  55. nfo->meta_data = NULL;
  56. #ifdef WITH_GTK // XXX replace g_* functions with POSIX equiv
  57. AVDictionaryEntry *tag = NULL;
  58. // Tags in container
  59. while ((tag = av_dict_get(priv->formatContext->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {
  60. dbg(2, "FTAG: %s=%s", tag->key, tag->value);
  61. char * tmp = g_strdup_printf("%s%s<i>%s</i>:%s", nfo->meta_data?nfo->meta_data:"",nfo->meta_data?"\n":"", tag->key, tag->value);
  62. if (nfo->meta_data) g_free(nfo->meta_data);
  63. nfo->meta_data = tmp;
  64. }
  65. // Tags in stream
  66. tag=NULL;
  67. AVStream *stream = priv->formatContext->streams[priv->audioStream];
  68. while ((tag = av_dict_get(stream->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {
  69. dbg(2, "STAG: %s=%s", tag->key, tag->value);
  70. char * tmp = g_strdup_printf("%s%s<i>%s</i>:%s", nfo->meta_data?nfo->meta_data:"",nfo->meta_data?"\n":"", tag->key, tag->value);
  71. if (nfo->meta_data) g_free(nfo->meta_data);
  72. nfo->meta_data = tmp;
  73. }
  74. #endif
  75. }
  76. return 0;
  77. }
  78. static void *ad_open_ffmpeg(const char *fn, struct adinfo *nfo) {
  79. ffmpeg_audio_decoder *priv = (ffmpeg_audio_decoder*) calloc(1, sizeof(ffmpeg_audio_decoder));
  80. priv->m_tmpBufferStart=NULL;
  81. priv->m_tmpBufferLen=0;
  82. priv->decoder_clock=priv->output_clock=priv->seek_frame=0;
  83. priv->packet.size=0; priv->packet.data=NULL;
  84. if (avformat_open_input(&priv->formatContext, fn, NULL, NULL) <0) {
  85. dbg(0, "ffmpeg is unable to open file '%s'.", fn);
  86. free(priv); return(NULL);
  87. }
  88. if (avformat_find_stream_info(priv->formatContext, NULL) < 0) {
  89. avformat_close_input(&priv->formatContext);
  90. dbg(0, "av_find_stream_info failed" );
  91. free(priv); return(NULL);
  92. }
  93. priv->audioStream = -1;
  94. unsigned int i;
  95. for (i=0; i<priv->formatContext->nb_streams; i++) {
  96. if (priv->formatContext->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  97. priv->audioStream = i;
  98. break;
  99. }
  100. }
  101. if (priv->audioStream == -1) {
  102. dbg(0, "No Audio Stream found in file");
  103. avformat_close_input(&priv->formatContext);
  104. free(priv); return(NULL);
  105. }
  106. priv->codecContext = priv->formatContext->streams[priv->audioStream]->codec;
  107. priv->codec = avcodec_find_decoder(priv->codecContext->codec_id);
  108. if (priv->codec == NULL) {
  109. avformat_close_input(&priv->formatContext);
  110. dbg(0, "Codec not supported by ffmpeg");
  111. free(priv); return(NULL);
  112. }
  113. if (avcodec_open2(priv->codecContext, priv->codec, NULL) < 0) {
  114. dbg(0, "avcodec_open failed" );
  115. free(priv); return(NULL);
  116. }
  117. dbg(2, "ffmpeg - audio tics: %i/%i [sec]",priv->formatContext->streams[priv->audioStream]->time_base.num,priv->formatContext->streams[priv->audioStream]->time_base.den);
  118. int64_t len = priv->formatContext->duration - priv->formatContext->start_time;
  119. priv->formatContext->flags|=AVFMT_FLAG_GENPTS;
  120. priv->formatContext->flags|=AVFMT_FLAG_IGNIDX;
  121. priv->samplerate = priv->codecContext->sample_rate;
  122. priv->channels = priv->codecContext->channels ;
  123. priv->length = (int64_t)( len * priv->samplerate / AV_TIME_BASE );
  124. if (ad_info_ffmpeg((void*)priv, nfo)) {
  125. dbg(0, "invalid file info (sample-rate==0)");
  126. free(priv); return(NULL);
  127. }
  128. dbg(1, "ffmpeg - %s", fn);
  129. if (nfo)
  130. dbg(1, "ffmpeg - sr:%i c:%i d:%"PRIi64" f:%"PRIi64, nfo->sample_rate, nfo->channels, nfo->length, nfo->frames);
  131. return (void*) priv;
  132. }
  133. static int ad_close_ffmpeg(void *sf) {
  134. ffmpeg_audio_decoder *priv = (ffmpeg_audio_decoder*) sf;
  135. if (!priv) return -1;
  136. avcodec_close(priv->codecContext);
  137. avformat_close_input(&priv->formatContext);
  138. free(priv);
  139. return 0;
  140. }
  141. static void int16_to_float(int16_t *in, float *out, int num_channels, int num_samples, int out_offset) {
  142. int i,ii;
  143. for (i=0;i<num_samples;i++) {
  144. for (ii=0;ii<num_channels;ii++) {
  145. out[(i+out_offset)*num_channels+ii]= (float) in[i*num_channels+ii]/ 32768.0;
  146. }
  147. }
  148. }
  149. static ssize_t ad_read_ffmpeg(void *sf, float* d, size_t len) {
  150. ffmpeg_audio_decoder *priv = (ffmpeg_audio_decoder*) sf;
  151. if (!priv) return -1;
  152. size_t frames = len / priv->channels;
  153. size_t written = 0;
  154. ssize_t ret = 0;
  155. while (ret >= 0 && written < frames) {
  156. dbg(3,"loop: %i/%i (bl:%lu)",written, frames, priv->m_tmpBufferLen );
  157. if (priv->seek_frame == 0 && priv->m_tmpBufferLen > 0 ) {
  158. int s = MIN(priv->m_tmpBufferLen / priv->channels, frames - written );
  159. int16_to_float(priv->m_tmpBufferStart, d, priv->channels, s , written);
  160. written += s;
  161. priv->output_clock+=s;
  162. s = s * priv->channels;
  163. priv->m_tmpBufferStart += s;
  164. priv->m_tmpBufferLen -= s;
  165. ret = 0;
  166. } else {
  167. priv->m_tmpBufferStart = priv->m_tmpBuffer;
  168. priv->m_tmpBufferLen = 0;
  169. if (!priv->pkt_ptr || priv->pkt_len <1 ) {
  170. if (priv->packet.data) av_free_packet(&priv->packet);
  171. ret = av_read_frame(priv->formatContext, &priv->packet);
  172. if (ret<0) { dbg(1, "reached end of file."); break; }
  173. priv->pkt_len = priv->packet.size;
  174. priv->pkt_ptr = priv->packet.data;
  175. }
  176. if (priv->packet.stream_index != priv->audioStream) {
  177. priv->pkt_ptr = NULL;
  178. continue;
  179. }
  180. /* decode all chunks in packet */
  181. int data_size= AVCODEC_MAX_AUDIO_FRAME_SIZE;
  182. #if 0 // TODO ffcompat.h -- this works but is not optimal (channels may not be planar/interleaved)
  183. AVFrame avf; // TODO statically allocate
  184. memset(&avf, 0, sizeof(AVFrame)); // not sure if that is needed
  185. int got_frame = 0;
  186. ret = avcodec_decode_audio4(priv->codecContext, &avf, &got_frame, &priv->packet);
  187. data_size = avf.linesize[0];
  188. memcpy(priv->m_tmpBuffer, avf.data[0], avf.linesize[0] * sizeof(uint8_t));
  189. #else // this was deprecated in LIBAVCODEC_VERSION_MAJOR 53
  190. ret = avcodec_decode_audio3(priv->codecContext,
  191. priv->m_tmpBuffer, &data_size, &priv->packet);
  192. #endif
  193. if (ret < 0 || ret > priv->pkt_len) {
  194. #if 0
  195. dbg(0, "audio decode error");
  196. return -1;
  197. #endif
  198. priv->pkt_len=0;
  199. ret=0;
  200. continue;
  201. }
  202. priv->pkt_len -= ret; priv->pkt_ptr += ret;
  203. /* sample exact alignment */
  204. if (priv->packet.pts != AV_NOPTS_VALUE) {
  205. priv->decoder_clock = priv->samplerate * av_q2d(priv->formatContext->streams[priv->audioStream]->time_base) * priv->packet.pts;
  206. } else {
  207. dbg(0, "!!! NO PTS timestamp in file");
  208. priv->decoder_clock += (data_size>>1) / priv->channels;
  209. }
  210. if (data_size>0) {
  211. priv->m_tmpBufferLen+= (data_size>>1); // 2 bytes per sample
  212. }
  213. /* align buffer after seek. */
  214. if (priv->seek_frame > 0) {
  215. const int diff = priv->output_clock-priv->decoder_clock;
  216. if (diff<0) {
  217. /* seek ended up past the wanted sample */
  218. dbg(0, " !!! Audio seek failed.");
  219. return -1;
  220. } else if (priv->m_tmpBufferLen < (diff*priv->channels)) {
  221. /* wanted sample not in current buffer - keep going */
  222. dbg(2, " !!! seeked sample was not in decoded buffer. frames-to-go: %li", diff);
  223. priv->m_tmpBufferLen = 0;
  224. } else if (diff!=0 && data_size > 0) {
  225. /* wanted sample is in current buffer but not at the beginnning */
  226. dbg(2, " !!! sync buffer to seek. (diff:%i)", diff);
  227. priv->m_tmpBufferStart+= diff*priv->codecContext->channels;
  228. priv->m_tmpBufferLen -= diff*priv->codecContext->channels;
  229. #if 1
  230. memmove(priv->m_tmpBuffer, priv->m_tmpBufferStart, priv->m_tmpBufferLen);
  231. priv->m_tmpBufferStart = priv->m_tmpBuffer;
  232. #endif
  233. priv->seek_frame=0;
  234. priv->decoder_clock += diff;
  235. } else if (data_size > 0) {
  236. dbg(2, "Audio exact sync-seek (%"PRIi64" == %"PRIi64")", priv->decoder_clock, priv->seek_frame);
  237. priv->seek_frame=0;
  238. } else {
  239. dbg(0, "Error: no audio data in packet");
  240. }
  241. }
  242. //dbg(0, "PTS: decoder:%"PRIi64". - want: %"PRIi64, priv->decoder_clock, priv->output_clock);
  243. //dbg(0, "CLK: frame: %"PRIi64" T:%.3fs",priv->decoder_clock, (float) priv->decoder_clock/priv->samplerate);
  244. }
  245. }
  246. if (written!=frames) {
  247. dbg(2, "short-read");
  248. }
  249. return written * priv->channels;
  250. }
  251. static int64_t ad_seek_ffmpeg(void *sf, int64_t pos) {
  252. ffmpeg_audio_decoder *priv = (ffmpeg_audio_decoder*) sf;
  253. if (!sf) return -1;
  254. if (pos == priv->output_clock) return pos;
  255. /* flush internal buffer */
  256. priv->m_tmpBufferLen = 0;
  257. priv->seek_frame = pos;
  258. priv->output_clock = pos;
  259. priv->pkt_len = 0; priv->pkt_ptr = NULL;
  260. priv->decoder_clock = 0;
  261. #if 0
  262. /* TODO seek at least 1 packet before target.
  263. * for mpeg compressed files, the
  264. * output may depend on past frames! */
  265. if (pos > 8192) pos -= 8192;
  266. else pos = 0;
  267. #endif
  268. const int64_t timestamp = pos / av_q2d(priv->formatContext->streams[priv->audioStream]->time_base) / priv->samplerate;
  269. dbg(2, "seek frame:%"PRIi64" - idx:%"PRIi64, pos, timestamp);
  270. av_seek_frame(priv->formatContext, priv->audioStream, timestamp, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
  271. avcodec_flush_buffers(priv->codecContext);
  272. return pos;
  273. }
  274. static int ad_eval_ffmpeg(const char *f) {
  275. char *ext = strrchr(f, '.');
  276. if (!ext) return 10;
  277. // libavformat.. guess_format..
  278. return 40;
  279. }
  280. #endif
  281. static const ad_plugin ad_ffmpeg = {
  282. #ifdef HAVE_FFMPEG
  283. &ad_eval_ffmpeg,
  284. &ad_open_ffmpeg,
  285. &ad_close_ffmpeg,
  286. &ad_info_ffmpeg,
  287. &ad_seek_ffmpeg,
  288. &ad_read_ffmpeg
  289. #else
  290. &ad_eval_null,
  291. &ad_open_null,
  292. &ad_close_null,
  293. &ad_info_null,
  294. &ad_seek_null,
  295. &ad_read_null
  296. #endif
  297. };
  298. /* dlopen handler */
  299. const ad_plugin * adp_get_ffmpeg() {
  300. #ifdef HAVE_FFMPEG
  301. static int ffinit = 0;
  302. if (!ffinit) {
  303. ffinit=1;
  304. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(53, 5, 0)
  305. avcodec_init();
  306. #endif
  307. av_register_all();
  308. avcodec_register_all();
  309. if(ad_debug_level <= 1)
  310. av_log_set_level(AV_LOG_QUIET);
  311. else
  312. av_log_set_level(AV_LOG_VERBOSE);
  313. }
  314. #endif
  315. return &ad_ffmpeg;
  316. }