summaryrefslogtreecommitdiffstats
path: root/rbutil/rbutilqt/talkfile.cpp
blob: fd6f4a2109fc0f075727e0a7f598ed1da4331f61 (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
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
/***************************************************************************
 *             __________               __   ___.
 *   Open      \______   \ ____   ____ |  | _\_ |__   _______  ___
 *   Source     |       _//  _ \_/ ___\|  |/ /| __ \ /  _ \  \/  /
 *   Jukebox    |    |   (  <_> )  \___|    < | \_\ (  <_> > <  <
 *   Firmware   |____|_  /\____/ \___  >__|_ \|___  /\____/__/\_ \
 *                     \/            \/     \/    \/            \/
 *
 *   Copyright (C) 2007 by Dominik Wenger
 *   $Id$
 *
 * All files in this archive are subject to the GNU General Public License.
 * See the file COPYING in the source tree root for full license agreement.
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 ****************************************************************************/

#include "talkfile.h"

TalkFileCreator::TalkFileCreator(QObject* parent): QObject(parent)
{

}

//! \brief Creates Talkfiles.
//!
//! \param logger A pointer to a Loggerobject
bool TalkFileCreator::createTalkFiles(ProgressloggerInterface* logger)
{
    m_abort = false;
    m_logger = logger;

    QMultiMap<QString,QString> fileList;
    QMultiMap<QString,QString> dirList;
    QStringList toSpeakList, voicedEntries, encodedEntries;
    QString errStr;

    m_logger->addItem(tr("Starting Talk file generation"),LOGINFO);

    //tts
    m_tts = TTSBase::getTTS(this,settings->value(RbSettings::Tts).toString());
    m_tts->setCfg(settings);

    if(!m_tts->start(&errStr))
    {
        m_logger->addItem(errStr.trimmed(),LOGERROR);
        m_logger->addItem(tr("Init of TTS engine failed"),LOGERROR);
        m_logger->abort();
        return false;
    }

    // Encoder
    m_enc = EncBase::getEncoder(this,settings->value(RbSettings::CurEncoder).toString());
    m_enc->setCfg(settings);

    if(!m_enc->start())
    {
        m_logger->addItem(tr("Init of Encoder engine failed"),LOGERROR);
        m_logger->abort();
        m_tts->stop();
        return false;
    }

    QCoreApplication::processEvents();

    connect(logger,SIGNAL(aborted()),this,SLOT(abort()));
    m_logger->setProgressMax(0);

    // read in Maps of paths - file/dirnames
    m_logger->addItem(tr("Reading Filelist..."),LOGINFO);
    if(createDirAndFileMaps(m_dir,&dirList,&fileList) == false)
    {
        m_logger->addItem(tr("Talk file creation aborted"),LOGERROR);
        doAbort(toSpeakList);
        return false;
    }

    // create List of all Files/Dirs to speak
    QMapIterator<QString, QString> dirIt(dirList);
    while (dirIt.hasNext())
    {
        dirIt.next();
        // insert only non dublicate dir entries into list
        if(!toSpeakList.contains(dirIt.value()))
        {
            qDebug() << "toSpeaklist dir:" << dirIt.value();
            toSpeakList.append(dirIt.value());
        }
    }
    QMapIterator<QString, QString> fileIt(fileList);
    while (fileIt.hasNext())
    {
        fileIt.next();
        // insert only non- dublictae file entries into list
        if(!toSpeakList.contains(fileIt.value()))
        {
            if(m_stripExtensions)
                toSpeakList.append(stripExtension(fileIt.value()));
            else
                toSpeakList.append(fileIt.value());
        }
    }

    // Voice entries
    m_logger->addItem(tr("Voicing entries..."),LOGINFO);
    TTSStatus voiceStatus= voiceList(toSpeakList,voicedEntries);
    if(voiceStatus == FatalError)
    {
        doAbort(toSpeakList);
        return false;
    }

    // Encoding Entries
    m_logger->addItem(tr("Encoding files..."),LOGINFO);
    if(encodeList(voicedEntries,encodedEntries) == false)
    {
        doAbort(toSpeakList);
        return false;
    }

    // Copying talk files
    m_logger->addItem(tr("Copying Talkfile for Dirs..."),LOGINFO);
    if(copyTalkDirFiles(dirList,&errStr) == false)
    {
        m_logger->addItem(errStr,LOGERROR);
        doAbort(toSpeakList);
        return false;
    }

    //Copying file talk files
    m_logger->addItem(tr("Copying Talkfile for Files..."),LOGINFO);
    if(copyTalkFileFiles(fileList,&errStr) == false)
    {
        m_logger->addItem(errStr,LOGERROR);
        doAbort(toSpeakList);
        return false;
    }

    // Deleting left overs
    if( !cleanup(toSpeakList))
        return false;

    m_tts->stop();
    m_enc->stop();
    m_logger->addItem(tr("Finished creating Talk files"),LOGOK);
    m_logger->setProgressMax(1);
    m_logger->setProgressValue(1);
    m_logger->abort();

    return true;
}

//! \brief resets the internal progress counter, and sets the Progressbar in the Logger
//!
//! \param max  The maximum to shich the Progressbar is set.
void TalkFileCreator::resetProgress(int max)
{
    m_progress = 0;
    m_logger->setProgressMax(max);
    m_logger->setProgressValue(m_progress);
}

//! \brief Strips everything after and including the last dot in a string. If there is no dot, nothing is changed
//!
//! \param filename The filename from which to strip the Extension
//! \returns the modified string
QString TalkFileCreator::stripExtension(QString filename)
{
    if(filename.lastIndexOf(".") != -1)
        return filename.left(filename.lastIndexOf("."));
    else
        return filename;
}

//! \brief Does needed Tasks when we need to abort. Cleans up Files. Stops the Logger, Stops TTS and Encoder
//!
//! \param cleanupList  List of filenames to give to cleanup()
void TalkFileCreator::doAbort(QStringList cleanupList)
{
    cleanup(cleanupList);
    m_logger->setProgressMax(1);
    m_logger->setProgressValue(0);
    m_logger->abort();
    m_tts->stop();
    m_enc->stop();
}

//! \brief Creates MultiMaps (paths -> File/dir names)  of all Dirs and Files in a Folder.
//!  Depending on settings, either Dirs  or Files can be ignored.
//! Also recursion is controlled by settings
//!
//! \param startDir     The dir where it beginns scanning
//! \param dirMap       The MulitMap where the dirs are stored
//! \param filMap       The MultiMap where Files are stored
//! \returns true on Success, false if User aborted.
bool TalkFileCreator::createDirAndFileMaps(QDir startDir,QMultiMap<QString,QString> *dirMap,QMultiMap<QString,QString> *fileMap)
{
    // create Iterator
    QDirIterator::IteratorFlags flags = QDirIterator::NoIteratorFlags;
    if(m_recursive)
        flags = QDirIterator::Subdirectories;

    QDirIterator it(startDir,flags);

    // read in Maps of paths - file/dirnames
    while (it.hasNext())
    {
        it.next();
        if(m_abort)
        {
            return false;
        }

        QFileInfo fileInf = it.fileInfo();

        // its a dir
        if(fileInf.isDir())
        {
            QDir dir = fileInf.dir();

            // insert into List
            if(!dir.dirName().isEmpty() && m_talkFolders)
            {
                qDebug() << "Dir: " << dir.dirName() << " - " << dir.path();
                dirMap->insert(dir.path(),dir.dirName());
            }
        }
        else  // its a File
        {
            // insert into List
            if( !fileInf.fileName().isEmpty() && !fileInf.fileName().endsWith(".talk") && m_talkFiles)
            {
                qDebug() << "File: " << fileInf.fileName() << " - " << fileInf.path();
                fileMap->insert(fileInf.path(),fileInf.fileName());
            }
        }
        QCoreApplication::processEvents();
    }
    return true;
}

//! \brief Voices a List of string to the temp dir. Progress is handled inside.
//!
//!  \param toSpeak QStringList with the Entries to voice.
//! \param errString pointer to where the Error cause is written
//! \returns true on success, false on error or user abort
TTSStatus TalkFileCreator::voiceList(QStringList toSpeak,QStringList& voicedEntries)
{
    resetProgress(toSpeak.size());
    QStringList errors;

    bool warnings = false;
    for(int i=0; i < toSpeak.size(); i++)
    {
        if(m_abort)
        {
            m_logger->addItem(tr("Talk file creation aborted"), LOGERROR);
            return FatalError;
        }

        QString filename = QDir::tempPath()+ "/"+  toSpeak[i] + ".wav";

        QString error;
        TTSStatus status = m_tts->voice(toSpeak[i],filename, &error);
        if(status == Warning)
        {
            warnings = true;
            m_logger->addItem(tr("Voicing of %1 failed: %2").arg(toSpeak[i]).arg(error),
                    LOGWARNING);
        }
        else if (status == FatalError)
        {
            m_logger->addItem(tr("Voicing of %1 failed: %2").arg(toSpeak[i]).arg(error),
                    LOGERROR);
            return FatalError;
        }
        else
            voicedEntries.append(toSpeak[i]);
        m_logger->setProgressValue(++m_progress);
        QCoreApplication::processEvents();
    }
    if(warnings)
        return Warning;
    else
        return NoError;
}


//! \brief Encodes a List of strings from/to the temp dir. Progress is handled inside.
//! It expects the inputfile in the temp dir with the name in the List appended with ".wav"
//!
//!  \param toSpeak QStringList with the Entries to encode.
//! \param errString pointer to where the Error cause is written
//! \returns true on success, false on error or user abort
bool TalkFileCreator::encodeList(QStringList toEncode,QStringList& encodedEntries)
{
    resetProgress(toEncode.size());
    for(int i=0; i < toEncode.size(); i++)
    {
        if(m_abort)
        {
            m_logger->addItem(tr("Talk file creation aborted"), LOGERROR);
            return false;
        }

        QString wavfilename = QDir::tempPath()+ "/"+   toEncode[i] + ".wav";
        QString filename = QDir::tempPath()+ "/"+  toEncode[i] + ".talk";

        if(!m_enc->encode(wavfilename,filename))
        {
            m_logger->addItem(tr("Encoding of %1 failed").arg(filename), LOGERROR);
            return false;
        }
        encodedEntries.append(toEncode[i]);
        m_logger->setProgressValue(++m_progress);
        QCoreApplication::processEvents();
    }
    return true;
}

//! \brief copys Talkfile for Dirs from the temp dir to the target. Progress and installlog is handled inside
//!
//! \param dirMap   a MultiMap of Paths -> Dirnames
//! \param errString Pointer to a QString where the error cause is written.
//! \returns true on success, false on error or user abort
bool TalkFileCreator::copyTalkDirFiles(QMultiMap<QString,QString> dirMap,QString* errString)
{
    resetProgress(dirMap.size());

    QSettings installlog(m_mountpoint + "/.rockbox/rbutil.log", QSettings::IniFormat, 0);
    installlog.beginGroup("talkfiles");

    QMapIterator<QString, QString> it(dirMap);
    while (it.hasNext())
    {
        it.next();
        if(m_abort)
        {
            *errString = tr("Talk file creation aborted");
            return false;
        }

        QString source = QDir::tempPath()+ "/"+  it.value() + ".talk";

        if(!QFileInfo(source).exists())
            continue; // this file was skipped in one of the previous steps

        QString target = it.key() + "/" + "_dirname.talk";

        // remove target if it exists, and if we should overwrite it
        if(m_overwriteTalk && QFile::exists(target))
            QFile::remove(target);

        // copying
        if(!QFile::copy(source,target))
        {
            *errString = tr("Copying of %1 to %2 failed").arg(source).arg(target);
            return false;
        }

        // add to installlog
        QString now = QDate::currentDate().toString("yyyyMMdd");
        installlog.setValue(target.remove(0,m_mountpoint.length()),now);

        m_logger->setProgressValue(++m_progress);
        QCoreApplication::processEvents();
    }
    installlog.endGroup();
    installlog.sync();
    return true;
}

//! \brief copys Talkfile for Files from the temp dir to the target. Progress and installlog is handled inside
//!
//! \param fileMap   a MultiMap of Paths -> Filenames
//! \param errString Pointer to a QString where the error cause is written.
//! \returns true on success, false on error or user abort
bool TalkFileCreator::copyTalkFileFiles(QMultiMap<QString,QString> fileMap,QString* errString)
{
    resetProgress(fileMap.size());

    QSettings installlog(m_mountpoint + "/.rockbox/rbutil.log", QSettings::IniFormat, 0);
    installlog.beginGroup("talkfiles");

    QMapIterator<QString, QString> it(fileMap);
    while (it.hasNext())
    {
        it.next();
        if(m_abort)
        {
            *errString = tr("Talk file creation aborted");
            return false;
        }

        QString source;
        QString target = it.key() + "/" + it.value() + ".talk";

        // correct source if we hav stripExtension enabled
        if(m_stripExtensions)
            source = QDir::tempPath()+ "/"+ stripExtension(it.value()) + ".talk";
        else
            source = QDir::tempPath()+ "/"+  it.value() + ".talk";

        if(!QFileInfo(source).exists())
            continue; // this file was skipped in one of the previous steps

        // remove target if it exists, and if we should overwrite it
        if(m_overwriteTalk && QFile::exists(target))
            QFile::remove(target);

        // copy file
        qDebug() << "copying: " << source << " to " << target;
        if(!QFile::copy(source,target))
        {
            *errString = tr("Copying of %1 to %2 failed").arg(source).arg(target);
            return false;
        }

        //  add to Install log
        QString now = QDate::currentDate().toString("yyyyMMdd");
        installlog.setValue(target.remove(0,m_mountpoint.length()),now);

        m_logger->setProgressValue(++m_progress);
        QCoreApplication::processEvents();
    }
    installlog.endGroup();
    installlog.sync();
    return true;
}


//! \brief Cleans up Files potentially left in the temp dir
//!
//! \param list List of file to try to delete in the temp dir. Function appends ".wav" and ".talk" to the filenames
bool TalkFileCreator::cleanup(QStringList list)
{
    m_logger->addItem(tr("Cleaning up.."),LOGINFO);

    for(int i=0; i < list.size(); i++)
    {
        if(QFile::exists(QDir::tempPath()+ "/"+  list[i] + ".wav"))
                QFile::remove(QDir::tempPath()+ "/"+  list[i] + ".wav");
        if(QFile::exists(QDir::tempPath()+ "/"+  list[i] + ".talk"))
                QFile::remove(QDir::tempPath()+ "/"+  list[i] + ".talk");

        QCoreApplication::processEvents();
    }
    return true;
}

//! \brief slot, which is connected to the abort of the Logger. Sets a flag, so Creating Talkfiles ends at the next possible position
//!
void TalkFileCreator::abort()
{
    m_abort = true;
}