-
Notifications
You must be signed in to change notification settings - Fork 341
/
mythraopconnection.cpp
1794 lines (1595 loc) · 55.4 KB
/
mythraopconnection.cpp
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <QTcpSocket>
#include <QTextStream>
#include <QTimer>
#include <QtEndian>
#include <utility>
#include "mythlogging.h"
#include "mythcorecontext.h"
#include "mythdirs.h"
#include "serverpool.h"
#include "audiooutput.h"
#include "audiooutpututil.h"
#include "mythraopdevice.h"
#include "mythraopconnection.h"
#include "mythairplayserver.h"
#include "mythmainwindow.h"
#include <unistd.h> // for usleep()
#define LOC QString("RAOP Conn: ")
#define MAX_PACKET_SIZE 2048
RSA *MythRAOPConnection::g_rsa = nullptr;
QString MythRAOPConnection::g_rsaLastError;
// RAOP RTP packet type
#define TIMING_REQUEST 0x52
#define TIMING_RESPONSE 0x53
#define SYNC 0x54
#define FIRSTSYNC (0x54 | 0x80)
#define RANGE_RESEND 0x55
#define AUDIO_RESEND 0x56
#define AUDIO_DATA 0x60
#define FIRSTAUDIO_DATA (0x60 | 0x80)
// Size (in ms) of audio buffered in audio card
#define AUDIOCARD_BUFFER 500
// How frequently we may call ProcessAudio (via QTimer)
// ideally 20ms, but according to documentation
// anything lower than 50ms on windows, isn't reliable
#define AUDIO_BUFFER 100
class RaopNetStream : public QTextStream
{
public:
explicit RaopNetStream(QIODevice *device) : QTextStream(device)
{
};
RaopNetStream &operator<<(const QString &str)
{
LOG(VB_PLAYBACK, LOG_DEBUG,
LOC + QString("Sending(%1): ").arg(str.length()) + str);
QTextStream *q = this;
*q << str;
return *this;
};
};
MythRAOPConnection::MythRAOPConnection(QObject *parent, QTcpSocket *socket,
QByteArray id, int port)
: QObject(parent),
m_socket(socket),
m_hardwareId(std::move(id)),
m_dataPort(port)
{
m_id = GetNotificationCenter()->Register(this);
memset(&m_aesKey, 0, sizeof(m_aesKey));
}
MythRAOPConnection::~MythRAOPConnection()
{
CleanUp();
for (QTcpSocket *client : qAsConst(m_eventClients))
{
client->close();
client->deleteLater();
}
m_eventClients.clear();
if (m_eventServer)
{
m_eventServer->disconnect();
m_eventServer->close();
m_eventServer->deleteLater();
m_eventServer = nullptr;
}
// delete main socket
if (m_socket)
{
m_socket->disconnect();
m_socket->close();
m_socket->deleteLater();
m_socket = nullptr;
}
if (m_textStream)
{
delete m_textStream;
m_textStream = nullptr;
}
if (m_id > 0)
{
GetNotificationCenter()->UnRegister(this, m_id);
}
}
void MythRAOPConnection::CleanUp(void)
{
// delete audio timer
StopAudioTimer();
// stop and delete watchdog timer
if (m_watchdogTimer)
{
m_watchdogTimer->stop();
delete m_watchdogTimer;
m_watchdogTimer = nullptr;
}
if (m_dequeueAudioTimer)
{
m_dequeueAudioTimer->stop();
delete m_dequeueAudioTimer;
m_dequeueAudioTimer = nullptr;
}
if (m_clientTimingSocket)
{
m_clientTimingSocket->disconnect();
m_clientTimingSocket->close();
delete m_clientTimingSocket;
m_clientTimingSocket = nullptr;
}
// delete data socket
if (m_dataSocket)
{
m_dataSocket->disconnect();
m_dataSocket->close();
m_dataSocket->deleteLater();
m_dataSocket = nullptr;
}
// client control socket
if (m_clientControlSocket)
{
m_clientControlSocket->disconnect();
m_clientControlSocket->close();
m_clientControlSocket->deleteLater();
m_clientControlSocket = nullptr;
}
// close audio decoder
DestroyDecoder();
// free decoded audio buffer
ResetAudio();
// close audio device
CloseAudioDevice();
// Tell listeners we're done
if (m_playbackStarted)
{
gCoreContext->emitTVPlaybackStopped();
}
}
bool MythRAOPConnection::Init(void)
{
// connect up the request socket
m_textStream = new RaopNetStream(m_socket);
m_textStream->setCodec("UTF-8");
if (!connect(m_socket, SIGNAL(readyRead()), this, SLOT(readClient())))
{
LOG(VB_PLAYBACK, LOG_ERR, LOC + "Failed to connect client socket signal.");
return false;
}
// create the data socket
m_dataSocket = new ServerPool();
if (!connect(m_dataSocket, SIGNAL(newDatagram(QByteArray, QHostAddress, quint16)),
this, SLOT(udpDataReady(QByteArray, QHostAddress, quint16))))
{
LOG(VB_PLAYBACK, LOG_ERR, LOC + "Failed to connect data socket signal.");
return false;
}
// try a few ports in case the first is in use
m_dataPort = m_dataSocket->tryBindingPort(m_dataPort, RAOP_PORT_RANGE);
if (m_dataPort < 0)
{
LOG(VB_PLAYBACK, LOG_ERR, LOC + "Failed to bind to a port for data.");
return false;
}
LOG(VB_PLAYBACK, LOG_INFO, LOC +
QString("Bound to port %1 for incoming data").arg(m_dataPort));
// load the private key
if (!LoadKey())
return false;
// use internal volume control
m_allowVolumeControl = gCoreContext->GetBoolSetting("MythControlsVolume", true);
// start the watchdog timer to auto delete the client after a period of inactivity
m_watchdogTimer = new QTimer();
connect(m_watchdogTimer, SIGNAL(timeout()), this, SLOT(timeout()));
m_watchdogTimer->start(10000);
m_dequeueAudioTimer = new QTimer();
connect(m_dequeueAudioTimer, SIGNAL(timeout()), this, SLOT(ProcessAudio()));
return true;
}
/**
* Socket incoming data signal handler
* use for audio, control and timing socket
*/
void MythRAOPConnection::udpDataReady(QByteArray buf, const QHostAddress& /*peer*/,
quint16 /*port*/)
{
// restart the idle timer
if (m_watchdogTimer)
m_watchdogTimer->start(10000);
if (!m_audio || !m_codec || !m_codecContext)
return;
uint8_t type = 0;
uint16_t seq = 0;
uint64_t timestamp = 0;
if (!GetPacketType(buf, type, seq, timestamp))
{
LOG(VB_PLAYBACK, LOG_DEBUG, LOC +
QString("Packet doesn't start with valid Rtp Header (0x%1)")
.arg((uint8_t)buf[0], 0, 16));
return;
}
switch (type)
{
case SYNC:
case FIRSTSYNC:
ProcessSync(buf);
ProcessAudio();
return;
case FIRSTAUDIO_DATA:
m_nextSequence = seq;
m_nextTimestamp = timestamp;
// With iTunes we know what the first sequence is going to be.
// iOS device do not tell us before streaming start what the first
// packet is going to be.
m_streamingStarted = true;
break;
case AUDIO_DATA:
case AUDIO_RESEND:
break;
case TIMING_RESPONSE:
ProcessTimeResponse(buf);
return;
default:
LOG(VB_PLAYBACK, LOG_DEBUG, LOC +
QString("Packet type (0x%1) not handled")
.arg(type, 0, 16));
return;
}
timestamp = framesToMs(timestamp);
if (timestamp < m_currentTimestamp)
{
LOG(VB_PLAYBACK, LOG_DEBUG, LOC +
QString("Received packet %1 too late, ignoring")
.arg(seq));
return;
}
// regular data packet
if (type == AUDIO_DATA || type == FIRSTAUDIO_DATA)
{
if (m_streamingStarted && seq != m_nextSequence)
SendResendRequest(timestamp, m_nextSequence, seq);
m_nextSequence = seq + 1;
m_nextTimestamp = timestamp;
m_streamingStarted = true;
}
if (!m_streamingStarted)
return;
// resent packet
if (type == AUDIO_RESEND)
{
if (m_resends.contains(seq))
{
LOG(VB_PLAYBACK, LOG_DEBUG, LOC +
QString("Received required resend %1 (with ts:%2 last:%3)")
.arg(seq).arg(timestamp).arg(m_nextSequence));
m_resends.remove(seq);
}
else
{
LOG(VB_PLAYBACK, LOG_WARNING, LOC +
QString("Received unexpected resent packet %1")
.arg(seq));
}
}
// Check that the audio packet is valid, do so by decoding it. If an error
// occurs, ask to resend it
auto *decoded = new QList<AudioData>();
int numframes = decodeAudioPacket(type, &buf, decoded);
if (numframes < 0)
{
// an error occurred, ask for the audio packet once again.
LOG(VB_PLAYBACK, LOG_ERR, LOC + QString("Error decoding audio"));
SendResendRequest(timestamp, seq, seq+1);
delete decoded;
return;
}
AudioPacket frames { seq, decoded };
m_audioQueue.insert(timestamp, frames);
ProcessAudio();
}
void MythRAOPConnection::ProcessSync(const QByteArray &buf)
{
bool first = (uint8_t)buf[0] == 0x90; // First sync is 0x90,0x55
const char *req = buf.constData();
uint64_t current_ts = qFromBigEndian(*(uint32_t *)(req + 4));
uint64_t next_ts = qFromBigEndian(*(uint32_t *)(req + 16));
uint64_t current = framesToMs(current_ts);
uint64_t next = framesToMs(next_ts);
m_currentTimestamp = current;
m_nextTimestamp = next;
m_bufferLength = m_nextTimestamp - m_currentTimestamp;
if (current_ts > m_progressStart)
{
m_progressCurrent = next_ts;
SendNotification(true);
}
if (first)
{
LOG(VB_PLAYBACK, LOG_DEBUG, LOC + QString("Receiving first SYNC packet"));
}
else
{
LOG(VB_PLAYBACK, LOG_DEBUG, LOC + QString("Receiving SYNC packet"));
}
timeval t {};
gettimeofday(&t, nullptr);
m_timeLastSync = t.tv_sec * 1000 + t.tv_usec / 1000;
LOG(VB_PLAYBACK, LOG_DEBUG, LOC + QString("SYNC: cur:%1 next:%2 time:%3")
.arg(m_currentTimestamp).arg(m_nextTimestamp).arg(m_timeLastSync));
int64_t delay = framesToMs((uint64_t)m_audioQueue.size() * m_framesPerPacket);
int64_t audiots = m_audio->GetAudiotime();
int64_t currentLatency = 0LL;
if (m_audioStarted)
{
currentLatency = audiots - (int64_t)m_currentTimestamp;
}
LOG(VB_PLAYBACK, LOG_DEBUG, LOC +
QString("RAOP timestamps: about to play:%1 desired:%2 latency:%3")
.arg(audiots).arg(m_currentTimestamp)
.arg(currentLatency));
delay += m_audio->GetAudioBufferedTime();
delay += currentLatency;
LOG(VB_PLAYBACK, LOG_DEBUG, LOC +
QString("Queue=%1 buffer=%2ms ideal=%3ms diffts:%4ms")
.arg(m_audioQueue.size())
.arg(delay)
.arg(m_bufferLength)
.arg(m_bufferLength-delay));
if (m_adjustedLatency <= 0 && m_audioStarted &&
(-currentLatency > AUDIOCARD_BUFFER))
{
// Too much delay in playback.
// The threshold is a value chosen to be loose enough so it doesn't
// trigger too often, but should be low enough to detect any accidental
// interruptions.
// Will drop some frames in next ProcessAudio
LOG(VB_PLAYBACK, LOG_DEBUG, LOC +
QString("Too much delay (%1ms), adjusting")
.arg(m_bufferLength - delay));
m_adjustedLatency = m_cardLatency + m_networkLatency;
// Expire old audio
ExpireResendRequests(m_currentTimestamp - m_adjustedLatency);
int res = ExpireAudio(m_currentTimestamp - m_adjustedLatency);
if (res > 0)
{
LOG(VB_PLAYBACK, LOG_DEBUG, LOC + QString("Drop %1 packets").arg(res));
}
m_audioStarted = false;
}
}
/**
* SendResendRequest:
* Request RAOP client to resend missed RTP packets
*/
void MythRAOPConnection::SendResendRequest(uint64_t timestamp,
uint16_t expected, uint16_t got)
{
if (!m_clientControlSocket)
return;
int16_t missed = (got < expected) ?
(int16_t)(((int32_t)got + UINT16_MAX + 1) - expected) :
got - expected;
LOG(VB_PLAYBACK, LOG_INFO, LOC +
QString("Missed %1 packet(s): expected %2 got %3 ts:%4")
.arg(missed).arg(expected).arg(got).arg(timestamp));
std::array<uint8_t,8> req { 0x80, RANGE_RESEND | 0x80};
*(uint16_t *)(&req[2]) = qToBigEndian(m_seqNum++);
*(uint16_t *)(&req[4]) = qToBigEndian(expected); // missed seqnum
*(uint16_t *)(&req[6]) = qToBigEndian(missed); // count
if (m_clientControlSocket->writeDatagram((char *)req.data(), req.size(),
m_peerAddress, m_clientControlPort)
== (qint64)req.size())
{
for (uint16_t count = 0; count < missed; count++)
{
LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("Sent resend for %1")
.arg(expected + count));
m_resends.insert(expected + count, timestamp);
}
}
else
LOG(VB_PLAYBACK, LOG_ERR, LOC + "Failed to send resend request.");
}
/**
* ExpireResendRequests:
* Expire resend requests that are older than timestamp. Those requests are
* expired when audio with older timestamp has already been played
*/
void MythRAOPConnection::ExpireResendRequests(uint64_t timestamp)
{
if (m_resends.isEmpty())
return;
QMutableMapIterator<uint16_t,uint64_t> it(m_resends);
while (it.hasNext())
{
it.next();
if (it.value() < timestamp && m_streamingStarted)
{
LOG(VB_PLAYBACK, LOG_WARNING, LOC +
QString("Never received resend packet %1").arg(it.key()));
m_resends.remove(it.key());
}
}
}
/**
* SendTimeRequest:
* Send a time request to the RAOP client.
*/
void MythRAOPConnection::SendTimeRequest(void)
{
if (!m_clientControlSocket) // should never happen
return;
timeval t {};
gettimeofday(&t, nullptr);
std::array<uint8_t,32> req {
0x80, TIMING_REQUEST | 0x80,
// this is always 0x00 0x07 according to http://blog.technologeek.org/airtunes-v2
// no other value works
0x00, 0x07
};
*(uint32_t *)(&req[24]) = qToBigEndian((uint32_t)t.tv_sec);
*(uint32_t *)(&req[28]) = qToBigEndian((uint32_t)t.tv_usec);
if (m_clientTimingSocket->writeDatagram((char *)req.data(), req.size(), m_peerAddress,
m_clientTimingPort) != (qint64)req.size())
{
LOG(VB_PLAYBACK, LOG_ERR, LOC + "Failed to send resend time request.");
return;
}
LOG(VB_PLAYBACK, LOG_DEBUG, LOC +
QString("Requesting master time (Local %1.%2)")
.arg(t.tv_sec).arg(t.tv_usec));
}
/**
* ProcessTimeResponse:
* Calculate the network latency, we do not use the reference time send by itunes
* instead we measure the time lapsed between the request and the response
* the latency is calculated in ms
*/
void MythRAOPConnection::ProcessTimeResponse(const QByteArray &buf)
{
timeval t1 {};
timeval t2 {};
const char *req = buf.constData();
t1.tv_sec = qFromBigEndian(*(uint32_t *)(req + 8));
t1.tv_usec = qFromBigEndian(*(uint32_t *)(req + 12));
gettimeofday(&t2, nullptr);
uint64_t time1 = t1.tv_sec * 1000 + t1.tv_usec / 1000;
uint64_t time2 = t2.tv_sec * 1000 + t2.tv_usec / 1000;
LOG(VB_PLAYBACK, LOG_DEBUG, LOC + QString("Read back time (Local %1.%2)")
.arg(t1.tv_sec).arg(t1.tv_usec));
// network latency equal time difference in ms between request and response
// divide by two for approximate time of one way trip
m_networkLatency = (time2 - time1) / 2;
LOG(VB_AUDIO, LOG_DEBUG, LOC + QString("Network Latency: %1ms")
.arg(m_networkLatency));
// now calculate the time difference between the client and us.
// this is NTP time, where sec is in seconds, and ticks is in 1/2^32s
uint32_t sec = qFromBigEndian(*(uint32_t *)(req + 24));
uint32_t ticks = qFromBigEndian(*(uint32_t *)(req + 28));
// convert ticks into ms
int64_t master = NTPToLocal(sec, ticks);
m_clockSkew = master - time2;
}
uint64_t MythRAOPConnection::NTPToLocal(uint32_t sec, uint32_t ticks)
{
return (int64_t)sec * 1000LL + (((int64_t)ticks * 1000LL) >> 32);
}
bool MythRAOPConnection::GetPacketType(const QByteArray &buf, uint8_t &type,
uint16_t &seq, uint64_t ×tamp)
{
// All RAOP packets start with | 0x80/0x90 (first sync) | PACKET_TYPE |
if ((uint8_t)buf[0] != 0x80 && (uint8_t)buf[0] != 0x90)
{
return false;
}
type = buf[1];
// Is it first sync packet?
if ((uint8_t)buf[0] == 0x90 && type == FIRSTSYNC)
{
return true;
}
if (type != FIRSTAUDIO_DATA)
{
type &= ~0x80;
}
if (type != AUDIO_DATA && type != FIRSTAUDIO_DATA && type != AUDIO_RESEND)
return true;
const char *ptr = buf.constData();
if (type == AUDIO_RESEND)
{
ptr += 4;
}
seq = qFromBigEndian(*(uint16_t *)(ptr + 2));
timestamp = qFromBigEndian(*(uint32_t *)(ptr + 4));
return true;
}
// Audio decode / playback related routines
uint32_t MythRAOPConnection::decodeAudioPacket(uint8_t type,
const QByteArray *buf,
QList<AudioData> *dest)
{
const char *data_in = buf->constData();
int len = buf->size();
if (type == AUDIO_RESEND)
{
data_in += 4;
len -= 4;
}
data_in += 12;
len -= 12;
if (len < 16)
return -1;
int aeslen = len & ~0xf;
std::array<uint8_t,16> iv {};
std::array<uint8_t,MAX_PACKET_SIZE> decrypted_data {};
std::copy(m_aesIV.cbegin(), m_aesIV.cbegin() + iv.size(), iv.data());
AES_cbc_encrypt((const unsigned char *)data_in,
decrypted_data.data(), aeslen,
&m_aesKey, iv.data(), AES_DECRYPT);
std::copy(data_in + aeslen, data_in + len - aeslen,
decrypted_data.data() + aeslen);
AVPacket tmp_pkt;
AVCodecContext *ctx = m_codecContext;
av_init_packet(&tmp_pkt);
tmp_pkt.data = decrypted_data.data();
tmp_pkt.size = len;
uint32_t frames_added = 0;
auto *samples = (uint8_t *)av_mallocz(AudioOutput::kMaxSizeBuffer);
while (tmp_pkt.size > 0)
{
int data_size = 0;
int ret = AudioOutputUtil::DecodeAudio(ctx, samples,
data_size, &tmp_pkt);
if (ret < 0)
{
av_free(samples);
return -1;
}
if (data_size)
{
int num_samples = data_size /
(ctx->channels * av_get_bytes_per_sample(ctx->sample_fmt));
frames_added += num_samples;
AudioData block {samples, data_size, num_samples};
dest->append(block);
}
tmp_pkt.data += ret;
tmp_pkt.size -= ret;
}
return frames_added;
}
void MythRAOPConnection::ProcessAudio()
{
if (!m_streamingStarted || !m_audio)
return;
if (m_audio->IsPaused())
{
// ALSA takes a while to unpause, enough to have SYNC starting to drop
// packets, so unpause as early as possible
m_audio->Pause(false);
}
timeval t {};
gettimeofday(&t, nullptr);
uint64_t dtime = (t.tv_sec * 1000 + t.tv_usec / 1000) - m_timeLastSync;
uint64_t rtp = dtime + m_currentTimestamp;
uint64_t buffered = m_audioStarted ? m_audio->GetAudioBufferedTime() : 0;
// Keep audio framework buffer as short as possible, keeping everything in
// m_audioQueue, so we can easily reset the least amount possible
if (buffered > AUDIOCARD_BUFFER)
return;
// Also make sure m_audioQueue never goes to less than 1/3 of the RDP stream
// total latency, this should gives us enough time to receive missed packets
int64_t queue = framesToMs((uint64_t)m_audioQueue.size() * m_framesPerPacket);
if (queue < m_bufferLength / 3)
return;
rtp += buffered;
// How many packets to add to the audio card, to fill AUDIOCARD_BUFFER
int max_packets = ((AUDIOCARD_BUFFER - buffered)
* m_frameRate / 1000) / m_framesPerPacket;
int i = 0;
uint64_t timestamp = 0;
QMapIterator<uint64_t,AudioPacket> packet_it(m_audioQueue);
while (packet_it.hasNext() && i <= max_packets)
{
packet_it.next();
timestamp = packet_it.key();
if (timestamp < rtp)
{
if (!m_audioStarted)
{
m_audio->Reset(); // clear audio card
}
AudioPacket frames = packet_it.value();
if (m_lastSequence != frames.seq)
{
LOG(VB_PLAYBACK, LOG_ERR, LOC +
QString("Audio discontinuity seen. Played %1 (%3) expected %2")
.arg(frames.seq).arg(m_lastSequence).arg(timestamp));
m_lastSequence = frames.seq;
}
m_lastSequence++;
for (const auto & data : qAsConst(*frames.data))
{
int offset = 0;
int framecnt = 0;
if (m_adjustedLatency > 0)
{
// calculate how many frames we have to drop to catch up
offset = (m_adjustedLatency * m_frameRate / 1000) *
m_audio->GetBytesPerFrame();
if (offset > data.length)
offset = data.length;
framecnt = offset / m_audio->GetBytesPerFrame();
m_adjustedLatency -= framesToMs(framecnt+1);
LOG(VB_PLAYBACK, LOG_DEBUG, LOC +
QString("ProcessAudio: Dropping %1 frames to catch up "
"(%2ms to go)")
.arg(framecnt).arg(m_adjustedLatency));
timestamp += framesToMs(framecnt);
}
m_audio->AddData((char *)data.data + offset,
data.length - offset,
timestamp, framecnt);
timestamp += m_audio->LengthLastData();
}
i++;
m_audioStarted = true;
}
else // QMap is sorted, so no need to continue if not found
break;
}
ExpireAudio(timestamp);
m_lastTimestamp = timestamp;
// restart audio timer should we stop receiving data on regular interval,
// we need to continue processing the audio queue
m_dequeueAudioTimer->start(AUDIO_BUFFER);
}
int MythRAOPConnection::ExpireAudio(uint64_t timestamp)
{
int res = 0;
QMutableMapIterator<uint64_t,AudioPacket> packet_it(m_audioQueue);
while (packet_it.hasNext())
{
packet_it.next();
if (packet_it.key() < timestamp)
{
AudioPacket frames = packet_it.value();
if (frames.data)
{
for (const auto & data : qAsConst(*frames.data))
av_free(data.data);
delete frames.data;
}
m_audioQueue.remove(packet_it.key());
res++;
}
}
return res;
}
void MythRAOPConnection::ResetAudio(void)
{
if (m_audio)
{
m_audio->Reset();
}
ExpireAudio(UINT64_MAX);
ExpireResendRequests(UINT64_MAX);
m_audioStarted = false;
}
void MythRAOPConnection::timeout(void)
{
LOG(VB_PLAYBACK, LOG_INFO, LOC + "Closing connection after inactivity.");
m_socket->disconnectFromHost();
}
void MythRAOPConnection::audioRetry(void)
{
if (!m_audio && OpenAudioDevice())
{
CreateDecoder();
}
if (m_audio && m_codec && m_codecContext)
{
StopAudioTimer();
}
}
/**
* readClient: signal handler for RAOP client connection
* Handle initialisation of session
*/
void MythRAOPConnection::readClient(void)
{
auto *socket = dynamic_cast<QTcpSocket *>(sender());
if (!socket)
return;
QByteArray data = socket->readAll();
LOG(VB_PLAYBACK, LOG_DEBUG, LOC + QString("readClient(%1): ")
.arg(data.size()) + data.constData());
// For big content, we may be called several times for a single packet
if (!m_incomingPartial)
{
m_incomingHeaders.clear();
m_incomingContent.clear();
m_incomingSize = 0;
QTextStream stream(data);
QString line;
do
{
line = stream.readLine();
if (line.size() == 0)
break;
LOG(VB_PLAYBACK, LOG_DEBUG, LOC + QString("Header(%1) = %2")
.arg(m_socket->peerAddress().toString())
.arg(line));
m_incomingHeaders.append(line);
if (line.contains("Content-Length:"))
{
m_incomingSize = line.mid(line.indexOf(" ") + 1).toInt();
}
}
while (!line.isNull());
if (m_incomingHeaders.empty())
return;
if (!stream.atEnd())
{
int pos = stream.pos();
if (pos > 0)
{
m_incomingContent.append(data.mid(pos));
}
}
}
else
{
m_incomingContent.append(data);
}
// If we haven't received all the content yet, wait (see when receiving
// coverart
if (m_incomingContent.size() < m_incomingSize)
{
m_incomingPartial = true;
return;
}
m_incomingPartial = false;
LOG(VB_PLAYBACK, LOG_DEBUG, LOC + QString("Content(%1) = %2")
.arg(m_incomingContent.size()).arg(m_incomingContent.constData()));
ProcessRequest(m_incomingHeaders, m_incomingContent);
}
void MythRAOPConnection::ProcessRequest(const QStringList &header,
const QByteArray &content)
{
if (header.isEmpty())
return;
RawHash tags = FindTags(header);
if (!tags.contains("CSeq"))
{
LOG(VB_PLAYBACK, LOG_ERR, LOC + "ProcessRequest: Didn't find CSeq");
return;
}
QString option = header[0].left(header[0].indexOf(" "));
// process RTP-info field
bool gotRTP = false;
uint16_t RTPseq = 0;
uint64_t RTPtimestamp = 0;
if (tags.contains("RTP-Info"))
{
gotRTP = true;
QString data = tags["RTP-Info"];
QStringList items = data.split(";");
for (const QString& item : qAsConst(items))
{
if (item.startsWith("seq"))
{
RTPseq = item.mid(item.indexOf("=") + 1).trimmed().toUShort();
}
else if (item.startsWith("rtptime"))
{
RTPtimestamp = item.mid(item.indexOf("=") + 1).trimmed().toUInt();
}
}
LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("RTP-Info: seq=%1 rtptime=%2")
.arg(RTPseq).arg(RTPtimestamp));
}
if (gCoreContext->GetBoolSetting("AirPlayPasswordEnabled", false))
{
if (m_nonce.isEmpty())
{
m_nonce = GenerateNonce();
}
if (!tags.contains("Authorization"))
{
// 60 seconds to enter password.
m_watchdogTimer->start(60000);
FinishAuthenticationResponse(m_textStream, m_socket, tags["CSeq"]);
return;
}
QByteArray auth;
if (DigestMd5Response(tags["Authorization"], option, m_nonce,
gCoreContext->GetSetting("AirPlayPassword"),
auth) == auth)
{
LOG(VB_PLAYBACK, LOG_INFO, LOC + "RAOP client authenticated");
}
else
{
LOG(VB_PLAYBACK, LOG_INFO, LOC + "RAOP authentication failed");
FinishAuthenticationResponse(m_textStream, m_socket, tags["CSeq"]);
return;
}
}
*m_textStream << "RTSP/1.0 200 OK\r\n";
if (tags.contains("Apple-Challenge"))
{
LOG(VB_PLAYBACK, LOG_DEBUG, LOC + QString("Received Apple-Challenge"));
*m_textStream << "Apple-Response: ";
if (!LoadKey())
return;
int tosize = RSA_size(LoadKey());
auto *to = new uint8_t[tosize];
QByteArray challenge =
QByteArray::fromBase64(tags["Apple-Challenge"].toLatin1());
int challenge_size = challenge.size();
if (challenge_size != 16)
{
LOG(VB_PLAYBACK, LOG_ERR, LOC +
QString("Decoded challenge size %1, expected 16")
.arg(challenge_size));
if (challenge_size > 16)
challenge_size = 16;
}
int i = 0;
std::array<uint8_t,38> from {};
std::copy(challenge.cbegin(), challenge.cbegin() + challenge_size,
from.data());
i += challenge_size;
if (m_socket->localAddress().protocol() ==
QAbstractSocket::IPv4Protocol)
{
uint32_t ip = m_socket->localAddress().toIPv4Address();
ip = qToBigEndian(ip);
memcpy(&from[i], &ip, 4);
i += 4;
}
else if (m_socket->localAddress().protocol() ==
QAbstractSocket::IPv6Protocol)
{
Q_IPV6ADDR ip = m_socket->localAddress().toIPv6Address();
if(memcmp(&ip,
"\x00\x00\x00\x00" "\x00\x00\x00\x00" "\x00\x00\xff\xff",
12) == 0)
{
memcpy(&from[i], &ip[12], 4);
i += 4;
}
else
{
memcpy(&from[i], &ip, 16);
i += 16;
}
}
memcpy(&from[i], m_hardwareId.constData(), AIRPLAY_HARDWARE_ID_SIZE);
i += AIRPLAY_HARDWARE_ID_SIZE;