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.

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