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.

332 lines
11KB

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