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 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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 "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 LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(54, 0, 0)
  183. // TODO use av_frame_alloc() and av_frame_free() with newer ffmpeg
  184. AVFrame avf;
  185. memset(&avf, 0, sizeof(AVFrame));
  186. int got_frame = 0;
  187. ret = avcodec_decode_audio4(priv->codecContext, &avf, &got_frame, &priv->packet);
  188. if (ret >= 0 && got_frame) {
  189. int ch, plane_size;
  190. const int planar = av_sample_fmt_is_planar(priv->codecContext->sample_fmt);
  191. data_size = av_samples_get_buffer_size(&plane_size, priv->codecContext->channels, avf.nb_samples, priv->codecContext->sample_fmt, 1);
  192. if (data_size <= AVCODEC_MAX_AUDIO_FRAME_SIZE) {
  193. memcpy(priv->m_tmpBuffer, avf.extended_data[0], plane_size);
  194. if (planar && priv->codecContext->channels > 1) {
  195. uint8_t *out = ((uint8_t *)priv->m_tmpBuffer) + plane_size;
  196. for (ch = 1; ch < priv->codecContext->channels; ch++) {
  197. memcpy(out, avf.extended_data[ch], plane_size);
  198. out += plane_size;
  199. }
  200. }
  201. }
  202. } else {
  203. ret = -1;
  204. }
  205. #elif LIBAVUTIL_VERSION_INT > AV_VERSION_INT(49, 15, 0) && LIBAVCODEC_VERSION_INT > AV_VERSION_INT(52, 20, 1) // ??
  206. // this was deprecated in LIBAVCODEC_VERSION_MAJOR 53
  207. ret = avcodec_decode_audio3(priv->codecContext,
  208. priv->m_tmpBuffer, &data_size, &priv->packet);
  209. #else
  210. int len = priv->packet.size;
  211. uint8_t *ptr = priv->packet.data;
  212. ret = avcodec_decode_audio2(priv->codecContext,
  213. priv->m_tmpBuffer, &data_size, ptr, len);
  214. #endif
  215. if (ret < 0 || ret > priv->pkt_len) {
  216. #if 0
  217. dbg(0, "audio decode error");
  218. return -1;
  219. #endif
  220. priv->pkt_len=0;
  221. ret=0;
  222. continue;
  223. }
  224. priv->pkt_len -= ret; priv->pkt_ptr += ret;
  225. /* sample exact alignment */
  226. if (priv->packet.pts != AV_NOPTS_VALUE) {
  227. priv->decoder_clock = priv->samplerate * av_q2d(priv->formatContext->streams[priv->audioStream]->time_base) * priv->packet.pts;
  228. } else {
  229. dbg(0, "!!! NO PTS timestamp in file");
  230. priv->decoder_clock += (data_size>>1) / priv->channels;
  231. }
  232. if (data_size>0) {
  233. priv->m_tmpBufferLen+= (data_size>>1); // 2 bytes per sample
  234. }
  235. /* align buffer after seek. */
  236. if (priv->seek_frame > 0) {
  237. const int diff = priv->output_clock-priv->decoder_clock;
  238. if (diff<0) {
  239. /* seek ended up past the wanted sample */
  240. dbg(0, " !!! Audio seek failed.");
  241. return -1;
  242. } else if (priv->m_tmpBufferLen < (diff*priv->channels)) {
  243. /* wanted sample not in current buffer - keep going */
  244. dbg(2, " !!! seeked sample was not in decoded buffer. frames-to-go: %li", diff);
  245. priv->m_tmpBufferLen = 0;
  246. } else if (diff!=0 && data_size > 0) {
  247. /* wanted sample is in current buffer but not at the beginnning */
  248. dbg(2, " !!! sync buffer to seek. (diff:%i)", diff);
  249. priv->m_tmpBufferStart+= diff*priv->codecContext->channels;
  250. priv->m_tmpBufferLen -= diff*priv->codecContext->channels;
  251. #if 1
  252. memmove(priv->m_tmpBuffer, priv->m_tmpBufferStart, priv->m_tmpBufferLen);
  253. priv->m_tmpBufferStart = priv->m_tmpBuffer;
  254. #endif
  255. priv->seek_frame=0;
  256. priv->decoder_clock += diff;
  257. } else if (data_size > 0) {
  258. dbg(2, "Audio exact sync-seek (%"PRIi64" == %"PRIi64")", priv->decoder_clock, priv->seek_frame);
  259. priv->seek_frame=0;
  260. } else {
  261. dbg(0, "Error: no audio data in packet");
  262. }
  263. }
  264. //dbg(0, "PTS: decoder:%"PRIi64". - want: %"PRIi64, priv->decoder_clock, priv->output_clock);
  265. //dbg(0, "CLK: frame: %"PRIi64" T:%.3fs",priv->decoder_clock, (float) priv->decoder_clock/priv->samplerate);
  266. }
  267. }
  268. if (written!=frames) {
  269. dbg(2, "short-read");
  270. }
  271. return written * priv->channels;
  272. }
  273. static int64_t ad_seek_ffmpeg(void *sf, int64_t pos) {
  274. ffmpeg_audio_decoder *priv = (ffmpeg_audio_decoder*) sf;
  275. if (!sf) return -1;
  276. if (pos == priv->output_clock) return pos;
  277. /* flush internal buffer */
  278. priv->m_tmpBufferLen = 0;
  279. priv->seek_frame = pos;
  280. priv->output_clock = pos;
  281. priv->pkt_len = 0; priv->pkt_ptr = NULL;
  282. priv->decoder_clock = 0;
  283. #if 0
  284. /* TODO seek at least 1 packet before target.
  285. * for mpeg compressed files, the
  286. * output may depend on past frames! */
  287. if (pos > 8192) pos -= 8192;
  288. else pos = 0;
  289. #endif
  290. const int64_t timestamp = pos / av_q2d(priv->formatContext->streams[priv->audioStream]->time_base) / priv->samplerate;
  291. dbg(2, "seek frame:%"PRIi64" - idx:%"PRIi64, pos, timestamp);
  292. av_seek_frame(priv->formatContext, priv->audioStream, timestamp, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
  293. avcodec_flush_buffers(priv->codecContext);
  294. return pos;
  295. }
  296. static int ad_eval_ffmpeg(const char *f) {
  297. char *ext = strrchr(f, '.');
  298. if (!ext) return 10;
  299. // libavformat.. guess_format..
  300. return 40;
  301. }
  302. #endif
  303. static const ad_plugin ad_ffmpeg = {
  304. #ifdef HAVE_FFMPEG
  305. &ad_eval_ffmpeg,
  306. &ad_open_ffmpeg,
  307. &ad_close_ffmpeg,
  308. &ad_info_ffmpeg,
  309. &ad_seek_ffmpeg,
  310. &ad_read_ffmpeg
  311. #else
  312. &ad_eval_null,
  313. &ad_open_null,
  314. &ad_close_null,
  315. &ad_info_null,
  316. &ad_seek_null,
  317. &ad_read_null
  318. #endif
  319. };
  320. /* dlopen handler */
  321. const ad_plugin * adp_get_ffmpeg() {
  322. #ifdef HAVE_FFMPEG
  323. static int ffinit = 0;
  324. if (!ffinit) {
  325. ffinit=1;
  326. #if LIBAVFORMAT_VERSION_INT < AV_VERSION_INT(53, 5, 0)
  327. avcodec_init();
  328. #endif
  329. av_register_all();
  330. avcodec_register_all();
  331. if(ad_debug_level <= 1)
  332. av_log_set_level(AV_LOG_QUIET);
  333. else
  334. av_log_set_level(AV_LOG_VERBOSE);
  335. }
  336. #endif
  337. return &ad_ffmpeg;
  338. }