-
Notifications
You must be signed in to change notification settings - Fork 1
/
hikevent.cpp
3189 lines (2857 loc) · 127 KB
/
hikevent.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
#define PY_SSIZE_T_CLEAN
#include <iostream>
#include <time.h>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <Python.h>
#include "HCNetSDK.h"
#include <sys/queue.h>
#include <iconv.h>
#include <signal.h>
#include <arpa/inet.h>
#include "LinuxPlayM4.h"
#define USECOLOR 1
extern "C" {
#include "hikbase.h"
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavformat/avio.h>
#include <libavutil/file.h>
#include <libavutil/time.h>
#include "libswresample/swresample.h"
#include <libavutil/frame.h>
#include <libavutil/mem.h>
#include <libavutil/imgutils.h>
#include <libavutil/samplefmt.h>
#include <libavutil/timestamp.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
}
using namespace std;
#define HPR_ERROR -1
#define HPR_OK 0
#define DVR_REMOTE_CALL_COMMAND 0x4000001
#define DVR_VIDEO_DATA 0x4000002
#define DVR_REMOTE_CALL_STATUS 0x4000003
#define DVR_FLV_DATA 0x4000004
#define DVR_MP4_DATA 0x4000005
#define sprintfDVRTime(struAlarmTime) "%04d-%02d-%02d %02d:%02d:%02d", struAlarmTime.wYear, struAlarmTime.byMonth, struAlarmTime.byDay, struAlarmTime.byHour, struAlarmTime.byMinute, struAlarmTime.bySecond
struct entry {
long lCommand;
char *pAlarmInfo;
size_t dwBufLen;
TAILQ_ENTRY(entry) entries;
};
typedef struct {
PyObject_HEAD
char *ip;
char *user;
char *passwd;
char *error_buffer;
LONG lUserID;
LONG lHandle;
LONG lCallHandle;
LONG lVoiceHandler;
NET_DVR_COMPRESSION_AUDIO compressAudioType;
bool alarmChannelOpened;
bool callChannelOpened;
TAILQ_HEAD(tailhead, entry) head;
TAILQ_HEAD(decode_ctx_tailhead, hik_queue_s) decode_ctx;
pthread_mutex_t lock;
NET_DVR_DEVICEINFO_V30 struDeviceInfo;
NET_DVR_USER_LOGIN_INFO struLoginInfo = {0};
NET_DVR_DEVICEINFO_V40 struDeviceInfoV40 = {0};
LONG nPort;
pthread_t *decodeThread;
// AVCodecContext *codec_ctx;
// AVCodecParserContext *parser;
// AVPacket *pkt;
// AVFrame *frame;
/* Type-specific fields go here. */
} PyHIKEvent_Object;
void CALLBACK MessageCallback(LONG lCommand, NET_DVR_ALARMER *pAlarmer, char *pAlarmInfo, DWORD dwBufLen, void* pUser)
{
PyHIKEvent_Object *self = (PyHIKEvent_Object*)pUser;
struct entry *elem = (struct entry *)calloc(1, sizeof(struct entry));
if (elem)
{
elem->lCommand = lCommand;
elem->pAlarmInfo = (char *)malloc(dwBufLen);
memcpy(elem->pAlarmInfo, pAlarmInfo, dwBufLen);
elem->dwBufLen = dwBufLen;
pthread_mutex_lock(&self->lock);
TAILQ_INSERT_HEAD(&self->head, elem, entries);
pthread_mutex_unlock(&self->lock);
}
}
int CALLBACK MessageCallback_V31(LONG lCommand, NET_DVR_ALARMER *pAlarmer, char *pAlarmInfo, DWORD dwBufLen, void* pUser)
{
MessageCallback(lCommand, pAlarmer, pAlarmInfo, dwBufLen, pUser);
return 0;
}
static PyObject *
hikevent_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
static char error_buffer[256];
PyHIKEvent_Object *ps;
ps = (PyHIKEvent_Object *) type->tp_alloc(type, 0);
if (ps == NULL) return NULL;
static char *kwlist[] = {(char *)"host", (char *)"user", (char *)"passwd", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "sss", kwlist, &ps->ip, &ps->user, &ps->passwd)) {
PyErr_SetString(PyExc_TypeError,
"No enough params provide, required: IP, user, passwd");
return NULL;
}
TAILQ_INIT(&ps->head);
TAILQ_INIT(&ps->decode_ctx);
if (pthread_mutex_init(&ps->lock, NULL) != 0) {
PyErr_SetString(PyExc_TypeError, "mutex init has failed");
return NULL;
}
ps->error_buffer = error_buffer;
// 初始化
NET_DVR_Init();
//设置连接时间与重连时间
NET_DVR_SetConnectTime(2000, 1);
NET_DVR_SetReconnect(10000, true);
ps->struLoginInfo.bUseAsynLogin = false;
ps->struLoginInfo.wPort = 8000;
memcpy(ps->struLoginInfo.sDeviceAddress, ps->ip, NET_DVR_DEV_ADDRESS_MAX_LEN);
memcpy(ps->struLoginInfo.sUserName, ps->user, strlen(ps->user) > NAME_LEN ? NAME_LEN : strlen(ps->user));
memcpy(ps->struLoginInfo.sPassword, ps->passwd, strlen(ps->passwd) > NAME_LEN ? NAME_LEN : strlen(ps->passwd));
ps->lVoiceHandler = -1;
ps->lUserID = NET_DVR_Login_V40(&ps->struLoginInfo, &ps->struDeviceInfoV40);
if (ps->lUserID < 0)
{
sprintf(error_buffer, "Login error, %d\n", NET_DVR_GetLastError());
PyErr_SetString(PyExc_TypeError, error_buffer);
NET_DVR_Cleanup();
return NULL;
}
// NET_DVR_SetDVRMessageCallBack_V31(MessageCallback_V31, (void *)ps);
NET_DVR_SetDVRMessageCallBack_V51(0, MessageCallback, (void *)ps);
return (PyObject *) ps;
}
extern "C"
{
static PyObject *receiveAlarmEvent(PyObject *self, PyObject *args) {
PyHIKEvent_Object *ps = (PyHIKEvent_Object *)self;
if (ps->alarmChannelOpened)
{
Py_RETURN_NONE;
return NULL;
}
NET_DVR_SETUPALARM_PARAM_V50 struSetupAlarmParam = { 0 };
struSetupAlarmParam.dwSize = sizeof(struSetupAlarmParam);
struSetupAlarmParam.byRetAlarmTypeV40 = 1; // variable size
// struSetupAlarmParam.byLevel = 2; // low priority
struSetupAlarmParam.byLevel = 0; // high priority
struSetupAlarmParam.byAlarmInfoType = 1;
struSetupAlarmParam.byRetDevInfoVersion = 1;
struSetupAlarmParam.byRetVQDAlarmType = 1; //Prefer VQD Alarm type of NET_DVR_VQD_ALARM
struSetupAlarmParam.byFaceAlarmDetection = 1;//m_comFaceAlarmType.GetCurSel();
struSetupAlarmParam.byRetDevInfoVersion = TRUE;
struSetupAlarmParam.byAlarmInfoType = 1;
struSetupAlarmParam.bySupport = 1 | 2 | 8;
struSetupAlarmParam.byDeployType = 0;
ps->lHandle = NET_DVR_SetupAlarmChan_V50(ps->lUserID, &struSetupAlarmParam, (char *)"<SubscribeEvent version=\"2.0\" xmlns=\"http://www.isapi.org/ver20/XMLSchema\"><eventMode>all</eventMode><changedUploadSub/></SubscribeEvent> ", 0);
if (ps->lHandle < 0)
{
LONG pErrorNo = NET_DVR_GetLastError();
sprintf(ps->error_buffer, "NET_DVR_SetupAlarmChan_V50 error, %d: %s Handle ID: %d\n", pErrorNo, NET_DVR_GetErrorMsg(&pErrorNo), ps->lHandle);
PyErr_SetString(PyExc_TypeError, ps->error_buffer);
NET_DVR_Logout(ps->lUserID);
NET_DVR_Cleanup();
return NULL;
}
ps->alarmChannelOpened = true;
Py_RETURN_NONE;
}
static PyObject *unlock(PyObject *self, PyObject *args) {
long cmdType = 1;
if (!PyArg_ParseTuple(args, "|I", &cmdType)) {
return NULL;
}
PyHIKEvent_Object *ps = (PyHIKEvent_Object *)self;
if (FALSE == NET_DVR_ControlGateway(ps->lUserID, -1, cmdType))
{
LONG pErrorNo = NET_DVR_GetLastError();
sprintf(ps->error_buffer, "NET_DVR_ControlGateway error, %d: %s\n", pErrorNo, NET_DVR_GetErrorMsg(&pErrorNo));
PyErr_SetString(PyExc_TypeError, ps->error_buffer);
return NULL;
}
// NET_DVR_CONTROL_GATEWAY ctrl;
// memset(&ctrl, 0, sizeof(ctrl));
// ctrl.dwSize = sizeof(NET_DVR_CONTROL_GATEWAY);
// ctrl.byCommand = 1;
// ctrl.dwGatewayIndex = 1;
// ctrl.byLockType = 0;
// ctrl.wLockID = 0;
// strncpy((char*)ctrl.byControlSrc, "MANAGER",NAME_LEN);
// ctrl.byControlType = 1;
// if (FALSE == NET_DVR_RemoteControl(ps->lUserID, NET_DVR_REMOTECONTROL_GATEWAY, &ctrl, sizeof(NET_DVR_CONTROL_GATEWAY)))
// {
// LONG pErrorNo = NET_DVR_GetLastError();
// sprintf(ps->error_buffer, "NET_DVR_RemoteControl error, %d: %s\n", pErrorNo, NET_DVR_GetErrorMsg(&pErrorNo));
// PyErr_SetString(PyExc_TypeError, ps->error_buffer);
// return NULL;
// }
Py_RETURN_NONE;
}
void CALLBACK fRemoteCallCallback(DWORD dwType, void *lpBuffer, DWORD dwBufLen, void* pUser)
{
PyHIKEvent_Object *self = (PyHIKEvent_Object*)pUser;
//NET_SDK_CALLBACK_TYPE_STATUS
//NET_SDK_CALLBACK_TYPE_PROGRESS
//NET_SDK_CALLBACK_TYPE_DATA
if (dwType == NET_SDK_CALLBACK_TYPE_DATA)
{
struct entry *elem = (struct entry *)calloc(1, sizeof(struct entry));
if (elem)
{
elem->lCommand = DVR_REMOTE_CALL_COMMAND;
elem->pAlarmInfo = (char *)malloc(dwBufLen);
memcpy(elem->pAlarmInfo, lpBuffer, dwBufLen);
elem->dwBufLen = dwBufLen;
pthread_mutex_lock(&self->lock);
TAILQ_INSERT_HEAD(&self->head, elem, entries);
pthread_mutex_unlock(&self->lock);
}
// NET_DVR_VIDEO_CALL_PARAM *callParam = (NET_DVR_VIDEO_CALL_PARAM*)lpBuffer;
} else if (dwType == NET_SDK_CALLBACK_TYPE_STATUS)
{
NET_SDK_CALLBACK_STATUS_NORMAL *status = (NET_SDK_CALLBACK_STATUS_NORMAL *)lpBuffer;
fprintf(stderr, "Receive RemoteCall Callback Event %d %d size: %d\n", dwType, *status, dwBufLen);
struct entry *elem = (struct entry *)calloc(1, sizeof(struct entry));
if (elem)
{
elem->lCommand = DVR_REMOTE_CALL_STATUS;
elem->pAlarmInfo = NULL;
elem->dwBufLen = *status;
pthread_mutex_lock(&self->lock);
TAILQ_INSERT_HEAD(&self->head, elem, entries);
pthread_mutex_unlock(&self->lock);
}
} else {
fprintf(stderr, "Receive RemoteCall Callback Event %d\n", dwType);
}
}
static PyObject *receiveRemoteCall(PyObject *self, PyObject *args) {
PyHIKEvent_Object *ps = (PyHIKEvent_Object *)self;
if (ps->callChannelOpened)
{
Py_RETURN_NONE;
return NULL;
}
NET_DVR_VIDEO_CALL_COND struVideoCallCond;
memset(&struVideoCallCond, 0, sizeof(struVideoCallCond));
struVideoCallCond.dwSize = sizeof(struVideoCallCond);
if (-1 == (ps->lCallHandle = NET_DVR_StartRemoteConfig(ps->lUserID, NET_DVR_VIDEO_CALL_SIGNAL_PROCESS, (char *)&struVideoCallCond, sizeof(struVideoCallCond), fRemoteCallCallback, ps)))
{
LONG pErrorNo = NET_DVR_GetLastError();
sprintf(ps->error_buffer, "NET_DVR_SendRemoteConfig error, %d: %s\n", pErrorNo, NET_DVR_GetErrorMsg(&pErrorNo));
PyErr_SetString(PyExc_TypeError, ps->error_buffer);
return NULL;
}
ps->callChannelOpened = true;
Py_RETURN_NONE;
}
static PyObject *stopRemoteCall(PyObject *self, PyObject *args) {
PyHIKEvent_Object *ps = (PyHIKEvent_Object *)self;
if (!ps->callChannelOpened)
{
Py_RETURN_NONE;
return NULL;
}
if (!NET_DVR_StopRemoteConfig(ps->lCallHandle))
{
LONG pErrorNo = NET_DVR_GetLastError();
sprintf(ps->error_buffer, "NET_DVR_StopRemoteConfig error, %d: %s\n", pErrorNo, NET_DVR_GetErrorMsg(&pErrorNo));
PyErr_SetString(PyExc_TypeError, ps->error_buffer);
return NULL;
}
ps->callChannelOpened = false;
Py_RETURN_NONE;
}
static PyObject *remoteCallCommand(PyObject *self, PyObject *args) {
PyHIKEvent_Object *ps = (PyHIKEvent_Object *)self;
NET_DVR_VIDEO_CALL_PARAM struCallCmd;
memset(&struCallCmd, 0, sizeof(NET_DVR_VIDEO_CALL_PARAM));
long cmdType;
if (!PyArg_ParseTuple(args, "I|iiiii", &cmdType, &struCallCmd.wPeriod, &struCallCmd.wBuildingNumber, &struCallCmd.wUnitNumber, &struCallCmd.wFloorNumber, &struCallCmd.wRoomNumber)) {
return NULL;
}
struCallCmd.dwSize = sizeof(NET_DVR_VIDEO_CALL_PARAM);
// 0- 请求呼叫,1- 取消本次呼叫,2- 接听本次呼叫,3- 拒绝本地来电呼叫,4- 被叫响铃超时,5- 结束本次通话,6- 设备正在通话中,7- 客户端正在通话中
struCallCmd.dwCmdType = cmdType;
if (FALSE == NET_DVR_SendRemoteConfig(ps->lUserID, NET_DVR_VIDEO_CALL_SIGNAL_PROCESS, (char *)&struCallCmd, sizeof(NET_DVR_VIDEO_CALL_PARAM)))
{
LONG pErrorNo = NET_DVR_GetLastError();
sprintf(ps->error_buffer, "NET_DVR_SendRemoteConfig error, %d: %s\n", pErrorNo, NET_DVR_GetErrorMsg(&pErrorNo));
PyErr_SetString(PyExc_TypeError, ps->error_buffer);
return NULL;
}
// if (cmdType == 2)
// {
// NET_DVR_StartVoiceCom_V30(ps->lUserID, 1, 0, NULL, NULL);
// }
Py_RETURN_NONE;
}
static PyObject *getDeviceInfo(PyObject *self, PyObject *args) {
PyHIKEvent_Object *ps = (PyHIKEvent_Object *)self;
NET_DVR_DEV_BASE_INFO devConfig;
NET_DVR_DEVICEID_INFO devInfo;
uint32_t lpStatusList;
memset(&devInfo, 0, sizeof(devInfo));
devInfo.dwSize = sizeof(NET_DVR_DEVICEID_INFO);
if (!NET_DVR_GetDeviceConfig(ps->lUserID, NET_DVR_GET_DEV_BASEINFO, 1, &devInfo, sizeof(devInfo), &lpStatusList, &devConfig, sizeof(devConfig)))
{
LONG pErrorNo = NET_DVR_GetLastError();
sprintf(ps->error_buffer, "NET_DVR_GetDeviceConfig error, %d: %s\n", pErrorNo, NET_DVR_GetErrorMsg(&pErrorNo));
PyErr_SetString(PyExc_TypeError, ps->error_buffer);
return NULL;
}
size_t srclen = strlen((char *)devConfig.sDevName);
char outbuf[NAME_LEN * 2];
size_t outlen = NAME_LEN * 2;
iconv_t cvSess = iconv_open("utf-8", "gb2312");
/* 由于iconv()函数会修改指针,所以要保存源指针 */
char *srcstart = (char *)devConfig.sDevName;
char *tempoutbuf = outbuf;
/* 进行转换
*@param cd iconv_open()产生的句柄
*@param srcstart 需要转换的字符串
*@param srclen 存放还有多少字符没有转换
*@param tempoutbuf 存放转换后的字符串
*@param outlen 存放转换后,tempoutbuf剩余的空间
*
* */
int ret = iconv (cvSess, &srcstart, &srclen, &tempoutbuf, &outlen);
if (ret == -1)
{
sprintf(ps->error_buffer, "iconv name to utf-8 error, %d\n", errno);
return NULL;
}
iconv_close(cvSess);
// return Py_BuildValue("{s:s#,s:i,s:s}", "DVRName", outbuf, NAME_LEN * 2 - outlen, "DVRID", devConfig.dwDVRID, "SN", devConfig.sSerialNumber );
return Py_BuildValue("{s:s#,s:i,s:s}", "DevName", outbuf, NAME_LEN * 2 - outlen );
}
static PyObject *getPicture(PyObject *self, PyObject *args) {
PyHIKEvent_Object *ps = (PyHIKEvent_Object *)self;
NET_DVR_PICPARAM_V50 picParams;
memset(&picParams, 0, sizeof(picParams));
picParams.struParam.wPicSize = 5;
picParams.struParam.wPicQuality = 1;
long lChannelNo = 1;
if (!PyArg_ParseTuple(args, "|I", &lChannelNo)) {
return NULL;
}
char *picBuffer = (char *)malloc(16 * 1048576); // 16 MB Buffer
DWORD picSize = 0;
if (picBuffer == NULL)
{
sprintf(ps->error_buffer, "allocate buffer failed\n");
PyErr_SetString(PyExc_TypeError, ps->error_buffer);
return NULL;
}
if (!NET_DVR_CapturePicture_V50(ps->lUserID, lChannelNo, &picParams, picBuffer, 16 * 1048576, &picSize))
{
LONG pErrorNo = NET_DVR_GetLastError();
sprintf(ps->error_buffer, "NET_DVR_CapturePicture_V50 error, %d: %s\n", pErrorNo, NET_DVR_GetErrorMsg(&pErrorNo));
PyErr_SetString(PyExc_TypeError, ps->error_buffer);
return NULL;
}
PyObject *ret = Py_BuildValue("y#", picBuffer, picSize);
free(picBuffer);
return ret;
}
static PyObject *getChannelName(PyObject *self, PyObject *args) {
PyHIKEvent_Object *ps = (PyHIKEvent_Object *)self;
NET_DVR_PICCFG_V40 picConfig;
long cameraNo;
DWORD lReceivedConfigSize;
if (!PyArg_ParseTuple(args, "I", &cameraNo)) {
return NULL;
}
if (!NET_DVR_GetDVRConfig(ps->lUserID, NET_DVR_GET_PICCFG_V40, cameraNo, &picConfig, sizeof(picConfig), &lReceivedConfigSize))
{
LONG pErrorNo = NET_DVR_GetLastError();
sprintf(ps->error_buffer, "NET_DVR_PICCFG_V40 error, %d: %s\n", pErrorNo, NET_DVR_GetErrorMsg(&pErrorNo));
PyErr_SetString(PyExc_TypeError, ps->error_buffer);
return NULL;
}
size_t srclen = strlen((char *)picConfig.sChanName);
char outbuf[NAME_LEN * 2];
size_t outlen = NAME_LEN * 2;
iconv_t cvSess = iconv_open("utf-8", "gb2312");
/* 由于iconv()函数会修改指针,所以要保存源指针 */
char *srcstart = (char *)picConfig.sChanName;
char *tempoutbuf = outbuf;
/* 进行转换
*@param cd iconv_open()产生的句柄
*@param srcstart 需要转换的字符串
*@param srclen 存放还有多少字符没有转换
*@param tempoutbuf 存放转换后的字符串
*@param outlen 存放转换后,tempoutbuf剩余的空间
*
* */
int ret = iconv (cvSess, &srcstart, &srclen, &tempoutbuf, &outlen);
if (ret == -1)
{
sprintf(ps->error_buffer, "iconv name to utf-8 error, %d\n", errno);
return NULL;
}
iconv_close(cvSess);
return Py_BuildValue("s#", outbuf, NAME_LEN * 2 - outlen);
}
void CALLBACK fdwVoiceDataCallBack(LONG lVoiceComHandle, char *pRecvDataBuffer, DWORD dwBufSize, BYTE byAudioFlag, DWORD pUser)
{
}
void CALLBACK fVoiceDataCallBack(LONG lVoiceComHandle, char *pRecvDataBuffer, DWORD dwBufSize, BYTE byAudioFlag, void *pUser)
{
}
static PyObject *addDVRChannel(PyObject *self, PyObject *args) {
PyHIKEvent_Object *ps = (PyHIKEvent_Object *)self;
NET_DVR_AUDIO_CHANNEL channelInfo;
memset(&channelInfo, 0, sizeof(NET_DVR_AUDIO_CHANNEL));
long cameraNo;
if (!PyArg_ParseTuple(args, "I", &cameraNo)) {
return NULL;
}
if (cameraNo > 1)
{
cameraNo = ps->struDeviceInfoV40.struDeviceV30.byStartDTalkChan + cameraNo - 1;
}
channelInfo.dwChannelNum = cameraNo;
if (FALSE == NET_DVR_GetCurrentAudioCompress_V50(ps->lUserID, &channelInfo, &ps->compressAudioType))
{
LONG pErrorNo = NET_DVR_GetLastError();
sprintf(ps->error_buffer, "NET_DVR_GetCurrentAudioCompress error, %d: %s\n", pErrorNo, NET_DVR_GetErrorMsg(&pErrorNo));
PyErr_SetString(PyExc_TypeError, ps->error_buffer);
return NULL;
}
int sampleRate = ps->compressAudioType.byAudioSamplingRate;
switch(ps->compressAudioType.byAudioSamplingRate)
{
case 1: sampleRate = 16000; break;
case 2: sampleRate = 32000; break;
case 3: sampleRate = 48000; break;
case 4: sampleRate = 44100; break;
case 5: sampleRate = 8000; break;
// default:
// sprintf(ps->error_buffer, "Unknow sample rate, %d\n", ps->compressAudioType.byAudioSamplingRate);
// PyErr_SetString(PyExc_TypeError, ps->error_buffer);
// return NULL;
}
// NET_DVR_ClientAudioStart();
long lVoiceHandler = NET_DVR_AddDVR_V30(ps->lUserID, cameraNo);
if (lVoiceHandler == -1)
{
LONG pErrorNo = NET_DVR_GetLastError();
sprintf(ps->error_buffer, "NET_DVR_AddDVR_V30 error, %d: %s\n", pErrorNo, NET_DVR_GetErrorMsg(&pErrorNo));
PyErr_SetString(PyExc_TypeError, ps->error_buffer);
return NULL;
}
return Py_BuildValue("{s:i,s:i,s:i}", "AudioEncode", ps->compressAudioType.byAudioEncType,
"SampleRate", sampleRate, "handler", lVoiceHandler);
}
static PyObject *delDVRChannel(PyObject *self, PyObject *args) {
PyHIKEvent_Object *ps = (PyHIKEvent_Object *)self;
long handler;
if (!PyArg_ParseTuple(args, "I", &handler)) {
return NULL;
}
if (!NET_DVR_DelDVR_V30(handler))
{
LONG pErrorNo = NET_DVR_GetLastError();
sprintf(ps->error_buffer, "NET_DVR_DelDVR_V30 error, %d: %s\n", pErrorNo, NET_DVR_GetErrorMsg(&pErrorNo));
PyErr_SetString(PyExc_TypeError, ps->error_buffer);
return NULL;
}
Py_RETURN_NONE;
}
static PyObject *startVoiceTalk(PyObject *self, PyObject *args) {
PyHIKEvent_Object *ps = (PyHIKEvent_Object *)self;
NET_DVR_AUDIO_CHANNEL channelInfo;
memset(&channelInfo, 0, sizeof(NET_DVR_AUDIO_CHANNEL));
long cameraNo;
if (!PyArg_ParseTuple(args, "I", &cameraNo)) {
return NULL;
}
if (cameraNo >= 1)
{
cameraNo = ps->struDeviceInfoV40.struDeviceV30.byStartDTalkChan + cameraNo - 1;
} else {
cameraNo = ps->struDeviceInfoV40.struDeviceV30.byStartDChan;
}
if (ps->lVoiceHandler != -1 && ps->lVoiceHandler != 0)
{
if (FALSE == NET_DVR_StopVoiceCom(ps->lVoiceHandler))
{
LONG pErrorNo = NET_DVR_GetLastError();
sprintf(ps->error_buffer, "NET_DVR_StopVoiceCom error, %d: %s\n", pErrorNo, NET_DVR_GetErrorMsg(&pErrorNo));
PyErr_SetString(PyExc_TypeError, ps->error_buffer);
return NULL;
}
}
ps->lVoiceHandler = NET_DVR_StartVoiceCom_MR_V30(ps->lUserID, cameraNo, fVoiceDataCallBack, NULL);
if (ps->lVoiceHandler == -1)
{
LONG pErrorNo = NET_DVR_GetLastError();
sprintf(ps->error_buffer, "NET_DVR_StartVoiceCom_MR_V30 error, %d: %s\n", pErrorNo, NET_DVR_GetErrorMsg(&pErrorNo));
PyErr_SetString(PyExc_TypeError, ps->error_buffer);
return NULL;
}
channelInfo.dwChannelNum = cameraNo;
if (FALSE == NET_DVR_GetCurrentAudioCompress_V50(ps->lUserID, &channelInfo, &ps->compressAudioType))
{
LONG pErrorNo = NET_DVR_GetLastError();
sprintf(ps->error_buffer, "NET_DVR_GetCurrentAudioCompress error, %d: %s\n", pErrorNo, NET_DVR_GetErrorMsg(&pErrorNo));
PyErr_SetString(PyExc_TypeError, ps->error_buffer);
return NULL;
}
int sampleRate = ps->compressAudioType.byAudioSamplingRate;
switch(ps->compressAudioType.byAudioSamplingRate)
{
case 1: sampleRate = 16000; break;
case 2: sampleRate = 32000; break;
case 3: sampleRate = 48000; break;
case 4: sampleRate = 44100; break;
case 5: sampleRate = 8000; break;
default: sampleRate = 8000; break;
// default:
// sprintf(ps->error_buffer, "Unknow sample rate, %d\n", ps->compressAudioType.byAudioSamplingRate);
// PyErr_SetString(PyExc_TypeError, ps->error_buffer);
// return NULL;
}
return Py_BuildValue("{s:i,s:i,s:i}", "AudioEncode", ps->compressAudioType.byAudioEncType,
"SampleRate", sampleRate, "handler", ps->lVoiceHandler);
}
static PyObject *stopVoiceTalk(PyObject *self, PyObject *args) {
PyHIKEvent_Object *ps = (PyHIKEvent_Object *)self;
if (ps->lVoiceHandler == -1)
{
sprintf(ps->error_buffer, "Voice Talk is not started");
PyErr_SetString(PyExc_TypeError, ps->error_buffer);
return NULL;
}
if (FALSE == NET_DVR_StopVoiceCom(ps->lVoiceHandler))
{
LONG pErrorNo = NET_DVR_GetLastError();
sprintf(ps->error_buffer, "NET_DVR_StopVoiceCom error, %d: %s\n", pErrorNo, NET_DVR_GetErrorMsg(&pErrorNo));
PyErr_SetString(PyExc_TypeError, ps->error_buffer);
return NULL;
}
ps->lVoiceHandler = 0;
Py_RETURN_NONE;
}
static PyObject *sendVoice(PyObject *self, PyObject *args) {
PyHIKEvent_Object *ps = (PyHIKEvent_Object *)self;
char *inputBuffer;
Py_ssize_t bufferLength;
LONG specifiedVoiceHandler = -1;
if (!PyArg_ParseTuple(args, "y#|iii", &inputBuffer, &bufferLength, &ps->compressAudioType.byAudioEncType, &specifiedVoiceHandler)) {
return NULL;
}
/**************Encode Audio in G.722 Mode**************/
LPVOID hEncInstance = 0;
NET_DVR_AUDIOENC_INFO info_param;
NET_DVR_AUDIOENC_PROCESS_PARAM enc_proc_param;
memset(&enc_proc_param, 0 ,sizeof(NET_DVR_AUDIOENC_PROCESS_PARAM));
unsigned char *encode_input[8192]; //20ms
unsigned char *encoded_data[8192];
enc_proc_param.in_buf = (unsigned char *)encode_input; //输入数据缓冲区,存放编码前PCM原始音频数据
enc_proc_param.out_buf = (unsigned char *)encoded_data; //输出数据缓冲区,存放编码后音频数据
int blockcount= 0;
const char *encoderName = NULL;
if (ps->compressAudioType.byAudioEncType == 0)
{
encoderName = "G722";
hEncInstance = NET_DVR_InitG722Encoder(&info_param); //初始化G722编码
} else if (ps->compressAudioType.byAudioEncType == 1)
{
encoderName = "G711_U";
enc_proc_param.g711_type = 0;
hEncInstance = NET_DVR_InitG711Encoder(&info_param);
info_param.in_frame_size /= 2;
} else if (ps->compressAudioType.byAudioEncType == 2)
{
encoderName = "G711_A";
enc_proc_param.g711_type = 1;
hEncInstance = NET_DVR_InitG711Encoder(&info_param);
} else if (ps->compressAudioType.byAudioEncType == 4)
{
encoderName = "G726";
// hEncInstance = NET_DVR_InitG726Encoder(&info_param);
}
if ((long)hEncInstance == -1)
{
LONG pErrorNo = NET_DVR_GetLastError();
sprintf(ps->error_buffer, "NET_DVR_Init%sEncoder error, %d: %s\n", encoderName, pErrorNo, NET_DVR_GetErrorMsg(&pErrorNo));
PyErr_SetString(PyExc_TypeError, ps->error_buffer);
return NULL;
}
int offset = 0;
while (offset < bufferLength)
{
blockcount++;
if (info_param.in_frame_size > bufferLength - offset)
break;
memcpy(enc_proc_param.in_buf, inputBuffer + offset, info_param.in_frame_size);
offset+=info_param.in_frame_size;
//PCM数据输入,编码成G722
BOOL ret = FALSE;
if (ps->compressAudioType.byAudioEncType == 0)
{
ret = NET_DVR_EncodeG722Frame(hEncInstance, &enc_proc_param);
} else if (ps->compressAudioType.byAudioEncType == 1 || ps->compressAudioType.byAudioEncType == 2)
{
ret = NET_DVR_EncodeG711Frame(hEncInstance, &enc_proc_param);//((DWORD)enc_proc_param.g711_type, (BYTE *)enc_proc_param.in_buf, (BYTE *)enc_proc_param.out_buf);
enc_proc_param.out_frame_size = 160;
} else if (ps->compressAudioType.byAudioEncType == 4)
{
// ret = NET_DVR_EncodeG726Frame(hEncInstance, &enc_proc_param);
ret = false;
}
if (ret == FALSE)
{
LONG pErrorNo = NET_DVR_GetLastError();
sprintf(ps->error_buffer, "NET_DVR_Encode%sFrame error, %d: %s\n", encoderName, pErrorNo, NET_DVR_GetErrorMsg(&pErrorNo));
PyErr_SetString(PyExc_TypeError, ps->error_buffer);
return NULL;
}
if (!NET_DVR_VoiceComSendData(specifiedVoiceHandler != -1 ? specifiedVoiceHandler : ps->lVoiceHandler, (char*)enc_proc_param.out_buf, enc_proc_param.out_frame_size))
{
LONG pErrorNo = NET_DVR_GetLastError();
sprintf(ps->error_buffer, "NET_DVR_VoiceComSendData error, %d: %s\n", pErrorNo, NET_DVR_GetErrorMsg(&pErrorNo));
PyErr_SetString(PyExc_TypeError, ps->error_buffer);
return NULL;
}
// printf("sending %d size = %d\n", blockcount, enc_proc_param.out_frame_size);
sleep(0.02);
}
if (ps->compressAudioType.byAudioEncType == 0)
{
NET_DVR_ReleaseG722Decoder(&hEncInstance); //初始化G722编码
} else if (ps->compressAudioType.byAudioEncType == 1)
{
NET_DVR_ReleaseG711Encoder(&hEncInstance);
} else if (ps->compressAudioType.byAudioEncType == 2)
{
NET_DVR_ReleaseG711Encoder(&hEncInstance);
} else if (ps->compressAudioType.byAudioEncType == 4)
{
// hEncInstance = NET_DVR_InitG726Encoder(&info_param);
}
Py_RETURN_NONE;
}
void yv12toYUV(char *outYuv, char *inYv12, int width, int height, int widthStep)
{
int col, row;
unsigned int Y, U, V;
int tmp;
int idx;
for (row = 0; row<height; row++)
{
idx = row * widthStep;
// int rowptr = row*width;
for (col = 0; col<width; col++)
{
tmp = (row / 2)*(width / 2) + (col / 2);
Y = (unsigned int)inYv12[row*width + col];
U = (unsigned int)inYv12[width*height + width*height / 4 + tmp];
V = (unsigned int)inYv12[width*height + tmp];
if ((idx + col * 3 + 2)> (1200 * widthStep))
{
//printf("row * widthStep=%d,idx+col*3+2=%d.\n",1200 * widthStep,idx+col*3+2);
}
outYuv[idx + col * 3] = Y;
outYuv[idx + col * 3 + 1] = U;
outYuv[idx + col * 3 + 2] = V;
}
}
}
void CALLBACK DecCBFun(int nPort, char * pBuf, int nSize, FRAME_INFO * pFrameInfo, void *pUser, int nReserved2)
{
long lFrameType = pFrameInfo->nType;
HIKEvent_DecodeThread *dp = (HIKEvent_DecodeThread *)pUser;
PyHIKEvent_Object *ps = (PyHIKEvent_Object *)dp->ps;
uint8_t *video_src_data[4], *video_dst_data[4];
if (lFrameType != T_YV12)
{
fprintf(stderr, "Non support frame type\n");
return;
}
if (ps == NULL)
{
fprintf(stderr, "Error: cannnot found decode context\n");
return;
}
if (dp->sws_ctx == NULL)
{
dp->sws_ctx = sws_getContext(pFrameInfo->nWidth, pFrameInfo->nHeight, AV_PIX_FMT_YUV420P,
pFrameInfo->nWidth, pFrameInfo->nHeight, AV_PIX_FMT_RGB24,
SWS_FAST_BILINEAR, NULL, NULL, NULL);
/* allocate image where the decoded image will be put */
int ret = av_image_alloc(video_src_data, dp->video_src_linesize,
pFrameInfo->nWidth, pFrameInfo->nHeight, AV_PIX_FMT_YUV420P, 1);
if (ret < 0) {
fprintf(stderr, "Could not allocate raw video buffer\n");
return;
}
/* allocate image where the decoded image will be put */
ret = av_image_alloc(video_dst_data, dp->video_dst_linesize,
pFrameInfo->nWidth, pFrameInfo->nHeight, AV_PIX_FMT_RGB24, 1);
if (ret < 0) {
fprintf(stderr, "Could not allocate raw video buffer\n");
return;
}
av_freep(&video_src_data[0]);
av_freep(&video_dst_data[0]);
}
if (lFrameType == T_YV12)
{
char *yuvData = (char *)malloc(8 + pFrameInfo->nWidth * pFrameInfo->nHeight * 3);
*((uint32_t *)yuvData) = pFrameInfo->nWidth;
*((uint32_t *)yuvData+1) = pFrameInfo->nHeight;
/* convert to destination format */
video_src_data[0] = (uint8_t*)pBuf;
video_src_data[1] = (uint8_t*)(pBuf + pFrameInfo->nHeight * pFrameInfo->nWidth + pFrameInfo->nHeight * pFrameInfo->nWidth / 4);
video_src_data[2] = (uint8_t*)(pBuf + pFrameInfo->nHeight * pFrameInfo->nWidth);
video_dst_data[0] = (uint8_t *)(yuvData + 8);
sws_scale(dp->sws_ctx, (const uint8_t * const*)video_src_data,
dp->video_src_linesize, 0, pFrameInfo->nHeight, video_dst_data, dp->video_dst_linesize);
struct entry *elem = (struct entry *)calloc(1, sizeof(struct entry));
elem->lCommand = DVR_VIDEO_DATA;
// elem->pAlarmInfo = yuvData;
elem->pAlarmInfo = yuvData;
elem->dwBufLen = 8 + pFrameInfo->nWidth * pFrameInfo->nHeight * 3;
memcpy(elem->pAlarmInfo, yuvData, elem->dwBufLen);
pthread_mutex_lock(&ps->lock);
TAILQ_INSERT_TAIL(&ps->head, elem, entries);
pthread_mutex_unlock(&ps->lock);
}
}
void *decode_thread(void *data)
{
HIKEvent_DecodeThread *dp = (HIKEvent_DecodeThread *)data;
PyHIKEvent_Object *ps = (PyHIKEvent_Object *)dp->ps;
AVClass dec_cls = {
.class_name = "HIKEVENT",
.item_name = av_default_item_name,
.version = LIBAVUTIL_VERSION_INT
};
AVClass *pdec_cls = &dec_cls;
size_t avio_ctx_buffer_size = 1024 * 1024;
AVFormatContext *pFormatCtx = NULL;
dp->last_packet_rx = microtime();
if (dp->decode_way >= 3)
{
pthread_create(&dp->process_thread, NULL, process_thread, dp);
}
//ffmpeg打开流的回调
auto onReadData = [](void* pUser, uint8_t* buf, int bufSize)->int
{
HIKEvent_DecodeThread *dp = (HIKEvent_DecodeThread *)pUser;
PyHIKEvent_Object *ps = (PyHIKEvent_Object *)dp->ps;
while (!dp->stop && (dp->decode_way != 3 || ESRCH != pthread_kill(dp->process_thread, 0)))
{
pthread_mutex_lock(&dp->lock);
if (TAILQ_EMPTY(&dp->decode_head))
{
pthread_mutex_unlock(&dp->lock);
if (microtime() - dp->last_packet_rx >= 3)
{
fprintf(stderr, "Decode Thread: Receive Packet Timeout\n");
return AVERROR_EOF;
}
sleep(0.02);
} else
{
dp->last_packet_rx = microtime();
struct hik_queue_s *p = TAILQ_FIRST(&dp->decode_head);
if ((int)(p->dwBufLen - p->start) < bufSize)
{
TAILQ_REMOVE(&dp->decode_head, p, entries);
}
pthread_mutex_unlock(&dp->lock);
size_t wsize = (int)(p->dwBufLen - p->start) > bufSize ? bufSize : (int)(p->dwBufLen - p->start);
memcpy(buf, p->data + p->start, wsize);
p->start += wsize;
if (p->dwBufLen - p->start == 0)
{
free(p->data);
free(p);
}
return wsize;
}
}
return 0;
};
//ffmpeg打开流的回调
auto onWriteData = [](void* pUser, uint8_t* buf, int bufSize)->int
{
HIKEvent_DecodeThread *dp = (HIKEvent_DecodeThread *)pUser;
PyHIKEvent_Object *ps = (PyHIKEvent_Object *)dp->ps;
struct entry *elem = (struct entry *)calloc(1, sizeof(struct entry));
elem->lCommand = DVR_FLV_DATA;
elem->pAlarmInfo = (char *)malloc(bufSize + 2);
*(int16_t *)elem->pAlarmInfo = dp->channel;
memcpy(elem->pAlarmInfo + 2, buf, bufSize);
elem->dwBufLen = bufSize;
pthread_mutex_lock(&ps->lock);
TAILQ_INSERT_TAIL(&ps->head, elem, entries);
pthread_mutex_unlock(&ps->lock);
return bufSize;
};
int video_stream_idx = -1;
AVCodecContext *dec_ctx = NULL;
static uint8_t *video_src_data[4] = {NULL};
static int video_src_bufsize;
static uint8_t *video_dst_data[4] = {NULL};
static int video_dst_bufsize;
AVFrame *frame;
AVPacket *pkt;
if (dp->decode_way > 0)
{
//ffmpeg-------------------------------
uint8_t* avio_ctx_buffer = (uint8_t*)av_malloc(avio_ctx_buffer_size);
if (!avio_ctx_buffer)
{
av_log(&pdec_cls, AV_LOG_ERROR, "av_malloc ctx buffer failed!");
return NULL;
}
AVIOContext *pb = avio_alloc_context(avio_ctx_buffer, avio_ctx_buffer_size, 0, dp, onReadData, NULL, NULL);
if (pb == nullptr) //分配空间失败
{
av_freep(&avio_ctx_buffer);
av_log(&pdec_cls, AV_LOG_ERROR, "avio_alloc_context failed");
goto end;
}
pFormatCtx = init_input_ctx(pb, dp->playback ? 1 : 0);
if (pFormatCtx == NULL)
{
if (pb->buffer != NULL)
{
av_freep(&pb->buffer);
pb->buffer = NULL;
}
avio_context_free(&pb);
goto end;
}
dp->pInputCtx = pFormatCtx;
if (dp->decode_way >= 3)
{
uint8_t *avio_output_ctx_buffer = (uint8_t *)av_malloc(avio_ctx_buffer_size);
if (!avio_output_ctx_buffer)
{
av_log(&pdec_cls, AV_LOG_ERROR, "av_malloc ctx buffer failed!");