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.

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