af_asyncts.c 11 KB

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