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.

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