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.

313 lines
9.9KB

  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. static const AVOption options[] = {
  44. { "compensate", "Stretch/squeeze the data to make it match the timestamps", OFFSET(resample), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, A },
  45. { "min_delta", "Minimum difference between timestamps and audio data "
  46. "(in seconds) to trigger padding/trimmin the data.", OFFSET(min_delta_sec), AV_OPT_TYPE_FLOAT, { .dbl = 0.1 }, 0, INT_MAX, A },
  47. { "max_comp", "Maximum compensation in samples per second.", OFFSET(max_comp), AV_OPT_TYPE_INT, { .i64 = 500 }, 0, INT_MAX, A },
  48. { "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 },
  49. { NULL },
  50. };
  51. static const AVClass async_class = {
  52. .class_name = "asyncts filter",
  53. .item_name = av_default_item_name,
  54. .option = options,
  55. .version = LIBAVUTIL_VERSION_INT,
  56. };
  57. static int init(AVFilterContext *ctx, const char *args)
  58. {
  59. ASyncContext *s = ctx->priv;
  60. int ret;
  61. s->class = &async_class;
  62. av_opt_set_defaults(s);
  63. if ((ret = av_set_options_string(s, args, "=", ":")) < 0) {
  64. av_log(ctx, AV_LOG_ERROR, "Error parsing options string '%s'.\n", args);
  65. return ret;
  66. }
  67. av_opt_free(s);
  68. s->pts = AV_NOPTS_VALUE;
  69. s->first_frame = 1;
  70. return 0;
  71. }
  72. static void uninit(AVFilterContext *ctx)
  73. {
  74. ASyncContext *s = ctx->priv;
  75. if (s->avr) {
  76. avresample_close(s->avr);
  77. avresample_free(&s->avr);
  78. }
  79. }
  80. static int config_props(AVFilterLink *link)
  81. {
  82. ASyncContext *s = link->src->priv;
  83. int ret;
  84. s->min_delta = s->min_delta_sec * link->sample_rate;
  85. link->time_base = (AVRational){1, link->sample_rate};
  86. s->avr = avresample_alloc_context();
  87. if (!s->avr)
  88. return AVERROR(ENOMEM);
  89. av_opt_set_int(s->avr, "in_channel_layout", link->channel_layout, 0);
  90. av_opt_set_int(s->avr, "out_channel_layout", link->channel_layout, 0);
  91. av_opt_set_int(s->avr, "in_sample_fmt", link->format, 0);
  92. av_opt_set_int(s->avr, "out_sample_fmt", link->format, 0);
  93. av_opt_set_int(s->avr, "in_sample_rate", link->sample_rate, 0);
  94. av_opt_set_int(s->avr, "out_sample_rate", link->sample_rate, 0);
  95. if (s->resample)
  96. av_opt_set_int(s->avr, "force_resampling", 1, 0);
  97. if ((ret = avresample_open(s->avr)) < 0)
  98. return ret;
  99. return 0;
  100. }
  101. /* get amount of data currently buffered, in samples */
  102. static int64_t get_delay(ASyncContext *s)
  103. {
  104. return avresample_available(s->avr) + avresample_get_delay(s->avr);
  105. }
  106. static void handle_trimming(AVFilterContext *ctx)
  107. {
  108. ASyncContext *s = ctx->priv;
  109. if (s->pts < s->first_pts) {
  110. int delta = FFMIN(s->first_pts - s->pts, avresample_available(s->avr));
  111. av_log(ctx, AV_LOG_VERBOSE, "Trimming %d samples from start\n",
  112. delta);
  113. avresample_read(s->avr, NULL, delta);
  114. s->pts += delta;
  115. } else if (s->first_frame)
  116. s->pts = s->first_pts;
  117. }
  118. static int request_frame(AVFilterLink *link)
  119. {
  120. AVFilterContext *ctx = link->src;
  121. ASyncContext *s = ctx->priv;
  122. int ret = 0;
  123. int nb_samples;
  124. s->got_output = 0;
  125. while (ret >= 0 && !s->got_output)
  126. ret = ff_request_frame(ctx->inputs[0]);
  127. /* flush the fifo */
  128. if (ret == AVERROR_EOF) {
  129. if (s->first_pts != AV_NOPTS_VALUE)
  130. handle_trimming(ctx);
  131. if (nb_samples = get_delay(s)) {
  132. AVFrame *buf = ff_get_audio_buffer(link, nb_samples);
  133. if (!buf)
  134. return AVERROR(ENOMEM);
  135. ret = avresample_convert(s->avr, buf->extended_data,
  136. buf->linesize[0], nb_samples, NULL, 0, 0);
  137. if (ret <= 0) {
  138. av_frame_free(&buf);
  139. return (ret < 0) ? ret : AVERROR_EOF;
  140. }
  141. buf->pts = s->pts;
  142. return ff_filter_frame(link, buf);
  143. }
  144. }
  145. return ret;
  146. }
  147. static int write_to_fifo(ASyncContext *s, AVFrame *buf)
  148. {
  149. int ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
  150. buf->linesize[0], buf->nb_samples);
  151. av_frame_free(&buf);
  152. return ret;
  153. }
  154. static int filter_frame(AVFilterLink *inlink, AVFrame *buf)
  155. {
  156. AVFilterContext *ctx = inlink->dst;
  157. ASyncContext *s = ctx->priv;
  158. AVFilterLink *outlink = ctx->outputs[0];
  159. int nb_channels = av_get_channel_layout_nb_channels(buf->channel_layout);
  160. int64_t pts = (buf->pts == AV_NOPTS_VALUE) ? buf->pts :
  161. av_rescale_q(buf->pts, inlink->time_base, outlink->time_base);
  162. int out_size, ret;
  163. int64_t delta;
  164. /* buffer data until we get the next timestamp */
  165. if (s->pts == AV_NOPTS_VALUE || pts == AV_NOPTS_VALUE) {
  166. if (pts != AV_NOPTS_VALUE) {
  167. s->pts = pts - get_delay(s);
  168. }
  169. return write_to_fifo(s, buf);
  170. }
  171. if (s->first_pts != AV_NOPTS_VALUE) {
  172. handle_trimming(ctx);
  173. if (!avresample_available(s->avr))
  174. return write_to_fifo(s, buf);
  175. }
  176. /* when we have two timestamps, compute how many samples would we have
  177. * to add/remove to get proper sync between data and timestamps */
  178. delta = pts - s->pts - get_delay(s);
  179. out_size = avresample_available(s->avr);
  180. if (labs(delta) > s->min_delta ||
  181. (s->first_frame && delta && s->first_pts != AV_NOPTS_VALUE)) {
  182. av_log(ctx, AV_LOG_VERBOSE, "Discontinuity - %"PRId64" samples.\n", delta);
  183. out_size = av_clipl_int32((int64_t)out_size + delta);
  184. } else {
  185. if (s->resample) {
  186. int comp = av_clip(delta, -s->max_comp, s->max_comp);
  187. av_log(ctx, AV_LOG_VERBOSE, "Compensating %d samples per second.\n", comp);
  188. avresample_set_compensation(s->avr, comp, inlink->sample_rate);
  189. }
  190. delta = 0;
  191. }
  192. if (out_size > 0) {
  193. AVFrame *buf_out = ff_get_audio_buffer(outlink, out_size);
  194. if (!buf_out) {
  195. ret = AVERROR(ENOMEM);
  196. goto fail;
  197. }
  198. if (s->first_frame && delta > 0) {
  199. int ch;
  200. av_samples_set_silence(buf_out->extended_data, 0, delta,
  201. nb_channels, buf->format);
  202. for (ch = 0; ch < nb_channels; ch++)
  203. buf_out->extended_data[ch] += delta;
  204. avresample_read(s->avr, buf_out->extended_data, out_size);
  205. for (ch = 0; ch < nb_channels; ch++)
  206. buf_out->extended_data[ch] -= delta;
  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->nb_samples);
  228. s->first_frame = 0;
  229. fail:
  230. av_frame_free(&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. };