af_asyncts.c 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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/mathematics.h"
  21. #include "libavutil/opt.h"
  22. #include "libavutil/samplefmt.h"
  23. #include "audio.h"
  24. #include "avfilter.h"
  25. #include "internal.h"
  26. typedef struct ASyncContext {
  27. const AVClass *class;
  28. AVAudioResampleContext *avr;
  29. int64_t pts; ///< timestamp in samples of the first sample in fifo
  30. int min_delta; ///< pad/trim min threshold in samples
  31. /* options */
  32. int resample;
  33. float min_delta_sec;
  34. int max_comp;
  35. /* set by filter_samples() to signal an output frame to request_frame() */
  36. int got_output;
  37. } ASyncContext;
  38. #define OFFSET(x) offsetof(ASyncContext, x)
  39. #define A AV_OPT_FLAG_AUDIO_PARAM
  40. static const AVOption asyncts_options[] = {
  41. { "compensate", "Stretch/squeeze the data to make it match the timestamps", OFFSET(resample), AV_OPT_TYPE_INT, { 0 }, 0, 1, A },
  42. { "min_delta", "Minimum difference between timestamps and audio data "
  43. "(in seconds) to trigger padding/trimmin the data.", OFFSET(min_delta_sec), AV_OPT_TYPE_FLOAT, { 0.1 }, 0, INT_MAX, A },
  44. { "max_comp", "Maximum compensation in samples per second.", OFFSET(max_comp), AV_OPT_TYPE_INT, { 500 }, 0, INT_MAX, A },
  45. { "first_pts", "Assume the first pts should be this value.", OFFSET(pts), AV_OPT_TYPE_INT64, { AV_NOPTS_VALUE }, INT64_MIN, INT64_MAX, A },
  46. { NULL },
  47. };
  48. AVFILTER_DEFINE_CLASS(asyncts);
  49. static int init(AVFilterContext *ctx, const char *args)
  50. {
  51. ASyncContext *s = ctx->priv;
  52. int ret;
  53. s->class = &asyncts_class;
  54. av_opt_set_defaults(s);
  55. if ((ret = av_set_options_string(s, args, "=", ":")) < 0) {
  56. av_log(ctx, AV_LOG_ERROR, "Error parsing options string '%s'.\n", args);
  57. return ret;
  58. }
  59. av_opt_free(s);
  60. return 0;
  61. }
  62. static void uninit(AVFilterContext *ctx)
  63. {
  64. ASyncContext *s = ctx->priv;
  65. if (s->avr) {
  66. avresample_close(s->avr);
  67. avresample_free(&s->avr);
  68. }
  69. }
  70. static int config_props(AVFilterLink *link)
  71. {
  72. ASyncContext *s = link->src->priv;
  73. int ret;
  74. s->min_delta = s->min_delta_sec * link->sample_rate;
  75. link->time_base = (AVRational){1, link->sample_rate};
  76. s->avr = avresample_alloc_context();
  77. if (!s->avr)
  78. return AVERROR(ENOMEM);
  79. av_opt_set_int(s->avr, "in_channel_layout", link->channel_layout, 0);
  80. av_opt_set_int(s->avr, "out_channel_layout", link->channel_layout, 0);
  81. av_opt_set_int(s->avr, "in_sample_fmt", link->format, 0);
  82. av_opt_set_int(s->avr, "out_sample_fmt", link->format, 0);
  83. av_opt_set_int(s->avr, "in_sample_rate", link->sample_rate, 0);
  84. av_opt_set_int(s->avr, "out_sample_rate", link->sample_rate, 0);
  85. if (s->resample)
  86. av_opt_set_int(s->avr, "force_resampling", 1, 0);
  87. if ((ret = avresample_open(s->avr)) < 0)
  88. return ret;
  89. return 0;
  90. }
  91. static int request_frame(AVFilterLink *link)
  92. {
  93. AVFilterContext *ctx = link->src;
  94. ASyncContext *s = ctx->priv;
  95. int ret = 0;
  96. int nb_samples;
  97. s->got_output = 0;
  98. while (ret >= 0 && !s->got_output)
  99. ret = ff_request_frame(ctx->inputs[0]);
  100. /* flush the fifo */
  101. if (ret == AVERROR_EOF && (nb_samples = avresample_get_delay(s->avr))) {
  102. AVFilterBufferRef *buf = ff_get_audio_buffer(link, AV_PERM_WRITE,
  103. nb_samples);
  104. if (!buf)
  105. return AVERROR(ENOMEM);
  106. avresample_convert(s->avr, (void**)buf->extended_data, buf->linesize[0],
  107. nb_samples, NULL, 0, 0);
  108. buf->pts = s->pts;
  109. return ff_filter_samples(link, buf);
  110. }
  111. return ret;
  112. }
  113. static int write_to_fifo(ASyncContext *s, AVFilterBufferRef *buf)
  114. {
  115. int ret = avresample_convert(s->avr, NULL, 0, 0, (void**)buf->extended_data,
  116. buf->linesize[0], buf->audio->nb_samples);
  117. avfilter_unref_buffer(buf);
  118. return ret;
  119. }
  120. /* get amount of data currently buffered, in samples */
  121. static int64_t get_delay(ASyncContext *s)
  122. {
  123. return avresample_available(s->avr) + avresample_get_delay(s->avr);
  124. }
  125. static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *buf)
  126. {
  127. AVFilterContext *ctx = inlink->dst;
  128. ASyncContext *s = ctx->priv;
  129. AVFilterLink *outlink = ctx->outputs[0];
  130. int nb_channels = av_get_channel_layout_nb_channels(buf->audio->channel_layout);
  131. int64_t pts = (buf->pts == AV_NOPTS_VALUE) ? buf->pts :
  132. av_rescale_q(buf->pts, inlink->time_base, outlink->time_base);
  133. int out_size, ret;
  134. int64_t delta;
  135. /* buffer data until we get the first timestamp */
  136. if (s->pts == AV_NOPTS_VALUE) {
  137. if (pts != AV_NOPTS_VALUE) {
  138. s->pts = pts - get_delay(s);
  139. }
  140. return write_to_fifo(s, buf);
  141. }
  142. /* now wait for the next timestamp */
  143. if (pts == AV_NOPTS_VALUE) {
  144. return write_to_fifo(s, buf);
  145. }
  146. /* when we have two timestamps, compute how many samples would we have
  147. * to add/remove to get proper sync between data and timestamps */
  148. delta = pts - s->pts - get_delay(s);
  149. out_size = avresample_available(s->avr);
  150. if (labs(delta) > s->min_delta) {
  151. av_log(ctx, AV_LOG_VERBOSE, "Discontinuity - %"PRId64" samples.\n", delta);
  152. out_size = av_clipl_int32((int64_t)out_size + delta);
  153. } else {
  154. if (s->resample) {
  155. int comp = av_clip(delta, -s->max_comp, s->max_comp);
  156. av_log(ctx, AV_LOG_VERBOSE, "Compensating %d samples per second.\n", comp);
  157. avresample_set_compensation(s->avr, delta, inlink->sample_rate);
  158. }
  159. delta = 0;
  160. }
  161. if (out_size > 0) {
  162. AVFilterBufferRef *buf_out = ff_get_audio_buffer(outlink, AV_PERM_WRITE,
  163. out_size);
  164. if (!buf_out) {
  165. ret = AVERROR(ENOMEM);
  166. goto fail;
  167. }
  168. avresample_read(s->avr, (void**)buf_out->extended_data, out_size);
  169. buf_out->pts = s->pts;
  170. if (delta > 0) {
  171. av_samples_set_silence(buf_out->extended_data, out_size - delta,
  172. delta, nb_channels, buf->format);
  173. }
  174. ret = ff_filter_samples(outlink, buf_out);
  175. if (ret < 0)
  176. goto fail;
  177. s->got_output = 1;
  178. } else {
  179. av_log(ctx, AV_LOG_WARNING, "Non-monotonous timestamps, dropping "
  180. "whole buffer.\n");
  181. }
  182. /* drain any remaining buffered data */
  183. avresample_read(s->avr, NULL, avresample_available(s->avr));
  184. s->pts = pts - avresample_get_delay(s->avr);
  185. ret = avresample_convert(s->avr, NULL, 0, 0, (void**)buf->extended_data,
  186. buf->linesize[0], buf->audio->nb_samples);
  187. fail:
  188. avfilter_unref_buffer(buf);
  189. return ret;
  190. }
  191. AVFilter avfilter_af_asyncts = {
  192. .name = "asyncts",
  193. .description = NULL_IF_CONFIG_SMALL("Sync audio data to timestamps"),
  194. .init = init,
  195. .uninit = uninit,
  196. .priv_size = sizeof(ASyncContext),
  197. .inputs = (const AVFilterPad[]) {{ .name = "default",
  198. .type = AVMEDIA_TYPE_AUDIO,
  199. .filter_samples = filter_samples },
  200. { NULL }},
  201. .outputs = (const AVFilterPad[]) {{ .name = "default",
  202. .type = AVMEDIA_TYPE_AUDIO,
  203. .config_props = config_props,
  204. .request_frame = request_frame },
  205. { NULL }},
  206. };