File: AEEncoderFFmpeg.cpp

package info (click to toggle)
kodi 2%3A20.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 143,820 kB
  • sloc: cpp: 664,925; xml: 68,398; ansic: 37,223; python: 6,903; sh: 4,209; javascript: 2,325; makefile: 1,754; perl: 969; java: 513; cs: 390; objc: 340
file content (402 lines) | stat: -rw-r--r-- 12,076 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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
/*
 *  Copyright (C) 2010-2018 Team Kodi
 *  This file is part of Kodi - https://kodi.tv
 *
 *  SPDX-License-Identifier: GPL-2.0-or-later
 *  See LICENSES/README.md for more information.
 */

#define AC3_ENCODE_BITRATE 640000
#define DTS_ENCODE_BITRATE 1411200

#include "cores/AudioEngine/Encoders/AEEncoderFFmpeg.h"

#include "ServiceBroker.h"
#include "cores/AudioEngine/Utils/AEUtil.h"
#include "cores/FFmpeg.h"
#include "settings/Settings.h"
#include "settings/SettingsComponent.h"
#include "utils/log.h"

extern "C"
{
#include <libavutil/channel_layout.h>
}

#include <cassert>
#include <string.h>

using FFMPEG_HELP_TOOLS::FFMpegErrorToString;
using FFMPEG_HELP_TOOLS::FFMpegException;

CAEEncoderFFmpeg::CAEEncoderFFmpeg() : m_CodecCtx(NULL), m_SwrCtx(NULL)
{
}

CAEEncoderFFmpeg::~CAEEncoderFFmpeg()
{
  Reset();
  swr_free(&m_SwrCtx);
#if LIBAVCODEC_BUILD >= AV_VERSION_INT(59, 37, 100) && \
    LIBAVUTIL_BUILD >= AV_VERSION_INT(57, 28, 100)
  av_channel_layout_uninit(&m_CodecCtx->ch_layout);
#endif
  avcodec_free_context(&m_CodecCtx);
}

bool CAEEncoderFFmpeg::IsCompatible(const AEAudioFormat& format)
{
  if (!m_CodecCtx)
    return false;

  bool match = (
    format.m_dataFormat == m_CurrentFormat.m_dataFormat &&
    format.m_sampleRate == m_CurrentFormat.m_sampleRate
  );

  if (match)
  {
    CAEChannelInfo layout;
    BuildChannelLayout(AV_CH_LAYOUT_5POINT1_BACK, layout); /* hard coded for AC3 & DTS currently */
    match = (m_CurrentFormat.m_channelLayout == layout);
  }

  return match;
}

unsigned int CAEEncoderFFmpeg::BuildChannelLayout(const int64_t ffmap, CAEChannelInfo& layout)
{
  /* build the channel layout and count the channels */
  layout.Reset();
  if (ffmap & AV_CH_FRONT_LEFT           ) layout += AE_CH_FL  ;
  if (ffmap & AV_CH_FRONT_RIGHT          ) layout += AE_CH_FR  ;
  if (ffmap & AV_CH_FRONT_CENTER         ) layout += AE_CH_FC  ;
  if (ffmap & AV_CH_LOW_FREQUENCY        ) layout += AE_CH_LFE ;
  if (ffmap & AV_CH_BACK_LEFT            ) layout += AE_CH_BL  ;
  if (ffmap & AV_CH_BACK_RIGHT           ) layout += AE_CH_BR  ;
  if (ffmap & AV_CH_FRONT_LEFT_OF_CENTER ) layout += AE_CH_FLOC;
  if (ffmap & AV_CH_FRONT_RIGHT_OF_CENTER) layout += AE_CH_FROC;
  if (ffmap & AV_CH_BACK_CENTER          ) layout += AE_CH_BC  ;
  if (ffmap & AV_CH_SIDE_LEFT            ) layout += AE_CH_SL  ;
  if (ffmap & AV_CH_SIDE_RIGHT           ) layout += AE_CH_SR  ;
  if (ffmap & AV_CH_TOP_CENTER           ) layout += AE_CH_TC  ;
  if (ffmap & AV_CH_TOP_FRONT_LEFT       ) layout += AE_CH_TFL ;
  if (ffmap & AV_CH_TOP_FRONT_CENTER     ) layout += AE_CH_TFC ;
  if (ffmap & AV_CH_TOP_FRONT_RIGHT      ) layout += AE_CH_TFR ;
  if (ffmap & AV_CH_TOP_BACK_LEFT        ) layout += AE_CH_TBL ;
  if (ffmap & AV_CH_TOP_BACK_CENTER      ) layout += AE_CH_TBC ;
  if (ffmap & AV_CH_TOP_BACK_RIGHT       ) layout += AE_CH_TBR ;

  return layout.Count();
}

bool CAEEncoderFFmpeg::Initialize(AEAudioFormat &format, bool allow_planar_input)
{
  Reset();

  bool ac3 = CServiceBroker::GetSettingsComponent()->GetSettings()->GetBool(CSettings::SETTING_AUDIOOUTPUT_AC3PASSTHROUGH);

  FFMPEG_FMT_CONST AVCodec* codec = nullptr;

  /* fallback to ac3 if we support it, we might not have DTS support */
  if (ac3)
  {
    m_CodecName = "AC3";
    m_CodecID = AV_CODEC_ID_AC3;
    m_BitRate = AC3_ENCODE_BITRATE;
    codec = avcodec_find_encoder(m_CodecID);
  }

  /* check we got the codec */
  if (!codec)
    return false;

  m_CodecCtx = avcodec_alloc_context3(codec);
  if (!m_CodecCtx)
    return false;

  m_CodecCtx->bit_rate = m_BitRate;
  m_CodecCtx->sample_rate = format.m_sampleRate;
#if LIBAVCODEC_BUILD >= AV_VERSION_INT(59, 37, 100) && \
    LIBAVUTIL_BUILD >= AV_VERSION_INT(57, 28, 100)
  av_channel_layout_uninit(&m_CodecCtx->ch_layout);
  av_channel_layout_from_mask(&m_CodecCtx->ch_layout, AV_CH_LAYOUT_5POINT1_BACK);
#else
  m_CodecCtx->channel_layout = AV_CH_LAYOUT_5POINT1_BACK;
#endif

  /* select a suitable data format */
  if (codec->sample_fmts)
  {
    bool hasFloat  = false;
    bool hasDouble = false;
    bool hasS32 = false;
    bool hasS16 = false;
    bool hasU8 = false;
    bool hasFloatP = false;
    bool hasUnknownFormat = false;

    for(int i = 0; codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; ++i)
    {
      switch (codec->sample_fmts[i])
      {
        case AV_SAMPLE_FMT_FLT: hasFloat  = true; break;
        case AV_SAMPLE_FMT_DBL: hasDouble = true; break;
        case AV_SAMPLE_FMT_S32: hasS32    = true; break;
        case AV_SAMPLE_FMT_S16: hasS16    = true; break;
        case AV_SAMPLE_FMT_U8 : hasU8     = true; break;
        case AV_SAMPLE_FMT_FLTP:
          if (allow_planar_input)
            hasFloatP  = true;
          else
            hasUnknownFormat = true;
          break;
        case AV_SAMPLE_FMT_NONE: return false;
        default: hasUnknownFormat = true; break;
      }
    }

    if (hasFloat)
    {
      m_CodecCtx->sample_fmt = AV_SAMPLE_FMT_FLT;
      format.m_dataFormat = AE_FMT_FLOAT;
    }
    else if (hasFloatP)
    {
      m_CodecCtx->sample_fmt = AV_SAMPLE_FMT_FLTP;
      format.m_dataFormat = AE_FMT_FLOATP;
    }
    else if (hasDouble)
    {
      m_CodecCtx->sample_fmt = AV_SAMPLE_FMT_DBL;
      format.m_dataFormat = AE_FMT_DOUBLE;
    }
    else if (hasS32)
    {
      m_CodecCtx->sample_fmt = AV_SAMPLE_FMT_S32;
      format.m_dataFormat = AE_FMT_S32NE;
    }
    else if (hasS16)
    {
      m_CodecCtx->sample_fmt = AV_SAMPLE_FMT_S16;
      format.m_dataFormat = AE_FMT_S16NE;
    }
    else if (hasU8)
    {
      m_CodecCtx->sample_fmt = AV_SAMPLE_FMT_U8;
      format.m_dataFormat = AE_FMT_U8;
    }
    else if (hasUnknownFormat)
    {
      m_CodecCtx->sample_fmt = codec->sample_fmts[0];
      format.m_dataFormat = AE_FMT_FLOAT;
      m_NeedConversion = true;
      CLog::Log(LOGINFO,
                "CAEEncoderFFmpeg::Initialize - Unknown audio format, it will be resampled.");
    }
    else
    {
      CLog::Log(
          LOGERROR,
          "CAEEncoderFFmpeg::Initialize - Unable to find a suitable data format for the codec ({})",
          m_CodecName);
#if LIBAVCODEC_BUILD >= AV_VERSION_INT(59, 37, 100) && \
    LIBAVUTIL_BUILD >= AV_VERSION_INT(57, 28, 100)
      av_channel_layout_uninit(&m_CodecCtx->ch_layout);
#endif
      avcodec_free_context(&m_CodecCtx);
      return false;
    }
  }

#if LIBAVCODEC_BUILD >= AV_VERSION_INT(59, 37, 100) && \
    LIBAVUTIL_BUILD >= AV_VERSION_INT(57, 28, 100)
  uint64_t mask = m_CodecCtx->ch_layout.u.mask;
  av_channel_layout_uninit(&m_CodecCtx->ch_layout);
  av_channel_layout_from_mask(&m_CodecCtx->ch_layout, mask);
  m_CodecCtx->ch_layout.nb_channels = BuildChannelLayout(mask, m_Layout);
#else
  m_CodecCtx->channels = BuildChannelLayout(m_CodecCtx->channel_layout, m_Layout);
#endif

  /* open the codec */
  if (avcodec_open2(m_CodecCtx, codec, NULL))
  {
#if LIBAVCODEC_BUILD >= AV_VERSION_INT(59, 37, 100) && \
    LIBAVUTIL_BUILD >= AV_VERSION_INT(57, 28, 100)
    av_channel_layout_uninit(&m_CodecCtx->ch_layout);
#endif
    avcodec_free_context(&m_CodecCtx);
    return false;
  }

  format.m_frames = m_CodecCtx->frame_size;
#if LIBAVCODEC_BUILD >= AV_VERSION_INT(59, 37, 100) && \
    LIBAVUTIL_BUILD >= AV_VERSION_INT(57, 28, 100)
  int channels = m_CodecCtx->ch_layout.nb_channels;
#else
  int channels = m_CodecCtx->channels;
#endif
  format.m_frameSize = channels * (CAEUtil::DataFormatToBits(format.m_dataFormat) >> 3);
  format.m_channelLayout = m_Layout;

  m_CurrentFormat = format;
  m_NeededFrames = format.m_frames;
  m_OutputRatio   = (double)m_NeededFrames / m_OutputSize;
  m_SampleRateMul = 1.0 / (double)m_CodecCtx->sample_rate;

  if (m_NeedConversion)
  {
#if LIBSWRESAMPLE_BUILD >= AV_VERSION_INT(4, 7, 100) && \
    LIBAVUTIL_BUILD >= AV_VERSION_INT(57, 28, 100)
    int ret = swr_alloc_set_opts2(&m_SwrCtx, &m_CodecCtx->ch_layout, m_CodecCtx->sample_fmt,
                                  m_CodecCtx->sample_rate, &m_CodecCtx->ch_layout,
                                  AV_SAMPLE_FMT_FLT, m_CodecCtx->sample_rate, 0, NULL);
    if (ret || swr_init(m_SwrCtx) < 0)
#else
    m_SwrCtx = swr_alloc_set_opts(NULL,
                      m_CodecCtx->channel_layout, m_CodecCtx->sample_fmt, m_CodecCtx->sample_rate,
                      m_CodecCtx->channel_layout, AV_SAMPLE_FMT_FLT, m_CodecCtx->sample_rate,
                      0, NULL);
    if (!m_SwrCtx || swr_init(m_SwrCtx) < 0)
#endif
    {
      CLog::Log(LOGERROR, "CAEEncoderFFmpeg::Initialize - Failed to initialise resampler.");
      swr_free(&m_SwrCtx);
#if LIBAVCODEC_BUILD >= AV_VERSION_INT(59, 37, 100) && \
    LIBAVUTIL_BUILD >= AV_VERSION_INT(57, 28, 100)
      av_channel_layout_uninit(&m_CodecCtx->ch_layout);
#endif
      avcodec_free_context(&m_CodecCtx);
      return false;
    }
  }
  CLog::Log(LOGINFO, "CAEEncoderFFmpeg::Initialize - {} encoder ready", m_CodecName);
  return true;
}

void CAEEncoderFFmpeg::Reset()
{
  m_BufferSize = 0;
}

unsigned int CAEEncoderFFmpeg::GetBitRate()
{
  return m_BitRate;
}

AVCodecID CAEEncoderFFmpeg::GetCodecID()
{
  return m_CodecID;
}

unsigned int CAEEncoderFFmpeg::GetFrames()
{
  return m_NeededFrames;
}

int CAEEncoderFFmpeg::Encode(uint8_t *in, int in_size, uint8_t *out, int out_size)
{
  int size = 0;
  int err = AVERROR_UNKNOWN;
  AVFrame* frame = nullptr;
  AVPacket* pkt = nullptr;

  if (!m_CodecCtx)
    return size;

  try
  {
    /* allocate the input frame and output packet
     * sadly, we have to alloc/dealloc it everytime since we have no guarantee the
     * data argument will be constant over iterated calls and the frame needs to
     * setup pointers inside data */
    frame = av_frame_alloc();
    pkt = av_packet_alloc();
    if (!frame || !pkt)
      throw FFMpegException(
          "Failed to allocate \"AVFrame\" or \"AVPacket\" for encoding (error '{}')",
          strerror(errno));

    frame->nb_samples = m_CodecCtx->frame_size;
    frame->format = m_CodecCtx->sample_fmt;
#if LIBAVCODEC_BUILD >= AV_VERSION_INT(59, 37, 100) && \
    LIBAVUTIL_BUILD >= AV_VERSION_INT(57, 28, 100)
    av_channel_layout_uninit(&frame->ch_layout);
    av_channel_layout_copy(&frame->ch_layout, &m_CodecCtx->ch_layout);
    int channelNum = m_CodecCtx->ch_layout.nb_channels;
#else
    frame->channel_layout = m_CodecCtx->channel_layout;
    frame->channels = m_CodecCtx->channels;
    int channelNum = m_CodecCtx->channels;
#endif

    avcodec_fill_audio_frame(frame, channelNum, m_CodecCtx->sample_fmt, in, in_size, 0);

    /* encode it */
    err = avcodec_send_frame(m_CodecCtx, frame);
    if (err < 0)
      throw FFMpegException("Error sending a frame for encoding (error '{}')",
                            FFMpegErrorToString(err));

    err = avcodec_receive_packet(m_CodecCtx, pkt);
    // err < 0 - we cannot cope with it
    // err is EAGAIN or EOF - return to caller as well
    if (err >= 0)
    {
      if (pkt->size <= out_size)
      {
        memset(out, 0, out_size);
        memcpy(out, pkt->data, pkt->size);
        size = pkt->size;
      }
      else
      {
        CLog::LogF(LOGERROR, "Encoded pkt size ({}) is bigger than buffer ({})", pkt->size,
                   out_size);
      }

      av_packet_unref(pkt);
    }
  }
  catch (const FFMpegException& caught)
  {
    CLog::Log(LOGERROR, "CAEEncoderFFmpeg::{} - {}", __func__, caught.what());
  }

#if LIBAVCODEC_BUILD >= AV_VERSION_INT(59, 37, 100) && \
    LIBAVUTIL_BUILD >= AV_VERSION_INT(57, 28, 100)
  av_channel_layout_uninit(&frame->ch_layout);
#endif

  /* free temporary data */
  av_frame_free(&frame);

  /* free the packet */
  av_packet_free(&pkt);

  /* return the number of frames used */
  return size;
}

int CAEEncoderFFmpeg::GetData(uint8_t **data)
{
  int size;
  *data = m_Buffer;
  size = m_BufferSize;
  m_BufferSize = 0;
  return size;
}

double CAEEncoderFFmpeg::GetDelay(unsigned int bufferSize)
{
  if (!m_CodecCtx)
    return 0;

  int frames = m_CodecCtx->delay;
  if (m_BufferSize)
    frames += m_NeededFrames;

  return ((double)frames + ((double)bufferSize * m_OutputRatio)) * m_SampleRateMul;
}