File: Record-Qt.cpp

package info (click to toggle)
kwave 25.04.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 23,272 kB
  • sloc: cpp: 56,173; xml: 817; perl: 688; sh: 57; makefile: 11
file content (546 lines) | stat: -rw-r--r-- 16,160 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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
/*************************************************************************
          Record-Qt.cpp  -  device for audio recording via Qt Multimedia
                             -------------------
    begin                : Sun Mar 20 2016
    copyright            : (C) 2016 by Thomas Eschenbacher
    email                : Thomas.Eschenbacher@gmx.de
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include "config.h"
#ifdef HAVE_QT_AUDIO_SUPPORT

#include <algorithm>
#include <new>

#include <QApplication>
#include <QAudioDevice>
#include <QAudioFormat>
#include <QAudioSource>
#include <QCursor>
#include <QFileInfo>
#include <QIODevice>
#include <QLatin1Char>
#include <QLocale>
#include <QMediaDevices>
#include <QString>
#include <QThread>
#include <QVariant>
#include <QtGlobal>

#include <KLocalizedString>

#include "libkwave/Compression.h"
#include "libkwave/SampleFormat.h"
#include "libkwave/String.h"
#include "libkwave/Utils.h"

#include "Record-Qt.h"

/** gui name of the default device */
#define DEFAULT_DEVICE (i18n("Default device") + _("|sound_note"))

/**
 * factor that determines how much the device device buffer should be larger
 * compared to the buffers used by the record plugin
 */
#define BUFFER_SIZE_OVERCOMMIT 2

//***************************************************************************
Kwave::RecordQt::RecordQt()
    :QObject(nullptr),
     Kwave::RecordDevice(),
     m_lock(),
     m_device_name_map(),
     m_available_devices(),
     m_input(nullptr),
     m_source(nullptr),
     m_sample_format(Kwave::SampleFormat::Unknown),
     m_tracks(0),
     m_rate(0.0),
     m_compression(Kwave::Compression::NONE),
     m_bits_per_sample(0),
     m_device(),
     m_initialized(false)
{
    connect(this, SIGNAL(sigCreateRequested(QAudioFormat&,uint)),
            this, SLOT(createInMainThread(QAudioFormat&,uint)),
            Qt::BlockingQueuedConnection);
    connect(this, SIGNAL(sigCloseRequested()),
            this, SLOT(closeInMainThread()),
            Qt::BlockingQueuedConnection);
}

//***************************************************************************
Kwave::RecordQt::~RecordQt()
{
    close();
}

//***************************************************************************
Kwave::SampleFormat::Format Kwave::RecordQt::sampleFormat()
{
    return m_sample_format;
}

//***************************************************************************
int Kwave::RecordQt::setSampleFormat(Kwave::SampleFormat::Format new_format)
{
    if (m_sample_format == new_format) return 0;
    close();
    m_sample_format = new_format;
    return 0;
}

//***************************************************************************
QList<Kwave::SampleFormat::Format> Kwave::RecordQt::detectSampleFormats()
{
    QList<Kwave::SampleFormat::Format> list;
    QMutexLocker _lock(&m_lock); // context: main thread

    const QAudioDevice info(getDevice(m_device));

    // no devices at all -> empty
    if (info.isNull()) return list;

    // add sample formats compatible with current bit per sample
    auto supported_formats = info.supportedSampleFormats();
    switch (Kwave::toInt(m_bits_per_sample)) {
        case 8:
            if (supported_formats.contains(QAudioFormat::UInt8)) {
                list.append(Kwave::SampleFormat::Unsigned);
            }
            break;
        case 16:
            if (supported_formats.contains(QAudioFormat::Int16)) {
                list.append(Kwave::SampleFormat::Signed);
            }
            break;
        case 32:
            if (supported_formats.contains(QAudioFormat::Int32)) {
                list.append(Kwave::SampleFormat::Signed);
            }
            if (supported_formats.contains(QAudioFormat::Float)) {
                list.append(Kwave::SampleFormat::Float);
            }
            break;
        default:
            break;
    }

    return list;
}

//***************************************************************************
Kwave::byte_order_t Kwave::RecordQt::endianness()
{
    return Kwave::CpuEndian;
}

//***************************************************************************
int Kwave::RecordQt::bitsPerSample()
{
    return m_bits_per_sample;
}

//***************************************************************************
int Kwave::RecordQt::setBitsPerSample(unsigned int new_bits)
{
    if (new_bits == m_bits_per_sample) return 0;

    close();
    m_bits_per_sample = new_bits;
    return 0;
}

//***************************************************************************
QList< unsigned int > Kwave::RecordQt::supportedBits()
{
    QList<unsigned int> list;
    QMutexLocker _lock(&m_lock); // context: main thread

    const QAudioDevice info(getDevice(m_device));

    // no devices at all -> empty
    if (info.isNull()) return list;

    // iterate over all supported bits per sample
    unsigned int bits = 0;
    for (QAudioFormat::SampleFormat format : info.supportedSampleFormats()) {
        switch (format) {
            case QAudioFormat::UInt8:
                bits = 8;
                break;
            case QAudioFormat::Int16:
                bits = 16;
                break;
            case QAudioFormat::Int32:
            case QAudioFormat::Float:
                bits = 32;
                break;
            default:
                bits = 0;
                break;
        }
        if (!list.contains(bits) && (bits > 0))
            list.append(bits);
    }

    std::sort(list.begin(), list.end(), std::less<unsigned int>());
    return list;
}

//***************************************************************************
Kwave::Compression::Type Kwave::RecordQt::compression()
{
    return m_compression;
}

//***************************************************************************
int Kwave::RecordQt::setCompression(Kwave::Compression::Type new_compression)
{
    if (new_compression != m_compression) {
        close();
        m_compression = new_compression;
    }
    return 0;
}

//***************************************************************************
QList<Kwave::Compression::Type> Kwave::RecordQt::detectCompressions()
{
    QList<Kwave::Compression::Type> list;
    list.append(Kwave::Compression::NONE);
    return list;
}

//***************************************************************************
double Kwave::RecordQt::sampleRate()
{
    return m_rate;
}

//***************************************************************************
int Kwave::RecordQt::setSampleRate(double& new_rate)
{
    if (qFuzzyCompare(new_rate, m_rate))  return 0;

    close();
    m_rate = new_rate;
    return 0;
}

//***************************************************************************
QList< double > Kwave::RecordQt::detectSampleRates()
{
    QList<double> list;
    QMutexLocker _lock(&m_lock); // context: main thread

    const QAudioDevice info(getDevice(m_device));

    // no devices at all -> empty
    if (info.isNull()) return list;

    static const int known_rates[] = {
        8000,
        9600,
        11025,
        16000,
        22050,
        24000,
        32000,
        44100,
        48000,
        64000,
        88200,
        96000,
        128000,
        192000
    };

    for (const int rate : known_rates) {
        if (rate < info.minimumSampleRate() || rate > info.maximumSampleRate()) {
            continue;
        }

        QAudioFormat format = info.preferredFormat();
        format.setSampleRate(rate);
        if (info.isFormatSupported(format)) {
            list.append(rate);
        }
    }
    std::sort(list.begin(), list.end(), std::less<double>());
    return list;
}

//***************************************************************************
int Kwave::RecordQt::tracks()
{
    return m_tracks;
}

//***************************************************************************
int Kwave::RecordQt::setTracks(unsigned int &tracks)
{
    if (tracks == m_tracks) return 0;
    if (tracks > 255) tracks = 255;

    close();
    m_tracks = static_cast<quint8>(tracks);
    return 0;
}

//***************************************************************************
int Kwave::RecordQt::detectTracks(unsigned int &min, unsigned int &max)
{
    QMutexLocker _lock(&m_lock); // context: main thread

    const QAudioDevice info(getDevice(m_device));

    min = info.minimumChannelCount();
    max = info.maximumChannelCount();

    return (max > 0) ? max : -1;
}

//***************************************************************************
QAudioDevice Kwave::RecordQt::getDevice(const QString &device) const
{
    // check for default device
    if (!device.length() || (device == DEFAULT_DEVICE))
        return QMediaDevices::defaultAudioInput();

    // check if the device name is known
    if (m_device_name_map.isEmpty() || !m_device_name_map.contains(device))
        return QAudioDevice();

    // translate the path into a Qt audio output device name
    // iterate over all available devices
    const QByteArray dev_id = m_device_name_map[device];
    for (const QAudioDevice &dev : m_available_devices) {
        if (dev.id() == dev_id)
            return QAudioDevice(dev);
    }

    // fallen through: return empty info
    return QAudioDevice();
}

//***************************************************************************
void Kwave::RecordQt::closeInMainThread()
{
    if (m_source) {
        m_source->close();
        m_source = nullptr;
    }
    if (m_input) {
        m_input->stop();
        m_input->reset();
        delete m_input;
        m_input = nullptr;
    }

    m_initialized = false;
}

//***************************************************************************
int Kwave::RecordQt::close()
{
    QMutexLocker _lock(&m_lock);

    if (QThread::currentThread() == qApp->thread())
        closeInMainThread();
    else
        emit sigCloseRequested();

    return 0;
}

//***************************************************************************
int Kwave::RecordQt::read(QByteArray &buffer, unsigned int offset)
{
    if (buffer.isNull() || buffer.isEmpty())
        return 0; // no buffer, nothing to do

    unsigned int buffer_size = static_cast<unsigned int>(buffer.size());

    // we configure our device at a late stage, otherwise we would not
    // know the internal buffer size
    if (!m_initialized) {
        int err = initialize(buffer_size);
        if (err < 0) return -EAGAIN;
        m_initialized = true;
    }
    Q_ASSERT(m_source);
    Q_ASSERT(m_input);
    if (!m_source || !m_input)
        return -ENODEV;

    // adjust the buffer size if is has been changed in the plugin
    if ((buffer_size > 0) && (m_input->bufferSize() != buffer_size))
        m_input->setBufferSize(buffer_size * BUFFER_SIZE_OVERCOMMIT);

    char  *p      = buffer.data()   + offset;
    qint64 len    = buffer.length() - offset;
    qint64 length = m_source->read(p, len);

    return (length < 1) ? -EAGAIN : Kwave::toInt(length);
}

//***************************************************************************
QString Kwave::RecordQt::open(const QString& device)
{

    // close the previous device
    close();

    QMutexLocker _lock(&m_lock);

    // make sure we have a valid list of devices
    scanDevices();

    const QAudioDevice info(getDevice(device));
    if (info.isNull()) {
        return QString::number(ENODEV);
    }

    m_device = device;
    return QString();
}

//***************************************************************************
QStringList Kwave::RecordQt::supportedDevices()
{
    QMutexLocker _lock(&m_lock); // context: main thread

    // re-validate the list if necessary
    if (m_device_name_map.isEmpty() || m_available_devices.isEmpty())
        scanDevices();

    QStringList list = m_device_name_map.keys();

    // move the "default" device to the start of the list
    if (list.contains(DEFAULT_DEVICE))
        list.move(list.indexOf(DEFAULT_DEVICE), 0);

    if (!list.isEmpty()) list.append(_("#TREE#"));

    return list;
}

//***************************************************************************
int Kwave::RecordQt::initialize(unsigned int buffer_size)
{
    // do sanity checks of the current parameters, otherwise Qt crashes
    // with floating point errors or similar
    if (m_rate < 1.0)          return -EINVAL;
    if (m_bits_per_sample < 1) return -EINVAL;
    if (m_tracks < 1)          return -EINVAL;
    if (!m_device.length())    return -EINVAL;

    const QAudioDevice info(getDevice(m_device));

    // find a supported sample format
    QAudioFormat format(info.preferredFormat());
    switch (Kwave::toInt(m_bits_per_sample)) {
        case 8:
            format.setSampleFormat(QAudioFormat::UInt8);
            break;
        case 16:
            format.setSampleFormat(QAudioFormat::Int16);
            break;
        case 32:
            if (format.sampleFormat() == QAudioFormat::Float) {
                break;
            } else {
                format.setSampleFormat(QAudioFormat::Int32);
            }
            break;
        default:
            qWarning("%u bits per sample are not supported",
                     m_bits_per_sample);
            return -EIO;
    }
    format.setChannelCount(Kwave::toInt(m_tracks));
    format.setSampleRate(Kwave::toInt(m_rate));

    if (!format.isValid() || !info.isFormatSupported(format)) {
        qWarning("format not supported");
        return -EIO;
    }


    // create a new Qt output device
    if (QThread::currentThread() == qApp->thread())
        createInMainThread(format, buffer_size);
    else
        emit sigCreateRequested(format, buffer_size);

    return (m_source && m_input) ? 0 : -EAGAIN;
}

//***************************************************************************
void Kwave::RecordQt::createInMainThread(QAudioFormat &format,
                                         unsigned int buffer_size)
{
    QMutexLocker _lock(&m_lock);

    // create a new audio device for the selected format
    m_input = new(std::nothrow) QAudioSource(format, this);
    Q_ASSERT(m_input);
    if (!m_input) return;

    // set the buffer size, before starting to record
    m_input->setBufferSize(buffer_size * BUFFER_SIZE_OVERCOMMIT);

    // start recording engine
    m_source = m_input->start();
}

//***************************************************************************
void Kwave::RecordQt::scanDevices()
{
    m_available_devices.clear();
    m_device_name_map.clear();

    // get the list of available audio output devices from Qt
    for (const QAudioDevice &device : QMediaDevices::audioInputs())
    {
        QByteArray qt_name = device.id();

        // for debugging: list all devices
//      qDebug("    name='%s'", DBG(qt_name));

        // device name not available ?
        if (!qt_name.length()) {
            qWarning("RecordQt::supportedDevices() "
                      "=> BUG: device with no name?");
            continue;
        }

        QString gui_name = device.description() + _("|sound_note");
        if (m_device_name_map.contains(gui_name)) {
            qWarning("RecordQt::supportedDevices() "
            "=> BUG: duplicate device name: '%s'", DBG(gui_name));
            continue;
        }

        m_available_devices.append(device);
        m_device_name_map[gui_name] = qt_name;
    }
}

#endif /* HAVE_QT_AUDIO_SUPPORT */

//***************************************************************************
//***************************************************************************

#include "moc_Record-Qt.cpp"