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.

367 lines
12KB

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