File: tempoprocessor.cpp

package info (click to toggle)
olive-editor 20200620-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 40,228 kB
  • sloc: cpp: 51,932; sh: 56; makefile: 7; xml: 7
file content (277 lines) | stat: -rw-r--r-- 7,495 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
/***

  Olive - Non-Linear Video Editor
  Copyright (C) 2019 Olive Team

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.

***/

#include "tempoprocessor.h"

extern "C" {
#include <libavfilter/buffersink.h>
#include <libavfilter/buffersrc.h>
#include <libavutil/opt.h>
}

#include <QDebug>

#include "codec/ffmpeg/ffmpegcommon.h"

OLIVE_NAMESPACE_ENTER

TempoProcessor::TempoProcessor() :
  filter_graph_(nullptr),
  buffersrc_ctx_(nullptr),
  buffersink_ctx_(nullptr),
  processed_frame_(nullptr),
  open_(false)
{

}

bool TempoProcessor::IsOpen() const
{
  return open_;
}

const double &TempoProcessor::GetSpeed() const
{
  return speed_;
}

bool TempoProcessor::Open(const AudioParams &params, const double& speed)
{
  if (open_) {
    return true;
  }

  params_ = params;
  speed_ = speed;

  // Create AVFilterGraph instance
  filter_graph_ = avfilter_graph_alloc();
  if (!filter_graph_) {
    qCritical() << "Failed to create AVFilterGraph";
    Close();
    return false;
  }

  // Set up audio buffer args
  char filter_args[200];
  snprintf(filter_args, 200, "time_base=%d/%d:sample_rate=%d:sample_fmt=%d:channel_layout=0x%" PRIx64,
           1,
           params_.sample_rate(),
           params_.sample_rate(),
           FFmpegCommon::GetFFmpegSampleFormat(params_.format()),
           params.channel_layout());

  // Create buffer and buffersink
  if (avfilter_graph_create_filter(&buffersrc_ctx_, avfilter_get_by_name("abuffer"), "in", filter_args, nullptr, filter_graph_) < 0) {
    qCritical() << "Failed to create audio buffer source";
    Close();
    return false;
  }

  if (avfilter_graph_create_filter(&buffersink_ctx_, avfilter_get_by_name("abuffersink"), "out", nullptr, nullptr, filter_graph_) < 0) {
    qCritical() << "Failed to create audio buffer sink";
    Close();
    return false;
  }

  // Create audio tempo filters: FFmpeg's atempo can only be set between 0.5 and 2.0. If the requested speed is outside
  // those boundaries, we need to daisychain more than one together.
  double base = (speed_ > 1.0) ? 2.0 : 0.5;
  double speed_log = log(speed_) / log(base);

  // This is the number of how many 0.5 or 2.0 tempos we need to daisychain
  int whole = qFloor(speed_log);

  // Set speed_log to the remainder
  speed_log -= whole;

  AVFilterContext* previous_filter = buffersrc_ctx_;

  for (int i=0;i<=whole;i++) {
    double filter_tempo = (i == whole) ? qPow(base, speed_log) : base;

    if (qFuzzyCompare(filter_tempo, 1.0)) {
      // This filter would do nothing
      continue;
    }

    previous_filter = CreateTempoFilter(filter_graph_,
                                        previous_filter,
                                        filter_tempo);

    if (!previous_filter) {
      qCritical() << "Failed to create audio tempo filter";
      Close();
      return false;
    }
  }

  // Link the last filter to the buffersink
  if (avfilter_link(previous_filter, 0, buffersink_ctx_, 0) != 0) {
    qCritical() << "Failed to link final filter and buffer sink";
    Close();
    return false;
  }

  // Config graph
  if (avfilter_graph_config(filter_graph_, nullptr) < 0) {
    qCritical() << "Failed to configure filter graph";
    Close();
    return false;
  }

  timestamp_ = 0;

  open_ = true;

  flushed_ = false;

  return true;
}

void TempoProcessor::Push(const char *data, int length)
{
  if (flushed_) {
    if (length > 0) {
      qCritical() << "Tried to push" << length << "bytes after TempoProcessor was closed";
    }
    return;
  }

  AVFrame* src_frame;

  if (length == 0) {
    // No audio data, flush the last out of the filter graph
    src_frame = nullptr;
    flushed_ = true;
  } else {
    src_frame = av_frame_alloc();

    if (!src_frame) {
      qCritical() << "Failed to allocate source frame";
      return;
    }

    // Allocate a buffer for the number of samples we got
    src_frame->sample_rate = params_.sample_rate();
    src_frame->format = FFmpegCommon::GetFFmpegSampleFormat(params_.format());
    src_frame->channel_layout = params_.channel_layout();
    src_frame->nb_samples = params_.bytes_to_samples(length);
    src_frame->pts = timestamp_;
    timestamp_ += src_frame->nb_samples;

    if (av_frame_get_buffer(src_frame, 0) < 0) {
      qCritical() << "Failed to allocate buffer for source frame";
      av_frame_free(&src_frame);
      return;
    }

    // Copy buffer from data array to frame
    memcpy(src_frame->data[0], data, static_cast<size_t>(length));
  }

  int ret = av_buffersrc_add_frame_flags(buffersrc_ctx_, src_frame, AV_BUFFERSRC_FLAG_KEEP_REF);

  if (ret < 0) {
    qCritical() << "Failed to feed buffer source" << ret;
  }

  if (src_frame) {
    av_frame_free(&src_frame);
  }
}

int TempoProcessor::Pull(char *data, int max_length)
{
  if (!processed_frame_) {
    processed_frame_ = av_frame_alloc();

    // Try to pull samples from the buffersink
    int ret = av_buffersink_get_frame(buffersink_ctx_, processed_frame_);

    if (ret < 0) {
      // We couldn't pull for some reason, if the error was EAGAIN, we just need to send more samples. Otherwise the
      // error might be fatal...
      if (ret != AVERROR(EAGAIN)) {
        qCritical() << "Failed to pull from buffersink" << ret;
      }

      av_frame_free(&processed_frame_);

      return 0;
    }

    processed_frame_byte_index_ = 0;
    processed_frame_max_bytes_ = params_.samples_to_bytes(processed_frame_->nb_samples);
  }

  // Determine how many bytes we should copy into the data array
  int copy_length = qMin(max_length, processed_frame_max_bytes_ - processed_frame_byte_index_);

  // Copy the bytes
  memcpy(data, processed_frame_->data[0] + processed_frame_byte_index_, static_cast<size_t>(copy_length));

  // Add the copied amount to the current index
  processed_frame_byte_index_ += copy_length;

  // If the index has reached the limit of this processed frame, we can dispose of the frame now
  if (processed_frame_byte_index_ == processed_frame_max_bytes_) {
    av_frame_free(&processed_frame_);
    processed_frame_ = nullptr;
  }

  return copy_length;
}

void TempoProcessor::Close()
{
  open_ = false;

  if (filter_graph_) {
    avfilter_graph_free(&filter_graph_);
    filter_graph_ = nullptr;
  }

  if (processed_frame_) {
    av_frame_free(&processed_frame_);
    processed_frame_ = nullptr;
  }

  buffersrc_ctx_ = nullptr;
  buffersink_ctx_ = nullptr;
}

AVFilterContext *TempoProcessor::CreateTempoFilter(AVFilterGraph* graph, AVFilterContext* link, const double &tempo)
{
  // Set up tempo param, which is taken as a C string
  char speed_param[20];
  snprintf(speed_param, 20, "%f", tempo);

  AVFilterContext* tempo_ctx = nullptr;

  if (avfilter_graph_create_filter(&tempo_ctx, avfilter_get_by_name("atempo"), "atempo", speed_param, nullptr, graph) >= 0
      && avfilter_link(link, 0, tempo_ctx, 0) == 0) {
    return tempo_ctx;
  }

  return nullptr;
}

OLIVE_NAMESPACE_EXIT