summaryrefslogtreecommitdiffstats
path: root/src/engine/sidechain/enginerecord.cpp
blob: 8d00f090a2f6818c31f3046d298eaca485678409 (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
403
404
405
406
407
408
409
410
/***************************************************************************
                          enginerecord.cpp  -  class to record the mix
                             -------------------
    copyright            : (C) 2007 by John Sully
    copyright            : (C) 2010 by Tobias Rafreider
    email                :
***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 "engine/sidechain/enginerecord.h"

#include "preferences/usersettings.h"
#include "controlobject.h"
#include "controlobjectslave.h"
#include "encoder/encoder.h"

#ifdef __FFMPEGFILE__
#include "encoder/encoderffmpegmp3.h"
#include "encoder/encoderffmpegvorbis.h"
#else
#include "encoder/encodermp3.h"
#include "encoder/encodervorbis.h"
#endif

#include "errordialoghandler.h"
#include "mixer/playerinfo.h"
#include "recording/defs_recording.h"
#include "util/event.h"

const int kMetaDataLifeTimeout = 16;

EngineRecord::EngineRecord(UserSettingsPointer _config)
        : m_pConfig(_config),
          m_pEncoder(NULL),
          m_pSndfile(NULL),
          m_frames(0),
          m_recordedDuration(0),
          m_iMetaDataLife(0),
          m_cueTrack(0),
          m_bCueIsEnabled(false) {
    m_sfInfo.frames = 0;
    m_sfInfo.samplerate = 0;
    m_sfInfo.channels = 0;
    m_sfInfo.format = 0;
    m_sfInfo.sections = 0;
    m_sfInfo.seekable = 0;

    m_pRecReady = new ControlObjectSlave(RECORDING_PREF_KEY, "status", this);
    m_pSamplerate = new ControlObjectSlave("[Master]", "samplerate", this);
    m_sampleRate = m_pSamplerate->get();
}

EngineRecord::~EngineRecord() {
    closeCueFile();
    closeFile();
    delete m_pRecReady;
    delete m_pSamplerate;
}

void EngineRecord::updateFromPreferences() {
    m_encoding = m_pConfig->getValueString(ConfigKey(RECORDING_PREF_KEY, "Encoding")).toLatin1();
    // returns a number from 1 .. 10
    m_OGGquality = m_pConfig->getValueString(ConfigKey(RECORDING_PREF_KEY, "OGG_Quality")).toLatin1();
    m_MP3quality = m_pConfig->getValueString(ConfigKey(RECORDING_PREF_KEY, "MP3_Quality")).toLatin1();
    m_fileName = m_pConfig->getValueString(ConfigKey(RECORDING_PREF_KEY, "Path"));
    m_baTitle = m_pConfig->getValueString(ConfigKey(RECORDING_PREF_KEY, "Title")).toLatin1();
    m_baAuthor = m_pConfig->getValueString(ConfigKey(RECORDING_PREF_KEY, "Author")).toLatin1();
    m_baAlbum = m_pConfig->getValueString(ConfigKey(RECORDING_PREF_KEY, "Album")).toLatin1();
    m_cueFileName = m_pConfig->getValueString(ConfigKey(RECORDING_PREF_KEY, "CuePath")).toLatin1();
    m_bCueIsEnabled = m_pConfig->getValueString(ConfigKey(RECORDING_PREF_KEY, "CueEnabled")).toInt();
    m_sampleRate = m_pSamplerate->get();

    // Delete m_pEncoder if it has been initialized (with maybe) different bitrate.
    if (m_pEncoder) {
        delete m_pEncoder;
        m_pEncoder = NULL;
    }

    if (m_encoding == ENCODING_MP3) {
#ifdef __FFMPEGFILE__
        m_pEncoder = new EncoderFfmpegMp3(this);
#else
        m_pEncoder = new EncoderMp3(this);
#endif
        m_pEncoder->updateMetaData(m_baAuthor.data(),m_baTitle.data(),m_baAlbum.data());

        if(m_pEncoder->initEncoder(Encoder::convertToBitrate(m_MP3quality.toInt()),
                                   m_sampleRate) < 0) {
            delete m_pEncoder;
            m_pEncoder = NULL;
#ifdef __FFMPEGFILE__
            qDebug() << "MP3 recording is not supported. FFMPEG mp3 could not be initialized";
#else
            qDebug() << "MP3 recording is not supported. Lame could not be initialized";
#endif
        }
    } else if (m_encoding == ENCODING_OGG) {
#ifdef __FFMPEGFILE__
        m_pEncoder = new EncoderFfmpegVorbis(this);
#else
        m_pEncoder = new EncoderVorbis(this);
#endif
        m_pEncoder->updateMetaData(m_baAuthor.data(),m_baTitle.data(),m_baAlbum.data());

        if (m_pEncoder->initEncoder(Encoder::convertToBitrate(m_OGGquality.toInt()),
                                   m_sampleRate) < 0) {
            delete m_pEncoder;
            m_pEncoder = NULL;
#ifdef __FFMPEGFILE__
            qDebug() << "OGG recording is not supported. FFMPEG OGG/Vorbis could not be initialized";
#else
            qDebug() << "OGG recording is not supported. OGG/Vorbis library could not be initialized";
#endif
        }
    }
    // If we use WAVE OR AIFF the encoder will be NULL at all times.
}

bool EngineRecord::metaDataHasChanged()
{
    if (m_iMetaDataLife < kMetaDataLifeTimeout) {
        m_iMetaDataLife++;
        return false;
    }
    m_iMetaDataLife = 0;

    TrackPointer pTrack = PlayerInfo::instance().getCurrentPlayingTrack();
    if (!pTrack)
        return false;

    if (m_pCurrentTrack) {
        if (!pTrack->getId().isValid() || !m_pCurrentTrack->getId().isValid()) {
            if ((pTrack->getArtist() == m_pCurrentTrack->getArtist()) &&
                (pTrack->getTitle() == m_pCurrentTrack->getArtist())) {
                return false;
            }
        }
        else if (pTrack->getId() == m_pCurrentTrack->getId()) {
            return false;
        }
    }

    m_pCurrentTrack = pTrack;
    return true;
}

void EngineRecord::process(const CSAMPLE* pBuffer, const int iBufferSize) {

    float recordingStatus = m_pRecReady->get();

    if (recordingStatus == RECORD_OFF) {
        //qDebug("Setting record flag to: OFF");
        if (fileOpen()) {
            Event::end("EngineRecord recording");
            closeFile();  // Close file and free encoder.
            emit(isRecording(false));
        }
    } else if (recordingStatus == RECORD_READY) {
        // If we are ready for recording, i.e, the output file has been selected, we
        // open a new file.
        updateFromPreferences();  // Update file location from preferences.
        if (openFile()) {
            Event::start("EngineRecord recording");
            qDebug("Setting record flag to: ON");
            m_pRecReady->set(RECORD_ON);
            emit(isRecording(true));  // will notify the RecordingManager

            // Since we just started recording, timeout and clear the metadata.
            m_iMetaDataLife = kMetaDataLifeTimeout;
            m_pCurrentTrack = TrackPointer();

            // clean frames couting and get current sample rate.
            m_frames = 0;
            m_sampleRate = m_pSamplerate->get();

            if (m_bCueIsEnabled) {
                openCueFile();
                m_cueTrack = 0;
            }
        } else {  // Maybe the encoder could not be initialized
            qDebug("Setting record flag to: OFF");
            m_pRecReady->slotSet(RECORD_OFF);
            emit(isRecording(false));
        }
    } else if (recordingStatus == RECORD_ON) {
        // If recording is enabled process audio to compressed or uncompressed data.
        if (m_encoding == ENCODING_WAVE || m_encoding == ENCODING_AIFF) {
            if (m_pSndfile != NULL) {
                sf_write_float(m_pSndfile, pBuffer, iBufferSize);
                emit(bytesRecorded(iBufferSize * 2));
            }
        } else {
            if (m_pEncoder) {
                // Compress audio. Encoder will call method 'write()' below to
                // write a file stream
                m_pEncoder->encodeBuffer(pBuffer, iBufferSize);
            }
        }

        // update frames counting and recorded duration (seconds)
        m_frames += iBufferSize / 2;
        unsigned long lastDuration = m_recordedDuration;
        m_recordedDuration = m_frames / m_sampleRate;

        // gets recorded duration and emit signal that will be used
        // by RecordingManager to update the label besides start/stop button
        if (lastDuration != m_recordedDuration) {
            emit(durationRecorded(getRecordedDurationStr()));
        }

        if (m_bCueIsEnabled) {
            if (metaDataHasChanged()) {
                m_cueTrack++;
                writeCueLine();
                m_cueFile.flush();
            }
        }
    }
}

QString EngineRecord::getRecordedDurationStr() {
    return QString("%1:%2")
                 .arg(m_recordedDuration / 60, 2, 'f', 0, '0')   // minutes
                 .arg(m_recordedDuration % 60, 2, 'f', 0, '0');  // seconds
}

void EngineRecord::writeCueLine() {
    if (!m_pCurrentTrack) {
        return;
    }

    // CDDA is specified as having 75 frames a second
    unsigned long cueFrame = ((unsigned long)
                                ((m_frames / (m_sampleRate / 75)))
                                    % 75);

    m_cueFile.write(QString("  TRACK %1 AUDIO\n")
                    .arg