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.

319 lines
10KB

  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. int comp; ///< current resample compensation
  35. /* options */
  36. int resample;
  37. float min_delta_sec;
  38. int max_comp;
  39. /* set by filter_frame() to signal an output frame to request_frame() */
  40. int got_output;
  41. } ASyncContext;
  42. #define OFFSET(x) offsetof(ASyncContext, x)
  43. #define A AV_OPT_FLAG_AUDIO_PARAM
  44. #define F AV_OPT_FLAG_FILTERING_PARAM
  45. static const AVOption asyncts_options[] = {
  46. { "compensate", "Stretch/squeeze the data to make it match the timestamps", OFFSET(resample), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, A|F },
  47. { "min_delta", "Minimum difference between timestamps and audio data "
  48. "(in seconds) to trigger padding/trimmin the data.", OFFSET(min_delta_sec), AV_OPT_TYPE_FLOAT, { .dbl = 0.1 }, 0, INT_MAX, A|F },
  49. { "max_comp", "Maximum compensation in samples per second.", OFFSET(max_comp), AV_OPT_TYPE_INT, { .i64 = 500 }, 0, INT_MAX, A|F },
  50. { "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 },
  51. { NULL },
  52. };
  53. AVFILTER_DEFINE_CLASS(asyncts);
  54. static int init(AVFilterContext *ctx)
  55. {
  56. ASyncContext *s = ctx->priv;
  57. s->pts = AV_NOPTS_VALUE;
  58. s->first_frame = 1;
  59. return 0;
  60. }
  61. static void uninit(AVFilterContext *ctx)
  62. {
  63. ASyncContext *s = ctx->priv;
  64. if (s->avr) {
  65. avresample_close(s->avr);
  66. avresample_free(&s->avr);
  67. }
  68. }
  69. static int config_props(AVFilterLink *link)
  70. {
  71. ASyncContext *s = link->src->priv;
  72. int ret;
  73. s->min_delta = s->min_delta_sec * link->sample_rate;
  74. link->time_base = (AVRational){1, link->sample_rate};
  75. s->avr = avresample_alloc_context();
  76. if (!s->avr)
  77. return AVERROR(ENOMEM);
  78. av_opt_set_int(s->avr, "in_channel_layout", link->channel_layout, 0);
  79. av_opt_set_int(s->avr, "out_channel_layout", link->channel_layout, 0);
  80. av_opt_set_int(s->avr, "in_sample_fmt", link->format, 0);
  81. av_opt_set_int(s->avr, "out_sample_fmt", link->format, 0);
  82. av_opt_set_int(s->avr, "in_sample_rate", link->sample_rate, 0);
  83. av_opt_set_int(s->avr, "out_sample_rate", link->sample_rate, 0);
  84. if (s->resample)
  85. av_opt_set_int(s->avr, "force_resampling", 1, 0);
  86. if ((ret = avresample_open(s->avr)) < 0)
  87. return ret;
  88. return 0;
  89. }
  90. /* get amount of data currently buffered, in samples */
  91. static int64_t get_delay(ASyncContext *s)
  92. {
  93. return avresample_available(s->avr) + avresample_get_delay(s->avr);
  94. }
  95. static void handle_trimming(AVFilterContext *ctx)
  96. {
  97. ASyncContext *s = ctx->priv;
  98. if (s->pts < s->first_pts) {
  99. int delta = FFMIN(s->first_pts - s->pts, avresample_available(s->avr));
  100. av_log(ctx, AV_LOG_VERBOSE, "Trimming %d samples from start\n",
  101. delta);
  102. avresample_read(s->avr, NULL, delta);
  103. s->pts += delta;
  104. } else if (s->first_frame)
  105. s->pts = s->first_pts;
  106. }
  107. static int request_frame(AVFilterLink *link)
  108. {
  109. AVFilterContext *ctx = link->src;
  110. ASyncContext *s = ctx->priv;
  111. int ret = 0;
  112. int nb_samples;
  113. s->got_output = 0;
  114. while (ret >= 0 && !s->got_output)
  115. ret = ff_request_frame(ctx->inputs[0]);
  116. /* flush the fifo */
  117. if (ret == AVERROR_EOF) {
  118. if (s->first_pts != AV_NOPTS_VALUE)
  119. handle_trimming(ctx);
  120. if (nb_samples = get_delay(s)) {
  121. AVFrame *buf = ff_get_audio_buffer(link, nb_samples);
  122. if (!buf)
  123. return AVERROR(ENOMEM);
  124. ret = avresample_convert(s->avr, buf->extended_data,
  125. buf->linesize[0], nb_samples, NULL, 0, 0);
  126. if (ret <= 0) {
  127. av_frame_free(&buf);
  128. return (ret < 0) ? ret : AVERROR_EOF;
  129. }
  130. buf->pts = s->pts;
  131. return ff_filter_frame(link, buf);
  132. }
  133. }
  134. return ret;
  135. }
  136. static int write_to_fifo(ASyncContext *s, AVFrame *buf)
  137. {
  138. int ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
  139. buf->linesize[0], buf->nb_samples);
  140. av_frame_free(&buf);
  141. return ret;
  142. }
  143. static int filter_frame(AVFilterLink *inlink, AVFrame *buf)
  144. {
  145. AVFilterContext *ctx = inlink->dst;
  146. ASyncContext *s = ctx->priv;
  147. AVFilterLink *outlink = ctx->outputs[0];
  148. int nb_channels = av_get_channel_layout_nb_channels(buf->channel_layout);
  149. int64_t pts = (buf->pts == AV_NOPTS_VALUE) ? buf->pts :
  150. av_rescale_q(buf->pts, inlink->time_base, outlink->time_base);
  151. int out_size, ret;
  152. int64_t delta;
  153. int64_t new_pts;
  154. /* buffer data until we get the next timestamp */
  155. if (s->pts == AV_NOPTS_VALUE || pts == AV_NOPTS_VALUE) {
  156. if (pts != AV_NOPTS_VALUE) {
  157. s->pts = pts - get_delay(s);
  158. }
  159. return write_to_fifo(s, buf);
  160. }
  161. if (s->first_pts != AV_NOPTS_VALUE) {
  162. handle_trimming(ctx);
  163. if (!avresample_available(s->avr))
  164. return write_to_fifo(s, buf);
  165. }
  166. /* when we have two timestamps, compute how many samples would we have
  167. * to add/remove to get proper sync between data and timestamps */
  168. delta = pts - s->pts - get_delay(s);
  169. out_size = avresample_available(s->avr);
  170. if (labs(delta) > s->min_delta ||
  171. (s->first_frame && delta && s->first_pts != AV_NOPTS_VALUE)) {
  172. av_log(ctx, AV_LOG_VERBOSE, "Discontinuity - %"PRId64" samples.\n", delta);
  173. out_size = av_clipl_int32((int64_t)out_size + delta);
  174. } else {
  175. if (s->resample) {
  176. // adjust the compensation if delta is non-zero
  177. int delay = get_delay(s);
  178. int comp = s->comp + av_clip(delta * inlink->sample_rate / delay,
  179. -s->max_comp, s->max_comp);
  180. if (comp != s->comp) {
  181. av_log(ctx, AV_LOG_VERBOSE, "Compensating %d samples per second.\n", comp);
  182. if (avresample_set_compensation(s->avr, comp, inlink->sample_rate) == 0) {
  183. s->comp = comp;
  184. }
  185. }
  186. }
  187. // adjust PTS to avoid monotonicity errors with input PTS jitter
  188. pts -= delta;
  189. delta = 0;
  190. }
  191. if (out_size > 0) {
  192. AVFrame *buf_out = ff_get_audio_buffer(outlink, out_size);
  193. if (!buf_out) {
  194. ret = AVERROR(ENOMEM);
  195. goto fail;
  196. }
  197. if (s->first_frame && delta > 0) {
  198. int ch;
  199. av_samples_set_silence(buf_out->extended_data, 0, delta,
  200. nb_channels, buf->format);
  201. for (ch = 0; ch < nb_channels; ch++)
  202. buf_out->extended_data[ch] += delta;
  203. avresample_read(s->avr, buf_out->extended_data, out_size);
  204. for (ch = 0; ch < nb_channels; ch++)
  205. buf_out->extended_data[ch] -= delta;
  206. } else {
  207. avresample_read(s->avr, buf_out->extended_data, out_size);
  208. if (delta > 0) {
  209. av_samples_set_silence(buf_out->extended_data, out_size - delta,
  210. delta, nb_channels, buf->format);
  211. }
  212. }
  213. buf_out->pts = s->pts;
  214. ret = ff_filter_frame(outlink, buf_out);
  215. if (ret < 0)
  216. goto fail;
  217. s->got_output = 1;
  218. } else if (avresample_available(s->avr)) {
  219. av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "
  220. "whole buffer.\n");
  221. }
  222. /* drain any remaining buffered data */
  223. avresample_read(s->avr, NULL, avresample_available(s->avr));
  224. new_pts = pts - avresample_get_delay(s->avr);
  225. /* check for s->pts monotonicity */
  226. if (new_pts > s->pts) {
  227. s->pts = new_pts;
  228. ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
  229. buf->linesize[0], buf->nb_samples);
  230. } else {
  231. av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "
  232. "whole buffer.\n");
  233. ret = 0;
  234. }
  235. s->first_frame = 0;
  236. fail:
  237. av_frame_free(&buf);
  238. return ret;
  239. }
  240. static const AVFilterPad avfilter_af_asyncts_inputs[] = {
  241. {
  242. .name = "default",
  243. .type = AVMEDIA_TYPE_AUDIO,
  244. .filter_frame = filter_frame
  245. },
  246. { NULL }
  247. };
  248. static const AVFilterPad avfilter_af_asyncts_outputs[] = {
  249. {
  250. .name = "default",
  251. .type = AVMEDIA_TYPE_AUDIO,
  252. .config_props = config_props,
  253. .request_frame = request_frame
  254. },
  255. { NULL }
  256. };
  257. AVFilter avfilter_af_asyncts = {
  258. .name = "asyncts",
  259. .description = NULL_IF_CONFIG_SMALL("Sync audio data to timestamps"),
  260. .init = init,
  261. .uninit = uninit,
  262. .priv_size = sizeof(ASyncContext),
  263. .priv_class = &asyncts_class,
  264. .inputs = avfilter_af_asyncts_inputs,
  265. .outputs = avfilter_af_asyncts_outputs,
  266. };