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.

315 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. /* 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. AVFilterBufferRef *buf = ff_get_audio_buffer(link, AV_PERM_WRITE,
  133. 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. avfilter_unref_bufferp(&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, AVFilterBufferRef *buf)
  149. {
  150. int ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
  151. buf->linesize[0], buf->audio->nb_samples);
  152. avfilter_unref_buffer(buf);
  153. return ret;
  154. }
  155. static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *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->audio->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. /* buffer data until we get the next timestamp */
  166. if (s->pts == AV_NOPTS_VALUE || pts == AV_NOPTS_VALUE) {
  167. if (pts != AV_NOPTS_VALUE) {
  168. s->pts = pts - get_delay(s);
  169. }
  170. return write_to_fifo(s, buf);
  171. }
  172. if (s->first_pts != AV_NOPTS_VALUE) {
  173. handle_trimming(ctx);
  174. if (!avresample_available(s->avr))
  175. return write_to_fifo(s, buf);
  176. }
  177. /* when we have two timestamps, compute how many samples would we have
  178. * to add/remove to get proper sync between data and timestamps */
  179. delta = pts - s->pts - get_delay(s);
  180. out_size = avresample_available(s->avr);
  181. if (labs(delta) > s->min_delta ||
  182. (s->first_frame && delta && s->first_pts != AV_NOPTS_VALUE)) {
  183. av_log(ctx, AV_LOG_VERBOSE, "Discontinuity - %"PRId64" samples.\n", delta);
  184. out_size = av_clipl_int32((int64_t)out_size + delta);
  185. } else {
  186. if (s->resample) {
  187. int comp = av_clip(delta, -s->max_comp, s->max_comp);
  188. av_log(ctx, AV_LOG_VERBOSE, "Compensating %d samples per second.\n", comp);
  189. avresample_set_compensation(s->avr, comp, inlink->sample_rate);
  190. }
  191. delta = 0;
  192. }
  193. if (out_size > 0) {
  194. AVFilterBufferRef *buf_out = ff_get_audio_buffer(outlink, AV_PERM_WRITE,
  195. out_size);
  196. if (!buf_out) {
  197. ret = AVERROR(ENOMEM);
  198. goto fail;
  199. }
  200. if (s->first_frame && delta > 0) {
  201. int ch;
  202. av_samples_set_silence(buf_out->extended_data, 0, delta,
  203. nb_channels, buf->format);
  204. for (ch = 0; ch < nb_channels; ch++)
  205. buf_out->extended_data[ch] += delta;
  206. avresample_read(s->avr, buf_out->extended_data, out_size);
  207. for (ch = 0; ch < nb_channels; ch++)
  208. buf_out->extended_data[ch] -= delta;
  209. } else {
  210. avresample_read(s->avr, buf_out->extended_data, out_size);
  211. if (delta > 0) {
  212. av_samples_set_silence(buf_out->extended_data, out_size - delta,
  213. delta, nb_channels, buf->format);
  214. }
  215. }
  216. buf_out->pts = s->pts;
  217. ret = ff_filter_frame(outlink, buf_out);
  218. if (ret < 0)
  219. goto fail;
  220. s->got_output = 1;
  221. } else if (avresample_available(s->avr)) {
  222. av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "
  223. "whole buffer.\n");
  224. }
  225. /* drain any remaining buffered data */
  226. avresample_read(s->avr, NULL, avresample_available(s->avr));
  227. s->pts = pts - avresample_get_delay(s->avr);
  228. ret = avresample_convert(s->avr, NULL, 0, 0, buf->extended_data,
  229. buf->linesize[0], buf->audio->nb_samples);
  230. s->first_frame = 0;
  231. fail:
  232. avfilter_unref_buffer(buf);
  233. return ret;
  234. }
  235. static const AVFilterPad avfilter_af_asyncts_inputs[] = {
  236. {
  237. .name = "default",
  238. .type = AVMEDIA_TYPE_AUDIO,
  239. .filter_frame = filter_frame,
  240. },
  241. { NULL }
  242. };
  243. static const AVFilterPad avfilter_af_asyncts_outputs[] = {
  244. {
  245. .name = "default",
  246. .type = AVMEDIA_TYPE_AUDIO,
  247. .config_props = config_props,
  248. .request_frame = request_frame
  249. },
  250. { NULL }
  251. };
  252. AVFilter avfilter_af_asyncts = {
  253. .name = "asyncts",
  254. .description = NULL_IF_CONFIG_SMALL("Sync audio data to timestamps"),
  255. .init = init,
  256. .uninit = uninit,
  257. .priv_size = sizeof(ASyncContext),
  258. .inputs = avfilter_af_asyncts_inputs,
  259. .outputs = avfilter_af_asyncts_outputs,
  260. };