This commit is contained in:
ascendhuawei
2020-09-16 11:50:53 -07:00
commit a61dda4612
97 changed files with 15410 additions and 0 deletions
View File
+115
View File
@@ -0,0 +1,115 @@
import numpy as np
from PIL import Image
import copy
import acl
#from utils import *
from atlas_utils.constants import *
class AclImage():
def __init__(self, image, width=0, height=0,
size=0, memory_type=MEMORY_NORMAL):
self._data = None
self._np_array = None
self._memory_type = memory_type
self.width = 0
self.height = 0
self.channels = 0
self.size = 0
if isinstance(image, str):
self._instance_by_image_file(image)
elif str(type(image))=="<class 'numpy.ndarray'>":
self._instance_by_numpy_array(image,width,height)
elif isinstance(image, int):
self._instance_by_buffer(image, width, height, size)
else:
print("Create instance failed for unknow image data type")
def _instance_by_numpy_array(self, image,width,height):
self._data = image
self._type = IMAGE_DATA_NUMPY
self.size = self._data.itemsize * self._data.size
self.width = width
self.height = height
def _instance_by_image_file(self, image_path):
self._data = np.fromfile(image_path, dtype=np.byte)
self._type = IMAGE_DATA_NUMPY
self.size = self._data.itemsize * self._data.size
image = Image.open(image_path)
self.width, self.height = image.size
def _instance_by_buffer(self, image_buffer, width, height, size):
self.width = width
self.height = height
self.size = size
self._data = image_buffer
self._type = IMAGE_DATA_BUFFER
def tobytes(self):
if self._type == IMAGE_DATA_NUMPY:
return self._data
else:
return acl.util.ptr_to_numpy(self._data, (self.size, ), NPY_BYTE).tobytes()
def data(self):
if self._type == IMAGE_DATA_NUMPY:
return acl.util.numpy_to_ptr(self._data)
else:
return self._data
def copy_to_device(self, run_mode):
device_ptr = None
if run_mode == ACL_HOST:
device_ptr = copy_data_host_to_device(self.data(), self.size)
else:
device_ptr = copy_data_device_to_device(self.data(), self.size)
if device_ptr is None:
print("Copy image to device failed ")
return None
print("image copyt to device ", device_ptr, "%d, %d, %d"%(self.width,
self.height, self.size))
return AclImage(device_ptr, self.width,
self.height, self.size, MEMORY_DEVICE)
def copy_as_nparray(self):
if self._type == IMAGE_DATA_BUFFER:
#np_output = np.zeros(self.size, dtype=np.byte)
#if not np_output.flags['C_CONTIGUOUS']:
# np_output = np.ascontiguousarray(np_output)
np_output_ptr, ret = acl.rt.malloc(self.size, ACL_MEM_MALLOC_NORMAL_ONLY)
print("image ", np_output_ptr)
ret = acl.rt.memcpy(np_output_ptr, self.size, self._data, self.size, 3)
if (ret != ACL_ERROR_NONE):
print("Copy mage to np array failed for memcpy error ", ret)
return None
return copy.deepcopy(acl.util.ptr_to_numpy(np_output_ptr, (self.size, ), NPY_BYTE))
else:
return self._data.copy()
def destroy(self):
if (self._data is None) or (self.size == 0):
print("Release image abnormaly, data is None")
return
if self._memory_type == MEMORY_DEVICE:
acl.rt.free(self._data)
elif self._memory_type == MEMORY_HOST:
acl.rt.free_host(self._data)
elif self._memory_type == MEMORY_DVPP:
acl.media.dvpp_free(self._data)
self._data = None
self.size = 0
def __del__(self):
self.destroy()
+83
View File
@@ -0,0 +1,83 @@
# !/usr/bin/env python
# -*- coding:utf-8 -*-
#
from ctypes import *
import os
import time
import sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
from lib.atlasutil_so import libatlas
from constants import *
from acl_image import AclImage
CAMERA_OK = 0
CAMERA_ERROR = 1
CAMERA_CLOSED = 0
CAMERA_OPENED = 1
INVALID_IMAGE_PTR = 0
class CameraOutputC(Structure):
_fields_ = [
('size', c_int),
('data', POINTER(c_ubyte))
]
class Camera():
def __init__(self, id, fps=20, size=(1280, 720)):
self._id = id
self._fps = fps
self._width = size[0]
self._height = size[1]
self._size = int(self._width * self._height * 3 / 2)
self._status = CAMERA_CLOSED
if CAMERA_OK == self._open():
self._status = CAMERA_OPENED
else:
print("Open camera %d failed"%(id))
def _open(self):
ret = libatlas.OpenCameraEx(self._id, self._fps,
self._width, self._height)
print(ret)
if (ret != CAMERA_OK):
print("ERROR:Open camera %d failed ,ret = %d"%(self._id, ret))
return CAMERA_ERROR
self._status = CAMERA_OPENED
return CAMERA_OK
def is_opened(self):
return (self._status == CAMERA_OPENED)
def read(self):
frame_data = CameraOutputC()
ret = libatlas.ReadCameraFrame(self._id, byref(frame_data))
if (ret != CAMERA_OK):
print("ERROR:Read camera %d failed"%(self._id))
return None
return AclImage(addressof(frame_data.data.contents),
self._width, self._height, self._size, MEMORY_DVPP)
def close(self):
print("Close camera ", self._id)
libatlas.CloseCameraEx(self._id)
def __del__(self):
self.close()
if __name__ == "__main__":
cap = Camera(id=0, fps=20, size=(1280, 720))
start = time.time()
for i in range(0,100):
image = cap.read()
print("Read 100 frame exhaust ", time.time() - start)
+188
View File
@@ -0,0 +1,188 @@
"""
Copyright (R) @huawei.com, all rights reserved
-*- coding:utf-8 -*-
CREATED: 2020-6-04 20:12:13
MODIFIED: 2020-6-06 14:04:45
"""
SUCCESS = 0
FAILED = 1
ACL_DEVICE = 0
ACL_HOST = 1
MEMORY_NORMAL = 0
MEMORY_HOST = 1
MEMORY_DEVICE = 2
MEMORY_DVPP = 3
MEMORY_CTYPES = 4
IMAGE_DATA_NUMPY = 0
IMAGE_DATA_BUFFER = 1
# error code
ACL_ERROR_NONE = 0
ACL_ERROR_INVALID_PARAM = 100000
ACL_ERROR_UNINITIALIZE = 100001
ACL_ERROR_REPEAT_INITIALIZE = 100002
ACL_ERROR_INVALID_FILE = 100003
ACL_ERROR_WRITE_FILE = 100004
ACL_ERROR_INVALID_FILE_SIZE = 100005
ACL_ERROR_PARSE_FILE = 100006
ACL_ERROR_FILE_MISSING_ATTR = 100007
ACL_ERROR_FILE_ATTR_INVALID = 100008
ACL_ERROR_INVALID_DUMP_CONFIG = 100009
ACL_ERROR_INVALID_PROFILING_CONFIG = 100010
ACL_ERROR_INVALID_MODEL_ID = 100011
ACL_ERROR_DESERIALIZE_MODEL = 100012
ACL_ERROR_PARSE_MODEL = 100013
ACL_ERROR_READ_MODEL_FAILURE = 100014
ACL_ERROR_MODEL_SIZE_INVALID = 100015
ACL_ERROR_MODEL_MISSING_ATTR = 100016
ACL_ERROR_MODEL_INPUT_NOT_MATCH = 100017
ACL_ERROR_MODEL_OUTPUT_NOT_MATCH = 100018
ACL_ERROR_MODEL_NOT_DYNAMIC = 100019
ACL_ERROR_OP_TYPE_NOT_MATCH = 100020
ACL_ERROR_OP_INPUT_NOT_MATCH = 100021
ACL_ERROR_OP_OUTPUT_NOT_MATCH = 100022
ACL_ERROR_OP_ATTR_NOT_MATCH = 100023
ACL_ERROR_OP_NOT_FOUND = 100024
ACL_ERROR_OP_LOAD_FAILED = 100025
ACL_ERROR_UNSUPPORTED_DATA_TYPE = 100026
ACL_ERROR_FORMAT_NOT_MATCH = 100027
ACL_ERROR_BIN_SELECTOR_NOT_REGISTERED = 100028
ACL_ERROR_KERNEL_NOT_FOUND = 100029
ACL_ERROR_BIN_SELECTOR_ALREADY_REGISTERED = 100030
ACL_ERROR_KERNEL_ALREADY_REGISTERED = 100031
ACL_ERROR_INVALID_QUEUE_ID = 100032
ACL_ERROR_REPEAT_SUBSCRIBE = 100033
ACL_ERROR_STREAM_NOT_SUBSCRIBE = 100034
ACL_ERROR_THREAD_NOT_SUBSCRIBE = 100035
ACL_ERROR_WAIT_CALLBACK_TIMEOUT = 100036
ACL_ERROR_REPEAT_FINALIZE = 100037
ACL_ERROR_BAD_ALLOC = 200000
ACL_ERROR_API_NOT_SUPPORT = 200001
ACL_ERROR_INVALID_DEVICE = 200002
ACL_ERROR_MEMORY_ADDRESS_UNALIGNED = 200003
ACL_ERROR_RESOURCE_NOT_MATCH = 200004
ACL_ERROR_INVALID_RESOURCE_HANDLE = 200005
ACL_ERROR_STORAGE_OVER_LIMIT = 300000
ACL_ERROR_INTERNAL_ERROR = 500000
ACL_ERROR_FAILURE = 500001
ACL_ERROR_GE_FAILURE = 500002
ACL_ERROR_RT_FAILURE = 500003
ACL_ERROR_DRV_FAILURE = 500004
# rule for mem
ACL_MEM_MALLOC_HUGE_FIRST = 0
ACL_MEM_MALLOC_HUGE_ONLY = 1
ACL_MEM_MALLOC_NORMAL_ONLY = 2
# rule for memory copy
ACL_MEMCPY_HOST_TO_HOST = 0
ACL_MEMCPY_HOST_TO_DEVICE = 1
ACL_MEMCPY_DEVICE_TO_HOST = 2
ACL_MEMCPY_DEVICE_TO_DEVICE = 3
# input
LAST_ONE = -1
LAST_TWO = -2
type_dict = {
"bool": 0,
"int8": 1,
"int16": 2,
"int32": 4,
"int64": 8,
"uint8": 1,
"uint16": 2,
"uint32": 4,
"uint64": 8,
"float16": 2,
"float32": 4,
"float64": 8,
"float_": 8
}
NPY_BOOL = 0
NPY_BYTE = 1
NPY_UBYTE = 2
NPY_SHORT = 3
NPY_USHORT = 4
NPY_INT = 5
NPY_UINT = 6
NPY_LONG = 7
NPY_ULONG = 8
NPY_LONGLONG = 9
NPY_ULONGLONG = 10
ACL_DT_UNDEFINED = -1
ACL_FLOAT = 0
ACL_FLOAT16 = 1
ACL_INT8 = 2
ACL_INT32 = 3
ACL_UINT8 = 4
ACL_INT16 = 6
ACL_UINT16 = 7
ACL_UINT32 = 8
ACL_INT64 = 9
ACL_UINT64 = 10
ACL_DOUBLE = 11
ACL_BOOL = 12
# data format
ACL_FORMAT_UNDEFINED = -1
ACL_FORMAT_NCHW = 0
ACL_FORMAT_NHWC = 1
ACL_FORMAT_ND = 2
ACL_FORMAT_NC1HWC0 = 3
ACL_FORMAT_FRACTAL_Z = 4
ACL_DT_UNDEFINED = -1
ACL_FLOAT = 0
ACL_FLOAT16 = 1
ACL_INT8 = 2
ACL_INT32 = 3
ACL_UINT8 = 4
ACL_INT16 = 6
ACL_UINT16 = 7
ACL_UINT32 = 8
ACL_INT64 = 9
ACL_UINT64 = 10
ACL_DOUBLE = 11
ACL_BOOL = 12
acl_dtype = {
"dt_undefined": -1,
"float": 0,
"float16": 1,
"int8": 2,
"int32": 3,
"uint8": 4,
"int16": 6,
"uint16": 7,
"uint32": 8,
"int64": 9,
"double": 11,
"bool": 12
}
ACL_CALLBACK_NO_BLOCK = 0
ACL_CALLBACK_BLOCK = 1
PIXEL_FORMAT_YUV_400 = 0 # 0, YUV400 8bit
PIXEL_FORMAT_YUV_SEMIPLANAR_420 = 1 # 1, YUV420SP NV12 8bit
PIXEL_FORMAT_YVU_SEMIPLANAR_420 = 2 # 2, YUV420SP NV21 8bit
PIXEL_FORMAT_YUV_SEMIPLANAR_422 = 3 # 3, YUV422SP NV12 8bit
PIXEL_FORMAT_YVU_SEMIPLANAR_422 = 4 # 4, YUV422SP NV21 8bit
PIXEL_FORMAT_YUV_SEMIPLANAR_444 = 5 # 5, YUV444SP NV12 8bit
PIXEL_FORMAT_YVU_SEMIPLANAR_444 = 6 # 6, YUV444SP NV21 8bit
PIXEL_FORMAT_YUYV_PACKED_422 = 7 # 7, YUV422P YUYV 8bit
PIXEL_FORMAT_UYVY_PACKED_422 = 8 # 8, YUV422P UYVY 8bit
PIXEL_FORMAT_YVYU_PACKED_422 = 9 # 9, YUV422P YVYU 8bit
PIXEL_FORMAT_VYUY_PACKED_422 = 10 # 10, YUV422P VYUY 8bit
PIXEL_FORMAT_YUV_PACKED_444 = 11 # 11, YUV444P 8bit
PIXEL_FORMAT_RGB_888 = 12 # 12, RGB888
PIXEL_FORMAT_BGR_888 = 13 # 13, BGR888
PIXEL_FORMAT_ARGB_8888 = 14 # 14, ARGB8888
PIXEL_FORMAT_ABGR_8888 = 15 # 15, ABGR8888
PIXEL_FORMAT_RGBA_8888 = 16 # 16, RGBA8888
PIXEL_FORMAT_BGRA_8888 = 17 # 17, BGRA8888
PIXEL_FORMAT_YUV_SEMI_PLANNER_420_10BIT = 18 # 18, YUV420SP 10bit
PIXEL_FORMAT_YVU_SEMI_PLANNER_420_10BIT = 19 # 19, YVU420sp 10bit
PIXEL_FORMAT_YVU_PLANAR_420 = 20 # 20, YUV420P 8bit
# images format
IMG_EXT = ['.jpg', '.JPG', '.png', '.PNG', '.bmp', '.BMP', '.jpeg', '.JPEG']
View File
+20
View File
@@ -0,0 +1,20 @@
import threading
import ctypes
import os
class _AtlasutilLib(object):
_instance_lock = threading.Lock()
lib = ctypes.CDLL(os.path.dirname(os.path.abspath(__file__)) + '/libatlasutil.so')
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
if not hasattr(_AtlasutilLib, "_instance"):
with _AtlasutilLib._instance_lock:
if not hasattr(_AtlasutilLib, "_instance"):
_AtlasutilLib._instance = object.__new__(cls)
return _AtlasutilLib._instance
libatlas = _AtlasutilLib.lib
Binary file not shown.
Binary file not shown.
+59
View File
@@ -0,0 +1,59 @@
TOPDIR := $(patsubst %,%,$(CURDIR))
ifndef DDK_PATH
$(error "Can not find DDK_PATH env, please set it in environment!.")
endif
LOCAL_MODULE_NAME := libatlasutil.so
CC := aarch64-linux-gnu-g++
LOCAL_DIR := .
OUT_DIR = out
OBJ_DIR = $(OUT_DIR)/obj
DEPS_DIR = $(OUT_DIR)/deps
LOCAL_LIBRARY=$(OUT_DIR)/$(LOCAL_MODULE_NAME)
OUT_INC_DIR = $(OUT_DIR)/include
INC_DIR = \
-I$(HOME)/Ascend/driver/ \
-I$(DDK_PATH)/../arm64-linux_gcc7.3.0/acllib/include/
CC_FLAGS := $(INC_DIR) -DENABLE_DVPP_INTERFACE -std=c++11 -fPIC -Wall -O2
LNK_FLAGS := \
-L$(NPU_HOST_LIB) \
-L$(HOME)/Ascend/driver \
-lmedia_mini \
-lascendcl \
-lacl_dvpp \
-shared
SRCS := $(patsubst $(LOCAL_DIR)/%.cpp, %.cpp, $(shell find $(LOCAL_DIR) -name "*.cpp"))
OBJS := $(addprefix $(OBJ_DIR)/, $(patsubst %.cpp, %.o,$(SRCS)))
ALL_OBJS := $(OBJS)
all: do_pre_build do_build
do_pre_build:
$(Q)echo - do [$@]
$(Q)mkdir -p $(OBJ_DIR)
$(Q)mkdir -p $(OUT_INC_DIR)
do_build: $(LOCAL_LIBRARY) | do_pre_build
$(Q)echo - do [$@]
$(LOCAL_LIBRARY): $(ALL_OBJS)
$(Q)echo [LD] $@
$(Q)$(CC) $(CC_FLAGS) -o $@ $^ -Wl,--whole-archive -Wl,--no-whole-archive -Wl,--start-group -Wl,--end-group -Wl,-rpath='/home/HwHiAiUser/HIAI_PROJECTS/ascend_lib' $(LNK_FLAGS)
$(OBJS): $(OBJ_DIR)/%.o : %.cpp | do_pre_build
$(Q)echo [CC] $@
$(Q)mkdir -p $(dir $@)
$(Q)$(CC) $(CC_FLAGS) $(INC_DIR) -c -fstack-protector-all $< -o $@
clean:
rm -rf $(TOPDIR)/out
+209
View File
@@ -0,0 +1,209 @@
/**
* ============================================================================
*
* Copyright (C) 2018, Hisilicon Technologies Co., Ltd. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1 Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2 Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3 Neither the names of the copyright holders nor the names of the
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* ============================================================================
*/
#include <memory>
#include <sys/time.h>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include "acl/acl.h"
#include "acl/ops/acl_dvpp.h"
#include "atlas_utils_common.h"
using namespace std;
extern "C" {
#if 0
void* CopyDataHostToDvpp(void* data, int size) {
void* buffer = nullptr;
auto aclRet = acldvppMalloc(&buffer, size);
if (aclRet != ACL_ERROR_NONE) {
ASC_LOG_ERROR("acl malloc dvpp data failed, dataSize=%u, ret=%d",
size, aclRet);
return nullptr;
}
printf("malloc dvpp memory size %d ok", size);
// copy input to device memory
aclRet = aclrtMemcpy(buffer, size, data, size, ACL_MEMCPY_HOST_TO_DEVICE);
if (aclRet != ACL_ERROR_NONE) {
ASC_LOG_ERROR("acl memcpy data to dvpp failed, size %u, error %d", size, aclRet);
acldvppFree(buffer);
return nullptr;
}
printf("copy data to dvpp ok");
return buffer;
}
void* CopyDataHostToDevice(void* data, int size) {
void* buffer = nullptr;
auto aclRet = aclrtMalloc(&buffer, size, ACL_MEM_MALLOC_NORMAL_ONLY);
if (aclRet != ACL_ERROR_NONE) {
ASC_LOG_ERROR("acl malloc device memory failed, dataSize=%u, ret=%d",
size, aclRet);
return nullptr;
}
// copy input to device memory
aclRet = aclrtMemcpy(buffer, size, data, size, ACL_MEMCPY_HOST_TO_DEVICE);
if (aclRet != ACL_ERROR_NONE) {
ASC_LOG_ERROR("acl memcpy data to dev failed, size %u, error %d", size, aclRet);
aclrtFree(buffer);
return nullptr;
}
return buffer;
}
void* CopyDataDeviceToDevice(void* data, int size) {
void* buffer = nullptr;
auto aclRet = aclrtMalloc(&buffer, size, ACL_MEM_MALLOC_NORMAL_ONLY);
if (aclRet != ACL_ERROR_NONE) {
ASC_LOG_ERROR("acl malloc device memory failed, dataSize=%u, ret=%d",
size, aclRet);
return nullptr;
}
// copy input to device memory
aclRet = aclrtMemcpy(buffer, size, data, size, ACL_MEMCPY_DEVICE_TO_DEVICE);
if (aclRet != ACL_ERROR_NONE) {
ASC_LOG_ERROR("acl memcpy data to dev failed, size %u, error %d", size, aclRet);
aclrtFree(buffer);
return nullptr;
}
return buffer;
}
void* CopyDataDeviceToHost(void* deviceData, uint32_t dataLen) {
void *outHostData = nullptr;
aclError ret = aclrtMallocHost(&outHostData, dataLen);
if (ret != ACL_ERROR_NONE) {
ASC_LOG_ERROR("aclrtMallocHost failed, ret[%d]", ret);
return nullptr;
}
ret = aclrtMemcpy(outHostData, dataLen, deviceData,
dataLen, ACL_MEMCPY_DEVICE_TO_HOST);
if (ret != ACL_ERROR_NONE) {
ASC_LOG_ERROR("aclrtMemcpy failed, ret[%d]", ret);
aclrtFreeHost(outHostData);
return nullptr;
}
return outHostData;
}
void* CopyDataDeviceToNewBuf(void* deviceData, uint32_t dataLen) {
uint8_t* outHostData = new uint8_t[dataLen];
/* aclError ret = aclrtMallocHost(&outHostData, dataLen);
if (ret != ACL_ERROR_NONE) {
ASC_LOG_ERROR("aclrtMallocHost failed, ret[%d]", ret);
return nullptr;
}
*/
int ret = aclrtMemcpy(outHostData, dataLen, deviceData,
dataLen, ACL_MEMCPY_DEVICE_TO_HOST);
if (ret != ACL_ERROR_NONE) {
ASC_LOG_ERROR("aclrtMemcpy failed, ret[%d]", ret);
aclrtFreeHost(outHostData);
return nullptr;
}
return (void *)outHostData;
}
void SaveBinFile(const char* filename, void* data, uint32_t size) {
FILE *outFileFp = fopen(filename, "wb+");
if (outFileFp == nullptr) {
ASC_LOG_ERROR("Save file %s failed for open error", filename);
return;
}
fwrite(data, 1, size, outFileFp);
fflush(outFileFp);
fclose(outFileFp);
}
char* ReadBinFile(const std::string& fileName, uint32_t& fileSize)
{
std::ifstream binFile(fileName, std::ifstream::binary);
if (binFile.is_open() == false) {
ASC_LOG_ERROR("open file %s failed", fileName.c_str());
return nullptr;
}
binFile.seekg(0, binFile.end);
uint32_t binFileBufferLen = binFile.tellg();
if (binFileBufferLen == 0) {
ASC_LOG_ERROR("binfile is empty, filename is %s", fileName.c_str());
binFile.close();
return nullptr;
}
binFile.seekg(0, binFile.beg);
char* binFileBufferData = new(std::nothrow) char[binFileBufferLen];
if (binFileBufferData == nullptr) {
ASC_LOG_ERROR("malloc binFileBufferData failed");
binFile.close();
return nullptr;
}
binFile.read(binFileBufferData, binFileBufferLen);
binFile.close();
fileSize = binFileBufferLen;
return binFileBufferData;
}
int ReadImageFile(ImageData* image, const string& filename) {
char* data;
uint32_t size = 0;
data = ReadBinFile(filename, size);
if (data == nullptr) {
ASC_LOG_ERROR("Read image file %s failed", filename.c_str());
return STATUS_ERROR;
}
image->data = SHARED_PRT_U8_BUF(data);
image->size = size;
printf("read image ok, size %d", size);
return STATUS_OK;
}
#endif
}
+130
View File
@@ -0,0 +1,130 @@
/**
* ============================================================================
*
* Copyright (C) 2018, Hisilicon Technologies Co., Ltd. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1 Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2 Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3 Neither the names of the copyright holders nor the names of the
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* ============================================================================
*/
#ifndef _ATLAS_UTILS_COMMON_H_
#define _ATLAS_UTILS_COMMON_H_
#include <memory>
#include <mutex>
#include <unistd.h>
#include <vector>
#include "acl/acl_base.h"
using namespace std;
#define STATUS_ERROR -1
#define STATUS_OK 0
#define ALIGN_UP(num, align) (((num) + (align) - 1) & ~((align) - 1))
#define ALIGN_UP2(num) ALIGN_UP(num, 2)
#define ALIGN_UP16(num) ALIGN_UP(num, 16)
#define ALIGN_UP128(num) ALIGN_UP(num, 128)
#define YUV420SP_SIZE(width, height) ((width) * (height) * 3 / 2)
//#define SHARED_PRT_DVPP_BUF(buf) (shared_ptr<uint8_t>((uint8_t *)(buf), [](uint8_t* p) { acldvppFree(p); }))
//#define SHARED_PRT_U8_BUF(buf) (shared_ptr<uint8_t>((uint8_t *)(buf), [](uint8_t* p) { delete[](p); }))
#define ASC_LOG_ERROR(fmt, ...) \
do{aclAppLog(ACL_ERROR, __FUNCTION__, __FILE__, __LINE__, fmt, ##__VA_ARGS__); \
printf(fmt"\n", ##__VA_ARGS__);}while(0)
#define ASC_LOG_INFO(fmt, ...) \
do{aclAppLog(ACL_INFO, __FUNCTION__, __FILE__, __LINE__, fmt, ##__VA_ARGS__); \
printf(fmt"\n", ##__VA_ARGS__);}while(0)
#define ASC_LOG_DEBUG(fmt, ...) \
do{aclAppLog(ACL_DEBUG, __FUNCTION__, __FILE__, __LINE__, fmt, ##__VA_ARGS__); \
printf(fmt"\n", ##__VA_ARGS__);}while(0)
#if 0
struct ImageData {
bool isAligned = false;
uint32_t format = 1; //PIXEL_FORMAT_YUV_SEMIPLANAR_420;
uint32_t width = 0;
uint32_t height = 0;
uint32_t alignWidth = 0;
uint32_t alignHeight = 0;
uint32_t size = 0;
std::shared_ptr<uint8_t> data;
};
struct FrameData {
bool isFinished = false;
uint32_t width = 0;
uint32_t height = 0;
uint32_t frameId = 0;
ImageData image;
};
struct Resolution {
uint32_t width;
uint32_t height;
};
struct BoxArea {
uint32_t ltx;
uint32_t lty;
uint32_t width;
uint32_t height;
};
struct DataBuffer {
uint32_t size;
std::shared_ptr<void> data;
};
struct DetectionData {
ImageData image;
std::vector<DataBuffer> output;
};
struct AtlasMessage {
int dest;
int msgId;
std::shared_ptr<void> data;
};
extern "C" {
void* CopyDataDeviceToHost(void* deviceData, uint32_t dataLen);
void* CopyDataHostToDvpp(void* data, int size);
void* CopyDataHostToDevice(void* data, int size);
void* CopyDataDeviceToDevice(void* data, int size);
void* CopyDataDeviceToNewBuf(void* deviceData, uint32_t dataLen);
void SaveBinFile(const char* filename, void* data, uint32_t size);
int ReadImageFile(ImageData* image, const string& filename);
}
#endif
#endif /* HIAI_APP_IMAGE_POOL_H_ */
+164
View File
@@ -0,0 +1,164 @@
/**
* ============================================================================
*
* Copyright (C) 2018, Hisilicon Technologies Co., Ltd. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1 Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2 Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3 Neither the names of the copyright holders nor the names of the
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* ============================================================================
*/
#include <stdio.h>
#include <stdarg.h>
#include <time.h>
#include <memory>
#include <sys/time.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include "acl/acl.h"
#include "acl/ops/acl_dvpp.h"
#include "atlas_utils_common.h"
#include "camera.h"
using namespace std;
extern "C" {
#include "peripheral_api.h"
#include "camera.h"
CameraManager g_CameraMgr;
int CameraInit(int id, int fps, int width, int height) {
if (!g_CameraMgr.hwInited) {
MediaLibInit();
g_CameraMgr.hwInited = 1;
}
Camera& cap = CAMERA(id);
cap.frameSize = YUV420SP_SIZE(width, height);
cap.id = id;
cap.fps = fps;
cap.width = width;
cap.height = height;
cap.inited = true;
return STATUS_OK;
}
int ConfigCamera(int id, int fps, int width, int height) {
int ret = SetCameraProperty(id, CAMERA_PROP_FPS, &fps);
if (ret == LIBMEDIA_STATUS_FAILED) {
ASC_LOG_ERROR("Set camera fps failed");
return STATUS_ERROR;
}
CameraResolution resolution;
resolution.width = width;
resolution.height = height;
ret = SetCameraProperty(id, CAMERA_PROP_RESOLUTION, &resolution);
if (ret == LIBMEDIA_STATUS_FAILED) {
ASC_LOG_ERROR("Set camera resolution failed");
return STATUS_ERROR;
}
CameraCapMode mode = CAMERA_CAP_ACTIVE;
ret = SetCameraProperty(id, CAMERA_PROP_CAP_MODE, &mode);
if (ret == LIBMEDIA_STATUS_FAILED) {
ASC_LOG_ERROR("Set camera mode:%d failed", mode);
return STATUS_ERROR;
}
return STATUS_OK;
}
int OpenCameraEx(int id, int fps, int width, int height) {
if ((id < 0) || (id >= CAMERA_NUM)) {
ASC_LOG_ERROR("Open camera failed for invalid id %d", id);
return STATUS_ERROR;
}
if (!CAMERA(id).inited) {
CameraInit(id, fps, width, height);
}
CameraStatus status = QueryCameraStatus(id);
if (status == CAMERA_STATUS_CLOSED){
// Open Camera
if (LIBMEDIA_STATUS_FAILED == OpenCamera(id)) {
ASC_LOG_ERROR("Camera%d closed, and open failed.", id);
return STATUS_ERROR;
}
} else if (status != CAMERA_STATUS_OPEN) {
ASC_LOG_ERROR("Invalid camera%d status %d", id, status);
return STATUS_ERROR;
}
//Set camera property
if (STATUS_OK != ConfigCamera(id, fps, width, height)) {
CloseCamera(id);
ASC_LOG_ERROR("Set camera%d property failed", id);
return STATUS_ERROR;
}
ASC_LOG_INFO("Open camera %d success", id);
return STATUS_OK;
}
int ReadCameraFrame(int id, CameraOutput& frame) {
int size = CAMERA(id).frameSize;
void* data = nullptr;
auto aclRet = acldvppMalloc(&data, size);
if (aclRet != ACL_ERROR_NONE) {
ASC_LOG_ERROR("acl malloc dvpp data failed, dataSize=%u, ret=%d",
size, aclRet);
return STATUS_ERROR;
}
int ret = ReadFrameFromCamera(id, (void*)data, (int *)&size);
if ((ret == LIBMEDIA_STATUS_FAILED) ||
(size != CAMERA(id).frameSize)) {
acldvppFree(data);
ASC_LOG_ERROR("Get image from camera %d failed, size %d", id, size);
return STATUS_ERROR;
}
frame.size = size;
frame.data = (uint8_t*)data;
ASC_LOG_INFO("cpp image ptr 0x%x", data);
return STATUS_OK;
}
int CloseCameraEx(int cameraId) {
if (LIBMEDIA_STATUS_FAILED == CloseCamera(cameraId)) {
ASC_LOG_ERROR("Close camera %d failed", cameraId);
return STATUS_ERROR;
}
return STATUS_OK;
}
}
+63
View File
@@ -0,0 +1,63 @@
/**
* ============================================================================
*
* Copyright (C) 2018, Hisilicon Technologies Co., Ltd. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1 Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2 Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3 Neither the names of the copyright holders nor the names of the
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* ============================================================================
*/
#ifndef _CAMERA_H
#define _CAMERA_H
#define CAMERA_NUM (2)
#define CAMERA(i) (g_CameraMgr.cap[i])
struct CameraOutput {
int size;
uint8_t* data;
};
struct Camera {
bool inited = false;
int id = 255;
int fps = 0;
int width = 0;
int height = 0;
int frameSize = 0;
};
struct CameraManager {
bool hwInited = 0;
Camera cap[CAMERA_NUM];
};
#endif
Binary file not shown.
Binary file not shown.
Binary file not shown.
+6
View File
@@ -0,0 +1,6 @@
from .presenter_datatype import *
from .presenter_agent import *
from .presenter_channel import *
#from .presenter_message_pb2 import *
__all__ = ['presenter_datatype.py', 'presenter_agent', 'presenter_channel', 'presenter_message_pb']
@@ -0,0 +1,75 @@
# !/usr/bin/env python
# -*- coding:utf-8 -*-
import time
from threading import Thread
from .socket_client import AgentSocket
from . import presenter_message as pm
from . import presenter_datatype as datatype
class PresenterAgent():
def __init__(self, server_ip, port):
self.socket = AgentSocket(server_ip, port)
self._closed = False
def connect_server(self):
return self.socket.connect()
def start_heard_beat_thread(self):
self.heart_beat_thread = Thread(target=self._keep_alive)
self.heart_beat_thread.start()
def _keep_alive(self):
msg = pm.heartbeat_message()
while True:
if self._closed:
print("ERROR:Heard beat thread exit")
break
self.socket.send_msg(msg)
time.sleep(2)
def exit(self):
self.socket.close()
self._closed = True
def StartPresenterAgent(msg_queue, server_ip, port, open_status, data_respone_counter):
agent = PresenterAgent(server_ip, port)
ret = agent.connect_server()
if ret:
print("ERROR:Connect server failed, ret =", ret)
return
open_status.value = datatype.STATUS_CONNECTED
while True:
data = msg_queue.get()
if open_status.value == datatype.STATUS_EXITING:
open_status.value = datatype.STATUS_EXITTED
agent.exit()
break
if data:
agent.socket.send_msg(data)
msg_name, msg_body = agent.socket.recv_msg()
if (msg_name == None) or (msg_body == None):
print("ERROR:Recv invalid message, message name ", msg_name)
continue
if ((open_status.value == datatype.STATUS_CONNECTED)
and pm.is_open_channel_response(msg_name)):
print("Received open channel respone")
open_status.value = datatype.STATUS_OPENED
agent.start_heard_beat_thread()
print("presenter agent change connect_status to ", open_status.value)
if ((open_status.value == datatype.STATUS_OPENED) and
pm.is_image_frame_response(msg_name)):
data_respone_counter.value += 1
print("send ok ", data_respone_counter.value)
@@ -0,0 +1,159 @@
# !/usr/bin/env python
# -*- coding:utf-8 -*-
import ctypes
from ctypes import *
import time
import configparser
from multiprocessing import Process, Queue, Manager
import queue
import numpy as np
import sys
sys.path.append('..')
import acl
from ..constants import *
from ..lib.atlasutil_so import libatlas
from .presenter_datatype import *
from . import presenter_agent as agent
from . import presenter_message as pm
class DataBufC(Structure):
_fields_ = [
('size', c_int),
('data', POINTER(c_ubyte))
]
class DataBuf():
def __init__(self, data, data_size):
self.data = data
self.size = data_size
self.nparray = None
def copy_to_local(self):
src_data = DataBufC()
src_data.data = cast(self.data, POINTER(c_ubyte))
src_data.size = self.size
dest_data = DataBufC()
ret = libatlas.CopyDataToLocal(byref(dest_data), byref(src_data))
if ret:
print("Copy data to local failed")
return None
return DataBuf(dest_data.data, dest_data.size)
def tobytes(self):
self.nparray = np.frombuffer((ctypes.c_ubyte * self.size).from_address(ctypes.addressof(self.data.contents)), dtype=np.uint8)
return self.nparray.tobytes()
def destroy(self):
data_buf = DataBufC()
data_buf.data = cast(self.data, POINTER(c_ubyte))
data_buf.size = self.size
libatlas.ReleaseDataBuf(byref(data_buf))
self.data = None
self.size = 0
class PresenterChannel():
def __init__(self, server_ip, port, name='video', type=CONTENT_TYPE_VIDEO):
self._server_ip = server_ip
self._port = port
self._type = type
self._name = name
self.agent_msg_queue = Queue()
self.open_status = Manager().Value('i', STATUS_DISCONNECT)
self.data_respone_counter = Manager().Value('i', 0)
self._send_counter = 0
self._send_buffer = queue.Queue(64)
self.send_cnt = 0
self.relase_cnt = 0
def startup(self):
agent_process = Process(target=agent.StartPresenterAgent,
args=(self.agent_msg_queue, self._server_ip,self._port,
self.open_status, self.data_respone_counter))
agent_process.start()
time.sleep(0.5)
self._send_open_channel_request(self._name, self._type)
return self._wait_open_status(STATUS_OPENED)
def _wait_open_status(self, listen_status):
ret = STATUS_ERROR
for i in range(0, 100):
time.sleep(0.1)
if self.open_status.value == listen_status:
print("Open status is %d now"%(listen_status))
ret = STATUS_OK
break
return ret
def send_message(self, data):
self.agent_msg_queue.put(data)
self._send_counter += 1
def _send_open_channel_request(self, channel_name, content_type):
request_msg = pm.open_channel_request(channel_name, content_type)
self.send_message(request_msg)
def _release_send_success_data(self):
release_num = self._send_buffer.qsize() - \
(self._send_counter - self.data_respone_counter.value)
if release_num > 0:
for i in range(0, release_num):
data = self._send_buffer.get_nowait()
data.destroy()
data = None
self.relase_cnt += 1
#print("Released send success images ", self.relase_cnt)
def send_detection_data(self, image_width, image_height,
image_data, detection_result):
if self._send_buffer.full() is True:
print("ERROR:Send detection data failed for buffer is full")
return False
image_buf = DataBuf(image_data.data(), image_data.size).copy_to_local()
request_msg = pm.image_frame_request(image_width, image_height,
image_buf.tobytes(), detection_result)
self.send_message(request_msg)
self._send_buffer.put(image_buf)
self._release_send_success_data()
return True
def _send_heart_beat_message(self):
msg = pm.heartbeat_message()
self.send_message(msg)
def __del__(self):
self.open_status.value = STATUS_EXITING
print("Presenter channel close...")
self._send_heart_beat_message()
if STATUS_OK == self._wait_open_status(STATUS_EXITTED):
print("Presenter channel closed")
else:
print("Presenter channel close failed for presenter agent no response")
def get_presenter_server_addr(config_file):
config = configparser.ConfigParser()
config.read(config_file)
presenter_server_ip = config['baseconf']['presenter_server_ip']
port = int(config['baseconf']['presenter_server_port'])
print("presenter server ip %s, port %d"%(presenter_server_ip, port))
return presenter_server_ip, port
def open_channel(config_file, channel_name='video', channel_type = CONTENT_TYPE_VIDEO):
server_ip, port = get_presenter_server_addr(config_file)
channel = PresenterChannel(server_ip, port, channel_name, channel_type)
ret = channel.startup()
if ret:
print("ERROR:Open channel failed")
return None
return channel
@@ -0,0 +1,38 @@
STATUS_DISCONNECT = 0
STATUS_CONNECTED = 1
STATUS_OPEN_CH_REQUEST = 2
STATUS_OPENED = 3
STATUS_EXITING = 4
STATUS_EXITTED = 5
CONTENT_TYPE_IMAGE = 0
CONTENT_TYPE_VIDEO = 1
STATUS_OK = 0
STATUS_ERROR = 1
class Point():
def __init__(self, x=0, y=0):
self.x = x
self.y = y
class Box():
def __init__(self, lt, rb):
self.lt = Point(lt)
self.rb = Point(rb)
def box_valid(self):
return ((self.lt.x >= 0)
and (self.lt.y >= 0)
and (self.rb.x >= self.lt.x)
and (self.rb.y >= self.lt.y))
class ObjectDetectionResult():
def __init__(self, ltx=0, lty=0, rbx=0, rby=0, text=None):
self.object_class = 0
self.confidence = 0
self.box = Box((ltx, lty), (rbx, rby))
self.result_text = text
@@ -0,0 +1,67 @@
syntax = "proto3";
package ascend.presenter.proto;
enum OpenChannelErrorCode {
kOpenChannelErrorNone = 0;
kOpenChannelErrorNoSuchChannel = 1;
kOpenChannelErrorChannelAlreadyOpened = 2;
kOpenChannelErrorOther = -1;
}
enum ChannelContentType {
kChannelContentTypeImage = 0;
kChannelContentTypeVideo = 1;
}
// By Protocol Buffer Style Guide, need to use underscore_separated_names
// for field names
message OpenChannelRequest {
string channel_name = 1;
ChannelContentType content_type = 2;
}
message OpenChannelResponse {
OpenChannelErrorCode error_code = 1;
string error_message = 2;
}
message HeartbeatMessage {
}
enum ImageFormat {
kImageFormatJpeg = 0;
}
message Coordinate {
uint32 x = 1;
uint32 y = 2;
}
message Rectangle_Attr {
Coordinate left_top = 1;
Coordinate right_bottom = 2;
string label_text = 3;
}
message PresentImageRequest {
ImageFormat format = 1;
uint32 width = 2;
uint32 height = 3;
bytes data = 4;
repeated Rectangle_Attr rectangle_list = 5;
}
enum PresentDataErrorCode {
kPresentDataErrorNone = 0;
kPresentDataErrorUnsupportedType = 1;
kPresentDataErrorUnsupportedFormat = 2;
kPresentDataErrorOther = -1;
}
message PresentImageResponse {
PresentDataErrorCode error_code = 1;
string error_message = 2;
}
@@ -0,0 +1,56 @@
# !/usr/bin/env python
# -*- coding:utf-8 -*-
import struct
import socket
from . import presenter_message_pb2 as pb2
def pack_message(msg_name, msg_data):
buf = msg_data.SerializeToString()
msg_body_len = len(buf)
msg_name_len = len(msg_name)
msg_total_len = msg_name_len + msg_body_len + 5
data = b''
msg_total_len = socket.htonl(msg_total_len)
pack_data = struct.pack('IB', msg_total_len, msg_name_len)
data += pack_data
data += msg_name.encode()
data += buf
return data
def open_channel_request(channel_name, content_type):
request = pb2.OpenChannelRequest()
request.channel_name = channel_name
request.content_type = content_type
return pack_message(pb2._OPENCHANNELREQUEST.full_name, request)
def image_frame_request(image_width, image_height, image_data, detection_result):
request = pb2.PresentImageRequest()
request.format = 0
request.width = image_width
request.height = image_height
request.data = image_data
for i in range(0, len(detection_result)):
myadd = request.rectangle_list.add()
myadd.left_top.x = detection_result[i].box.lt.x
myadd.left_top.y = detection_result[i].box.lt.y
myadd.right_bottom.x = detection_result[i].box.rb.x
myadd.right_bottom.y = detection_result[i].box.rb.y
myadd.label_text = detection_result[i].result_text
return pack_message(pb2._PRESENTIMAGEREQUEST.full_name, request)
def heartbeat_message():
return pack_message(pb2._HEARTBEATMESSAGE.full_name, pb2.HeartbeatMessage())
def is_open_channel_response(msg_name):
return (msg_name == pb2._OPENCHANNELRESPONSE.full_name)
def is_image_frame_response(msg_name):
return (msg_name == pb2._PRESENTIMAGERESPONSE.full_name)
@@ -0,0 +1,493 @@
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: presenter_message.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='presenter_message.proto',
package='ascend.presenter.proto',
syntax='proto3',
serialized_pb=_b('\n\x17presenter_message.proto\x12\x16\x61scend.presenter.proto\"l\n\x12OpenChannelRequest\x12\x14\n\x0c\x63hannel_name\x18\x01 \x01(\t\x12@\n\x0c\x63ontent_type\x18\x02 \x01(\x0e\x32*.ascend.presenter.proto.ChannelContentType\"n\n\x13OpenChannelResponse\x12@\n\nerror_code\x18\x01 \x01(\x0e\x32,.ascend.presenter.proto.OpenChannelErrorCode\x12\x15\n\rerror_message\x18\x02 \x01(\t\"\x12\n\x10HeartbeatMessage\"\"\n\nCoordinate\x12\t\n\x01x\x18\x01 \x01(\r\x12\t\n\x01y\x18\x02 \x01(\r\"\x94\x01\n\x0eRectangle_Attr\x12\x34\n\x08left_top\x18\x01 \x01(\x0b\x32\".ascend.presenter.proto.Coordinate\x12\x38\n\x0cright_bottom\x18\x02 \x01(\x0b\x32\".ascend.presenter.proto.Coordinate\x12\x12\n\nlabel_text\x18\x03 \x01(\t\"\xb7\x01\n\x13PresentImageRequest\x12\x33\n\x06\x66ormat\x18\x01 \x01(\x0e\x32#.ascend.presenter.proto.ImageFormat\x12\r\n\x05width\x18\x02 \x01(\r\x12\x0e\n\x06height\x18\x03 \x01(\r\x12\x0c\n\x04\x64\x61ta\x18\x04 \x01(\x0c\x12>\n\x0erectangle_list\x18\x05 \x03(\x0b\x32&.ascend.presenter.proto.Rectangle_Attr\"o\n\x14PresentImageResponse\x12@\n\nerror_code\x18\x01 \x01(\x0e\x32,.ascend.presenter.proto.PresentDataErrorCode\x12\x15\n\rerror_message\x18\x02 \x01(\t*\xa5\x01\n\x14OpenChannelErrorCode\x12\x19\n\x15kOpenChannelErrorNone\x10\x00\x12\"\n\x1ekOpenChannelErrorNoSuchChannel\x10\x01\x12)\n%kOpenChannelErrorChannelAlreadyOpened\x10\x02\x12#\n\x16kOpenChannelErrorOther\x10\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01*P\n\x12\x43hannelContentType\x12\x1c\n\x18kChannelContentTypeImage\x10\x00\x12\x1c\n\x18kChannelContentTypeVideo\x10\x01*#\n\x0bImageFormat\x12\x14\n\x10kImageFormatJpeg\x10\x00*\xa4\x01\n\x14PresentDataErrorCode\x12\x19\n\x15kPresentDataErrorNone\x10\x00\x12$\n kPresentDataErrorUnsupportedType\x10\x01\x12&\n\"kPresentDataErrorUnsupportedFormat\x10\x02\x12#\n\x16kPresentDataErrorOther\x10\xff\xff\xff\xff\xff\xff\xff\xff\xff\x01\x62\x06proto3')
)
_OPENCHANNELERRORCODE = _descriptor.EnumDescriptor(
name='OpenChannelErrorCode',
full_name='ascend.presenter.proto.OpenChannelErrorCode',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='kOpenChannelErrorNone', index=0, number=0,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='kOpenChannelErrorNoSuchChannel', index=1, number=1,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='kOpenChannelErrorChannelAlreadyOpened', index=2, number=2,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='kOpenChannelErrorOther', index=3, number=-1,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=780,
serialized_end=945,
)
_sym_db.RegisterEnumDescriptor(_OPENCHANNELERRORCODE)
OpenChannelErrorCode = enum_type_wrapper.EnumTypeWrapper(_OPENCHANNELERRORCODE)
_CHANNELCONTENTTYPE = _descriptor.EnumDescriptor(
name='ChannelContentType',
full_name='ascend.presenter.proto.ChannelContentType',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='kChannelContentTypeImage', index=0, number=0,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='kChannelContentTypeVideo', index=1, number=1,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=947,
serialized_end=1027,
)
_sym_db.RegisterEnumDescriptor(_CHANNELCONTENTTYPE)
ChannelContentType = enum_type_wrapper.EnumTypeWrapper(_CHANNELCONTENTTYPE)
_IMAGEFORMAT = _descriptor.EnumDescriptor(
name='ImageFormat',
full_name='ascend.presenter.proto.ImageFormat',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='kImageFormatJpeg', index=0, number=0,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=1029,
serialized_end=1064,
)
_sym_db.RegisterEnumDescriptor(_IMAGEFORMAT)
ImageFormat = enum_type_wrapper.EnumTypeWrapper(_IMAGEFORMAT)
_PRESENTDATAERRORCODE = _descriptor.EnumDescriptor(
name='PresentDataErrorCode',
full_name='ascend.presenter.proto.PresentDataErrorCode',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='kPresentDataErrorNone', index=0, number=0,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='kPresentDataErrorUnsupportedType', index=1, number=1,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='kPresentDataErrorUnsupportedFormat', index=2, number=2,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='kPresentDataErrorOther', index=3, number=-1,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=1067,
serialized_end=1231,
)
_sym_db.RegisterEnumDescriptor(_PRESENTDATAERRORCODE)
PresentDataErrorCode = enum_type_wrapper.EnumTypeWrapper(_PRESENTDATAERRORCODE)
kOpenChannelErrorNone = 0
kOpenChannelErrorNoSuchChannel = 1
kOpenChannelErrorChannelAlreadyOpened = 2
kOpenChannelErrorOther = -1
kChannelContentTypeImage = 0
kChannelContentTypeVideo = 1
kImageFormatJpeg = 0
kPresentDataErrorNone = 0
kPresentDataErrorUnsupportedType = 1
kPresentDataErrorUnsupportedFormat = 2
kPresentDataErrorOther = -1
_OPENCHANNELREQUEST = _descriptor.Descriptor(
name='OpenChannelRequest',
full_name='ascend.presenter.proto.OpenChannelRequest',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='channel_name', full_name='ascend.presenter.proto.OpenChannelRequest.channel_name', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='content_type', full_name='ascend.presenter.proto.OpenChannelRequest.content_type', index=1,
number=2, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=51,
serialized_end=159,
)
_OPENCHANNELRESPONSE = _descriptor.Descriptor(
name='OpenChannelResponse',
full_name='ascend.presenter.proto.OpenChannelResponse',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='error_code', full_name='ascend.presenter.proto.OpenChannelResponse.error_code', index=0,
number=1, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='error_message', full_name='ascend.presenter.proto.OpenChannelResponse.error_message', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=161,
serialized_end=271,
)
_HEARTBEATMESSAGE = _descriptor.Descriptor(
name='HeartbeatMessage',
full_name='ascend.presenter.proto.HeartbeatMessage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=273,
serialized_end=291,
)
_COORDINATE = _descriptor.Descriptor(
name='Coordinate',
full_name='ascend.presenter.proto.Coordinate',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='x', full_name='ascend.presenter.proto.Coordinate.x', index=0,
number=1, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='y', full_name='ascend.presenter.proto.Coordinate.y', index=1,
number=2, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=293,
serialized_end=327,
)
_RECTANGLE_ATTR = _descriptor.Descriptor(
name='Rectangle_Attr',
full_name='ascend.presenter.proto.Rectangle_Attr',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='left_top', full_name='ascend.presenter.proto.Rectangle_Attr.left_top', index=0,
number=1, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='right_bottom', full_name='ascend.presenter.proto.Rectangle_Attr.right_bottom', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='label_text', full_name='ascend.presenter.proto.Rectangle_Attr.label_text', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=330,
serialized_end=478,
)
_PRESENTIMAGEREQUEST = _descriptor.Descriptor(
name='PresentImageRequest',
full_name='ascend.presenter.proto.PresentImageRequest',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='format', full_name='ascend.presenter.proto.PresentImageRequest.format', index=0,
number=1, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='width', full_name='ascend.presenter.proto.PresentImageRequest.width', index=1,
number=2, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='height', full_name='ascend.presenter.proto.PresentImageRequest.height', index=2,
number=3, type=13, cpp_type=3, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='data', full_name='ascend.presenter.proto.PresentImageRequest.data', index=3,
number=4, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=_b(""),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='rectangle_list', full_name='ascend.presenter.proto.PresentImageRequest.rectangle_list', index=4,
number=5, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=481,
serialized_end=664,
)
_PRESENTIMAGERESPONSE = _descriptor.Descriptor(
name='PresentImageResponse',
full_name='ascend.presenter.proto.PresentImageResponse',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='error_code', full_name='ascend.presenter.proto.PresentImageResponse.error_code', index=0,
number=1, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='error_message', full_name='ascend.presenter.proto.PresentImageResponse.error_message', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=666,
serialized_end=777,
)
_OPENCHANNELREQUEST.fields_by_name['content_type'].enum_type = _CHANNELCONTENTTYPE
_OPENCHANNELRESPONSE.fields_by_name['error_code'].enum_type = _OPENCHANNELERRORCODE
_RECTANGLE_ATTR.fields_by_name['left_top'].message_type = _COORDINATE
_RECTANGLE_ATTR.fields_by_name['right_bottom'].message_type = _COORDINATE
_PRESENTIMAGEREQUEST.fields_by_name['format'].enum_type = _IMAGEFORMAT
_PRESENTIMAGEREQUEST.fields_by_name['rectangle_list'].message_type = _RECTANGLE_ATTR
_PRESENTIMAGERESPONSE.fields_by_name['error_code'].enum_type = _PRESENTDATAERRORCODE
DESCRIPTOR.message_types_by_name['OpenChannelRequest'] = _OPENCHANNELREQUEST
DESCRIPTOR.message_types_by_name['OpenChannelResponse'] = _OPENCHANNELRESPONSE
DESCRIPTOR.message_types_by_name['HeartbeatMessage'] = _HEARTBEATMESSAGE
DESCRIPTOR.message_types_by_name['Coordinate'] = _COORDINATE
DESCRIPTOR.message_types_by_name['Rectangle_Attr'] = _RECTANGLE_ATTR
DESCRIPTOR.message_types_by_name['PresentImageRequest'] = _PRESENTIMAGEREQUEST
DESCRIPTOR.message_types_by_name['PresentImageResponse'] = _PRESENTIMAGERESPONSE
DESCRIPTOR.enum_types_by_name['OpenChannelErrorCode'] = _OPENCHANNELERRORCODE
DESCRIPTOR.enum_types_by_name['ChannelContentType'] = _CHANNELCONTENTTYPE
DESCRIPTOR.enum_types_by_name['ImageFormat'] = _IMAGEFORMAT
DESCRIPTOR.enum_types_by_name['PresentDataErrorCode'] = _PRESENTDATAERRORCODE
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
OpenChannelRequest = _reflection.GeneratedProtocolMessageType('OpenChannelRequest', (_message.Message,), dict(
DESCRIPTOR = _OPENCHANNELREQUEST,
__module__ = 'presenter_message_pb2'
# @@protoc_insertion_point(class_scope:ascend.presenter.proto.OpenChannelRequest)
))
_sym_db.RegisterMessage(OpenChannelRequest)
OpenChannelResponse = _reflection.GeneratedProtocolMessageType('OpenChannelResponse', (_message.Message,), dict(
DESCRIPTOR = _OPENCHANNELRESPONSE,
__module__ = 'presenter_message_pb2'
# @@protoc_insertion_point(class_scope:ascend.presenter.proto.OpenChannelResponse)
))
_sym_db.RegisterMessage(OpenChannelResponse)
HeartbeatMessage = _reflection.GeneratedProtocolMessageType('HeartbeatMessage', (_message.Message,), dict(
DESCRIPTOR = _HEARTBEATMESSAGE,
__module__ = 'presenter_message_pb2'
# @@protoc_insertion_point(class_scope:ascend.presenter.proto.HeartbeatMessage)
))
_sym_db.RegisterMessage(HeartbeatMessage)
Coordinate = _reflection.GeneratedProtocolMessageType('Coordinate', (_message.Message,), dict(
DESCRIPTOR = _COORDINATE,
__module__ = 'presenter_message_pb2'
# @@protoc_insertion_point(class_scope:ascend.presenter.proto.Coordinate)
))
_sym_db.RegisterMessage(Coordinate)
Rectangle_Attr = _reflection.GeneratedProtocolMessageType('Rectangle_Attr', (_message.Message,), dict(
DESCRIPTOR = _RECTANGLE_ATTR,
__module__ = 'presenter_message_pb2'
# @@protoc_insertion_point(class_scope:ascend.presenter.proto.Rectangle_Attr)
))
_sym_db.RegisterMessage(Rectangle_Attr)
PresentImageRequest = _reflection.GeneratedProtocolMessageType('PresentImageRequest', (_message.Message,), dict(
DESCRIPTOR = _PRESENTIMAGEREQUEST,
__module__ = 'presenter_message_pb2'
# @@protoc_insertion_point(class_scope:ascend.presenter.proto.PresentImageRequest)
))
_sym_db.RegisterMessage(PresentImageRequest)
PresentImageResponse = _reflection.GeneratedProtocolMessageType('PresentImageResponse', (_message.Message,), dict(
DESCRIPTOR = _PRESENTIMAGERESPONSE,
__module__ = 'presenter_message_pb2'
# @@protoc_insertion_point(class_scope:ascend.presenter.proto.PresentImageResponse)
))
_sym_db.RegisterMessage(PresentImageResponse)
# @@protoc_insertion_point(module_scope)
+119
View File
@@ -0,0 +1,119 @@
# !/usr/bin/env python
# -*- coding:utf-8 -*-
import threading
import socket
import time
import struct
import time
from .presenter_datatype import *
class AgentSocket(object):
def __init__(self, server_ip, port):
self._server_address = (server_ip, port)
self._sock_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect(self):
ret = 0
for i in range(0,5):
ret = self._sock_client.connect_ex(self._server_address)
if ret == 0:
break
time.sleep(0.2)
return ret
def _read_socket(self, read_len):
has_read_len = 0
read_buf = b''
total_buf = b''
while has_read_len != read_len:
try:
read_buf = self._sock_client.recv(read_len - has_read_len)
except socket.error:
print("ERROR:Read socket failed")
return False, None
if read_buf == b'':
return False, None
total_buf += read_buf
has_read_len = len(total_buf)
return True, total_buf
def _read_msg_head(self, read_len):
ret, msg_head = self._read_socket(read_len)
#print("msg head data is :", msg_head)
if not ret:
print("ERROR:socket receive msg head null")
return None, None
# in Struct(), 'I' is unsigned int, 'B' is unsigned char
msg_head_data = struct.Struct('IB')
(msg_total_len, msg_name_len) = msg_head_data.unpack(msg_head)
msg_total_len = socket.ntohl(msg_total_len)
#print("msg total length is :", msg_total_len)
#print("msg name is :", msg_name_len)
return msg_total_len, msg_name_len
def _read_msg_name(self, msg_name_len):
ret, msg_name = self._read_socket(msg_name_len)
#print("direct msg name is :", msg_name)
if not ret:
print("ERROR:socket receive msg name null")
return False, None
try:
msg_name = msg_name.decode("utf-8")
#print("decode msg name is :", msg_name)
except Exception as e:
print("ERROR:msg name decode to utf-8 error")
return False, None
return True, msg_name
def _read_msg_body(self, msg_body_len):
#print("msg body length is :", msg_body_len)
ret, msg_body = self._read_socket(msg_body_len)
if not ret:
print("ERROR:socket receive msg body null")
return False, None
return True, msg_body
def recv_msg(self):
# Step1: read msg head
msg_total_len, msg_name_len = self._read_msg_head(5)
if msg_total_len is None:
print("ERROR:msg total len is None.")
return None
# Step2: read msg name
ret, msg_name = self._read_msg_name(msg_name_len)
if not ret:
return None
# Step3: read msg body
msg_body_len = msg_total_len - 5 - msg_name_len
if msg_body_len < 0:
print("ERROR:msg total len is 0")
return None
ret, msg_body = self._read_msg_body(msg_body_len)
if not ret:
return None
return msg_name, msg_body
def send_msg(self, data):
try:
self._sock_client.sendall(data)
except Exception as e:
print("ERROR:Send msg failed")
return 1
return 0
def close(self):
self._sock_client.shutdown(socket.SHUT_RDWR)
self._sock_client.close()
+71
View File
@@ -0,0 +1,71 @@
import acl
from atlas_utils.constants import *
from atlas_utils.lib.atlasutil_so import libatlas
def check_ret(message, ret):
if ret != ACL_ERROR_NONE:
raise Exception("{} failed ret={}"
.format(message, ret))
def copy_data_device_to_host(device_data, data_size):
host_buffer, ret = acl.rt.malloc_host(data_size)
if ret != ACL_ERROR_NONE:
print("Malloc host memory failed, error: ", ret)
return None
ret = acl.rt.memcpy(host_buffer, data_size,
device_data, data_size,
ACL_MEMCPY_DEVICE_TO_HOST)
if ret != ACL_ERROR_NONE:
print("Copy device data to host memory failed, error: ", ret)
acl.rt.free_host(host_buffer)
return None
return host_buffer
def copy_data_device_to_device(device_data, data_size):
device_buffer, ret = acl.rt.malloc(data_size, ACL_MEM_MALLOC_NORMAL_ONLY)
if ret != ACL_ERROR_NONE:
print("Malloc device memory failed, error: ", ret)
return None
ret = acl.rt.memcpy(device_buffer, data_size,
device_data, data_size,
ACL_MEMCPY_DEVICE_TO_DEVICE)
if ret != ACL_ERROR_NONE:
print("Copy device data to device memory failed, error: ", ret)
acl.rt.free(device_buffer)
return None
return device_buffer
def copy_data_host_to_device(host_data, data_size):
device_buffer, ret = acl.rt.malloc(data_size, ACL_MEM_MALLOC_NORMAL_ONLY)
if ret != ACL_ERROR_NONE:
print("Malloc device memory failed, error: ", ret)
return None
ret = acl.rt.memcpy(device_buffer, data_size,
host_data, data_size,
ACL_MEMCPY_HOST_TO_DEVICE)
if ret != ACL_ERROR_NONE:
print("Copy device data to device memory failed, error: ", ret)
acl.rt.free(device_buffer)
return None
return device_buffer
def align_up(value, align):
return int(int((value + align - 1) / align) * align)
def align_up16(value):
return align_up(value, 16)
def align_up2(value):
return align_up(value, 2)
def yuv420sp_size(width, height):
return width * height * 3 // 2
def unpack_bytes(dest, dest_size, src, src_size):
libatlas.UnpackFloatByteArray(dest, dest_size, src, src_size)