-
Notifications
You must be signed in to change notification settings - Fork 12
/
BonDriver_Mirakurun.cpp
executable file
·1004 lines (823 loc) · 25.9 KB
/
BonDriver_Mirakurun.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 "BonDriver_Mirakurun.h"
#pragma comment(lib, "ws2_32.lib")
#define BITRATE_CALC_TIME 500 //ms
//////////////////////////////////////////////////////////////////////
// 定数定義
//////////////////////////////////////////////////////////////////////
// ミューテックス名
#define MUTEX_NAME TEXT(TUNER_NAME)
// FIFOバッファ設定
#define ASYNCBUFFTIME 2 // バッファ長 = 2秒
#define ASYNCBUFFSIZE ( 0x200000 / TSDATASIZE * ASYNCBUFFTIME ) // 平均16Mbpsとする
#define REQRESERVNUM 8 // 非同期リクエスト予約数 //before 16
#define REQPOLLINGWAIT 20 // 非同期リクエストポーリング間隔(ms) //before 10
// 非同期リクエスト状態
#define IORS_IDLE 0x00 // リクエスト空
#define IORS_BUSY 0x01 // リクエスト受信中
#define IORS_RECV 0x02 // 受信完了、ストア待ち
static int Init(HMODULE hModule)
{
GetModuleFileName(hModule, g_IniFilePath, MAX_PATH);
wchar_t drive[_MAX_DRIVE];
wchar_t dir[_MAX_DIR];
wchar_t fname[_MAX_FNAME];
_wsplitpath_s(g_IniFilePath, drive, sizeof(drive), dir, sizeof(dir), fname, sizeof(fname), NULL, NULL);
wsprintf(g_IniFilePath, L"%s%s%s.ini\0", drive, dir, fname);
HANDLE hFile = CreateFile(g_IniFilePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
return -2;
}
CloseHandle(hFile);
size_t ret;
wchar_t tmpServerHost[MAX_HOST_LEN];
GetPrivateProfileString(L"GLOBAL", L"SERVER_HOST", L"localhost", tmpServerHost, sizeof(tmpServerHost), g_IniFilePath);
wcstombs_s(&ret, g_ServerHost, tmpServerHost, sizeof(g_ServerHost));
wchar_t tmpServerPort[MAX_PORT_LEN];
GetPrivateProfileString(L"GLOBAL", L"SERVER_PORT", L"8888", tmpServerPort, sizeof(tmpServerPort), g_IniFilePath);
wcstombs_s(&ret, g_ServerPort, tmpServerPort, sizeof(g_ServerPort));
g_DecodeB25 = GetPrivateProfileInt(L"GLOBAL", L"DECODE_B25", 0, g_IniFilePath);
g_Priority = GetPrivateProfileInt(L"GLOBAL", L"PRIORITY", 0, g_IniFilePath);
g_Service_Split = GetPrivateProfileInt(L"GLOBAL", L"SERVICE_SPLIT", 0, g_IniFilePath);
setlocale(LC_ALL, "japanese");
g_MagicPacket_Enable = GetPrivateProfileInt(L"GLOBAL", L"MAGICPACKET_ENABLE", 0, g_IniFilePath);
if (g_MagicPacket_Enable) {
wchar_t tmpMagicPacket_TargetMAC[18];
GetPrivateProfileString(L"GLOBAL", L"MAGICPACKET_TARGETMAC", L"00:00:00:00:00:00", tmpMagicPacket_TargetMAC, sizeof(tmpMagicPacket_TargetMAC), g_IniFilePath);
wcstombs_s(&ret, g_MagicPacket_TargetMAC, tmpMagicPacket_TargetMAC, sizeof(g_MagicPacket_TargetMAC));
for (int i = 0; i < 6; i++) {
BYTE b = 0;
char *p = &g_MagicPacket_TargetMAC[i * 3];
for (int j = 0; j < 2; j++) {
if (*p >= '0' && *p <= '9') {
b = b * 0x10 + (*p - '0');
} else if (*p >= 'a' && *p <= 'f') {
b = b * 0x10 + (10 + *p - 'a');
} else if (*p >= 'A' && *p <= 'F') {
b = b * 0x10 + (10 + *p - 'A');
}
p++;
}
g_MagicPacket_TargetMAC[i] = b;
}
wchar_t tmpMagicPacket_TargetIP[16];
GetPrivateProfileString(L"GLOBAL", L"MAGICPACKET_TARGETIP", L"0.0.0.0", tmpMagicPacket_TargetIP, sizeof(tmpMagicPacket_TargetIP), g_IniFilePath);
wcstombs_s(&ret, g_MagicPacket_TargetIP, tmpMagicPacket_TargetIP, sizeof(g_MagicPacket_TargetIP));
}
return 0;
}
BOOL APIENTRY DllMain(HINSTANCE hModule, DWORD fdwReason, LPVOID lpReserved)
{
switch (fdwReason) {
case DLL_PROCESS_ATTACH:
if (Init(hModule) != 0) {
return FALSE;
}
// モジュールハンドル保存
CBonTuner::m_hModule = hModule;
break;
case DLL_PROCESS_DETACH:
// 未開放の場合はインスタンス開放
if (CBonTuner::m_pThis) {
CBonTuner::m_pThis->Release();
}
break;
}
return TRUE;
}
inline DWORD DiffTime(DWORD BeginTime,DWORD EndTime)
{
if (BeginTime <= EndTime)
return EndTime-BeginTime;
return (0xFFFFFFFFUL-BeginTime)+EndTime+1UL;
}
//////////////////////////////////////////////////////////////////////
// インスタンス生成メソッド
//////////////////////////////////////////////////////////////////////
extern "C" __declspec(dllexport) IBonDriver * CreateBonDriver()
{
// スタンス生成(既存の場合はインスタンスのポインタを返す)
return (CBonTuner::m_pThis)? CBonTuner::m_pThis : ((IBonDriver *) new CBonTuner);
}
//////////////////////////////////////////////////////////////////////
// 構築/消滅
//////////////////////////////////////////////////////////////////////
// 静的メンバ初期化
CBonTuner * CBonTuner::m_pThis = NULL;
HINSTANCE CBonTuner::m_hModule = NULL;
CBonTuner::CBonTuner()
: m_bTunerOpen(FALSE)
, m_hMutex(NULL)
, m_pIoReqBuff(NULL)
, m_pIoPushReq(NULL)
, m_pIoPopReq(NULL)
, m_pIoGetReq(NULL)
, m_dwBusyReqNum(0UL)
, m_dwReadyReqNum(0UL)
, m_hPushIoThread(NULL)
, m_hPopIoThread(NULL)
, m_hOnStreamEvent(NULL)
, m_dwCurSpace(0UL)
, m_dwCurChannel(0xFFFFFFFFUL)
, m_sock(INVALID_SOCKET)
, m_fBitRate(0.0f)
, m_dwRecvBytes(0UL)
, m_dwLastCalcTick(0UL)
{
m_pThis = this;
// グローバル変数初期化
for (int i = 0; i < SPACE_NUM; i++) {
g_pType[i] = NULL;
}
// クリティカルセクション初期化
::InitializeCriticalSection(&m_CriticalSection);
//Initialize channel
InitChannel();
}
CBonTuner::~CBonTuner()
{
// 開かれてる場合は閉じる
CloseTuner();
// メモリ解放
for (int i = 0; i < SPACE_NUM; i++) {
if (g_pType[i]) {
free(g_pType[i]);
}
else {
break;
}
}
// クリティカルセクション削除
::DeleteCriticalSection(&m_CriticalSection);
// Winsock終了
if (m_bTunerOpen) {
WSACleanup();
}
m_pThis = NULL;
}
void CBonTuner::InitChannel()
{
// Mirakurun APIよりchannel取得
GetApiChannels(&g_Channel_JSON, g_Service_Split);
if (g_Channel_JSON.is<picojson::null>()) {
return;
}
if (!g_Channel_JSON.contains(0)) {
return;
}
// チューナ空間取得
int i = 0;
int j = 0;
while (j < SPACE_NUM - 1) {
if (!g_Channel_JSON.contains(i)) {
break;
}
picojson::object& channel_obj = g_Channel_JSON.get(i).get<picojson::object>();
const char *type;
if (g_Service_Split == 1) {
picojson::object& channel_detail = channel_obj["channel"].get<picojson::object>();
type = channel_detail["type"].get<std::string>().c_str();
}
else {
type = channel_obj["type"].get<std::string>().c_str();
}
if (!g_pType[0]) {
int len = (int)strlen(type) + 1;
g_pType[0] = (char *)malloc(len);
if (!g_pType[0]) {
break;
}
strcpy_s(g_pType[0], len, type);
}
else if (strcmp(g_pType[j], type)) {
int len = (int)strlen(type) + 1;
g_pType[++j] = (char *)malloc(len);
if (!g_pType[j]) {
j--;
break;
}
strcpy_s(g_pType[j], len, type);
g_Channel_Base[j] = i;
}
i++;
}
g_Max_Type = j;
}
const BOOL CBonTuner::OpenTuner()
{
if (g_Channel_JSON.is<picojson::null>()) {
return FALSE;
}
if (!m_bTunerOpen) {
// Winsock初期化
WSADATA stWsa;
if (WSAStartup(MAKEWORD(2,2), &stWsa) != 0) {
return FALSE;
}
if (g_MagicPacket_Enable) {
char magicpacket[102];
memset(&magicpacket, 0xff, 6);
for (int i = 0; i < 16; i++) {
memcpy(&magicpacket[i * 6 + 6], g_MagicPacket_TargetMAC, 6);
}
SOCKET s = socket(PF_INET, SOCK_DGRAM, 0);
if (s == SOCKET_ERROR) {
return FALSE;
}
SOCKADDR_IN addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(9);
addr.sin_addr.S_un.S_addr = inet_addr(g_MagicPacket_TargetIP);
sendto(s, magicpacket, sizeof(magicpacket), 0, (LPSOCKADDR)&addr, sizeof(addr));
DWORD dwLastTime = ::GetTickCount();
int countdown = 0;
for (countdown = 0; countdown < MAGICPACKET_WAIT_SECONDS; countdown++) {
try {
struct addrinfo hints;
struct addrinfo* res = NULL;
struct addrinfo* ai;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET6; //IPv6優先
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_NUMERICSERV;
if (getaddrinfo(g_ServerHost, g_ServerPort, &hints, &res) != 0) {
//printf("getaddrinfo(): %s\n", gai_strerror(err));
hints.ai_family = AF_INET; //IPv4限定
if (getaddrinfo(g_ServerHost, g_ServerPort, &hints, &res) != 0) {
throw 1UL;
}
}
for (ai = res; ai; ai = ai->ai_next) {
m_sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
if (m_sock == INVALID_SOCKET) {
continue;
}
if (connect(m_sock, ai->ai_addr, (int)ai->ai_addrlen) >= 0) {
// OK
break;
}
closesocket(m_sock);
m_sock = INVALID_SOCKET;
}
freeaddrinfo(res);
if (m_sock == INVALID_SOCKET) {
TCHAR szDebugOut[128];
::wsprintf(szDebugOut, TEXT("%s: CBonTuner::OpenTuner() connection error %d\n"), TUNER_NAME, WSAGetLastError());
::OutputDebugString(szDebugOut);
throw 1UL;
}
const char serverRequest[] = "GET / HTTP/1.0\r\n\r\n";
if (send(m_sock, serverRequest, (int)strlen(serverRequest), 0) < 0) {
TCHAR szDebugOut[128];
::wsprintf(szDebugOut, TEXT("%s: CBonTuner::OpenTuner() send error %d\n"), TUNER_NAME, WSAGetLastError());
::OutputDebugString(szDebugOut);
throw 1UL;
}
// Success
break;
}
catch (const DWORD dwErrorStep) {
if (::GetTickCount() - dwLastTime > (MAGICPACKET_WAIT_SECONDS * 1000)) {
TCHAR szDebugOut[1024];
::wsprintf(szDebugOut, TEXT("TimeOut\n"));
::OutputDebugString(szDebugOut);
return FALSE;
}
// エラー発生
TCHAR szDebugOut[1024];
::wsprintf(szDebugOut, TEXT("%s: CBonTuner::OpenTuner() dwErrorStep = %lu\n"), TUNER_NAME, dwErrorStep);
::OutputDebugString(szDebugOut);
Sleep(1000);
}
}
if (countdown >= MAGICPACKET_WAIT_SECONDS) {
// Failed
return FALSE;
}
}
m_bTunerOpen = TRUE;
}
//return SetChannel(0UL,0UL);
return TRUE;
}
void CBonTuner::CloseTuner()
{
// スレッド終了要求セット
m_bLoopIoThread = FALSE;
// イベント開放
if (m_hOnStreamEvent) {
::CloseHandle(m_hOnStreamEvent);
m_hOnStreamEvent = NULL;
}
// スレッド終了
if (m_hPushIoThread) {
if (::WaitForSingleObject(m_hPushIoThread, 1000) != WAIT_OBJECT_0) {
// スレッド強制終了
::TerminateThread(m_hPushIoThread, 0);
TCHAR szDebugOut[128];
::wsprintf(szDebugOut, TEXT("%s: CBonTuner::CloseTuner() ::TerminateThread(m_hPushIoThread)\n"), TUNER_NAME);
::OutputDebugString(szDebugOut);
}
::CloseHandle(m_hPushIoThread);
m_hPushIoThread = NULL;
}
if (m_hPopIoThread) {
if (::WaitForSingleObject(m_hPopIoThread, 1000) != WAIT_OBJECT_0) {
// スレッド強制終了
::TerminateThread(m_hPopIoThread, 0);
TCHAR szDebugOut[128];
::wsprintf(szDebugOut, TEXT("%s: CBonTuner::CloseTuner() ::TerminateThread(m_hPopIoThread)\n"), TUNER_NAME);
::OutputDebugString(szDebugOut);
}
::CloseHandle(m_hPopIoThread);
m_hPopIoThread = NULL;
}
// バッファ開放
FreeIoReqBuff(m_pIoReqBuff);
m_pIoReqBuff = NULL;
m_pIoPushReq = NULL;
m_pIoPopReq = NULL;
m_pIoGetReq = NULL;
m_dwBusyReqNum = 0UL;
m_dwReadyReqNum = 0UL;
// ソケットクローズ
if (m_sock != INVALID_SOCKET) {
closesocket(m_sock);
m_sock = INVALID_SOCKET;
}
// チャンネル初期化
m_dwCurSpace = 0UL;
m_dwCurChannel = 0xFFFFFFFFUL;
// ミューテックス開放
if (m_hMutex) {
::ReleaseMutex(m_hMutex);
::CloseHandle(m_hMutex);
m_hMutex = NULL;
}
m_fBitRate = 0.0f;
m_dwRecvBytes = 0UL;
}
const DWORD CBonTuner::WaitTsStream(const DWORD dwTimeOut)
{
// 終了チェック
if (!m_hOnStreamEvent || !m_bLoopIoThread) {
return WAIT_ABANDONED;
}
// イベントがシグナル状態になるのを待つ
const DWORD dwRet = ::WaitForSingleObject(m_hOnStreamEvent, (dwTimeOut)? dwTimeOut : INFINITE);
switch (dwRet) {
case WAIT_ABANDONED :
// チューナが閉じられた
return WAIT_ABANDONED;
case WAIT_OBJECT_0 :
case WAIT_TIMEOUT :
// ストリーム取得可能 or チューナが閉じられた
return (m_bLoopIoThread)? dwRet : WAIT_ABANDONED;
case WAIT_FAILED :
default:
// 例外
return WAIT_FAILED;
}
}
const DWORD CBonTuner::GetReadyCount()
{
// 取り出し可能TSデータ数を取得する
return m_dwReadyReqNum;
}
const BOOL CBonTuner::GetTsStream(BYTE *pDst, DWORD *pdwSize, DWORD *pdwRemain)
{
BYTE *pSrc = NULL;
// TSデータをバッファから取り出す
if (GetTsStream(&pSrc, pdwSize, pdwRemain)) {
if (*pdwSize) {
::CopyMemory(pDst, pSrc, *pdwSize);
}
return TRUE;
}
return FALSE;
}
const BOOL CBonTuner::GetTsStream(BYTE **ppDst, DWORD *pdwSize, DWORD *pdwRemain)
{
if (!m_pIoGetReq) {
return FALSE;
}
// TSデータをバッファから取り出す
if (m_dwReadyReqNum) {
if (m_pIoGetReq->dwState == IORS_RECV) {
// データコピー
*pdwSize = m_pIoGetReq->dwRxdSize;
*ppDst = m_pIoGetReq->RxdBuff;
// バッファ位置を進める
::EnterCriticalSection(&m_CriticalSection);
m_pIoGetReq = m_pIoGetReq->pNext;
m_dwReadyReqNum--;
*pdwRemain = m_dwReadyReqNum;
::LeaveCriticalSection(&m_CriticalSection);
return TRUE;
}
// 例外
return FALSE;
}
// 取り出し可能なデータがない
*pdwSize = 0;
*pdwRemain = 0;
return TRUE;
}
void CBonTuner::PurgeTsStream()
{
// バッファから取り出し可能データをパージする
::EnterCriticalSection(&m_CriticalSection);
m_pIoGetReq = m_pIoPopReq;
m_dwReadyReqNum = 0;
::LeaveCriticalSection(&m_CriticalSection);
}
void CBonTuner::Release()
{
// インスタンス開放
delete this;
}
LPCTSTR CBonTuner::GetTunerName(void)
{
// チューナ名を返す
return TEXT(TUNER_NAME);
}
const BOOL CBonTuner::IsTunerOpening(void)
{
// チューナの使用中の有無を返す(全プロセスを通して)
HANDLE hMutex = ::OpenMutex(MUTEX_ALL_ACCESS, FALSE, MUTEX_NAME);
if (hMutex) {
// 既にチューナは開かれている
::CloseHandle(hMutex);
return TRUE;
}
// チューナは開かれていない
return FALSE;
}
LPCTSTR CBonTuner::EnumTuningSpace(const DWORD dwSpace)
{
if (dwSpace > g_Max_Type) {
return NULL;
}
// 使用可能なチューニング空間を返す
static TCHAR buf[128];
::MultiByteToWideChar(CP_UTF8, 0, g_pType[dwSpace], -1, buf, sizeof(buf));
return buf;
}
LPCTSTR CBonTuner::EnumChannelName(const DWORD dwSpace, const DWORD dwChannel)
{
if (dwSpace > g_Max_Type) {
return NULL;
}
if (dwSpace < g_Max_Type) {
if (dwChannel >= g_Channel_Base[dwSpace + 1] - g_Channel_Base[dwSpace]) {
return NULL;
}
}
DWORD Bon_Channel = dwChannel + g_Channel_Base[dwSpace];
if (!g_Channel_JSON.contains(Bon_Channel)) {
return NULL;
}
picojson::object& channel_obj = g_Channel_JSON.get(Bon_Channel).get<picojson::object>();
const char *channel_name = channel_obj["name"].get<std::string>().c_str();
static TCHAR buf[128];
::MultiByteToWideChar(CP_UTF8, 0, channel_name, -1, buf, sizeof(buf));
return buf;
}
const DWORD CBonTuner::GetCurSpace(void)
{
// 現在のチューニング空間を返す
return m_dwCurSpace;
}
const DWORD CBonTuner::GetCurChannel(void)
{
// 現在のチャンネルを返す
return m_dwCurChannel;
}
CBonTuner::AsyncIoReq * CBonTuner::AllocIoReqBuff(const DWORD dwBuffNum)
{
if (dwBuffNum < 2) {
return NULL;
}
// メモリを確保する
AsyncIoReq *pNewBuff = new AsyncIoReq [dwBuffNum];
if (!pNewBuff) {
return NULL;
}
// ゼロクリア
::ZeroMemory(pNewBuff, sizeof(AsyncIoReq) * dwBuffNum);
// リンクを構築する
DWORD dwIndex;
for(dwIndex = 0 ; dwIndex < ( dwBuffNum - 1 ) ; dwIndex++) {
pNewBuff[dwIndex].pNext= &pNewBuff[dwIndex + 1];
}
pNewBuff[dwIndex].pNext = &pNewBuff[0];
return pNewBuff;
}
void CBonTuner::FreeIoReqBuff(CBonTuner::AsyncIoReq *pBuff)
{
if (!pBuff) {
return;
}
// バッファを開放する
delete [] pBuff;
}
DWORD WINAPI CBonTuner::PushIoThread(LPVOID pParam)
{
CBonTuner *pThis = (CBonTuner *)pParam;
DWORD dwLastTime = ::GetTickCount();
// ::OutputDebugString("CBonTuner::PushIoThread() Start!\n");
// ドライバにTSデータリクエストを発行する
while (pThis->m_bLoopIoThread) {
// リクエスト処理待ちが規定未満なら追加する
if (pThis->m_dwBusyReqNum < REQRESERVNUM) {
// ドライバにTSデータリクエストを発行する(HTTPなので受信要求のみ)
if (!pThis->PushIoRequest(pThis->m_sock)) {
// エラー発生
break;
}
} else {
// リクエスト処理待ちがフルの場合はウェイト
::Sleep(REQPOLLINGWAIT);
}
}
// ::OutputDebugString("CBonTuner::PushIoThread() End!\n");
return 0;
}
DWORD WINAPI CBonTuner::PopIoThread(LPVOID pParam)
{
CBonTuner *pThis = (CBonTuner *)pParam;
// 処理済リクエストをポーリングしてリクエストを完了させる
while (pThis->m_bLoopIoThread) {
// 処理済データがあればリクエストを完了する
if (pThis->m_dwBusyReqNum) {
// リクエストを完了する
if (!pThis->PopIoRequest(pThis->m_sock)) {
// エラー発生
break;
}
}
}
return 0;
}
const BOOL CBonTuner::PushIoRequest(SOCKET sock)
{
// ドライバに非同期リクエストを発行する
// オープンチェック
if (sock == INVALID_SOCKET)return FALSE;
// リクエストセット
m_pIoPushReq->dwRxdSize = 0;
// イベント設定
::ZeroMemory(&m_pIoPushReq->OverLapped, sizeof(WSAOVERLAPPED));
if (!(m_pIoPushReq->OverLapped.hEvent = ::CreateEvent(NULL, TRUE, FALSE, NULL)))return FALSE;
// HTTP受信を要求スルニダ!
DWORD Flags = 0;
WSABUF wsaBuf;
wsaBuf.buf = (char *)m_pIoPushReq->RxdBuff;
wsaBuf.len = sizeof(m_pIoPushReq->RxdBuff);
if (SOCKET_ERROR == WSARecv(sock, &wsaBuf, 1, &m_pIoPushReq->dwRxdSize, &Flags, &m_pIoPushReq->OverLapped, NULL)) {
int sock_err = WSAGetLastError();
if (sock_err != ERROR_IO_PENDING) {
return FALSE;
}
}
m_pIoPushReq->dwState = IORS_BUSY;
// バッファ状態更新
::EnterCriticalSection(&m_CriticalSection);
m_pIoPushReq = m_pIoPushReq->pNext;
m_dwBusyReqNum++;
::LeaveCriticalSection(&m_CriticalSection);
return TRUE;
}
const BOOL CBonTuner::PopIoRequest(SOCKET sock)
{
// 非同期リクエストを完了する
// オープンチェック
if (sock == INVALID_SOCKET) {
return FALSE;
}
// 状態チェック
if (m_pIoPopReq->dwState != IORS_BUSY) {
// 例外
return TRUE;
}
// リクエスト取得
DWORD Flags=0;
const BOOL bRet = ::WSAGetOverlappedResult(sock, &m_pIoPopReq->OverLapped, &m_pIoPopReq->dwRxdSize, FALSE, &Flags);
// エラーチェック
if (!bRet) {
int sock_err = WSAGetLastError();
if (sock_err == ERROR_IO_INCOMPLETE) {
// 処理未完了
::Sleep(REQPOLLINGWAIT);
return TRUE;
}
}
// 総受信サイズ加算
m_dwRecvBytes += m_pIoPopReq->dwRxdSize;
// ビットレート計算
if (DiffTime(m_dwLastCalcTick,::GetTickCount()) >= BITRATE_CALC_TIME) {
CalcBitRate();
}
// イベント削除
::CloseHandle(m_pIoPopReq->OverLapped.hEvent);
if (!bRet) {
// エラー発生
return FALSE;
}
m_pIoPopReq->dwState = IORS_RECV;
// バッファ状態更新
::EnterCriticalSection(&m_CriticalSection);
m_pIoPopReq = m_pIoPopReq->pNext;
m_dwBusyReqNum--;
m_dwReadyReqNum++;
::LeaveCriticalSection(&m_CriticalSection);
// イベントセット
::SetEvent(m_hOnStreamEvent);
return TRUE;
}
// チャンネル設定
const BOOL CBonTuner::SetChannel(const BYTE bCh)
{
return SetChannel((DWORD)0,(DWORD)bCh - 13);
}
// チャンネル設定
const BOOL CBonTuner::SetChannel(const DWORD dwSpace, const DWORD dwChannel)
{
if (dwSpace > g_Max_Type) {
return NULL;
}
DWORD Bon_Channel = dwChannel + g_Channel_Base[dwSpace];
if (!g_Channel_JSON.contains(Bon_Channel)) {
return NULL;
}
picojson::object& channel_obj = g_Channel_JSON.get(Bon_Channel).get<picojson::object>();
const char *type;
const char *channel;
char serviceId[6];
if (g_Service_Split == 1) {
picojson::object& channel_detail = channel_obj["channel"].get<picojson::object>();
type = channel_detail["type"].get<std::string>().c_str();
channel = channel_detail["channel"].get<std::string>().c_str();
sprintf_s(serviceId, "%u", (DWORD)channel_obj["serviceId"].get<double>());
}
else {
type = channel_obj["type"].get<std::string>().c_str();
channel = channel_obj["channel"].get<std::string>().c_str();
}
// 一旦クローズ
CloseTuner();
// バッファ確保
if (!(m_pIoReqBuff = AllocIoReqBuff(ASYNCBUFFSIZE))) {
return FALSE;
}
// バッファ位置同期
m_pIoPushReq = m_pIoReqBuff;
m_pIoPopReq = m_pIoReqBuff;
m_pIoGetReq = m_pIoReqBuff;
m_dwBusyReqNum = 0;
m_dwReadyReqNum = 0;
try{
char url[128];
char serverRequest[256];
// URL生成
if (g_Service_Split == 1) {
sprintf_s(url, "/api/channels/%s/%s/services/%s/stream?decode=%d", type, channel, serviceId, g_DecodeB25);
}
else {
sprintf_s(url, "/api/channels/%s/%s/stream?decode=%d", type, channel, g_DecodeB25);
}
sprintf_s(serverRequest, "GET %s HTTP/1.0\r\nX-Mirakurun-Priority: %d\r\n\r\n", url, g_Priority);
struct addrinfo hints;
struct addrinfo* res = NULL;
struct addrinfo* ai;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET6; //IPv6優先
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_NUMERICSERV;
if (getaddrinfo(g_ServerHost, g_ServerPort, &hints, &res) != 0) {
//printf("getaddrinfo(): %s\n", gai_strerror(err));
hints.ai_family = AF_INET; //IPv4限定
if (getaddrinfo(g_ServerHost, g_ServerPort, &hints, &res) != 0) {
throw 1UL;
}
}
for (ai = res; ai; ai = ai->ai_next) {
m_sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
if (m_sock == INVALID_SOCKET) {
continue;
}
if (connect(m_sock, ai->ai_addr, (int)ai->ai_addrlen) >= 0) {
// OK
break;
}
closesocket(m_sock);
m_sock = INVALID_SOCKET;
}
freeaddrinfo(res);
if (m_sock == INVALID_SOCKET) {
TCHAR szDebugOut[128];
::wsprintf(szDebugOut, TEXT("%s: CBonTuner::OpenTuner() connection error %d\n"), TUNER_NAME, WSAGetLastError());
::OutputDebugString(szDebugOut);
throw 1UL;
}
if (send(m_sock, serverRequest, (int)strlen(serverRequest), 0) < 0) {
TCHAR szDebugOut[128];
::wsprintf(szDebugOut, TEXT("%s: CBonTuner::OpenTuner() send error %d\n"), TUNER_NAME, WSAGetLastError());
::OutputDebugString(szDebugOut);
throw 1UL;
}
// イベント作成
if (!(m_hOnStreamEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL))) {
throw 2UL;
}
// スレッド起動
DWORD dwPushIoThreadID = 0UL, dwPopIoThreadID = 0UL;
m_hPushIoThread = ::CreateThread(NULL, 0UL, CBonTuner::PushIoThread, this, CREATE_SUSPENDED, &dwPopIoThreadID);
m_hPopIoThread = ::CreateThread(NULL, 0UL, CBonTuner::PopIoThread, this, CREATE_SUSPENDED, &dwPushIoThreadID);
if (!m_hPushIoThread || !m_hPopIoThread) {
if (m_hPushIoThread) {
::TerminateThread(m_hPushIoThread, 0UL);
::CloseHandle(m_hPushIoThread);
m_hPushIoThread = NULL;
}
if (m_hPopIoThread) {
::TerminateThread(m_hPopIoThread, 0UL);
::CloseHandle(m_hPopIoThread);
m_hPopIoThread = NULL;
}
throw 3UL;
}
// スレッド開始
m_bLoopIoThread = TRUE;
if (::ResumeThread(m_hPushIoThread) == 0xFFFFFFFFUL || ::ResumeThread(m_hPopIoThread) == 0xFFFFFFFFUL) {
throw 4UL;
}
// ミューテックス作成
if (!(m_hMutex = ::CreateMutex(NULL, TRUE, MUTEX_NAME))) {
throw 5UL;
}
} catch (const DWORD dwErrorStep) {
// エラー発生
TCHAR szDebugOut[1024];
::wsprintf(szDebugOut, TEXT("%s: CBonTuner::OpenTuner() dwErrorStep = %lu\n"), TUNER_NAME, dwErrorStep);
::OutputDebugString(szDebugOut);
CloseTuner();
return FALSE;
}
// チャンネル情報更新
m_dwCurSpace = dwSpace;
m_dwCurChannel = dwChannel;
// TSデータパージ
PurgeTsStream();
return TRUE;
}
// 信号レベル(ビットレート)取得
const float CBonTuner::GetSignalLevel(void)
{
CalcBitRate();
return m_fBitRate;
}
void CBonTuner::CalcBitRate()
{
DWORD dwCurrentTick = GetTickCount();
DWORD Span = DiffTime(m_dwLastCalcTick,dwCurrentTick);
if (Span >= BITRATE_CALC_TIME) {
m_fBitRate = (float)(((double)m_dwRecvBytes*(8*1000))/((double)Span*(1024*1024)));
m_dwRecvBytes = 0;
m_dwLastCalcTick = dwCurrentTick;
}
return;
}
void CBonTuner::GetApiChannels(picojson::value* channel_json, int service_split)
{
HttpClient client;
char url[512];
sprintf_s(url, "http://%s:%s/api/", g_ServerHost, g_ServerPort);
if (service_split == 1) {
strcat_s(url, "services");
}
else {
strcat_s(url, "channels");
}
HttpResponse response = client.get(url);
picojson::value v;
std::string err = picojson::parse(v, response.content);
if (err.empty()) {
*channel_json = v;
/*
// DEBUG
picojson::array channel_array = v.get<picojson::array>();
for (picojson::array::iterator it = channel_array.begin(); it != channel_array.end(); it++) {
picojson::object& channel = it->get<picojson::object>();
std::string channel_name = channel["name"].get<std::string>();
picojson::array& services = channel["services"].get<picojson::array>();
std::string tmp_debug("channel name : ");
tmp_debug.append(channel_name);
wchar_t debug[128];
mbstowcs(debug, tmp_debug.c_str(), sizeof(debug));
OutputDebugString(debug);