stream.cpp
39.6 KB
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
#include <QReadWriteLock>
#include <QWaitCondition>
#include <QThreadPool>
#include <QSemaphore>
#include <QMap>
#include <opencv/highgui.h>
#include <QtConcurrent>
#include "openbr_internal.h"
#include "openbr/core/common.h"
#include "openbr/core/opencvutils.h"
#include "openbr/core/qtutils.h"
using namespace cv;
namespace br
{
class Idiocy : public QObject
{
Q_OBJECT
public:
enum StreamModes { StreamVideo,
DistributeFrames,
Auto};
Q_ENUMS(StreamModes)
};
class FrameData
{
public:
int sequenceNumber;
TemplateList data;
};
// A buffer shared between adjacent processing stages in a stream
class SharedBuffer
{
public:
SharedBuffer() {}
virtual ~SharedBuffer() {}
virtual void addItem(FrameData * input)=0;
virtual void reset()=0;
virtual FrameData * tryGetItem()=0;
virtual int size()=0;
};
// for n - 1 boundaries, multiple threads call addItem, the frames are
// sequenced based on FrameData::sequence_number, and calls to getItem
// receive them in that order
class SequencingBuffer : public SharedBuffer
{
public:
SequencingBuffer()
{
next_target = 0;
}
void addItem(FrameData * input)
{
QMutexLocker bufferLock(&bufferGuard);
buffer.insert(input->sequenceNumber, input);
}
FrameData * tryGetItem()
{
QMutexLocker bufferLock(&bufferGuard);
if (buffer.empty() || buffer.begin().key() != this->next_target) {
return NULL;
}
QMap<int, FrameData *>::Iterator result = buffer.begin();
if (next_target != result.value()->sequenceNumber) {
qFatal("mismatched targets!");
}
next_target = next_target + 1;
FrameData * output = result.value();
buffer.erase(result);
return output;
}
virtual int size()
{
QMutexLocker lock(&bufferGuard);
return buffer.size();
}
virtual void reset()
{
if (size() != 0)
qDebug("Sequencing buffer has non-zero size during reset!");
QMutexLocker lock(&bufferGuard);
next_target = 0;
}
private:
QMutex bufferGuard;
int next_target;
QMap<int, FrameData *> buffer;
};
// For 1 - 1 boundaries, a double buffering scheme
// Producer/consumer read/write from separate buffers, and switch if their
// buffer runs out/overflows. Synchronization is handled by a read/write lock
// threads are "reading" if they are adding to/removing from their individual
// buffer, and writing if they access or swap with the other buffer.
class DoubleBuffer : public SharedBuffer
{
public:
DoubleBuffer()
{
inputBuffer = &buffer1;
outputBuffer = &buffer2;
}
int size()
{
QReadLocker readLock(&bufferGuard);
return inputBuffer->size() + outputBuffer->size();
}
// called from the producer thread
void addItem(FrameData * input)
{
QReadLocker readLock(&bufferGuard);
inputBuffer->append(input);
}
FrameData * tryGetItem()
{
QReadLocker readLock(&bufferGuard);
// There is something for us to get
if (!outputBuffer->empty()) {
FrameData * output = outputBuffer->first();
outputBuffer->removeFirst();
return output;
}
// Outputbuffer is empty, try to swap with the input buffer, we need a
// write lock to do that.
readLock.unlock();
QWriteLocker writeLock(&bufferGuard);
// Nothing on the input buffer either?
if (inputBuffer->empty()) {
return NULL;
}
// input buffer is non-empty, so swap the buffers
std::swap(inputBuffer, outputBuffer);
// Return a frame
FrameData * output = outputBuffer->first();
outputBuffer->removeFirst();
return output;
}
virtual void reset()
{
if (this->size() != 0)
qDebug("Shared buffer has non-zero size during reset!");
}
private:
// The read-write lock. The thread adding to this buffer can add
// to the current input buffer if it has a read lock. The thread
// removing from this buffer can remove things from the current
// output buffer if it has a read lock, or swap the buffers if it
// has a write lock.
QReadWriteLock bufferGuard;
// The buffer that is currently being added to
QList<FrameData *> * inputBuffer;
// The buffer that is currently being removed from
QList<FrameData *> * outputBuffer;
// The buffers pointed at by inputBuffer/outputBuffer
QList<FrameData *> buffer1;
QList<FrameData *> buffer2;
};
// Given a template as input, return N templates as output, one at a time on subsequent
// calls to getNext
class TemplateProcessor
{
public:
virtual ~TemplateProcessor() {}
virtual bool open(Template & input)=0;
virtual bool isOpen()=0;
virtual void close()=0;
virtual bool getNextTemplate(Template & output)=0;
protected:
Template basis;
};
static QMutex openLock;
// Read a video frame by frame using cv::VideoCapture
class VideoReader : public TemplateProcessor
{
public:
VideoReader() {}
bool open(Template &input)
{
basis = input;
// We can open either files (well actually this includes addresses of ip cameras
// through ffmpeg), or webcams. Webcam VideoCaptures are created through a separate
// overload of open that takes an integer, not a string.
// So, does this look like an integer?
bool is_int = false;
int anInt = input.file.name.toInt(&is_int);
if (is_int)
{
bool rc = video.open(anInt);
if (!rc)
{
qDebug("open failed!");
}
if (!video.isOpened())
{
qDebug("Video not open!");
}
} else {
// Yes, we should specify absolute path:
// http://stackoverflow.com/questions/9396459/loading-a-video-in-opencv-in-python
QString fileName = (Globals->path.isEmpty() ? "" : Globals->path + "/") + input.file.name;
// On windows, this appears to not be thread-safe
QMutexLocker lock(&openLock);
video.open(QFileInfo(fileName).absoluteFilePath().toStdString());
}
return video.isOpened();
}
bool isOpen() { return video.isOpened(); }
void close() { video.release(); }
bool getNextTemplate(Template & output)
{
if (!isOpen()) {
qDebug("video source is not open");
return false;
}
output.file = basis.file;
output.m() = cv::Mat();
cv::Mat temp;
bool res = video.read(temp);
if (!res) {
// The video capture broke, return false.
output.m() = cv::Mat();
close();
return false;
}
// This clone is critical, if we don't do it then the matrix will
// be an alias of an internal buffer of the video source, leading
// to various problems later.
output.m() = temp.clone();
return true;
}
protected:
cv::VideoCapture video;
};
class DirectReturn : public TemplateProcessor
{
public:
DirectReturn()
{
data_ok = false;
}
// We don't do anything, just prepare to return input when getNext is called.
bool open(Template &input)
{
basis = input;
data_ok =true;
return data_ok;
}
bool isOpen() { return data_ok; }
void close()
{
data_ok = false;
basis.clear();
}
bool getNextTemplate(Template & output)
{
if (!data_ok)
return false;
output = basis;
data_ok = false;
return true;
}
protected:
// Have we sent our template yet?
bool data_ok;
};
// Interface for sequentially getting data from some data source.
// Given a TemplateList, return single template frames sequentially by applying a TemplateProcessor
// to each individual template.
class DataSource
{
public:
DataSource(int maxFrames=500)
{
// The sequence number of the last frame
final_frame = -1;
for (int i=0; i < maxFrames;i++)
{
allFrames.addItem(new FrameData());
}
frameSource = NULL;
}
virtual ~DataSource()
{
while (true)
{
FrameData * frame = allFrames.tryGetItem();
if (frame == NULL)
break;
delete frame;
}
}
void close()
{
if (this->frameSource)
{
frameSource->close();
delete frameSource;
frameSource = NULL;
}
}
int size()
{
return this->templates.size();
}
bool open(const TemplateList & input, br::Idiocy::StreamModes _mode)
{
// Set up variables specific to us
current_template_idx = 0;
templates = input;
mode = _mode;
is_broken = false;
allReturned = false;
// The last frame isn't initialized yet
final_frame = -1;
// Start our sequence numbers from the input index
next_sequence_number = 0;
// Actually open the data source
bool open_res = openNextTemplate();
// We couldn't open the data source
if (!open_res) {
is_broken = true;
return false;
}
// Try to get a frame from the global pool
FrameData * firstFrame = allFrames.tryGetItem();
// If this fails, things have gone pretty badly.
if (firstFrame == NULL) {
is_broken = true;
return false;
}
// Read a frame from the video source
bool res = getNextFrame(*firstFrame);
// the data source broke already, we couldn't even get one frame
// from it even though it claimed to have opened successfully.
if (!res) {
is_broken = true;
return false;
}
// We read one frame ahead of the last one returned, this allows
// us to know which frame is the final frame when we return it.
lookAhead.append(firstFrame);
return true;
}
// non-blocking version of getFrame
// Returns a NULL FrameData if too many frames are out, or the
// data source is broken. Sets last_frame to true iff the FrameData
// returned is the last valid frame, and the data source is now broken.
FrameData * tryGetFrame(bool & last_frame)
{
last_frame = false;
if (is_broken) {
return NULL;
}
// Try to get a FrameData from the pool, if we can't it means too many
// frames are already out, and we will return NULL to indicate failure
FrameData * aFrame = allFrames.tryGetItem();
if (aFrame == NULL)
return NULL;
// Try to actually read a frame, if this returns false the data source is broken
bool res = getNextFrame(*aFrame);
// The datasource broke, update final_frame
if (!res)
{
QMutexLocker lock(&last_frame_update);
final_frame = lookAhead.back()->sequenceNumber;
allFrames.addItem(aFrame);
}
else {
lookAhead.push_back(aFrame);
}
// we will return the first frame on the lookAhead buffer
FrameData * rVal = lookAhead.first();
lookAhead.pop_front();
if (rVal->data.empty())
qDebug("returning empty frame from look ahead!");
// If this is the last frame, say so
if (rVal->sequenceNumber == final_frame) {
last_frame = true;
is_broken = true;
}
return rVal;
}
// Return a frame to the pool, returns true if the frame returned was the last
// frame issued, false otherwise
bool returnFrame(FrameData * inputFrame)
{
int frameNumber = inputFrame->sequenceNumber;
inputFrame->data.clear();
inputFrame->sequenceNumber = -1;
allFrames.addItem(inputFrame);
bool rval = false;
QMutexLocker lock(&last_frame_update);
if (frameNumber == final_frame) {
// We just received the last frame, better pulse
allReturned = true;
rval = true;
}
return rval;
}
void wake()
{
lastReturned.wakeAll();
}
bool waitLast()
{
QMutexLocker lock(&last_frame_update);
while (!allReturned)
{
// This would be a safer wait if we used a timeout, but
// theoretically that should never matter.
lastReturned.wait(&last_frame_update);
}
return true;
}
protected:
bool openNextTemplate()
{
if (this->current_template_idx >= this->templates.size())
return false;
bool open_res = false;
while (!open_res)
{
if (frameSource)
frameSource->close();
if (mode == br::Idiocy::Auto)
{
delete frameSource;
if (this->templates[this->current_template_idx].empty())
frameSource = new VideoReader();
else
frameSource = new DirectReturn();
}
else if (mode == br::Idiocy::DistributeFrames)
{
if (!frameSource)
frameSource = new DirectReturn();
}
else if (mode == br::Idiocy::StreamVideo)
{
if (!frameSource)
frameSource = new VideoReader();
}
open_res = frameSource->open(this->templates[current_template_idx]);
if (!open_res)
{
current_template_idx++;
if (current_template_idx >= this->templates.size())
return false;
}
}
return true;
}
bool getNextFrame(FrameData & output)
{
bool got_frame = false;
Template aTemplate;
while (!got_frame)
{
got_frame = frameSource->getNextTemplate(aTemplate);
// OK we got a frame
if (got_frame) {
// set the sequence number and tempalte of this frame
output.sequenceNumber = next_sequence_number;
output.data.append(aTemplate);
// set the frame number in the template's metadata
output.data.last().file.set("FrameNumber", output.sequenceNumber);
next_sequence_number++;
return true;
}
// advance to the next tempalte in our list
this->current_template_idx++;
bool open_res = this->openNextTemplate();
// couldn't get the next template? nothing to do, otherwise we try to read
// a frame at the top of this loop.
if (!open_res) {
return false;
}
}
return false;
}
// Index of the template in the templatelist we are currently reading from
int current_template_idx;
// What do we do to each template
br::Idiocy::StreamModes mode;
// list of templates we are workign from
TemplateList templates;
// processor for the current template
TemplateProcessor * frameSource;
int next_sequence_number;
int final_frame;
bool is_broken;
bool allReturned;
DoubleBuffer allFrames;
QList<FrameData *> lookAhead;
QWaitCondition lastReturned;
QMutex last_frame_update;
};
class ProcessingStage;
class BasicLoop : public QRunnable, public QFutureInterface<void>
{
public:
BasicLoop()
{
this->reportStarted();
}
void run();
QList<ProcessingStage *> * stages;
int start_idx;
FrameData * startItem;
};
class ProcessingStage
{
public:
friend class DirectStreamTransform;
public:
ProcessingStage(int nThreads = 1)
{
thread_count = nThreads;
}
virtual ~ProcessingStage() {}
virtual FrameData* run(FrameData * input, bool & should_continue, bool & final)=0;
virtual bool tryAcquireNextStage(FrameData *& input, bool & final)=0;
int stage_id;
virtual void reset()=0;
virtual void status()=0;
protected:
int thread_count;
SharedBuffer * inputBuffer;
ProcessingStage * nextStage;
QList<ProcessingStage *> * stages;
QThreadPool * threads;
Transform * transform;
};
class MultiThreadStage : public ProcessingStage
{
public:
MultiThreadStage(int _input) : ProcessingStage(_input) {}
// Not much to worry about here, we will project the input
// and try to continue to the next stage.
FrameData * run(FrameData * input, bool & should_continue, bool & final)
{
if (input == NULL) {
qFatal("null input to multi-thread stage");
}
input->data >> *transform;
should_continue = nextStage->tryAcquireNextStage(input, final);
return input;
}
// Called from a different thread than run. Nothing to worry about
// we offer no restrictions on when loops may enter this stage.
virtual bool tryAcquireNextStage(FrameData *& input, bool & final)
{
(void) input;
final = false;
return true;
}
void reset()
{
// nothing to do.
}
void status(){
qDebug("multi thread stage %d, nothing to worry about", this->stage_id);
}
};
class SingleThreadStage : public ProcessingStage
{
public:
SingleThreadStage(bool input_variance) : ProcessingStage(1)
{
currentStatus = STOPPING;
next_target = 0;
// If the previous stage is single-threaded, queued inputs
// are stored in a double buffer
if (input_variance) {
this->inputBuffer = new DoubleBuffer();
}
// If it's multi-threaded we need to put the inputs back in order
// before we can use them, so we use a sequencing buffer.
else {
this->inputBuffer = new SequencingBuffer();
}
}
~SingleThreadStage()
{
delete inputBuffer;
}
void reset()
{
QWriteLocker writeLock(&statusLock);
currentStatus = STOPPING;
next_target = 0;
inputBuffer->reset();
}
int next_target;
enum Status
{
STARTING,
STOPPING
};
QReadWriteLock statusLock;
Status currentStatus;
FrameData * run(FrameData * input, bool & should_continue, bool & final)
{
if (input == NULL)
qFatal("NULL input to stage %d", this->stage_id);
if (input->sequenceNumber != next_target)
{
qFatal("out of order frames for stage %d, got %d expected %d", this->stage_id, input->sequenceNumber, this->next_target);
}
next_target = input->sequenceNumber + 1;
// Project the input we got
transform->projectUpdate(input->data);
should_continue = nextStage->tryAcquireNextStage(input,final);
if (final)
return input;
// Is there anything on our input buffer? If so we should start a thread with that.
QWriteLocker lock(&statusLock);
FrameData * newItem = inputBuffer->tryGetItem();
if (!newItem)
{
this->currentStatus = STOPPING;
}
lock.unlock();
if (newItem)
startThread(newItem);
return input;
}
void startThread(br::FrameData * newItem)
{
BasicLoop * next = new BasicLoop();
next->stages = stages;
next->start_idx = this->stage_id;
next->startItem = newItem;
// We start threads with priority equal to their stage id
// This is intended to ensure progression, we do queued late stage
// jobs before queued early stage jobs, and so tend to finish frames
// rather than go stage by stage. In Qt 5.1, priorities are priorities
// so we use the stage_id directly.
this->threads->start(next, stage_id);
}
// Calledfrom a different thread than run.
bool tryAcquireNextStage(FrameData *& input, bool & final)
{
final = false;
inputBuffer->addItem(input);
QReadLocker lock(&statusLock);
// Thread is already running, we should just return
if (currentStatus == STARTING)
{
return false;
}
// Have to change to a write lock to modify currentStatus
lock.unlock();
QWriteLocker writeLock(&statusLock);
// But someone else might have started a thread in the meantime
if (currentStatus == STARTING)
{
return false;
}
// Ok we might start a thread, as long as we can get something back
// from the input buffer
input = inputBuffer->tryGetItem();
if (!input)
return false;
currentStatus = STARTING;
return true;
}
void status(){
qDebug("single thread stage %d, status starting? %d, next %d buffer size %d", this->stage_id, this->currentStatus == SingleThreadStage::STARTING, this->next_target, this->inputBuffer->size());
}
};
// Semi-functional, doesn't do anything productive outside of stream::train
class CollectSets : public TimeVaryingTransform
{
Q_OBJECT
public:
CollectSets() : TimeVaryingTransform(false, false) {}
QList<TemplateList> sets;
void projectUpdate(const TemplateList &src, TemplateList &dst)
{
(void) dst;
sets.append(src);
}
void train(const TemplateList & data)
{
(void) data;
}
};
// This stage reads new frames from the data source.
class ReadStage : public SingleThreadStage
{
public:
ReadStage(int activeFrames = 100) : SingleThreadStage(true), dataSource(activeFrames){ }
DataSource dataSource;
void reset()
{
dataSource.close();
SingleThreadStage::reset();
}
FrameData * run(FrameData * input, bool & should_continue, bool & final)
{
if (input == NULL)
qFatal("NULL frame in input stage");
// Can we enter the next stage?
should_continue = nextStage->tryAcquireNextStage(input, final);
// Try to get a frame from the datasource, we keep working on
// the frame we have, but we will queue another job for the next
// frame if a frame is currently available.
QWriteLocker lock(&statusLock);
bool last_frame = false;
FrameData * newFrame = dataSource.tryGetFrame(last_frame);
// Were we able to get a frame?
if (newFrame) startThread(newFrame);
// If not this stage will enter a stopped state.
else {
currentStatus = STOPPING;
}
lock.unlock();
return input;
}
// The last stage, trying to access the first stage
bool tryAcquireNextStage(FrameData *& input, bool & final)
{
// Return the frame, was it the last one?
final = dataSource.returnFrame(input);
input = NULL;
// OK we won't continue.
if (final) {
return false;
}
QReadLocker lock(&statusLock);
// If the first stage is already active we will just end.
if (currentStatus == STARTING)
{
return false;
}
// Otherwise we will try to continue, but to do so we have to
// escalate the lock, and sadly there is no way to do so without
// releasing the read-mode lock, and getting a new write-mode lock.
lock.unlock();
QWriteLocker writeLock(&statusLock);
// currentStatus might have changed in the gap between releasing the read
// lock and getting the write lock.
if (currentStatus == STARTING)
{
return false;
}
bool last_frame = false;
// Try to get a frame from the data source, if we get one we will
// continue to the first stage.
input = dataSource.tryGetFrame(last_frame);
if (!input) {
return false;
}
currentStatus = STARTING;
return true;
}
void status(){
qDebug("Read stage %d, status starting? %d, next frame %d buffer size %d", this->stage_id, this->currentStatus == SingleThreadStage::STARTING, this->next_target, this->dataSource.size());
}
};
void BasicLoop::run()
{
int current_idx = start_idx;
FrameData * target_item = startItem;
bool should_continue = true;
bool the_end = false;
forever
{
target_item = stages->at(current_idx)->run(target_item, should_continue, the_end);
if (!should_continue) {
break;
}
current_idx++;
current_idx = current_idx % stages->size();
}
if (the_end) {
dynamic_cast<ReadStage *> (stages->at(0))->dataSource.wake();
}
this->reportFinished();
}
class DirectStreamTransform : public CompositeTransform
{
Q_OBJECT
public:
Q_PROPERTY(int activeFrames READ get_activeFrames WRITE set_activeFrames RESET reset_activeFrames)
Q_PROPERTY(br::Idiocy::StreamModes readMode READ get_readMode WRITE set_readMode RESET reset_readMode)
BR_PROPERTY(int, activeFrames, 100)
BR_PROPERTY(br::Idiocy::StreamModes, readMode, br::Idiocy::Auto)
friend class StreamTransfrom;
void subProject(QList<TemplateList> & data, int end_idx)
{
if (end_idx == 0)
return;
CollectSets collector;
// Set transforms to the start, up to end_idx
QList<Transform *> backup = this->transforms;
transforms = backup.mid(0,end_idx);
// We use collector to retain the project structure at the end of the
// truncated stream.
transforms.append(&collector);
// Reinitialize, we now act as a shorter stream.
init();
QList<TemplateList> output;
for (int i=0; i < data.size(); i++) {
projectUpdate(data[i], data[i]);
output.append(collector.sets);
collector.sets.clear();
}
data = output;
transforms = backup;
}
void train(const QList<TemplateList> & data)
{
if (!trainable) {
qWarning("Attempted to train untrainable transform, nothing will happen.");
return;
}
for (int i=0; i < transforms.size(); i++) {
// OK we have a trainable transform, we need to get input data for it.
if (transforms[i]->trainable) {
QList<TemplateList> copy = data;
// Project from the start to the trainable stage.
subProject(copy,i);
transforms[i]->train(copy);
}
}
// Re-initialize because subProject probably messed us up.
init();
}
bool timeVarying() const { return true; }
void project(const Template &src, Template &dst) const
{
TemplateList in;
in.append(src);
TemplateList out;
CompositeTransform::project(in,out);
dst = out.first();
if (out.size() > 1)
qDebug("Returning first output template only");
}
void projectUpdate(const Template &src, Template &dst)
{
TemplateList in;
in.append(src);
TemplateList out;
projectUpdate(in,out);
dst = out.first();
if (out.size() > 1)
qDebug("Returning first output template only");
}
virtual void finalize(TemplateList & output)
{
(void) output;
// Nothing in particular to do here, stream calls finalize
// on all child transforms as part of projectUpdate
}
// start processing, consider all templates in src a continuous
// 'video'
void projectUpdate(const TemplateList & src, TemplateList & dst)
{
dst = src;
if (src.empty())
return;
bool res = readStage->dataSource.open(src,readMode);
if (!res) {
qDebug("stream failed to open %s", qPrintable(dst[0].file.name));
return;
}
// Start the first thread in the stream.
QWriteLocker lock(&readStage->statusLock);
readStage->currentStatus = SingleThreadStage::STARTING;
// We have to get a frame before starting the thread
bool last_frame = false;
FrameData * firstFrame = readStage->dataSource.tryGetFrame(last_frame);
if (firstFrame == NULL)
qFatal("Failed to read first frame of video");
readStage->startThread(firstFrame);
lock.unlock();
// Wait for the stream to process the last frame available from
// the data source.
bool wait_res = false;
wait_res = readStage->dataSource.waitLast();
// Now that there are no more incoming frames, call finalize
// on each transform in turn to collect any last templates
// they wish to issue.
TemplateList final_output;
// Push finalize through the stages
for (int i=0; i < this->transforms.size(); i++)
{
TemplateList output_set;
transforms[i]->finalize(output_set);
if (output_set.empty())
continue;
for (int j=i+1; j < transforms.size();j++)
{
transforms[j]->projectUpdate(output_set);
}
final_output.append(output_set);
}
// Clear dst, since we set it to src so that the datasource could open it
dst.clear();
// dst is set to all output received by the final stage, along
// with anything output via the calls to finalize.
foreach(const TemplateList & list, collector->sets) {
dst.append(list);
}
collector->sets.clear();
dst.append(final_output);
foreach(ProcessingStage * stage, processingStages) {
stage->reset();
}
}
// Create and link stages
void init()
{
if (transforms.isEmpty()) return;
for (int i=0; i < processingStages.size();i++)
delete processingStages[i];
processingStages.clear();
// call CompositeTransform::init so that trainable is set
// correctly.
CompositeTransform::init();
// We share a thread pool across streams attached to the same
// parent tranform, retrieve or create a thread pool based
// on our parent transform.
QMutexLocker poolLock(&poolsAccess);
QHash<QObject *, QThreadPool *>::Iterator it;
if (!pools.contains(this->parent())) {
it = pools.insert(this->parent(), new QThreadPool(this->parent()));
it.value()->setMaxThreadCount(Globals->parallelism);
}
else it = pools.find(this->parent());
threads = it.value();
poolLock.unlock();
// Are our children time varying or not? This decides whether
// we run them in single threaded or multi threaded stages
stage_variance.clear();
stage_variance.reserve(transforms.size());
foreach (const br::Transform *transform, transforms) {
stage_variance.append(transform->timeVarying());
}
// Additionally, we have a separate stage responsible for reading
// frames from the data source
readStage = new ReadStage(activeFrames);
processingStages.push_back(readStage);
readStage->stage_id = 0;
readStage->stages = &this->processingStages;
readStage->threads = this->threads;
// Initialize and link a processing stage for each of our child
// transforms.
int next_stage_id = 1;
bool prev_stage_variance = true;
for (int i =0; i < transforms.size(); i++)
{
if (stage_variance[i])
// Whether or not the previous stage is multi-threaded controls
// the type of input buffer we need in a single threaded stage.
processingStages.append(new SingleThreadStage(prev_stage_variance));
else
processingStages.append(new MultiThreadStage(Globals->parallelism));
processingStages.last()->stage_id = next_stage_id++;
// link nextStage pointers, the stage we just appeneded is i+1 since
// the read stage was added before this loop
processingStages[i]->nextStage = processingStages[i+1];
processingStages.last()->stages = &this->processingStages;
processingStages.last()->threads = this->threads;
processingStages.last()->transform = transforms[i];
prev_stage_variance = stage_variance[i];
}
// We also have the last stage, which just puts the output of the
// previous stages on a template list.
collectionStage = new SingleThreadStage(prev_stage_variance);
collectionStage->transform = this->collector.data();
processingStages.append(collectionStage);
collectionStage->stage_id = next_stage_id;
collectionStage->stages = &this->processingStages;
collectionStage->threads = this->threads;
// the last transform stage points to collection stage
processingStages[processingStages.size() - 2]->nextStage = collectionStage;
// And the collection stage points to the read stage, because this is
// a ring buffer.
collectionStage->nextStage = readStage;
}
DirectStreamTransform()
{
this->collector = QSharedPointer<CollectSets>(new CollectSets());
}
~DirectStreamTransform()
{
// Delete all the stages
for (int i = 0; i < processingStages.size(); i++) {
delete processingStages[i];
}
processingStages.clear();
}
protected:
QList<bool> stage_variance;
ReadStage * readStage;
SingleThreadStage * collectionStage;
QSharedPointer<CollectSets> collector;
QList<ProcessingStage *> processingStages;
// This is a map from parent transforms (of Streams) to thread pools. Rather
// than starting threads on the global thread pool, Stream uses separate thread pools
// keyed on their parent transform. This is necessary because stream's project starts
// threads, then enters an indefinite wait for them to finish. Since we are starting
// threads using thread pools, threads themselves are a limited resource. Therefore,
// the type of hold and wait done by stream project can lead to deadlock unless
// resources are ordered in such a way that a circular wait will not occur. The points
// of this hash is to introduce a resource ordering (on threads) that mirrors the structure
// of the algorithm. So, as long as the structure of the algorithm is a DAG, the wait done
// by stream project will not be circular, since every thread in stream project is waiting
// for threads at a lower level to do the work.
// This issue doesn't come up in distribute, since a thread waiting on a QFutureSynchronizer
// will steal work from those jobs, so in that sense distribute isn't doing a hold and wait.
// Waiting for a QFutureSynchronzier isn't really possible here since stream runs an indeteriminate
// number of jobs.
static QHash<QObject *, QThreadPool *> pools;
static QMutex poolsAccess;
QThreadPool * threads;
void _project(const Template &src, Template &dst) const
{
(void) src; (void) dst;
qFatal("nope");
}
void _project(const TemplateList & src, TemplateList & dst) const
{
(void) src; (void) dst;
qFatal("nope");
}
};
QHash<QObject *, QThreadPool *> DirectStreamTransform::pools;
QMutex DirectStreamTransform::poolsAccess;
BR_REGISTER(Transform, DirectStreamTransform)
class StreamTransform : public WrapperTransform
{
Q_OBJECT
public:
StreamTransform() : WrapperTransform(false)
{
}
Q_PROPERTY(int activeFrames READ get_activeFrames WRITE set_activeFrames RESET reset_activeFrames)
Q_PROPERTY(br::Idiocy::StreamModes readMode READ get_readMode WRITE set_readMode RESET reset_readMode)
BR_PROPERTY(int, activeFrames, 100)
BR_PROPERTY(br::Idiocy::StreamModes, readMode, br::Idiocy::Auto)
bool timeVarying() const { return true; }
void project(const Template &src, Template &dst) const
{
basis.project(src,dst);
}
void projectUpdate(const Template &src, Template &dst)
{
basis.projectUpdate(src,dst);
}
void projectUpdate(const TemplateList & src, TemplateList & dst)
{
basis.projectUpdate(src,dst);
}
void train(const QList<TemplateList> & data)
{
basis.train(data);
}
virtual void finalize(TemplateList & output)
{
(void) output;
// Nothing in particular to do here, stream calls finalize
// on all child transforms as part of projectUpdate
}
// reinterpret transform, set up the actual stream. We can only reinterpret pipes
void init()
{
if (!transform)
return;
trainable = transform->trainable;
basis.setParent(this->parent());
basis.transforms.clear();
basis.activeFrames = this->activeFrames;
basis.readMode = this->readMode;
// We need at least a CompositeTransform * to acess transform's children.
CompositeTransform * downcast = dynamic_cast<CompositeTransform *> (transform);
// If this isn't even a composite transform, or it's not a pipe, just set up
// basis with 1 stage.
if (!downcast || QString(transform->metaObject()->className()) != "br::PipeTransform")
{
basis.transforms.append(transform);
basis.init();
return;
}
if (downcast->transforms.empty())
{
qWarning("Trying to set up empty stream");
basis.init();
return;
}
// OK now we will regroup downcast's children
QList<QList<Transform *> > sets;
sets.append(QList<Transform *> ());
sets.last().append(downcast->transforms[0]);
if (downcast->transforms[0]->timeVarying())
sets.append(QList<Transform *> ());
for (int i=1;i < downcast->transforms.size(); i++) {
// If this is time varying it becomse its own stage
if (downcast->transforms[i]->timeVarying()) {
// If a set was already active, we add another one
if (!sets.last().empty()) {
sets.append(QList<Transform *>());
}
// add the item
sets.last().append(downcast->transforms[i]);
// Add another set to indicate separation.
sets.append(QList<Transform *>());
}
// otherwise, we can combine non time-varying stages
else {
sets.last().append(downcast->transforms[i]);
}
}
if (sets.last().empty())
sets.removeLast();
QList<Transform *> transform_set;
transform_set.reserve(sets.size());
for (int i=0; i < sets.size(); i++) {
// If this is a single transform set, we add that to the list
if (sets[i].size() == 1 ) {
transform_set.append(sets[i].at(0));
}
//otherwise we build a pipe
else {
CompositeTransform * pipe = dynamic_cast<CompositeTransform *>(Transform::make("Pipe([])", this));
pipe->transforms = sets[i];
pipe->init();
transform_set.append(pipe);
}
}
basis.transforms = transform_set;
basis.init();
}
Transform * smartCopy(bool & newTransform)
{
// We just want the DirectStream to begin with, so just return a copy of that.
DirectStreamTransform * res = (DirectStreamTransform *) basis.smartCopy(newTransform);
res->activeFrames = this->activeFrames;
return res;
}
private:
DirectStreamTransform basis;
};
BR_REGISTER(Transform, StreamTransform)
} // namespace br
#include "stream.moc"