af_asyncts.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. /*
  2. * This file is part of Libav.
  3. *
  4. * Libav is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2.1 of the License, or (at your option) any later version.
  8. *
  9. * Libav is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with Libav; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. #include "libavresample/avresample.h"
  19. #include "libavutil/audio_fifo.h"
  20. #include "libavutil/common.h"
  21. #include "libavutil/mathematics.h"
  22. #include "libavutil/opt.h"
  23. #include "libavutil/samplefmt.h"
  24. #include "audio.h"
  25. #include "avfilter.h"
  26. #include "internal.h"
  27. typedef struct ASyncContext {
  28. const AVClass *class;
  29. AVAudioResampleContext *avr;
  30. int64_t pts; ///< timestamp in samples of the first sample in fifo
  31. int min_delta; ///< pad/trim min threshold in samples
  32. int first_frame; ///< 1 until filter_frame() has processed at least 1 frame with a pts != AV_NOPTS_VALUE
  33. int64_t first_pts; ///< user-specified first expected pts, in samples
  34. /* options */
  35. int resample;
  36. float min_delta_sec;
  37. int max_comp;
  38. /* set by filter_frame() to signal an output frame to request_frame() */
  39. int got_output;
  40. } ASyncContext;
  41. #define OFFSET(x) offsetof(ASyncContext, x)
  42. #define A AV_OPT_FLAG_AUDIO_PARAM
  43. #define F AV_OPT_FLAG_FILTERING_PARAM
  44. static const AVOption asyncts_options[] = {
  45. { "compensate", "Stretch/squeeze the data to make it match the timestamps", OFFSET(resample), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, A|F },
  46. { "min_delta", "Minimum difference between timestamps and audio data "
  47. "(in seconds) to trigger padding/trimmin the data.", OFFSET(min_delta_sec), AV_OPT_TYPE_FLOAT, { .dbl = 0.1 }, 0, INT_MAX, A|F },
  48. { "max_comp", "Maximum compensation in samples per second.", OFFSET(max_comp), AV_OPT_TYPE_INT, { .i64 = 500 }, 0, INT_MAX, A|F },
  49. { "first_pts", "Assume the first pts should be this value.", OFFSET(first_pts), AV_OPT_TYPE_INT64, { .i64 = AV_NOPTS_VALUE }, INT64_MIN, INT64_MAX, A|F },
  50. { NULL },
  51. };
  52. AVFILTER_DEFINE_CLASS(asyncts);
  53. static int init(AVFilterContext *ctx, const char *args)
  54. {
  55. ASyncContext *s = ctx->priv;
  56. int ret;
  57. s->class = &asyncts_class;
  58. av_opt_set_defaults(s);
  59. if ((ret = av_set_options_string(s, args, "=", ":")) < 0)
  60. return ret;
  61. av_opt_free(s);
  62. s->pts = AV_NOPTS_VALUE;
  63. s->first_frame = 1;
  64. return 0;
  65. }
  66. static void uninit(AVFilterContext *ctx)
  67. {
  68. ASyncContext *s = ctx->priv;
  69. if (s->avr) {
  70. avresample_close(s->avr);
  71. avresample_free(&s->avr);
  72. }
  73. }
  74. static int config_props(AVFilterLink *link)
  75. {
  76. ASyncContext *s = link->src->priv;
  77. int ret;
  78. s->min_delta = s->min_delta_sec * link->sample_rate;
  79. link->time_base = (AVRational){1, link->sample_rate};
  80. s->avr = avresample_alloc_context();
  81. if (!s->avr)
  82. return AVERROR(ENOMEM);
  83. av_opt_set_int(s->avr, "in_channel_layout", link->channel_layout, 0);
  84. av_opt_set_int(s->avr, "out_channel_layout", link->channel_layout, 0);
  85. av_opt_set_int(s->avr, "in_sample_fmt", link->format, 0);
  86. av_opt_set_int(s->avr, "out_sample_fmt", link->format, 0);
  87. av_opt_set_int(s->avr, "in_sample_rate", link->sample_rate, 0);
  88. av_opt_set_int(s->avr, "out_sample_rate", link->sample_rate, 0);
  89. if (s->resample)
  90. av_opt_set_int(s->avr, "force_resampling", 1, 0);
  91. if ((ret = avresample_open(s->avr)) < 0)
  92. return ret;
  93. return 0;
  94. }
  95. /* get amount of data currently buffered, in samples */
  96. static int64_t get_delay(ASyncContext *s)
  97. {
  98. return avresample_available(s->avr) + avresample_get_delay(s->avr);
  99. }
  100. static void handle_trimming(AVFilterContext *ctx)
  101. {
  102. ASyncContext *s = ctx->priv;
  103. if (s->pts < s->first_pts) {
  104. int delta = FFMIN(s->first_pts - s->pts, avresample_available(s->avr));
  105. av_log(ctx, AV_LOG_VERBOSE, "Trimming %d samples from start\n",
  106. delta);
  107. avresample_read(s->avr, NULL, delta);
  108. s->pts += delta;
  109. } else if (s->first_frame)
  110. s->pts = s->first_pts;
  111. }
  112. static int request_frame(AVFilterLink *link)
  113. {
  114. AVFilterContext *ctx = link->src;
  115. ASyncContext *s = ctx->priv;
  116. int ret = 0;
  117. int nb_samples;
  118. s->got_output = 0;
  119. while (ret >= 0 && !s->got_output)
  120. ret = ff_request_frame(ctx->inputs[0]);
  121. /* flush the fifo */
  122. if (ret == AVERROR_EOF) {
  123. if (s->first_pts != AV_NOPTS_VALUE)
  124. handle_trimming(ctx);
  125. if (nb_samples = get_delay(s)) {
  126. AVFilterBufferRef *buf = ff_get_audio_buffer(link, AV_PERM_WRITE,
  127. nb_samples);
  128. if (!buf)
  129. return AVERROR(ENOMEM);
  130. ret = avresample_convert(s->avr, buf->extended_data,
  131. buf->linesize[0], nb_samples, NULL, 0, 0);
  132. if (ret <= 0) {
  133. avfilter_unref_bufferp(&buf);
  134. return (ret < 0) ? ret : AVERROR_EOF;
  135. }
  136. buf->pts = s->pts;
  137. return ff_filter_frame(link, buf);
  138. }
  139. }
  140. return ret;
  141. }
  142. static int write_to_fifo(ASyncContext *s, AVFilterBufferRef *buf)
  143. {
  144. int ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
  145. buf->linesize[0], buf->audio->nb_samples);
  146. avfilter_unref_buffer(buf);
  147. return ret;
  148. }
  149. static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)
  150. {
  151. AVFilterContext *ctx = inlink->dst;
  152. ASyncContext *s = ctx->priv;
  153. AVFilterLink *outlink = ctx->outputs[0];
  154. int nb_channels = av_get_channel_layout_nb_channels(buf->audio->channel_layout);
  155. int64_t pts = (buf->pts == AV_NOPTS_VALUE) ? buf->pts :
  156. av_rescale_q(buf->pts, inlink->time_base, outlink->time_base);
  157. int out_size, ret;
  158. int64_t delta;
  159. /* buffer data until we get the next timestamp */
  160. if (s->pts == AV_NOPTS_VALUE || pts == AV_NOPTS_VALUE) {
  161. if (pts != AV_NOPTS_VALUE) {
  162. s->pts = pts - get_delay(s);
  163. }
  164. return write_to_fifo(s, buf);
  165. }
  166. if (s->first_pts != AV_NOPTS_VALUE) {
  167. handle_trimming(ctx);
  168. if (!avresample_available(s->avr))
  169. return write_to_fifo(s, buf);
  170. }
  171. /* when we have two timestamps, compute how many samples would we have
  172. * to add/remove to get proper sync between data and timestamps */
  173. delta = pts - s->pts - get_delay(s);
  174. out_size = avresample_available(s->avr);
  175. if (labs(delta) > s->min_delta ||
  176. (s->first_frame && delta && s->first_pts != AV_NOPTS_VALUE)) {
  177. av_log(ctx, AV_LOG_VERBOSE, "Discontinuity - %"PRId64" samples.\n", delta);
  178. out_size = av_clipl_int32((int64_t)out_size + delta);
  179. } else {
  180. if (s->resample) {
  181. int comp = av_clip(delta, -s->max_comp, s->max_comp);
  182. av_log(ctx, AV_LOG_VERBOSE, "Compensating %d samples per second.\n", comp);
  183. avresample_set_compensation(s->avr, comp, inlink->sample_rate);
  184. }
  185. delta = 0;
  186. }
  187. if (out_size > 0) {
  188. AVFilterBufferRef *buf_out = ff_get_audio_buffer(outlink, AV_PERM_WRITE,
  189. out_size);
  190. if (!buf_out) {
  191. ret = AVERROR(ENOMEM);
  192. goto fail;
  193. }
  194. if (s->first_frame && delta > 0) {
  195. int planar = av_sample_fmt_is_planar(buf_out->format);
  196. int planes = planar ? nb_channels : 1;
  197. int block_size = av_get_bytes_per_sample(buf_out->format) *
  198. (planar ? 1 : nb_channels);
  199. int ch;
  200. av_samples_set_silence(buf_out->extended_data, 0, delta,
  201. nb_channels, buf->format);
  202. for (ch = 0; ch < planes; ch++)
  203. buf_out->extended_data[ch] += delta * block_size;
  204. avresample_read(s->avr, buf_out->extended_data, out_size);
  205. for (ch = 0; ch < planes; ch++)
  206. buf_out->extended_data[ch] -= delta * block_size;
  207. } else {
  208. avresample_read(s->avr, buf_out->extended_data, out_size);
  209. if (delta > 0) {
  210. av_samples_set_silence(buf_out->extended_data, out_size - delta,
  211. delta, nb_channels, buf->format);
  212. }
  213. }
  214. buf_out->pts = s->pts;
  215. ret = ff_filter_frame(outlink, buf_out);
  216. if (ret < 0)
  217. goto fail;
  218. s->got_output = 1;
  219. } else if (avresample_available(s->avr)) {
  220. av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "
  221. "whole buffer.\n");
  222. }
  223. /* drain any remaining buffered data */
  224. avresample_read(s->avr, NULL, avresample_available(s->avr));
  225. s->pts = pts - avresample_get_delay(s->avr);
  226. ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
  227. buf->linesize[0], buf->audio->nb_samples);
  228. s->first_frame = 0;
  229. fail:
  230. avfilter_unref_buffer(buf);
  231. return ret;
  232. }
  233. static const AVFilterPad avfilter_af_asyncts_inputs[] = {
  234. {
  235. .name = "default",
  236. .type = AVMEDIA_TYPE_AUDIO,
  237. .filter_frame = filter_frame
  238. },
  239. { NULL }
  240. };
  241. static const AVFilterPad avfilter_af_asyncts_outputs[] = {
  242. {
  243. .name = "default",
  244. .type = AVMEDIA_TYPE_AUDIO,
  245. .config_props = config_props,
  246. .request_frame = request_frame
  247. },
  248. { NULL }
  249. };
  250. AVFilter avfilter_af_asyncts = {
  251. .name = "asyncts",
  252. .description = NULL_IF_CONFIG_SMALL("Sync audio data to timestamps"),
  253. .init = init,
  254. .uninit = uninit,
  255. .priv_size = sizeof(ASyncContext),
  256. .inputs = avfilter_af_asyncts_inputs,
  257. .outputs = avfilter_af_asyncts_outputs,
  258. .priv_class = &asyncts_class,
  259. };