Add 2009 to copyright and fix its format
[skype-call-recorder.git] / call.cpp
blobc2b02f23f392ea89fe1ab73799927aa287589991
1 /*
2 Skype Call Recorder
3 Copyright 2008 - 2009 by jlh (jlh at gmx dot ch)
5 This program is free software; you can redistribute it and/or modify it
6 under the terms of the GNU General Public License as published by the
7 Free Software Foundation; either version 2 of the License, version 3 of
8 the License, or (at your option) any later version.
10 This program is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 The GNU General Public License version 2 is included with the source of
20 this program under the file name COPYING. You can also get a copy on
21 http://www.fsf.org/
24 #include <QStringList>
25 #include <QList>
26 #include <QTcpServer>
27 #include <QTcpSocket>
28 #include <QMessageBox>
29 #include <cstdlib>
30 #include <cmath>
31 #include <cstring>
33 #include "call.h"
34 #include "common.h"
35 #include "skype.h"
36 #include "wavewriter.h"
37 #include "mp3writer.h"
38 #include "vorbiswriter.h"
39 #include "preferences.h"
40 #include "gui.h"
42 // AutoSync - automatic resynchronization of the two streams. this class has a
43 // circular buffer that keeps track of the delay between the two streams. it
44 // calculates the running average and deviation and then tells if and how much
45 // correction should be applied.
47 AutoSync::AutoSync(int s, long p) :
48 size(s),
49 index(0),
50 sum(0),
51 sum2(0),
52 precision(p),
53 suppress(s)
55 delays = new long[size];
56 std::memset(delays, 0, sizeof(long) * size);
59 AutoSync::~AutoSync() {
60 delete[] delays;
63 void AutoSync::add(long d) {
64 long old = delays[index];
65 sum += d - old;
66 sum2 += (qint64)d * (qint64)d - (qint64)old * (qint64)old;
67 delays[index++] = d;
68 if (index >= size)
69 index = 0;
70 if (suppress)
71 suppress--;
74 long AutoSync::getSync() {
75 if (suppress)
76 return 0;
78 float avg = (float)sum / (float)size;
79 float dev = std::sqrt(((float)sum2 - (float)sum * (float)sum / (float)size) / (float)size);
81 if (std::fabs(avg) > (float)precision && dev < (float)precision)
82 return (long)avg;
84 return 0;
87 void AutoSync::reset() {
88 suppress = size;
91 // Call class
93 Call::Call(QObject *p, Skype *sk, CallID i) :
94 QObject(p),
95 skype(sk),
96 id(i),
97 status("UNKNOWN"),
98 writer(NULL),
99 isRecording(false),
100 shouldRecord(1),
101 sync(100 * 2 * 3, 320) // approx 3 seconds
103 debug(QString("Call %1: Call object contructed").arg(id));
105 // Call objects track calls even before they are in progress and also
106 // when they are not being recorded.
108 // TODO check if we actually should record this call here
109 // and ask if we're unsure
111 skypeName = skype->getObject(QString("CALL %1 PARTNER_HANDLE").arg(id));
112 if (skypeName.isEmpty()) {
113 debug(QString("Call %1: cannot get partner handle").arg(id));
114 skypeName = "UnknownCaller";
117 displayName = skype->getObject(QString("CALL %1 PARTNER_DISPNAME").arg(id));
118 if (displayName.isEmpty()) {
119 debug(QString("Call %1: cannot get partner display name").arg(id));
120 displayName = "Unnamed Caller";
124 Call::~Call() {
125 debug(QString("Call %1: Call object destructed").arg(id));
127 if (isRecording)
128 stopRecording();
130 delete confirmation;
132 setStatus("UNKNOWN");
134 // QT takes care of deleting servers and sockets
137 bool Call::okToDelete() const {
138 // this is used for checking whether past calls may now be deleted.
139 // when a past call hasn't been decided yet whether it should have been
140 // recorded, then it may not be deleted until the decision has been
141 // made by the user.
143 if (isRecording)
144 return false;
146 if (confirmation)
147 /* confirmation dialog still open */
148 return false;
150 return true;
153 bool Call::statusActive() const {
154 return status == "INPROGRESS" ||
155 status == "ONHOLD" ||
156 status == "LOCALHOLD" ||
157 status == "REMOTEHOLD";
160 void Call::setStatus(const QString &s) {
161 bool wasActive = statusActive();
162 status = s;
163 bool nowActive = statusActive();
165 if (!wasActive && nowActive) {
166 emit startedCall(id, skypeName);
167 startRecording();
168 } else if (wasActive && !nowActive) {
169 // don't stop recording when we get "FINISHED". just wait for
170 // the connections to close so that we really get all the data
171 emit stoppedCall(id);
175 bool Call::statusDone() const {
176 return status == "BUSY" ||
177 status == "CANCELLED" ||
178 status == "FAILED" ||
179 status == "FINISHED" ||
180 status == "MISSED" ||
181 status == "REFUSED" ||
182 status == "VM_FAILED";
183 // TODO: see what the deal is with REDIAL_PENDING (protocol 8)
186 QString Call::constructFileName() const {
187 return getFileName(skypeName, displayName, skype->getSkypeName(),
188 skype->getObject("PROFILE FULLNAME"), timeStartRecording);
191 QString Call::constructCommentTag() const {
192 QString str("Skype call between %1%2 and %3%4.");
193 QString dn1, dn2;
194 if (!displayName.isEmpty())
195 dn1 = QString(" (") + displayName + ")";
196 dn2 = skype->getObject("PROFILE FULLNAME");
197 if (!dn2.isEmpty())
198 dn2 = QString(" (") + dn2 + ")";
199 return str.arg(skypeName, dn1, skype->getSkypeName(), dn2);
202 void Call::setShouldRecord() {
203 // this sets shouldRecord based on preferences. shouldRecord is 0 if
204 // the call should not be recorded, 1 if we should ask and 2 if we
205 // should record
207 QStringList list = preferences.get(Pref::AutoRecordYes).toList();
208 if (list.contains(skypeName)) {
209 shouldRecord = 2;
210 return;
213 list = preferences.get(Pref::AutoRecordAsk).toList();
214 if (list.contains(skypeName)) {
215 shouldRecord = 1;
216 return;
219 list = preferences.get(Pref::AutoRecordNo).toList();
220 if (list.contains(skypeName)) {
221 shouldRecord = 0;
222 return;
225 QString def = preferences.get(Pref::AutoRecordDefault).toString();
226 if (def == "yes")
227 shouldRecord = 2;
228 else if (def == "ask")
229 shouldRecord = 1;
230 else if (def == "no")
231 shouldRecord = 0;
232 else
233 shouldRecord = 1;
236 void Call::ask() {
237 confirmation = new RecordConfirmationDialog(skypeName, displayName);
238 connect(confirmation, SIGNAL(yes()), this, SLOT(confirmRecording()));
239 connect(confirmation, SIGNAL(no()), this, SLOT(denyRecording()));
242 void Call::hideConfirmation(int should) {
243 if (confirmation) {
244 delete confirmation;
245 shouldRecord = should;
249 void Call::confirmRecording() {
250 shouldRecord = 2;
251 emit showLegalInformation();
254 void Call::denyRecording() {
255 // note that the call might already be finished by now
256 shouldRecord = 0;
257 stopRecording(true);
258 removeFile();
261 void Call::removeFile() {
262 debug(QString("Removing '%1'").arg(fileName));
263 QFile::remove(fileName);
266 void Call::startRecording(bool force) {
267 if (force)
268 hideConfirmation(2);
270 if (isRecording)
271 return;
273 if (force) {
274 emit showLegalInformation();
275 } else {
276 setShouldRecord();
277 if (shouldRecord == 0)
278 return;
279 if (shouldRecord == 1)
280 ask();
281 else // shouldRecord == 2
282 emit showLegalInformation();
285 debug(QString("Call %1: start recording").arg(id));
287 // set up encoder for appropriate format
289 timeStartRecording = QDateTime::currentDateTime();
290 QString fn = constructFileName();
292 stereo = preferences.get(Pref::OutputStereo).toBool();
293 stereoMix = preferences.get(Pref::OutputStereoMix).toInt();
295 QString format = preferences.get(Pref::OutputFormat).toString();
297 if (format == "wav")
298 writer = new WaveWriter;
299 else if (format == "mp3")
300 writer = new Mp3Writer;
301 else /*if (format == "vorbis")*/
302 writer = new VorbisWriter;
304 if (preferences.get(Pref::OutputSaveTags).toBool())
305 writer->setTags(constructCommentTag(), timeStartRecording);
307 bool b = writer->open(fn, skypeSamplingRate, stereo);
308 fileName = writer->fileName();
310 if (!b) {
311 QMessageBox *box = new QMessageBox(QMessageBox::Critical, PROGRAM_NAME " - Error",
312 QString(PROGRAM_NAME " could not open the file %1. Please verify the output file pattern.").arg(fileName));
313 box->setWindowModality(Qt::NonModal);
314 box->setAttribute(Qt::WA_DeleteOnClose);
315 box->show();
316 removeFile();
317 delete writer;
318 return;
321 serverLocal = new QTcpServer(this);
322 serverLocal->listen();
323 connect(serverLocal, SIGNAL(newConnection()), this, SLOT(acceptLocal()));
324 serverRemote = new QTcpServer(this);
325 serverRemote->listen();
326 connect(serverRemote, SIGNAL(newConnection()), this, SLOT(acceptRemote()));
328 QString rep1 = skype->sendWithReply(QString("ALTER CALL %1 SET_CAPTURE_MIC PORT=\"%2\"").arg(id).arg(serverLocal->serverPort()));
329 QString rep2 = skype->sendWithReply(QString("ALTER CALL %1 SET_OUTPUT SOUNDCARD=\"default\" PORT=\"%2\"").arg(id).arg(serverRemote->serverPort()));
331 if (!rep1.startsWith("ALTER CALL ") || !rep2.startsWith("ALTER CALL")) {
332 QMessageBox *box = new QMessageBox(QMessageBox::Critical, PROGRAM_NAME " - Error",
333 QString(PROGRAM_NAME " could not obtain the audio streams from Skype and can thus not record this call.\n\n"
334 "The replies from Skype were:\n%1\n%2").arg(rep1, rep2));
335 box->setWindowModality(Qt::NonModal);
336 box->setAttribute(Qt::WA_DeleteOnClose);
337 box->show();
338 removeFile();
339 delete writer;
340 delete serverRemote;
341 delete serverLocal;
342 return;
345 if (preferences.get(Pref::DebugWriteSyncFile).toBool()) {
346 syncFile.setFileName(fn + ".sync");
347 syncFile.open(QIODevice::WriteOnly);
348 syncTime.start();
351 isRecording = true;
352 emit startedRecording(id);
355 void Call::acceptLocal() {
356 socketLocal = serverLocal->nextPendingConnection();
357 serverLocal->close();
358 // we don't delete the server, since it contains the socket.
359 // we could reparent, but that automatic stuff of QT is great
360 connect(socketLocal, SIGNAL(readyRead()), this, SLOT(readLocal()));
361 connect(socketLocal, SIGNAL(disconnected()), this, SLOT(checkConnections()));
364 void Call::acceptRemote() {
365 socketRemote = serverRemote->nextPendingConnection();
366 serverRemote->close();
367 connect(socketRemote, SIGNAL(readyRead()), this, SLOT(readRemote()));
368 connect(socketRemote, SIGNAL(disconnected()), this, SLOT(checkConnections()));
371 void Call::readLocal() {
372 bufferLocal += socketLocal->readAll();
373 if (isRecording)
374 tryToWrite();
377 void Call::readRemote() {
378 bufferRemote += socketRemote->readAll();
379 if (isRecording)
380 tryToWrite();
383 void Call::checkConnections() {
384 if (socketLocal->state() == QAbstractSocket::UnconnectedState && socketRemote->state() == QAbstractSocket::UnconnectedState) {
385 debug(QString("Call %1: both connections closed, stop recording").arg(id));
386 stopRecording();
390 void Call::mixToMono(long samples) {
391 qint16 *localData = reinterpret_cast<qint16 *>(bufferLocal.data());
392 qint16 *remoteData = reinterpret_cast<qint16 *>(bufferRemote.data());
394 for (long i = 0; i < samples; i++)
395 localData[i] = ((qint32)localData[i] + (qint32)remoteData[i]) / (qint32)2;
398 void Call::mixToStereo(long samples, int pan) {
399 qint16 *localData = reinterpret_cast<qint16 *>(bufferLocal.data());
400 qint16 *remoteData = reinterpret_cast<qint16 *>(bufferRemote.data());
402 qint32 fl = 100 - pan;
403 qint32 fr = pan;
405 for (long i = 0; i < samples; i++) {
406 qint16 newLocal = ((qint32)localData[i] * fl + (qint32)remoteData[i] * fr + (qint32)50) / (qint32)100;
407 qint16 newRemote = ((qint32)localData[i] * fr + (qint32)remoteData[i] * fl + (qint32)50) / (qint32)100;
408 localData[i] = newLocal;
409 remoteData[i] = newRemote;
413 long Call::padBuffers() {
414 // pads the shorter buffer with silence, so they are both the same
415 // length afterwards. returns the new number of samples in each buffer
417 long l = bufferLocal.size();
418 long r = bufferRemote.size();
420 if (l < r) {
421 long amount = r - l;
422 bufferLocal.append(QByteArray(amount, 0));
423 debug(QString("Call %1: padding %2 samples on local buffer").arg(id).arg(amount / 2));
424 return r / 2;
425 } else if (l > r) {
426 long amount = l - r;
427 bufferRemote.append(QByteArray(amount, 0));
428 debug(QString("Call %1: padding %2 samples on remote buffer").arg(id).arg(amount / 2));
429 return l / 2;
432 return l / 2;
435 void Call::doSync(long s) {
436 if (s > 0) {
437 bufferLocal.append(QByteArray(s * 2, 0));
438 debug(QString("Call %1: padding %2 samples on local buffer").arg(id).arg(s));
439 } else {
440 bufferRemote.append(QByteArray(s * -2, 0));
441 debug(QString("Call %1: padding %2 samples on remote buffer").arg(id).arg(-s));
445 void Call::tryToWrite(bool flush) {
446 //debug(QString("Situation: %3, %4").arg(bufferLocal.size()).arg(bufferRemote.size()));
448 long samples; // number of samples to write
450 if (flush) {
451 // when flushing, we pad the shorter buffer, so that all
452 // available data is written. this shouldn't usually be a
453 // significant amount, but it might be if there was an audio
454 // I/O error in Skype.
455 samples = padBuffers();
456 } else {
457 long l = bufferLocal.size() / 2;
458 long r = bufferRemote.size() / 2;
460 sync.add(r - l);
462 long syncAmount = sync.getSync();
463 syncAmount = (syncAmount / 160) * 160;
465 if (syncAmount) {
466 doSync(syncAmount);
467 sync.reset();
468 l = bufferLocal.size() / 2;
469 r = bufferRemote.size() / 2;
472 if (syncFile.isOpen())
473 syncFile.write(QString("%1 %2 %3\n").arg(syncTime.elapsed()).arg(r - l).arg(syncAmount).toAscii().constData());
475 if (std::labs(r - l) > skypeSamplingRate * 20) {
476 // more than 20 seconds out of sync, something went
477 // wrong. avoid eating memory by accumulating data
478 long s = (r - l) / skypeSamplingRate;
479 debug(QString("Call %1: WARNING: seriously out of sync by %2s; padding").arg(id).arg(s));
480 samples = padBuffers();
481 sync.reset();
482 } else {
483 samples = l < r ? l : r;
485 // skype usually sends new PCM data every 10ms (160
486 // samples at 16kHz). let's accumulate at least 100ms
487 // of data before bothering to write it to disk
488 if (samples < skypeSamplingRate / 10)
489 return;
493 // got new samples to write to file, or have to flush. note that we
494 // have to flush even if samples == 0
496 bool success;
498 if (!stereo) {
499 // mono
500 mixToMono(samples);
501 QByteArray dummy;
502 success = writer->write(bufferLocal, dummy, samples, flush);
503 bufferRemote.remove(0, samples * 2);
504 } else if (stereoMix == 0) {
505 // local left, remote right
506 success = writer->write(bufferLocal, bufferRemote, samples, flush);
507 } else if (stereoMix == 100) {
508 // local right, remote left
509 success = writer->write(bufferRemote, bufferLocal, samples, flush);
510 } else {
511 mixToStereo(samples, stereoMix);
512 success = writer->write(bufferLocal, bufferRemote, samples, flush);
515 if (!success) {
516 QMessageBox *box = new QMessageBox(QMessageBox::Critical, PROGRAM_NAME " - Error",
517 QString(PROGRAM_NAME " encountered an error while writing this call to disk. Recording terminated."));
518 box->setWindowModality(Qt::NonModal);
519 box->setAttribute(Qt::WA_DeleteOnClose);
520 box->show();
521 stopRecording(false);
522 return;
525 // the writer will remove the samples from the buffers
526 //debug(QString("Call %1: wrote %2 samples").arg(id).arg(samples));
528 // TODO: handle the case where the two streams get out of sync (buffers
529 // not equally fulled by a significant amount). does skype document
530 // whether we always get two nice, equal, in-sync streams, even if
531 // there have been transmission errors? perl-script behavior: if out
532 // of sync by more than 6.4ms, then remove 1ms from the stream that's
533 // ahead.
536 void Call::stopRecording(bool flush) {
537 if (!isRecording)
538 return;
540 debug(QString("Call %1: stop recording").arg(id));
542 // NOTE: we don't delete the sockets here, because we may be here as a
543 // reaction to their disconnected() signals; and they don't like being
544 // deleted during their signals. we don't delete the servers either,
545 // since they own the sockets and we're too lazy to reparent. it's
546 // easiest to let QT handle all this on its own. there will be some
547 // memory wasted if you start/stop recording within the same call a few
548 // times, but unless you do it thousands of times, the waste is more
549 // than acceptable.
551 // flush data to writer
552 if (flush)
553 tryToWrite(true);
554 writer->close();
555 delete writer;
557 if (syncFile.isOpen())
558 syncFile.close();
560 // we must disconnect all signals from the sockets first, so that upon
561 // closing them it won't call checkConnections() and we don't land here
562 // recursively again
563 disconnect(socketLocal, 0, this, 0);
564 disconnect(socketRemote, 0, this, 0);
565 socketLocal->close();
566 socketRemote->close();
568 isRecording = false;
569 emit stoppedRecording(id);
572 // ---- CallHandler ----
574 CallHandler::CallHandler(QObject *parent, Skype *s) : QObject(parent), skype(s) {
577 CallHandler::~CallHandler() {
578 prune();
580 QList<Call *> list = calls.values();
581 if (!list.isEmpty()) {
582 debug(QString("Destroying CallHandler, these calls still exist:"));
583 for (int i = 0; i < list.size(); i++) {
584 Call *c = list.at(i);
585 debug(QString(" call %1, status=%2, okToDelete=%3").arg(c->getID()).arg(c->getStatus()).arg(c->okToDelete()));
589 delete legalInformationDialog;
592 void CallHandler::callCmd(const QStringList &args) {
593 CallID id = args.at(0).toInt();
595 if (ignore.contains(id))
596 return;
598 bool newCall = false;
600 Call *call;
602 if (calls.contains(id)) {
603 call = calls[id];
604 } else {
605 call = new Call(this, skype, id);
606 calls[id] = call;
607 newCall = true;
609 connect(call, SIGNAL(startedCall(int, const QString &)), this, SIGNAL(startedCall(int, const QString &)));
610 connect(call, SIGNAL(stoppedCall(int)), this, SIGNAL(stoppedCall(int)));
611 connect(call, SIGNAL(startedRecording(int)), this, SIGNAL(startedRecording(int)));
612 connect(call, SIGNAL(stoppedRecording(int)), this, SIGNAL(stoppedRecording(int)));
613 connect(call, SIGNAL(showLegalInformation()), this, SLOT(showLegalInformation()));
616 QString subCmd = args.at(1);
618 if (subCmd == "STATUS")
619 call->setStatus(args.at(2));
620 else if (newCall && subCmd == "DURATION")
621 // this is where we start recording calls that are already
622 // running, for example if the user starts this program after
623 // the call has been placed
624 call->setStatus("INPROGRESS");
626 prune();
629 void CallHandler::prune() {
630 QList<Call *> list = calls.values();
631 for (int i = 0; i < list.size(); i++) {
632 Call *c = list.at(i);
633 if (c->statusDone() && c->okToDelete()) {
634 // we ignore this call from now on, because Skype might still send
635 // us information about it, like "SEEN" or "VAA_INPUT_STATUS"
636 calls.remove(c->getID());
637 ignore.insert(c->getID());
638 delete c;
643 void CallHandler::startRecording(int id) {
644 if (!calls.contains(id))
645 return;
647 calls[id]->startRecording(true);
650 void CallHandler::stopRecording(int id) {
651 if (!calls.contains(id))
652 return;
654 Call *call = calls[id];
655 call->stopRecording();
656 call->hideConfirmation(2);
659 void CallHandler::stopRecordingAndDelete(int id) {
660 if (!calls.contains(id))
661 return;
663 Call *call = calls[id];
664 call->stopRecording();
665 call->removeFile();
666 call->hideConfirmation(0);
669 void CallHandler::showLegalInformation() {
670 if (preferences.get(Pref::SuppressLegalInformation).toBool())
671 return;
673 if (!legalInformationDialog)
674 legalInformationDialog = new LegalInformationDialog;
676 legalInformationDialog->raise();
677 legalInformationDialog->activateWindow();