/
ringbuffer.cpp
1613 lines (1398 loc) · 44.8 KB
/
ringbuffer.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
// ANSI C headers
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cerrno>
// POSIX C headers
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>
#include <fcntl.h>
// Qt headers
#include <QFile>
#include <QDateTime>
#include "ThreadedFileWriter.h"
#include "fileringbuffer.h"
#include "dvdringbuffer.h"
#include "bdringbuffer.h"
#include "streamingringbuffer.h"
#include "livetvchain.h"
#include "mythcontext.h"
#include "ringbuffer.h"
#include "mythconfig.h"
#include "remotefile.h"
#include "compat.h"
#include "util.h"
#include "mythlogging.h"
// about one second at 35mbit
#define BUFFER_SIZE_MINIMUM 4 * 1024 * 1024
#define BUFFER_FACTOR_NETWORK 2
#define BUFFER_FACTOR_BITRATE 2
#define BUFFER_FACTOR_MATROSKA 2
const int RingBuffer::kDefaultOpenTimeout = 2000; // ms
const int RingBuffer::kLiveTVOpenTimeout = 10000;
#define CHUNK 32768 /* readblocksize increments */
#define LOC QString("RingBuf(%1): ").arg(filename)
QMutex RingBuffer::subExtLock;
QStringList RingBuffer::subExt;
QStringList RingBuffer::subExtNoCheck;
/*
Locking relations:
rwlock->poslock->rbrlock->rbwlock
A child should never lock any of the parents without locking
the parent lock before the child lock.
void RingBuffer::Example1()
{
poslock.lockForWrite();
rwlock.lockForRead(); // error!
blah(); // <- does not implicitly aquire any locks
rwlock.unlock();
poslock.unlock();
}
void RingBuffer::Example2()
{
rwlock.lockForRead();
rbrlock.lockForWrite(); // ok!
blah(); // <- does not implicitly aquire any locks
rbrlock.unlock();
rwlock.unlock();
}
*/
/** \class RingBuffer
* \brief Implements a file/stream reader/writer.
*
* This class, despite its name, no-longer provides a ring buffer.
* It can buffer reads and provide support for streaming files.
* It also provides a wrapper for the ThreadedFileWriter which
* makes sure that the file reader does not read past where the
* wrapped TFW has written new data.
*
*/
/** \brief Creates a RingBuffer instance.
*
* You can explicitly disable the readahead thread by setting
* readahead to false, or by just not calling Start(void).
*
* \param lfilename Name of file to read or write.
* \param write If true an encapsulated writer is created
* \param readahead If false a call to Start(void) will not
* a pre-buffering thread, otherwise Start(void)
* will start a pre-buffering thread.
* \param timeout_ms if < 0, then we will not open the file.
* Otherwise it's how long to try opening
* the file after the first failure in
* milliseconds before giving up.
*/
RingBuffer *RingBuffer::Create(
const QString &xfilename, bool write,
bool usereadahead, int timeout_ms, bool stream_only)
{
QString lfilename = xfilename;
QString lower = lfilename.toLower();
if (write)
return new FileRingBuffer(lfilename, write, usereadahead, timeout_ms);
bool dvddir = false;
bool bddir = false;
bool httpurl = lower.startsWith("http://");
bool mythurl = lower.startsWith("myth://");
bool bdurl = lower.startsWith("bd:");
bool dvdurl = lower.startsWith("dvd:");
bool dvdext = lower.endsWith(".img") || lower.endsWith(".iso");
if (httpurl)
return new StreamingRingBuffer(lfilename);
if (!stream_only && mythurl)
{
struct stat fileInfo;
if ((RemoteFile::Exists(lfilename, &fileInfo)) &&
(S_ISDIR(fileInfo.st_mode)))
{
if (RemoteFile::Exists(lfilename + "/VIDEO_TS"))
dvddir = true;
else if (RemoteFile::Exists(lfilename + "/BDMV"))
bddir = true;
}
}
else if (!stream_only && !mythurl)
{
if (QFile::exists(lfilename + "/VIDEO_TS"))
dvddir = true;
else if (QFile::exists(lfilename + "/BDMV"))
bddir = true;
}
if (!stream_only && (dvdurl || dvddir || dvdext))
{
if (lfilename.left(6) == "dvd://") // 'Play DVD' sends "dvd:/" + dev
lfilename.remove(0,5); // e.g. "dvd://dev/sda"
else if (lfilename.left(5) == "dvd:/") // Less correct URI "dvd:" + path
lfilename.remove(0,4); // e.g. "dvd:/videos/ET"
else if (lfilename.left(4) == "dvd:") // Win32 URI "dvd:" + abs path
lfilename.remove(0,4); // e.g. "dvd:D:\"
if (mythurl || QFile::exists(lfilename))
LOG(VB_PLAYBACK, LOG_INFO, "Trying DVD at " + lfilename);
else
lfilename = "/dev/dvd";
return new DVDRingBuffer(lfilename);
}
else if (!stream_only && (bdurl || bddir))
{
if (lfilename.left(5) == "bd://") // 'Play DVD' sends "bd:/" + dev
lfilename.remove(0,4); // e.g. "bd://dev/sda"
else if (lfilename.left(4) == "bd:/") // Less correct URI "bd:" + path
lfilename.remove(0,3); // e.g. "bd:/videos/ET"
if (mythurl || QFile::exists(lfilename))
LOG(VB_PLAYBACK, LOG_INFO, "Trying BD at " + lfilename);
else
lfilename = "/dev/dvd";
return new BDRingBuffer(lfilename);
}
return new FileRingBuffer(
lfilename, write, usereadahead, timeout_ms);
}
RingBuffer::RingBuffer(RingBufferType rbtype) :
MThread("RingBuffer"),
type(rbtype),
readpos(0), writepos(0),
internalreadpos(0), ignorereadpos(-1),
rbrpos(0), rbwpos(0),
stopreads(false), safefilename(QString()),
filename(), subtitlefilename(),
tfw(NULL), fd2(-1),
writemode(false), remotefile(NULL),
bufferSize(BUFFER_SIZE_MINIMUM),
fileismatroska(false), unknownbitrate(false),
startreadahead(false), readAheadBuffer(NULL),
readaheadrunning(false), reallyrunning(false),
request_pause(false), paused(false),
ateof(false), readsallowed(false),
setswitchtonext(false),
rawbitrate(8000), playspeed(1.0f),
fill_threshold(65536), fill_min(-1),
readblocksize(CHUNK), wanttoread(0),
numfailures(0), commserror(false),
oldfile(false), livetvchain(NULL),
ignoreliveeof(false), readAdjust(0),
bitrateMonitorEnabled(false)
{
{
QMutexLocker locker(&subExtLock);
if (subExt.empty())
{
// Possible subtitle file extensions '.srt', '.sub', '.txt'
subExt += ".srt";
subExt += ".sub";
subExt += ".txt";
// Extensions for which a subtitle file should not exist
subExtNoCheck = subExt;
subExtNoCheck += ".gif";
subExtNoCheck += ".png";
}
}
}
/** \fn RingBuffer::~RingBuffer(void)
* \brief Shuts down any threads and closes any files.
*/
RingBuffer::~RingBuffer(void)
{
KillReadAheadThread();
rwlock.lockForWrite();
if (readAheadBuffer) // this only runs if thread is terminated
{
delete [] readAheadBuffer;
readAheadBuffer = NULL;
}
if (tfw)
{
tfw->Flush();
delete tfw;
tfw = NULL;
}
rwlock.unlock();
wait();
}
/** \fn RingBuffer::Reset(bool, bool, bool)
* \brief Resets the read-ahead thread and our position in the file
*/
void RingBuffer::Reset(bool full, bool toAdjust, bool resetInternal)
{
LOG(VB_FILE, LOG_INFO, LOC + QString("Reset(%1,%2,%3)")
.arg(full).arg(toAdjust).arg(resetInternal));
rwlock.lockForWrite();
poslock.lockForWrite();
numfailures = 0;
commserror = false;
setswitchtonext = false;
writepos = 0;
readpos = (toAdjust) ? (readpos - readAdjust) : 0;
if (readpos != 0)
{
LOG(VB_GENERAL, LOG_ERR, LOC +
QString("RingBuffer::Reset() nonzero readpos. toAdjust: %1 "
"readpos: %2 readAdjust: %3")
.arg(toAdjust).arg(readpos).arg(readAdjust));
}
readAdjust = 0;
readpos = (readpos < 0) ? 0 : readpos;
if (full)
ResetReadAhead(readpos);
if (resetInternal)
internalreadpos = readpos;
generalWait.wakeAll();
poslock.unlock();
rwlock.unlock();
}
/** \fn RingBuffer::UpdateRawBitrate(uint)
* \brief Set the raw bit rate, to allow RingBuffer adjust effective bitrate.
* \param raw_bitrate Streams average number of kilobits per second when
* playspeed is 1.0
*/
void RingBuffer::UpdateRawBitrate(uint raw_bitrate)
{
LOG(VB_FILE, LOG_INFO, LOC +
QString("UpdateRawBitrate(%1Kb)").arg(raw_bitrate));
if (raw_bitrate < 2500)
{
LOG(VB_FILE, LOG_INFO, LOC +
QString("UpdateRawBitrate(%1Kb) - ignoring bitrate,")
.arg(raw_bitrate) +
"\n\t\t\tappears to be abnormally low.");
return;
}
rwlock.lockForWrite();
rawbitrate = raw_bitrate;
CalcReadAheadThresh();
rwlock.unlock();
}
/** \fn RingBuffer::UpdatePlaySpeed(float)
* \brief Set the play speed, to allow RingBuffer adjust effective bitrate.
* \param play_speed Speed to set. (1.0 for normal speed)
*/
void RingBuffer::UpdatePlaySpeed(float play_speed)
{
rwlock.lockForWrite();
playspeed = play_speed;
CalcReadAheadThresh();
rwlock.unlock();
}
/** \fn RingBuffer::SetBufferSizeFactors(bool, bool)
* \brief Tells RingBuffer that the raw bitrate may be innacurate and the
* underlying container is matroska, both of which may require a larger
* buffer size.
*/
void RingBuffer::SetBufferSizeFactors(bool estbitrate, bool matroska)
{
rwlock.lockForWrite();
unknownbitrate = estbitrate;
fileismatroska = matroska;
rwlock.unlock();
CreateReadAheadBuffer();
}
/** \fn RingBuffer::CalcReadAheadThresh(void)
* \brief Calculates fill_min, fill_threshold, and readblocksize
* from the estimated effective bitrate of the stream.
*
* WARNING: Must be called with rwlock in write lock state.
*
*/
void RingBuffer::CalcReadAheadThresh(void)
{
uint estbitrate = 0;
readsallowed = false;
readblocksize = max(readblocksize, CHUNK);
// loop without sleeping if the buffered data is less than this
fill_threshold = 7 * bufferSize / 8;
const uint KB32 = 32*1024;
const uint KB64 = 64*1024;
const uint KB128 = 128*1024;
const uint KB256 = 256*1024;
const uint KB512 = 512*1024;
estbitrate = (uint) max(abs(rawbitrate * playspeed),
0.5f * rawbitrate);
estbitrate = min(rawbitrate * 3, estbitrate);
int rbs = (estbitrate > 2500) ? KB64 : KB32;
rbs = (estbitrate > 5000) ? KB128 : rbs;
rbs = (estbitrate > 9000) ? KB256 : rbs;
rbs = (estbitrate > 18000) ? KB512 : rbs;
readblocksize = max(rbs,readblocksize);
// minumum seconds of buffering before allowing read
float secs_min = 0.25;
// set the minimum buffering before allowing ffmpeg read
fill_min = (uint) ((estbitrate * secs_min) * 0.125f);
// make this a multiple of ffmpeg block size..
fill_min = ((fill_min / KB32) + 1) * KB32;
LOG(VB_FILE, LOG_INFO, LOC +
QString("CalcReadAheadThresh(%1 Kb)\n\t\t\t -> "
"threshhold(%2 KB) min read(%3 KB) blk size(%4 KB)")
.arg(estbitrate).arg(fill_threshold/1024)
.arg(fill_min/1024).arg(readblocksize/1024));
}
bool RingBuffer::IsNearEnd(double fps, uint vvf) const
{
rwlock.lockForRead();
int sz = ReadBufAvail();
uint rbs = readblocksize;
// telecom kilobytes (i.e. 1000 per k not 1024)
uint tmp = (uint) max(abs(rawbitrate * playspeed), 0.5f * rawbitrate);
uint kbits_per_sec = min(rawbitrate * 3, tmp);
rwlock.unlock();
// WARNING: readahead_frames can greatly overestimate or underestimate
// the number of frames available in the read ahead buffer
// when rh_frames is less than the keyframe distance.
double bytes_per_frame = kbits_per_sec * (1000.0/8.0) / fps;
double readahead_frames = sz / bytes_per_frame;
bool near_end = ((vvf + readahead_frames) < 10.0) || (sz < rbs*1.5);
LOG(VB_PLAYBACK, LOG_INFO, LOC + "IsReallyNearEnd()" +
QString(" br(%1KB)").arg(kbits_per_sec/8) +
QString(" sz(%1KB)").arg(sz / 1000) +
QString(" vfl(%1)").arg(vvf) +
QString(" frh(%1)").arg(((uint)readahead_frames)) +
QString(" ne:%1").arg(near_end));
return near_end;
}
/// \brief Returns number of bytes available for reading into buffer.
/// WARNING: Must be called with rwlock in locked state.
int RingBuffer::ReadBufFree(void) const
{
rbrlock.lockForRead();
rbwlock.lockForRead();
int ret = ((rbwpos >= rbrpos) ? rbrpos + bufferSize : rbrpos) - rbwpos - 1;
rbwlock.unlock();
rbrlock.unlock();
return ret;
}
/// \brief Returns number of bytes available for reading from buffer.
/// WARNING: Must be called with rwlock in locked state.
int RingBuffer::ReadBufAvail(void) const
{
rbrlock.lockForRead();
rbwlock.lockForRead();
int ret = (rbwpos >= rbrpos) ? rbwpos - rbrpos : bufferSize - rbrpos + rbwpos;
rbwlock.unlock();
rbrlock.unlock();
return ret;
}
/** \fn RingBuffer::ResetReadAhead(long long)
* \brief Restart the read-ahead thread at the 'newinternal' position.
*
* This is called after a Seek(long long, int) so that the read-ahead
* buffer doesn't contain any stale data, and so that it will read
* any new data from the new position in the file.
*
* WARNING: Must be called with rwlock and poslock in write lock state.
*
* \param newinternal Position in file to start reading data from
*/
void RingBuffer::ResetReadAhead(long long newinternal)
{
LOG(VB_FILE, LOG_INFO, LOC +
QString("ResetReadAhead(internalreadpos = %1->%2)")
.arg(internalreadpos).arg(newinternal));
rbrlock.lockForWrite();
rbwlock.lockForWrite();
CalcReadAheadThresh();
rbrpos = 0;
rbwpos = 0;
internalreadpos = newinternal;
ateof = false;
readsallowed = false;
setswitchtonext = false;
generalWait.wakeAll();
rbwlock.unlock();
rbrlock.unlock();
}
/**
* \brief Starts the read-ahead thread.
*
* If the RingBuffer constructor was not called with a usereadahead
* of true of if this was reset to false because we're dealing with
* a DVD the read ahead thread will not be started.
*
* If this RingBuffer is in write-mode a warning will be printed and
* the read ahead thread will not be started.
*
* If the read ahead thread is already running a warning will be printed
* and the read ahead thread will not be started.
*
*/
void RingBuffer::Start(void)
{
bool do_start = true;
rwlock.lockForWrite();
if (!startreadahead)
{
do_start = false;
}
else if (writemode)
{
LOG(VB_GENERAL, LOG_WARNING, LOC + "Not starting read ahead thread, "
"this is a write only RingBuffer");
do_start = false;
}
else if (readaheadrunning)
{
LOG(VB_GENERAL, LOG_WARNING, LOC + "Not starting read ahead thread, "
"already running");
do_start = false;
}
if (!do_start)
{
rwlock.unlock();
return;
}
StartReads();
MThread::start();
while (readaheadrunning && !reallyrunning)
generalWait.wait(&rwlock);
rwlock.unlock();
}
/** \fn RingBuffer::KillReadAheadThread(void)
* \brief Stops the read-ahead thread, and waits for it to stop.
*/
void RingBuffer::KillReadAheadThread(void)
{
while (isRunning())
{
rwlock.lockForWrite();
readaheadrunning = false;
StopReads();
generalWait.wakeAll();
rwlock.unlock();
MThread::wait(5000);
}
}
/** \fn RingBuffer::StopReads(void)
* \brief ????
* \sa StartReads(void), Pause(void)
*/
void RingBuffer::StopReads(void)
{
stopreads = true;
generalWait.wakeAll();
}
/** \fn RingBuffer::StartReads(void)
* \brief ????
* \sa StopReads(void), Unpause(void)
*/
void RingBuffer::StartReads(void)
{
stopreads = false;
generalWait.wakeAll();
}
/** \fn RingBuffer::Pause(void)
* \brief Pauses the read-ahead thread. Calls StopReads(void).
* \sa Unpause(void), WaitForPause(void)
*/
void RingBuffer::Pause(void)
{
StopReads();
rwlock.lockForWrite();
request_pause = true;
rwlock.unlock();
}
/** \fn RingBuffer::Unpause(void)
* \brief Unpauses the read-ahead thread. Calls StartReads(void).
* \sa Pause(void)
*/
void RingBuffer::Unpause(void)
{
StartReads();
rwlock.lockForWrite();
request_pause = false;
generalWait.wakeAll();
rwlock.unlock();
}
/// Returns false iff read-ahead is not running and read-ahead is not paused.
bool RingBuffer::isPaused(void) const
{
rwlock.lockForRead();
bool ret = !readaheadrunning || paused;
rwlock.unlock();
return ret;
}
/** \fn RingBuffer::WaitForPause(void)
* \brief Waits for Pause(void) to take effect.
*/
void RingBuffer::WaitForPause(void)
{
MythTimer t;
t.start();
rwlock.lockForRead();
while (readaheadrunning && !paused && request_pause)
{
generalWait.wait(&rwlock, 1000);
if (readaheadrunning && !paused && request_pause && t.elapsed() > 1000)
{
LOG(VB_GENERAL, LOG_WARNING, LOC +
QString("Waited %1 ms for ringbuffer pause..")
.arg(t.elapsed()));
}
}
rwlock.unlock();
}
bool RingBuffer::PauseAndWait(void)
{
const uint timeout = 500; // ms
if (request_pause)
{
if (!paused)
{
rwlock.unlock();
rwlock.lockForWrite();
if (request_pause)
{
paused = true;
generalWait.wakeAll();
}
rwlock.unlock();
rwlock.lockForRead();
}
if (request_pause && paused && readaheadrunning)
generalWait.wait(&rwlock, timeout);
}
if (!request_pause && paused)
{
rwlock.unlock();
rwlock.lockForWrite();
if (!request_pause)
{
paused = false;
generalWait.wakeAll();
}
rwlock.unlock();
rwlock.lockForRead();
}
return request_pause || paused;
}
void RingBuffer::CreateReadAheadBuffer(void)
{
rwlock.lockForWrite();
poslock.lockForWrite();
uint oldsize = bufferSize;
uint newsize = BUFFER_SIZE_MINIMUM;
if (remotefile)
{
newsize *= BUFFER_FACTOR_NETWORK;
if (fileismatroska)
newsize *= BUFFER_FACTOR_MATROSKA;
if (unknownbitrate)
newsize *= BUFFER_FACTOR_BITRATE;
}
// N.B. Don't try and make it smaller - bad things happen...
if (readAheadBuffer && oldsize >= newsize)
{
poslock.unlock();
rwlock.unlock();
return;
}
bufferSize = newsize;
if (readAheadBuffer)
{
char* newbuffer = new char[bufferSize + 1024];
memcpy(newbuffer, readAheadBuffer + rbwpos, oldsize - rbwpos);
memcpy(newbuffer + (oldsize - rbwpos), readAheadBuffer, rbwpos);
delete [] readAheadBuffer;
readAheadBuffer = newbuffer;
rbrpos = (rbrpos > rbwpos) ? (rbrpos - rbwpos) :
(rbrpos + oldsize - rbwpos);
rbwpos = oldsize;
}
else
{
readAheadBuffer = new char[bufferSize + 1024];
}
CalcReadAheadThresh();
poslock.unlock();
rwlock.unlock();
LOG(VB_FILE, LOG_INFO, LOC + QString("Created readAheadBuffer: %1Mb")
.arg(newsize >> 20));
}
void RingBuffer::run(void)
{
RunProlog();
// These variables are used to adjust the read block size
struct timeval lastread, now;
int readtimeavg = 300;
bool ignore_for_read_timing = true;
gettimeofday(&lastread, NULL); // this is just to keep gcc happy
CreateReadAheadBuffer();
rwlock.lockForWrite();
poslock.lockForWrite();
request_pause = false;
ResetReadAhead(0);
readaheadrunning = true;
reallyrunning = true;
generalWait.wakeAll();
poslock.unlock();
rwlock.unlock();
// NOTE: this must loop at some point hold only
// a read lock on rwlock, so that other functions
// such as reset and seek can take priority.
rwlock.lockForRead();
LOG(VB_FILE, LOG_INFO, LOC +
QString("Initial readblocksize %1K & fill_min %2K")
.arg(readblocksize/1024).arg(fill_min/1024));
while (readaheadrunning)
{
if (PauseAndWait())
{
ignore_for_read_timing = true;
continue;
}
long long totfree = ReadBufFree();
const uint KB32 = 32*1024;
// These are conditions where we don't want to go through
// the loop if they are true.
if (((totfree < KB32) && readsallowed) ||
(ignorereadpos >= 0) || commserror || stopreads)
{
ignore_for_read_timing |=
(ignorereadpos >= 0) || commserror || stopreads;
generalWait.wait(&rwlock, (stopreads) ? 50 : 1000);
continue;
}
// These are conditions where we want to sleep to allow
// other threads to do stuff.
if (setswitchtonext || (ateof && readsallowed))
{
ignore_for_read_timing = true;
generalWait.wait(&rwlock, 1000);
totfree = ReadBufFree();
}
int read_return = -1;
if (totfree >= KB32 && !commserror &&
!ateof && !setswitchtonext)
{
// limit the read size
if (readblocksize > totfree)
totfree = (int)(totfree / KB32) * KB32; // must be multiple of 32KB
else
totfree = readblocksize;
// adapt blocksize
gettimeofday(&now, NULL);
if (!ignore_for_read_timing)
{
int readinterval = (now.tv_sec - lastread.tv_sec ) * 1000 +
(now.tv_usec - lastread.tv_usec) / 1000;
readtimeavg = (readtimeavg * 9 + readinterval) / 10;
if (readtimeavg < 150 &&
(uint)readblocksize < (BUFFER_SIZE_MINIMUM >>2))
{
int old_block_size = readblocksize;
readblocksize = 3 * readblocksize / 2;
readblocksize = ((readblocksize+CHUNK-1) / CHUNK) * CHUNK;
LOG(VB_FILE, LOG_INFO, LOC +
QString("Avg read interval was %1 msec. "
"%2K -> %3K block size")
.arg(readtimeavg)
.arg(old_block_size/1024)
.arg(readblocksize/1024));
readtimeavg = 225;
}
else if (readtimeavg > 300 && readblocksize > CHUNK)
{
readblocksize -= CHUNK;
LOG(VB_FILE, LOG_INFO, LOC +
QString("Avg read interval was %1 msec. "
"%2K -> %3K block size")
.arg(readtimeavg)
.arg((readblocksize+CHUNK)/1024)
.arg(readblocksize/1024));
readtimeavg = 225;
}
}
ignore_for_read_timing = (totfree < readblocksize) ? true : false;
lastread = now;
rbwlock.lockForRead();
if (rbwpos + totfree > bufferSize)
{
totfree = bufferSize - rbwpos;
LOG(VB_FILE, LOG_DEBUG, LOC +
"Shrinking read, near end of buffer");
}
if (internalreadpos == 0)
{
totfree = max(fill_min, readblocksize);
LOG(VB_FILE, LOG_DEBUG, LOC +
"Reading enough data to start playback");
}
if (remotefile && livetvchain && livetvchain->HasNext())
remotefile->SetTimeout(true);
LOG(VB_FILE, LOG_DEBUG, LOC +
QString("safe_read(...@%1, %2) -- begin")
.arg(rbwpos).arg(totfree));
MythTimer sr_timer;
sr_timer.start();
int rbwposcopy = rbwpos;
// FileRingBuffer::safe_read(RemoteFile*...) acquires poslock;
// so we need to unlock this here to preserve locking order.
rbwlock.unlock();
read_return = safe_read(readAheadBuffer + rbwposcopy, totfree);
int sr_elapsed = sr_timer.elapsed();
uint64_t bps = !sr_elapsed ? 1000000001 :
(uint64_t)(((double)read_return * 8000.0) /
(double)sr_elapsed);
LOG(VB_FILE, LOG_INFO, LOC +
QString("safe_read(...@%1, %2) -> %3, took %4 ms %5")
.arg(rbwposcopy).arg(totfree).arg(read_return)
.arg(sr_elapsed)
.arg(QString("(%1Mbps)").arg((double)bps / 1000000.0)));
UpdateStorageRate(bps);
if (read_return >= 0)
{
poslock.lockForWrite();
rbwlock.lockForWrite();
if (rbwposcopy == rbwpos)
{
internalreadpos += read_return;
rbwpos = (rbwpos + read_return) % bufferSize;
LOG(VB_FILE, LOG_DEBUG,
LOC + QString("rbwpos += %1K requested %2K in read")
.arg(read_return/1024,3).arg(totfree/1024,3));
}
rbwlock.unlock();
poslock.unlock();
}
}
int used = bufferSize - ReadBufFree();
bool reads_were_allowed = readsallowed;
if ((0 == read_return) || (numfailures > 5) ||
(readsallowed != (used >= fill_min || ateof ||
setswitchtonext || commserror)))
{
// If readpos changes while the lock is released
// we should not handle the 0 read_return now.
long long old_readpos = readpos;
rwlock.unlock();
rwlock.lockForWrite();
commserror |= (numfailures > 5);
readsallowed = used >= fill_min || ateof ||
setswitchtonext || commserror;
if (0 == read_return && old_readpos == readpos)
{
if (livetvchain)
{
if (!setswitchtonext && !ignoreliveeof &&
livetvchain->HasNext())
{
livetvchain->SwitchToNext(true);
setswitchtonext = true;
}
}
else
{
LOG(VB_FILE, LOG_DEBUG,
LOC + "setting ateof (read_return == 0)");
ateof = true;
}
}
rwlock.unlock();
rwlock.lockForRead();
used = bufferSize - ReadBufFree();
}
LOG(VB_FILE, LOG_DEBUG, LOC + "@ end of read ahead loop");
if (!readsallowed || commserror || ateof || setswitchtonext ||
(wanttoread <= used && wanttoread > 0))
{
// To give other threads a good chance to handle these
// conditions, even if they are only requesting a read lock
// like us, yield (currently implemented with short usleep).
generalWait.wakeAll();
rwlock.unlock();
usleep(5 * 1000);
rwlock.lockForRead();
}
else
{
// yield if we have nothing to do...
if (!request_pause && reads_were_allowed &&
(used >= fill_threshold || ateof || setswitchtonext))
{
generalWait.wait(&rwlock, 50);
}
else if (readsallowed)
{ // if reads are allowed release the lock and yield so the
// reader gets a chance to read before the buffer is full.
generalWait.wakeAll();
rwlock.unlock();
usleep(5 * 1000);
rwlock.lockForRead();
}
}
}
rwlock.unlock();
rwlock.lockForWrite();
rbrlock.lockForWrite();
rbwlock.lockForWrite();
rbrpos = 0;
rbwpos = 0;
reallyrunning = false;
readsallowed = false;
delete [] readAheadBuffer;
readAheadBuffer = NULL;
rbwlock.unlock();
rbrlock.unlock();
rwlock.unlock();
RunEpilog();
}
long long RingBuffer::SetAdjustFilesize(void)
{
rwlock.lockForWrite();
poslock.lockForRead();
readAdjust += internalreadpos;
long long ra = readAdjust;
poslock.unlock();
rwlock.unlock();
return ra;
}
int RingBuffer::Peek(void *buf, int count)
{
int ret = ReadPriv(buf, count, true);
if (ret != count)
{
LOG(VB_GENERAL, LOG_WARNING, LOC +
QString("Peek() requested %1 bytes, but only returning %2")
.arg(count).arg(ret));
}
return ret;
}
bool RingBuffer::WaitForReadsAllowed(void)
{
MythTimer t;
t.start();
while (!readsallowed && !stopreads &&
!request_pause && !commserror && readaheadrunning)
{
generalWait.wait(&rwlock, 1000);
if (!readsallowed && t.elapsed() > 1000)