forked from jnohlgard/python-v4l2capture
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnamedpipeout.cpp
473 lines (395 loc) · 12.5 KB
/
namedpipeout.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
#include "namedpipeout.h"
#include "pixfmt.h"
#include <iostream>
#include <string>
using namespace std;
#include <stdio.h>
#include <tchar.h>
#include <strsafe.h>
#define BUFSIZE 1024*1024*10
int ProcessClientMessage(class InstanceConfig &instanceConfig);
VOID GetAnswerToRequest(char *pReply, LPDWORD pchBytes, class InstanceConfig &instanceConfig, class NamedPipeOut *, int frameCount);
class InstanceConfig
{
public:
std::string rxBuff;
UINT32 width, height, frameLen;
InstanceConfig()
{
width = 0;
height = 0;
frameLen = 0;
}
};
class ConnectionThreadInfo
{
public:
HANDLE hPipe;
class NamedPipeOut *parent;
ConnectionThreadInfo()
{
hPipe = INVALID_HANDLE_VALUE;
parent = NULL;
}
};
DWORD WINAPI InstanceThread(LPVOID lpvParam)
// This routine is a thread processing function to read from and reply to a client
// via the open pipe connection passed from the main loop. Note this allows
// the main loop to continue executing, potentially creating more threads of
// of this procedure to run concurrently, depending on the number of incoming
// client connections.
{
HANDLE hHeap = GetProcessHeap();
char* pRequest = (char*)HeapAlloc(hHeap, 0, BUFSIZE);
char* pReply = (char*)HeapAlloc(hHeap, 0, BUFSIZE);
DWORD cbBytesRead = 0, cbReplyBytes = 0, cbWritten = 0;
BOOL fSuccess = FALSE;
HANDLE hPipe = NULL;
class InstanceConfig instanceConfig;
// Do some extra error checking since the app will keep running even if this
// thread fails.
if (lpvParam == NULL)
{
printf( "\nERROR - Pipe Server Failure:\n");
printf( " InstanceThread got an unexpected NULL value in lpvParam.\n");
printf( " InstanceThread exitting.\n");
if (pReply != NULL) HeapFree(hHeap, 0, pReply);
if (pRequest != NULL) HeapFree(hHeap, 0, pRequest);
return (DWORD)-1;
}
if (pRequest == NULL)
{
printf( "\nERROR - Pipe Server Failure:\n");
printf( " InstanceThread got an unexpected NULL heap allocation.\n");
printf( " InstanceThread exitting.\n");
if (pReply != NULL) HeapFree(hHeap, 0, pReply);
return (DWORD)-1;
}
if (pReply == NULL)
{
printf( "\nERROR - Pipe Server Failure:\n");
printf( " InstanceThread got an unexpected NULL heap allocation.\n");
printf( " InstanceThread exitting.\n");
if (pRequest != NULL) HeapFree(hHeap, 0, pRequest);
return (DWORD)-1;
}
// Print verbose messages. In production code, this should be for debugging only.
printf("InstanceThread created, receiving and processing messages.\n");
// The thread's parameter is a handle to a pipe object instance.
class ConnectionThreadInfo *info = (class ConnectionThreadInfo *)lpvParam;
class NamedPipeOut *parent = info->parent;
hPipe = info->hPipe;
delete info;
//Initialise timer
SYSTEMTIME systime;
GetSystemTime(&systime);
FILETIME lastUpdateTime;
SystemTimeToFileTime(&systime, &lastUpdateTime);
int frameCount = 0;
// Loop until done reading
while (1)
{
SYSTEMTIME systime;
GetSystemTime(&systime);
FILETIME fiTime;
SystemTimeToFileTime(&systime, &fiTime);
LARGE_INTEGER fiTimeNum;
fiTimeNum.HighPart = fiTime.dwHighDateTime;
fiTimeNum.LowPart = fiTime.dwLowDateTime;
LARGE_INTEGER lastUpdate;
lastUpdate.HighPart = lastUpdateTime.dwHighDateTime;
lastUpdate.LowPart = lastUpdateTime.dwLowDateTime;
LARGE_INTEGER elapse;
elapse.QuadPart = fiTimeNum.QuadPart - lastUpdate.QuadPart;
float elapseMs = elapse.LowPart / 10000.f;
// Read client requests from the pipe. This simplistic code only allows messages
// up to BUFSIZE characters in length.
fSuccess = ReadFile(
hPipe, // handle to pipe
pRequest, // buffer to receive data
BUFSIZE, // size of buffer
&cbBytesRead, // number of bytes read
NULL); // not overlapped I/O
if (!fSuccess || cbBytesRead == 0)
{
if (GetLastError() == ERROR_BROKEN_PIPE)
{
_tprintf(TEXT("InstanceThread: client disconnected.\n"), GetLastError());
}
else
{
_tprintf(TEXT("InstanceThread ReadFile failed, GLE=%d.\n"), GetLastError());
}
break;
}
//Process received message
instanceConfig.rxBuff.append(pRequest, cbBytesRead);
if(elapseMs >= 10.f)
{
ProcessClientMessage(instanceConfig);
printf("elapse %f\n", elapseMs);
// Get response string
GetAnswerToRequest(pReply, &cbReplyBytes, instanceConfig, parent, frameCount);
frameCount++;
// Write the reply to the pipe.
fSuccess = WriteFile(
hPipe, // handle to pipe
pReply, // buffer to write from
cbReplyBytes, // number of bytes to write
&cbWritten, // number of bytes written
NULL); // not overlapped I/O
if (!fSuccess || cbReplyBytes != cbWritten)
{
_tprintf(TEXT("InstanceThread WriteFile failed, GLE=%d.\n"), GetLastError());
break;
}
lastUpdateTime=fiTime;
}
else
{
Sleep(1);
}
}
// Flush the pipe to allow the client to read the pipe's contents
// before disconnecting. Then disconnect the pipe, and close the
// handle to this pipe instance.
FlushFileBuffers(hPipe);
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
HeapFree(hHeap, 0, pRequest);
HeapFree(hHeap, 0, pReply);
printf("InstanceThread exitting.\n");
return 1;
}
VOID GetAnswerToRequest(char *pReply, LPDWORD pchBytes, class InstanceConfig &instanceConfig,
class NamedPipeOut *parent, int frameCount)
{
if(instanceConfig.frameLen + 8 < BUFSIZE)
{
//Return frame
UINT32 *numArr = (UINT32 *)pReply;
numArr[0] = 2;
numArr[1] = instanceConfig.frameLen;
unsigned char *imgPix = (unsigned char *)&pReply[8];
parent->Lock();
//Copy and resize frame if necessary (and invert y)
//TODO use bilinear sampling?
ResizeRgb24ImageNN(parent->currentFrame, parent->currentFrameLen,
parent->currentFrameWidth,
parent->currentFrameHeight,
imgPix,
instanceConfig.frameLen,
instanceConfig.width, instanceConfig.height, 1);
//memcpy(imgPix, parent->currentFrame, bytesToCopy);
parent->UnLock();
*pchBytes = 8 + instanceConfig.frameLen;
}
else
{
//Insufficient space in buffer
UINT32 *numArr = (UINT32 *)pReply;
numArr[0] = 3;
numArr[1] = 0;
*pchBytes = 8;
}
}
int ProcessClientMessage(class InstanceConfig &instanceConfig)
{
int count = 0;
int processing = 1;
while(processing && instanceConfig.rxBuff.size() > 8)
{
UINT32 *wordArray = (UINT32 *)instanceConfig.rxBuff.c_str();
UINT32 msgType = wordArray[0];
UINT32 msgLen = wordArray[1];
if(instanceConfig.rxBuff.size() >= 8+msgLen)
{
std::string msg(instanceConfig.rxBuff, 8, msgLen);
UINT32 *msgArray = (UINT32 *)msg.c_str();
//printf("%d %d %d\n", rxBuff.size(), msgType, msg.size());
instanceConfig.rxBuff.assign(instanceConfig.rxBuff, 8+msgLen, instanceConfig.rxBuff.size() - 8 - msgLen);
if(msgType == 1)
{
instanceConfig.width = msgArray[0];
instanceConfig.height = msgArray[1];
instanceConfig.frameLen = msgArray[2];
count ++;
}
if(msgType != 1)
{
printf("Buffer corruption detected\n");
return 0;
}
}
else
{
processing = 0;
}
}
printf("rx msg count %d\n", count);
printf("w%d h%d buff%d\n",instanceConfig.width, instanceConfig.height, instanceConfig.frameLen);
return 1;
}
//*******************************************************************************************
NamedPipeOut::NamedPipeOut(const char *devName) : Base_Video_Out()
{
HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
if(hr == RPC_E_CHANGED_MODE)
throw std::runtime_error("CoInitializeEx failed");
running = 0;
currentFrameAlloc = 0;
currentFrameLen = 0;
currentFrame = NULL;
currentFrameWidth = 0;
currentFrameHeight = 0;
InitializeCriticalSection(&lock);
}
NamedPipeOut::~NamedPipeOut()
{
CoUninitialize();
}
void NamedPipeOut::SendFrame(const char *imgIn, unsigned imgLen, const char *pxFmt, int width, int height,
unsigned long tv_sec,
unsigned long tv_usec)
{
cout << "NamedPipeOut::SendFrame" << endl;
//Convert from input pxFmt to BGR24.
unsigned char *bgrBuff = NULL;
unsigned bgrBuffLen = 0;
int ret = DecodeFrame((unsigned char*)imgIn, imgLen,
pxFmt,
width, height,
"BGR24",
&bgrBuff,
&bgrBuffLen);
if(ret>0 && bgrBuff != NULL)
{
this->Lock();
if(bgrBuffLen > this->currentFrameAlloc || this->currentFrame == NULL)
{
//Resize current frame buffer
if(this->currentFrame != NULL) delete [] this->currentFrame;
this->currentFrame = new unsigned char [bgrBuffLen];
this->currentFrameAlloc = bgrBuffLen;
}
//Copy new frame to local storage
memcpy(this->currentFrame, bgrBuff, bgrBuffLen);
this->currentFrameWidth = width;
this->currentFrameHeight = height;
this->currentFrameLen = bgrBuffLen;
//Free temporary buffer
delete [] bgrBuff;
bgrBuff = NULL;
bgrBuffLen = 0;
this->UnLock();
}
else
{
throw std::runtime_error("Cannot convert pixel format to BGR24");
}
}
void NamedPipeOut::Stop()
{
EnterCriticalSection(&lock);
this->running = 0;
LeaveCriticalSection(&lock);
}
int NamedPipeOut::WaitForStop()
{
return 1;
}
void NamedPipeOut::SetOutputSize(int width, int height)
{
}
void NamedPipeOut::SetOutputPxFmt(const char *fmt)
{
}
void NamedPipeOut::Run()
{
EnterCriticalSection(&lock);
this->running = 1;
int tmpRunning = this->running;
LeaveCriticalSection(&lock);
BOOL fConnected = FALSE;
DWORD dwThreadId = 0;
HANDLE hPipe = INVALID_HANDLE_VALUE, hThread = NULL;
LPTSTR lpszPipename = TEXT("\\\\.\\pipe\\testpipe");
// Creates an instance of the named pipe and
// then waits for a client to connect to it. When the client
// connects, a thread is created to handle communications
// with that client, and this loop is free to wait for the
// next client connect request. It is an infinite loop.
while (tmpRunning)
{
_tprintf( TEXT("\nPipe Server: Main thread awaiting client connection on %s\n"), lpszPipename);
hPipe = CreateNamedPipe(
lpszPipename, // pipe name
PIPE_ACCESS_DUPLEX, // read/write access
PIPE_TYPE_BYTE | // message type pipe
PIPE_READMODE_BYTE | // message-read mode
PIPE_WAIT, // blocking mode
PIPE_UNLIMITED_INSTANCES, // max. instances
BUFSIZE, // output buffer size
BUFSIZE, // input buffer size
0, // client time-out
NULL); // default security attribute
if (hPipe == INVALID_HANDLE_VALUE)
{
_tprintf(TEXT("CreateNamedPipe failed, GLE=%d.\n"), GetLastError());
return;
}
// Wait for the client to connect; if it succeeds,
// the function returns a nonzero value. If the function
// returns zero, GetLastError returns ERROR_PIPE_CONNECTED.
fConnected = ConnectNamedPipe(hPipe, NULL) ?
TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);
if (fConnected)
{
printf("Client connected, creating a processing thread.\n");
class ConnectionThreadInfo *info = new class ConnectionThreadInfo();
info->parent = this;
info->hPipe = hPipe;
// Create a thread for this client.
hThread = CreateThread(
NULL, // no security attribute
0, // default stack size
InstanceThread, // thread proc
(LPVOID) info, // thread parameter
0, // not suspended
&dwThreadId); // returns thread ID
if (hThread == NULL)
{
_tprintf(TEXT("CreateThread failed, GLE=%d.\n"), GetLastError());
return;
}
else CloseHandle(hThread);
}
else
// The client could not connect, so close the pipe.
CloseHandle(hPipe);
EnterCriticalSection(&lock);
tmpRunning = this->running;
LeaveCriticalSection(&lock);
}
}
void NamedPipeOut::Lock()
{
EnterCriticalSection(&lock);
}
void NamedPipeOut::UnLock()
{
LeaveCriticalSection(&lock);
}
//*******************************************************************************
void *NamedPipeOut_Worker_thread(void *arg)
{
class NamedPipeOut *argobj = (class NamedPipeOut*) arg;
argobj->Run();
return NULL;
}
std::vector<std::string> List_out_devices()
{
std::vector<std::string> out;
out.push_back("VirtualCamera");
return out;
}