summaryrefslogtreecommitdiffstats
path: root/src/sources/soundsourceopus.cpp
blob: 50b25610eecd58ee23bf5a845df34e79b7ef73e7 (plain)
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
#include "sources/soundsourceopus.h"

#include <QFileInfo>

#include "audio/streaminfo.h"
#include "util/logger.h"

namespace mixxx {

namespace {

const Logger kLogger("SoundSourceOpus");

// Decoded output of opusfile has a fixed sample rate of 48 kHz (fullband)
constexpr audio::SampleRate kSampleRate = audio::SampleRate(48000);

// http://opus-codec.org
//  - Sample rate 48 kHz (fullband)
//  - Frame sizes from 2.5 ms to 60 ms
//   => Up to 48000 kHz * 0.06 s = 2880 sample frames per data frame
// Prefetching 2 * 2880 sample frames while seeking limits the decoding
// errors to kMaxDecodingError during our tests.
//
// According to the API documentation of op_pcm_seek():
// "...decoding after seeking may not return exactly the same
// values as would be obtained by decoding the stream straight
// through. However, such differences are expected to be smaller
// than the loss introduced by Opus's lossy compression."
// This implementation internally uses prefetching to compensate
// those differences, although not completely. The following
// constant indicates the maximum expected difference for
// testing purposes.
constexpr SINT kNumberOfPrefetchFrames = 2 * 2880;

// Parameter for op_channel_count()
// See also: https://mf4.xiph.org/jenkins/view/opus/job/opusfile-unix/ws/doc/html/group__stream__info.html
constexpr int kCurrentStreamLink = -1; // get ... of the current (stream) link

// Parameter for op_pcm_total() and op_bitrate()
// See also: https://mf4.xiph.org/jenkins/view/opus/job/opusfile-unix/ws/doc/html/group__stream__info.html
constexpr int kEntireStreamLink = -1; // get ... of the whole/entire stream

class OggOpusFileOwner {
  public:
    explicit OggOpusFileOwner(OggOpusFile* pFile)
            : m_pFile(pFile) {
    }
    OggOpusFileOwner(OggOpusFileOwner&&) = delete;
    OggOpusFileOwner(const OggOpusFileOwner&) = delete;
    ~OggOpusFileOwner() {
        if (m_pFile) {
            op_free(m_pFile);
        }
    }
    operator OggOpusFile*() const {
        return m_pFile;
    }
    OggOpusFile* release() {
        OggOpusFile* pFile = m_pFile;
        m_pFile = nullptr;
        return pFile;
    }

  private:
    OggOpusFile* m_pFile;
};

} // anonymous namespace

//static
const QString SoundSourceProviderOpus::kDisplayName = QStringLiteral("Xiph.org libopusfile");

//static
const QStringList SoundSourceProviderOpus::kSupportedFileExtensions = {
        QStringLiteral("opus"),
};

SoundSourceProviderPriority SoundSourceProviderOpus::getPriorityHint(
        const QString& supportedFileExtension) const {
    Q_UNUSED(supportedFileExtension)
    // This reference decoder is supposed to produce more accurate
    // and reliable results than any other DEFAULT provider.
    return SoundSourceProviderPriority::Higher;
}

SoundSourceOpus::SoundSourceOpus(const QUrl& url)
        : SoundSource(url),
          m_pOggOpusFile(nullptr),
          m_curFrameIndex(0) {
}

SoundSourceOpus::~SoundSourceOpus() {
    close();
}

std::pair<MetadataSource::ImportResult, QDateTime>
SoundSourceOpus::importTrackMetadataAndCoverImage(
        TrackMetadata* pTrackMetadata,
        QImage* pCoverArt) const {
    auto const imported =
            SoundSource::importTrackMetadataAndCoverImage(
                    pTrackMetadata, pCoverArt);
    if (imported.first == ImportResult::Succeeded) {
        // Done if the default implementation in the base class
        // supports Opus files.
        return imported;
    }

    // Beginning with version 1.9.0 TagLib supports the Opus format.
    // Until this becomes the minimum version required by Mixxx tags
    // in .opus files must also be parsed using opusfile. The following
    // code should removed as soon as it is no longer needed!
    //
    // NOTE(uklotzde): The following code has been found in SoundSourceOpus
    // and will not be improved. We are aware of its shortcomings like
    // the lack of proper error handling.

    // From opus/opusfile.h
    // On Windows, this string must be UTF-8 (to allow access to
    // files whose names cannot be represented in the current
    // MBCS code page).
    // All other systems use the native character encoding.
#ifdef _WIN32
    QByteArray qBAFilename = getLocalFileName().toUtf8();
#else
    QByteArray qBAFilename = QFile::encodeName(getLocalFileName());
#endif

    int errorCode = 0;
    OggOpusFileOwner pOggOpusFile(
            op_open_file(qBAFilename.constData(), &errorCode));
    if (!pOggOpusFile || (errorCode != 0)) {
        kLogger.warning()
                << "Opening of OggOpusFile failed with error"
                << errorCode
                << ":"
                << getLocalFileName();
        // We couldn't do any better , so just return the (unsuccessful)
        // result from the base class.
        return imported;
    }

    // Cast to double is required for duration with sub-second precision
    const double dTotalFrames = op_pcm_total(pOggOpusFile, -1);
    const auto duration = Duration::fromMicros(
            static_cast<qint64>(1000000 * dTotalFrames / kSampleRate));
    pTrackMetadata->setStreamInfo(audio::StreamInfo{
            audio::SignalInfo{
                    audio::ChannelCount(op_channel_count(pOggOpusFile, -1)),
                    kSampleRate,
            },
            audio::Bitrate(op_bitrate(pOggOpusFile, -1) / 1000),
            duration,
    });

#ifndef TAGLIB_HAS_OPUSFILE
    const OpusTags* l_ptrOpusTags = op_tags(pOggOpusFile, -1);
    bool hasDate = false;
    for (int i = 0; i < l_ptrOpusTags->comments; ++i) {
        QString l_SWholeTag = QString(l_ptrOpusTags->user_comments[i]);
        QString l_STag = l_SWholeTag.left(l_SWholeTag.indexOf("="));
        QString l_SPayload = l_SWholeTag.right((l_SWholeTag.length() - l_SWholeTag.indexOf("=")) - 1);

        if (!l_STag.compare("ARTIST")) {
            pTrackMetadata->refTrackInfo().setArtist(l_SPayload);
        } else if (!l_STag.compare("ALBUM")) {
            pTrackMetadata->refAlbumInfo().setTitle(l_SPayload);
        } else if (!l_STag.compare("BPM")) {
            pTrackMetadata->refTrackInfo().setBpm(Bpm(l_SPayload.toDouble()));
        } else if (!l_STag.compare("DATE")) {
            // Prefer "DATE" over "YEAR"
            pTrackMetadata->refTrackInfo().setYear(l_SPayload.trimmed());
            // Avoid to overwrite "DATE" with "YEAR"
            hasDate |= !pTrackMetadata->getTrackInfo().getYear().isEmpty();
        } else if (!hasDate && !l_STag.compare("YEAR")) {
            pTrackMetadata->refTrackInfo().setYear(l_SPayload.trimmed());
        } else if (!l_STag.compare("GENRE")) {
            pTrackMetadata->refTrackInfo().setGenre(l_SPayload);
        } else if (!l_STag.compare("TRACKNUMBER")) {
            pTrackMetadata->refTrackInfo().setTrackNumber(l_SPayload);
        } else if (!l_STag.compare("COMPOSER")) {
            pTrackMetadata->refTrackInfo().setComposer(l_SPayload);
        } else if (!l_STag.compare("ALBUMARTIST")) {
            pTrackMetadata->refAlbumInfo().setArtist(l_SPayload);
        } else if (!l_STag.compare("TITLE")) {
            pTrackMetadata->refTrackInfo().setTitle(l_SPayload);
        } else if (!l_STag.compare("REPLAYGAIN_TRACK_GAIN")) {
            bool gainRatioValid = false;
            double gainRatio = ReplayGain::ratioFromString(l_SPayload, &gainRatioValid);
            if (gainRatioValid) {
                ReplayGain trackGain(pTrackMetadata->getTrackInfo().getReplayGain());
                trackGain.setRatio(gainRatio);
                pTrackMetadata->refTrackInfo().setReplayGain(trackGain);
            }
        } else if (!l_STag.compare("REPLAYGAIN_ALBUM_GAIN")) {
            bool gainRatioValid = false;
            double gainRatio = ReplayGain::ratioFromString(l_SPayload, &gainRatioValid);
            if (gainRatioValid) {
                ReplayGain albumGain(pTrackMetadata->getAlbumInfo().getReplayGain());
                albumGain.setRatio(gainRatio);
                pTrackMetadata->refAlbumInfo().setReplayGain(albumGain);
            }
        }
    }
#endif // TAGLIB_HAS_OPUSFILE

    return std::make_pair(
            ImportResult::Succeeded,
            QFileInfo(getLocalFileName()).lastModified());
}

SoundSource::OpenResult SoundSourceOpus::tryOpen(
        OpenMode /*mode*/,
        const OpenParams& params) {
    // From opus/opusfile.h
    // On Windows, this string must be UTF-8 (to allow access to
    // files whose names cannot be represented in the current
    // MBCS code page).
    // All other systems use the native character encoding.
#ifdef _WIN32
    QByteArray qBAFilename = getLocalFileName().toUtf8();
#else
    QByteArray qBAFilename = QFile::encodeName(getLocalFileName());
#endif

    int errorCode = 0;
    OggOpusFileOwner pOggOpusFile(
            op_open_file(qBAFilename.constData(), &errorCode));
    if (!pOggOpusFile || (errorCode != 0)) {
        kLogger.warning()
                << "Opening of OggOpusFile failed with error"
                << errorCode
                << ":"
                << getLocalFileName();
        return OpenResult::Failed;
    }
    if (!op_seekable(pOggOpusFile)) {
        kLogger.warning()
                << "Stream in"
                << getUrlString()
                << "is not