/**@ingroup tsk_condwait_group * Creates new conwait handle. You MUST call @ref tsk_condwait_destroy to free the handle. * @retval New condwait handle. * @sa @ref tsk_condwait_destroy. */ tsk_condwait_handle_t* tsk_condwait_create() { tsk_condwait_t *condwait = tsk_calloc(1, sizeof(tsk_condwait_t)); if(condwait) { #if TSK_UNDER_WINDOWS condwait->pcond = CreateEvent(NULL, TRUE, FALSE, NULL); if(!condwait->pcond) { TSK_FREE(condwait); } #else condwait->pcond = (CONDWAIT_T)tsk_calloc(1, sizeof(CONDWAIT_S)); if(pthread_cond_init(condwait->pcond, 0)) { TSK_DEBUG_ERROR("Failed to initialize the new conwait."); } if(!(condwait->mutex = tsk_mutex_create())) { pthread_cond_destroy(condwait->pcond); TSK_FREE(condwait); TSK_DEBUG_ERROR("Failed to initialize the internal mutex."); } #endif } if(!condwait) { TSK_DEBUG_ERROR("Failed to create new conwait."); } return condwait; }
/**@ingroup tsk_params_group * Converts a key-value-pair string (kvp) to @ref tsk_param_t object. * @param line The kvp (e.g. 'branch=z9hG4bK652hsge') string to parse. * @param size The size (length) of the kvp string. * @retval @ref tsk_param_t object. */ tsk_param_t *tsk_params_parse_param(const char* line, tsk_size_t size) { if(line && size){ const char* start = line; const char* end = (line + size); const char* equal = strstr(line, "="); tsk_param_t *param = tsk_param_create_null(); if(param && equal && equal<end){ if((param->name = tsk_calloc((equal-start)+1, sizeof(const char)))){ memcpy(param->name, start, (equal-start)); } if((param->value = tsk_calloc((end-equal-1)+1, sizeof(const char)))){ memcpy(param->value, equal+1, (end-equal-1)); } } else if(param){ if((param->name = tsk_calloc((end-start)+1, sizeof(const char)))){ memcpy(param->name, start, (end-start)); } } return param; } return tsk_null; }
int tdav_codec_mp4ves_open_decoder(tdav_codec_mp4ves_t* self) { int ret, size; if(!self->decoder.codec && !(self->decoder.codec = avcodec_find_decoder(CODEC_ID_MPEG4))){ TSK_DEBUG_ERROR("Failed to find MP4V-ES decoder"); return -1; } if(self->decoder.context){ TSK_DEBUG_ERROR("Decoder already opened"); return -1; } self->decoder.context = avcodec_alloc_context(); avcodec_get_context_defaults(self->decoder.context); self->decoder.context->pix_fmt = PIX_FMT_YUV420P; self->decoder.context->width = TMEDIA_CODEC_VIDEO(self)->out.width; self->decoder.context->height = TMEDIA_CODEC_VIDEO(self)->out.height; // Picture (YUV 420) if(!(self->decoder.picture = avcodec_alloc_frame())){ TSK_DEBUG_ERROR("Failed to create decoder picture"); return -2; } avcodec_get_frame_defaults(self->decoder.picture); size = avpicture_get_size(PIX_FMT_YUV420P, self->decoder.context->width, self->decoder.context->height); if(!(self->decoder.accumulator = tsk_calloc((size + FF_INPUT_BUFFER_PADDING_SIZE), sizeof(uint8_t)))){ TSK_DEBUG_ERROR("Failed to allocate decoder buffer"); return -2; } if(!(self->decoder.accumulator = tsk_calloc((size + FF_INPUT_BUFFER_PADDING_SIZE), sizeof(uint8_t)))){ TSK_DEBUG_ERROR("Failed to allocate decoder buffer"); return -2; } // Open decoder if((ret = avcodec_open(self->decoder.context, self->decoder.codec)) < 0){ TSK_DEBUG_ERROR("Failed to open MP4V-ES decoder"); return ret; } self->decoder.last_seq = 0; return ret; }
tsk_buffer_t* tmsrp_data_out_get(tmsrp_data_out_t* self) { tsk_buffer_t* ret = tsk_null; tsk_size_t toread; if(!self){ return tsk_null; } if(!(toread = self->size > TMSRP_MAX_CHUNK_SIZE ? TMSRP_MAX_CHUNK_SIZE : self->size)){ return tsk_null; } if(self->message){ ret = tsk_buffer_create(TSK_BUFFER_DATA(self->message), toread); tsk_buffer_remove(self->message, 0, toread); self->size = self->message->size; } else if(self->file){ // Buffer hack tsk_size_t read; ret = tsk_buffer_create_null(); ret->data = tsk_calloc(toread, sizeof(uint8_t)); ret->size = toread; if((read = fread(ret->data, sizeof(uint8_t), toread, self->file)) == toread){ self->size -= toread; } else{ TSK_OBJECT_SAFE_FREE(ret); } } return ret; }
/*== Add new socket ==*/ static int addSocket(tnet_fd_t fd, tnet_socket_type_t type, tnet_transport_t *transport, int take_ownership, int is_client) { transport_context_t *context = transport?transport->context:0; if(context){ transport_socket_t *sock = tsk_calloc(1, sizeof(transport_socket_t)); sock->fd = fd; sock->type = type; sock->owner = take_ownership ? 1 : 0; if(TNET_SOCKET_TYPE_IS_TLS(sock->type)){ sock->tlshandle = tnet_sockfd_set_tlsfiles(sock->fd, is_client, transport->tls.ca, transport->tls.pvk, transport->tls.pbk); } tsk_safeobj_lock(context); context->events[context->count] = WSACreateEvent(); context->sockets[context->count] = sock; context->count++; tsk_safeobj_unlock(context); return 0; } else{ TSK_DEBUG_ERROR("Context is Null."); return -1; } }
static int _v4l2_init_mmap(tdav_producer_video_v4l2_t* p_self, const char* device_name) { struct v4l2_requestbuffers req; V4L2_CLEAR(req); req.count = 4; req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; req.memory = V4L2_MEMORY_MMAP; if (-1 == _v4l2_xioctl(p_self->fd, VIDIOC_REQBUFS, &req)) { if (EINVAL == errno) { V4L2_DEBUG_ERROR("%s does not support memory mapping", device_name); return -1; } else { V4L2_DEBUG_ERROR("xioctl(%s, VIDIOC_REQBUFS) failed: %s error %d", device_name, strerror(errno), errno); return -1; } } if (req.count < 2) { V4L2_DEBUG_ERROR("Insufficient buffer memory on %s", device_name); return -1; } if (!(p_self->p_buffers = tsk_calloc(req.count, sizeof(*p_self->p_buffers)))) { V4L2_DEBUG_ERROR("Out of memory"); return -1; } for (p_self->n_buffers = 0; p_self->n_buffers < req.count; ++p_self->n_buffers) { struct v4l2_buffer buf; V4L2_CLEAR(buf); buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buf.memory = V4L2_MEMORY_MMAP; buf.index = p_self->n_buffers; if (-1 == _v4l2_xioctl(p_self->fd, VIDIOC_QUERYBUF, &buf)) { V4L2_DEBUG_ERROR("xioctl(%s, VIDIOC_REQBUFS) failed: %s error %d", device_name, strerror(errno), errno); return -1; } p_self->p_buffers[p_self->n_buffers].n_length = buf.length; p_self->p_buffers[p_self->n_buffers].p_start = mmap(NULL /* start anywhere */, buf.length, PROT_READ | PROT_WRITE /* required */, MAP_SHARED /* recommended */, p_self->fd, buf.m.offset); if (MAP_FAILED == p_self->p_buffers[p_self->n_buffers].p_start) { V4L2_DEBUG_ERROR("mmap(%s) failed: %s error %d", device_name, strerror(errno), errno); return -1; } } return 0; }
/*== Add new socket ==*/ int addSocket(tnet_fd_t fd, tnet_socket_type_t type, tnet_transport_t *transport, tsk_bool_t take_ownership, tsk_bool_t is_client) { transport_context_t *context = transport?transport->context:0; if (context) { transport_socket_t *sock = tsk_calloc(1, sizeof(transport_socket_t)); sock->fd = fd; sock->type = type; sock->owner = take_ownership; // TODO: Find out how to specify client certificate //if (TNET_SOCKET_TYPE_IS_TLS(sock->type)) { // sock->tlshandle = tnet_sockfd_set_tlsfiles(sock->fd, is_client, transport->tls.ca, transport->tls.pvk, transport->tls.pbk); //} tsk_safeobj_lock(context); context->sockets[context->count] = sock; context->count++; tsk_safeobj_unlock(context); TSK_DEBUG_INFO("Socket added"); return 0; } else{ TSK_DEBUG_ERROR("Context is Null."); return -1; } }
/*== Add new socket ==*/ int addSocket(tnet_fd_t fd, tnet_socket_type_t type, tnet_transport_t *transport, tsk_bool_t take_ownership, tsk_bool_t is_client) { transport_context_t *context = transport?transport->context:0; if(context){ transport_socket_xt *sock = tsk_calloc(1, sizeof(transport_socket_xt)); sock->fd = fd; sock->type = type; sock->owner = take_ownership; if((TNET_SOCKET_TYPE_IS_TLS(sock->type) || TNET_SOCKET_TYPE_IS_WSS(sock->type)) && transport->tls.enabled){ #if HAVE_OPENSSL sock->tlshandle = tnet_tls_socket_create(sock->fd, is_client ? transport->tls.ctx_client : transport->tls.ctx_server); #endif } tsk_safeobj_lock(context); context->ufds[context->count].fd = fd; context->ufds[context->count].events = (fd == context->pipeR) ? TNET_POLLIN : context->events; context->ufds[context->count].revents = 0; context->sockets[context->count] = sock; context->count++; tsk_safeobj_unlock(context); TSK_DEBUG_INFO("Socket added: fd=%d, tail.count=%d", fd, context->count); return 0; } else{ TSK_DEBUG_ERROR("Context is Null."); return -1; } }
/**@ingroup tsk_object_group * Creates new object. The object MUST be declared using @ref TSK_DECLARE_OBJECT macro. * @param objdef The object meta-data (definition). For more infomation see @ref tsk_object_def_t. * @param ... List of parameters to pass to the constructor(defined in the meta-data). * @retval @ref tsk_object_t object with a reference counter equal to 1. * @sa @ref tsk_object_new_2. */ tsk_object_t* tsk_object_new(const tsk_object_def_t *objdef, ...) { // Do not check "objdef", let the application die if it's null tsk_object_t *newobj = tsk_calloc(1, objdef->size); if(newobj){ (*(const tsk_object_def_t **) newobj) = objdef; TSK_OBJECT_HEADER(newobj)->refCount = 1; if(objdef->constructor){ va_list ap; tsk_object_t * newobj_ = newobj;// save va_start(ap, objdef); newobj = objdef->constructor(newobj, &ap); // must return new va_end(ap); if(!newobj){ // null if constructor failed to initialized the object if(objdef->destructor){ objdef->destructor(newobj_); } tsk_free(&newobj_); } #if TSK_DEBUG_OBJECTS TSK_DEBUG_INFO("N∞ objects:%d", ++tsk_objects_count); #endif } else{ TSK_DEBUG_WARN("No constructor found."); } } else{ TSK_DEBUG_ERROR("Failed to create new tsk_object."); } return newobj; }
/**@ingroup tsk_mutex_group * Creates new recursive mutex handle. * @param recursive whether we want a recursive mutex or not * @retval New mutex handle. It is up to you free the returned handle using @ref tsk_mutex_destroy. * @sa @ref tsk_mutex_destroy. */ tsk_mutex_handle_t* tsk_mutex_create_2(tsk_bool_t recursive) { MUTEX_T handle = tsk_null; #if TSK_UNDER_WINDOWS handle = CreateMutex(NULL, FALSE, NULL); #else int ret; pthread_mutexattr_t mta; if((ret = pthread_mutexattr_init(&mta))){ TSK_DEBUG_ERROR("pthread_mutexattr_init failed with error code %d", ret); return tsk_null; } if(recursive && (ret = pthread_mutexattr_settype(&mta, TSK_RECURSIVE_MUTEXATTR))){ TSK_DEBUG_ERROR("pthread_mutexattr_settype failed with error code %d", ret); pthread_mutexattr_destroy(&mta); return tsk_null; } /* if we are here: all is ok */ handle = tsk_calloc(1, sizeof(MUTEX_S)); if(pthread_mutex_init((MUTEX_T)handle, &mta)){ TSK_FREE(handle); } pthread_mutexattr_destroy(&mta); #endif if(!handle){ TSK_DEBUG_ERROR("Failed to create new mutex."); } return handle; }
/**@ingroup tsk_buffer_group * Appends data to the buffer. * @param self The buffer to append to. The buffer should be created using @ref tsk_buffer_create or @ref tsk_buffer_create_null. * @param data The data to append to the buffer. * @param size The size of the @a data to append. * @retval Zero if succeed and non-zero error code otherwise. * @sa @ref tsk_buffer_append_2. * * @code * tsk_buffer_t* buffer = tsk_buffer_create_null(); * tsk_buffer_append(buffer, "doubango", tsk_strlen("doubango")); * printf(TSK_BUFFER_TO_STRING(buffer)); * TSK_OBJECT_SAFE_FREE(buffer); * @endcode */ int tsk_buffer_append(tsk_buffer_t* self, const void* data, tsk_size_t size) { if(self && size){ tsk_size_t oldsize = self->size; tsk_size_t newsize = oldsize + size; if(oldsize){ self->data = tsk_realloc(self->data, newsize); } else{ self->data = tsk_calloc(size, sizeof(uint8_t)); } if(self->data){ if(data){ memcpy((void*)(TSK_BUFFER_TO_U8(self) + oldsize), data, size); } self->size = newsize; return 0; } } else{ TSK_DEBUG_ERROR("Invalid parameter"); } return -1; }
/**@ingroup tsk_string_group */ int tsk_sprintf_2(char** str, const char* format, va_list* ap) { int len = 0; va_list ap2; /* free previous value */ if(*str){ tsk_free((void**)str); } /* needed for 64bit platforms where vsnprintf will change the va_list */ tsk_va_copy(ap2, *ap); /* compute destination len for windows mobile */ #if defined(_WIN32_WCE) { int n; len = (tsk_strlen(format)*2); *str = (char*)tsk_calloc(1, len+1); for(;;){ if( (n = vsnprintf(*str, len, format, *ap)) >= 0 && (n<len) ){ len = n; goto done; } else{ len += 10; *str = tsk_realloc(*str, len+1); } } done: (*str)[len] = '\0'; } #else len = vsnprintf(0, 0, format, *ap); *str = (char*)tsk_calloc(1, len+1); vsnprintf(*str, len #if !defined(_MSC_VER) || defined(__GNUC__) +1 #endif , format, ap2); #endif va_end(ap2); return len; }
tmedia_param_t* tmedia_param_create(tmedia_param_access_type_t access_type, tmedia_type_t media_type, tmedia_param_plugin_type_t plugin_type, tmedia_param_value_type_t value_type, const char* key, void* value) { tmedia_param_t* param; if(!key ||!value){ TSK_DEBUG_ERROR("Invalid parameter"); return tsk_null; } if((param = tsk_object_new(tmedia_param_def_t))){ param->access_type = access_type; param->media_type = media_type; param->plugin_type = plugin_type; param->value_type = value_type; param->key = tsk_strdup(key); switch(value_type){ case tmedia_pvt_int32: if(param->value = tsk_calloc(1, sizeof(int32_t))){ memcpy(param->value, value, sizeof(int32_t)); //*((int32_t*)param->value) = *((int32_t*)value); } break; case tmedia_pvt_pobject: param->value = tsk_object_ref(value); break; case tmedia_pvt_pchar: param->value = tsk_strdup(value); break; case tmedia_pvt_int64: if(param->value = tsk_calloc(1, sizeof(int64_t))){ memcpy(param->value, value, sizeof(int64_t)); //*((int64_t*)param->value) = *((int64_t*)value); } break; } } else{ TSK_DEBUG_ERROR("Failed to create media parameter"); } return param; }
static int create_wavehdr(tdav_producer_waveapi_t* producer, tsk_size_t index) { if(!producer || index >= sizeof(producer->hWaveHeaders)/sizeof(LPWAVEHDR)){ TSK_DEBUG_ERROR("Invalid parameter"); return -1; } if(producer->hWaveHeaders[index]){ free_wavehdr(producer, index); } producer->hWaveHeaders[index] = tsk_calloc(1, sizeof(WAVEHDR)); producer->hWaveHeaders[index]->lpData = tsk_calloc(1, producer->bytes_per_notif); producer->hWaveHeaders[index]->dwBufferLength = producer->bytes_per_notif; producer->hWaveHeaders[index]->dwFlags = WHDR_BEGINLOOP | WHDR_ENDLOOP; producer->hWaveHeaders[index]->dwLoops = 0x01; producer->hWaveHeaders[index]->dwUser = index; return 0; }
tsk_semaphore_handle_t* tsk_semaphore_create_2(int initial_val) { SEMAPHORE_T handle = tsk_null; #if TSK_UNDER_WINDOWS # if TSK_UNDER_WINDOWS_RT handle = CreateSemaphoreEx(NULL, initial_val, 0x7FFFFFFF, NULL, 0x00000000, SEMAPHORE_ALL_ACCESS); # else handle = CreateSemaphore(NULL, initial_val, 0x7FFFFFFF, NULL); # endif #else handle = tsk_calloc(1, sizeof(SEMAPHORE_S)); #if TSK_USE_NAMED_SEM named_sem_t * nsem = (named_sem_t*)handle; snprintf(nsem->name, (sizeof(nsem->name)/sizeof(nsem->name[0])) - 1, "/sem/%llu/%d.", tsk_time_epoch(), rand() ^ rand()); if ((nsem->sem = sem_open(nsem->name, O_CREAT /*| O_EXCL*/, S_IRUSR | S_IWUSR, initial_val)) == SEM_FAILED) { #else if (sem_init((SEMAPHORE_T)handle, 0, initial_val)) { #endif TSK_FREE(handle); TSK_DEBUG_ERROR("Failed to initialize the new semaphore (errno=%d).", errno); } #endif if (!handle) { TSK_DEBUG_ERROR("Failed to create new semaphore"); } return handle; } /**@ingroup tsk_semaphore_group * Increments a semaphore. * @param handle The semaphore to increment. * @retval Zero if succeed and otherwise the function returns -1 and sets errno to indicate the error. * @sa @ref tsk_semaphore_decrement. */ int tsk_semaphore_increment(tsk_semaphore_handle_t* handle) { int ret = EINVAL; if (handle) { #if TSK_UNDER_WINDOWS if((ret = ReleaseSemaphore((SEMAPHORE_T)handle, 1L, NULL) ? 0 : -1)) #else if((ret = sem_post((SEMAPHORE_T)GET_SEM(handle)))) #endif { TSK_DEBUG_ERROR("sem_post function failed: %d", ret); } } return ret; }
/*********** * create a new jitterbuffer * return NULL if malloc doesn't work * else return jb with default_settings. */ jitterbuffer *jb_new() { jitterbuffer *jb; jb_dbg("N"); jb = tsk_calloc(1, sizeof(jitterbuffer)); if (!jb) { jb_err("cannot allocate jitterbuffer\n"); return NULL; } set_default_settings(jb); reset(jb); return jb; }
/** Duplicates the first @a n chars of @a s1. * @param s1 The string to duplicate. * @param n The number of characters to copy to the new string. * @retval null A copy of @a s1. **/ char* tsk_strndup(const char *s1, tsk_size_t n) { char *ret = tsk_null; if(s1 && n){ tsk_size_t len = tsk_strlen(s1); tsk_size_t nret = (n > len) ? (len) : (n); if((ret = tsk_calloc((nret+1), sizeof(uint8_t)))){ memcpy(ret, s1, nret); } } return ret; }
//================================================================================================= // Buffer object definition // static tsk_object_t* tsk_buffer_ctor(tsk_object_t * self, va_list * app) { tsk_buffer_t *buffer = (tsk_buffer_t *)self; const void *data = va_arg(*app, const void *); tsk_size_t size = va_arg(*app, tsk_size_t); if (size) { buffer->data = tsk_calloc((size+1), sizeof(uint8_t)); if (data) { memcpy(buffer->data, data, size); } buffer->size = size; } return self; }
tsk_plugin_t* tsk_plugin_create(const char* path) { tsk_plugin_t* plugin; symbol_get_def_count funcptr_get_def_count; tsk_plugin_handle_t* handle; #if TSK_UNDER_WINDOWS # if TSK_UNDER_WINDOWS_RT wchar_t* szPath = (wchar_t*)tsk_calloc(tsk_strlen(path) + 1, sizeof(wchar_t)); static const wchar_t* szFormat = L"%hs"; swprintf(szPath, tsk_strlen(path) * sizeof(wchar_t), szFormat, path); handle = LoadPackagedLibrary(szPath, 0x00000000); TSK_FREE(szPath); # else /* Windows desktop */ UINT currErrMode = SetErrorMode(SEM_FAILCRITICALERRORS); // save current ErrorMode. GetErrorMode() not supported on XP. SetErrorMode(currErrMode | SEM_FAILCRITICALERRORS); handle = LoadLibraryA(path); SetErrorMode(currErrMode); // restore ErrorMode # endif #else handle = dlopen(path, RTLD_NOW); #endif if(!handle){ TSK_DEBUG_ERROR("Failed to load library with path=%s", path); return tsk_null; } if(!(funcptr_get_def_count = (symbol_get_def_count)_tsk_plugin_handle_get_symbol(handle, TSK_PLUGIN_FUNC_NAME_DEF_COUNT))){ TSK_DEBUG_ERROR("Cannot find function with name=%s", TSK_PLUGIN_FUNC_NAME_DEF_COUNT); _tsk_plugin_handle_destroy(&handle); return tsk_null; } if(!(plugin = (tsk_plugin_t*)tsk_object_new(&tsk_plugin_def_s))){ TSK_DEBUG_ERROR("Failed to create plugin object"); _tsk_plugin_handle_destroy(&handle); return tsk_null; } plugin->handle = handle; plugin->def_count = funcptr_get_def_count(); plugin->path = tsk_strdup(path); TSK_DEBUG_INFO("Plugin with path=[%s] created with [%d] defs", plugin->path, plugin->def_count); return plugin; }
/*== Add new socket ==*/ static int addSocket(tnet_fd_t fd, tnet_socket_type_t type, tnet_transport_t *transport, tsk_bool_t take_ownership, tsk_bool_t is_client, tnet_tls_socket_handle_t* tlsHandle) { transport_context_t *context; if (TNET_SOCKET_TYPE_IS_TLS(type) || TNET_SOCKET_TYPE_IS_WSS(type)) { #if !HAVE_OPENSSL TSK_DEBUG_ERROR("Cannot create TLS socket: OpenSSL missing"); return -2; #endif } if ((context = transport ? transport->context : tsk_null)) { transport_socket_xt *sock = tsk_calloc(1, sizeof(transport_socket_xt)); sock->fd = fd; sock->type = type; sock->owner = take_ownership ? 1 : 0; if ((TNET_SOCKET_TYPE_IS_TLS(sock->type) || TNET_SOCKET_TYPE_IS_WSS(sock->type)) && transport->tls.enabled) { if (tlsHandle) { sock->tlshandle = tsk_object_ref(tlsHandle); } else { #if HAVE_OPENSSL sock->tlshandle = tnet_tls_socket_create(sock->fd, is_client ? transport->tls.ctx_client : transport->tls.ctx_server); #endif } } tsk_safeobj_lock(context); context->events[context->count] = WSACreateEvent(); context->sockets[context->count] = sock; context->count++; TSK_DEBUG_INFO("Transport[%s] sockets count = %u", transport->description, context->count); tsk_safeobj_unlock(context); return 0; } else { TSK_DEBUG_ERROR("Context is Null."); return -1; } }
// // [[DHCPv6 OPTION]] object definition // static tsk_object_t* tnet_dhcp6_option_ctor(tsk_object_t * self, va_list * app) { tnet_dhcp6_option_t *option = self; if(option){ tnet_dhcp6_option_code_t code = va_arg(*app, tnet_dhcp6_option_code_t); const void* payload = va_arg(*app, const void*); tsk_size_t payload_size = va_arg(*app, tsk_size_t); option->code = code; if(payload && payload_size){ if((option->data = (tnet_dhcp6_option_data_t*)tsk_calloc(payload_size, sizeof(uint8_t)))){ memcpy(option->data, payload, payload_size); option->len = (uint16_t)payload_size; } } } return self; }
/*== Add new socket ==*/ int addSocket(tnet_fd_t fd, tnet_socket_type_t type, tnet_transport_t *transport, tsk_bool_t take_ownership, tsk_bool_t is_client, tnet_tls_socket_handle_t* tlsHandle) { transport_context_t *context = transport?transport->context:0; if(context) { transport_socket_xt *sock = tsk_calloc(1, sizeof(transport_socket_xt)); sock->fd = fd; sock->type = type; sock->owner = take_ownership; if((TNET_SOCKET_TYPE_IS_TLS(sock->type) || TNET_SOCKET_TYPE_IS_WSS(sock->type)) && transport->tls.enabled) { if(tlsHandle) { sock->tlshandle = tsk_object_ref(tlsHandle); } else { #if HAVE_OPENSSL sock->tlshandle = tnet_tls_socket_create(sock->fd, is_client ? transport->tls.ctx_client : transport->tls.ctx_server); #endif } } tsk_safeobj_lock(context); context->ufds[context->count].fd = fd; context->ufds[context->count].events = (fd == context->pipeR) ? TNET_POLLIN : (TNET_POLLIN | TNET_POLLNVAL | TNET_POLLERR); if(TNET_SOCKET_TYPE_IS_STREAM(sock->type) && fd != context->pipeR) { context->ufds[context->count].events |= TNET_POLLOUT; // emulate WinSock2 FD_CONNECT event } context->ufds[context->count].revents = 0; context->sockets[context->count] = sock; context->count++; tsk_safeobj_unlock(context); TSK_DEBUG_INFO("Socket added[%s]: fd=%d, tail.count=%d", transport->description, fd, (int)context->count); return 0; } else { TSK_DEBUG_ERROR("Context is Null."); return -1; } }
/**@ingroup tsk_buffer_group * Reallocates the buffer. * @param self The buffer to realloc. * @param size The new size. * @retval Zero if succeed and non-zero error code otherwise. */ int tsk_buffer_realloc(tsk_buffer_t* self, tsk_size_t size) { if(self) { if(size == 0){ return tsk_buffer_cleanup(self); } if(self->size == 0){ // first time? self->data = tsk_calloc(size, sizeof(uint8_t)); } else if(self->size != size){ // only realloc if different sizes self->data = tsk_realloc(self->data, size); } self->size = size; return 0; } return -1; }
int tdav_codec_speex_open(tmedia_codec_t* self) { static int quality = SPEEX_DEFAULT_QUALITY; tdav_codec_speex_t* speex = (tdav_codec_speex_t*)self; switch(speex->type){ case tdav_codec_speex_type_nb: speex->encoder.state = speex_encoder_init(&speex_nb_mode); speex->decoder.state = speex_decoder_init(&speex_nb_mode); break; case tdav_codec_speex_type_wb: speex->encoder.state = speex_encoder_init(&speex_wb_mode); speex->decoder.state = speex_decoder_init(&speex_wb_mode); break; case tdav_codec_speex_type_uwb: speex->encoder.state = speex_encoder_init(&speex_uwb_mode); speex->decoder.state = speex_decoder_init(&speex_uwb_mode); break; default: TSK_DEBUG_ERROR("Not implemented"); return -2; } speex_decoder_ctl(speex->decoder.state, SPEEX_GET_FRAME_SIZE, &speex->decoder.size); speex->decoder.size *= sizeof(spx_int16_t); if(!(speex->decoder.buffer = tsk_calloc(speex->decoder.size, 1))){ speex->decoder.size = speex->decoder.size = 0; TSK_DEBUG_ERROR("Failed to allocate new buffer"); return -3; } speex_encoder_ctl(speex->encoder.state, SPEEX_SET_QUALITY, &quality); speex_encoder_ctl(speex->encoder.state, SPEEX_GET_FRAME_SIZE, &speex->encoder.size); speex_bits_init(&speex->encoder.bits); speex_bits_init(&speex->decoder.bits); speex_bits_reset(&speex->encoder.bits); speex_bits_reset(&speex->decoder.bits); return 0; }
static int _v4l2_init_userp(tdav_producer_video_v4l2_t* p_self, unsigned int buffer_size, const char* device_name) { struct v4l2_requestbuffers req; V4L2_CLEAR(req); req.count = 4; req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; req.memory = V4L2_MEMORY_USERPTR; if (-1 == _v4l2_xioctl(p_self->fd, VIDIOC_REQBUFS, &req)) { if (EINVAL == errno) { V4L2_DEBUG_ERROR("%s does not support user pointer i/o", device_name); return -1; } else { V4L2_DEBUG_ERROR("xioctl(%s, VIDIOC_REQBUFS) failed: %s error %d", device_name, strerror(errno), errno); return -1; } } if (!(p_self->p_buffers = tsk_calloc(4, sizeof(*p_self->p_buffers)))) { V4L2_DEBUG_ERROR("Out of memory"); return -1; } for (p_self->n_buffers = 0; p_self->n_buffers < 4; ++p_self->n_buffers) { p_self->p_buffers[p_self->n_buffers].n_length = buffer_size; p_self->p_buffers[p_self->n_buffers].p_start = tsk_malloc(buffer_size); if (!p_self->p_buffers[p_self->n_buffers].p_start) { V4L2_DEBUG_ERROR("Out of memory"); return -1; } } return 0; }
/**@ingroup tsk_object_group * Creates new object. The object MUST be declared using @ref TSK_DECLARE_OBJECT macro. * @param objdef The object meta-data (definition). For more infomation see @ref tsk_object_def_t. * @param ap Variable argument list to pass to the constructor(defined in the meta-data). * @retval @ref tsk_object_t object with a reference counter equal to 1. * @sa @ref tsk_object_new. */ tsk_object_t* tsk_object_new_2(const tsk_object_def_t *objdef, va_list* ap) { tsk_object_t *newobj = tsk_calloc(1, objdef->size); if(newobj){ (*(const tsk_object_def_t **) newobj) = objdef; TSK_OBJECT_HEADER(newobj)->refCount = 1; if(objdef->constructor){ newobj = objdef->constructor(newobj, ap); #if TSK_DEBUG_OBJECTS TSK_DEBUG_INFO("N∞ objects:%d", ++tsk_objects_count); #endif } else{ TSK_DEBUG_WARN("No constructor found."); } } else{ TSK_DEBUG_ERROR("Failed to create new tsk_object."); } return newobj; }
/* ============ Internal functions ================= */ int tdav_codec_mp4ves_open_encoder(tdav_codec_mp4ves_t* self) { int ret, size; int32_t max_bw_kpbs; if(!self->encoder.codec && !(self->encoder.codec = avcodec_find_encoder(CODEC_ID_MPEG4))){ TSK_DEBUG_ERROR("Failed to find mp4v encoder"); return -1; } if(self->encoder.context){ TSK_DEBUG_ERROR("Encoder already opened"); return -1; } self->encoder.context = avcodec_alloc_context(); avcodec_get_context_defaults(self->encoder.context); self->encoder.context->pix_fmt = PIX_FMT_YUV420P; self->encoder.context->time_base.num = 1; self->encoder.context->time_base.den = TMEDIA_CODEC_VIDEO(self)->in.fps; self->encoder.context->width = (self->encoder.rotation == 90 || self->encoder.rotation == 270) ? TMEDIA_CODEC_VIDEO(self)->out.height : TMEDIA_CODEC_VIDEO(self)->out.width; self->encoder.context->height = (self->encoder.rotation == 90 || self->encoder.rotation == 270) ? TMEDIA_CODEC_VIDEO(self)->out.width : TMEDIA_CODEC_VIDEO(self)->out.height; self->encoder.context->mb_decision = FF_MB_DECISION_RD; self->encoder.context->noise_reduction = 250; self->encoder.context->flags |= CODEC_FLAG_QSCALE; self->encoder.context->global_quality = FF_QP2LAMBDA * self->encoder.quality; max_bw_kpbs = TSK_CLAMP( 0, tmedia_get_video_bandwidth_kbps_2(TMEDIA_CODEC_VIDEO(self)->out.width, TMEDIA_CODEC_VIDEO(self)->out.height, TMEDIA_CODEC_VIDEO(self)->out.fps), self->encoder.max_bw_kpbs ); self->encoder.context->bit_rate = (max_bw_kpbs * 1024);// bps self->encoder.context->rtp_payload_size = MP4V_RTP_PAYLOAD_SIZE; self->encoder.context->opaque = tsk_null; self->encoder.context->profile = self->profile>>4; self->encoder.context->level = self->profile & 0x0F; self->encoder.context->gop_size = (TMEDIA_CODEC_VIDEO(self)->in.fps * MP4V_GOP_SIZE_IN_SECONDS); self->encoder.context->max_b_frames = 0; self->encoder.context->b_frame_strategy = 1; self->encoder.context->flags |= CODEC_FLAG_AC_PRED; // Picture (YUV 420) if(!(self->encoder.picture = avcodec_alloc_frame())){ TSK_DEBUG_ERROR("Failed to create MP4V-ES encoder picture"); return -2; } avcodec_get_frame_defaults(self->encoder.picture); size = avpicture_get_size(PIX_FMT_YUV420P, self->encoder.context->width, self->encoder.context->height); if(!(self->encoder.buffer = tsk_calloc(size, sizeof(uint8_t)))){ TSK_DEBUG_ERROR("Failed to allocate MP4V-ES encoder buffer"); return -2; } // Open encoder if((ret = avcodec_open(self->encoder.context, self->encoder.codec)) < 0){ TSK_DEBUG_ERROR("Failed to open MP4V-ES encoder"); return ret; } TSK_DEBUG_INFO("[MP4V-ES] bitrate=%d bps", self->encoder.context->bit_rate); return ret; }
void __CFReadStreamClientCallBack(CFReadStreamRef stream, CFStreamEventType eventType, void *clientCallBackInfo) { // Extract the context tnet_transport_t *transport = (tnet_transport_t *) clientCallBackInfo; transport_context_t *context = transport->context; /* lock context */ tsk_safeobj_lock(context); // Extract the native socket CFDataRef data = CFReadStreamCopyProperty(stream, kCFStreamPropertySocketNativeHandle); CFSocketNativeHandle fd; CFDataGetBytes(data, CFRangeMake(0, sizeof(CFSocketNativeHandle)), (UInt8*) &fd); CFRelease(data); transport_socket_t *sock = (transport_socket_t *) getSocket(context, fd); switch(eventType) { case kCFStreamEventOpenCompleted: { TSK_DEBUG_INFO("__CFReadStreamClientCallBack --> kCFStreamEventOpenCompleted"); break; } case kCFStreamEventHasBytesAvailable: { tsk_size_t len = 0; void *buffer = 0; tnet_transport_event_t* e; // Allocate a standard buffer len = TNET_BUFFER_SIZE; if (!(buffer = tsk_calloc(len, sizeof(uint8_t)))) { TSK_DEBUG_ERROR("TSK_CALLOC FAILED."); break; } // Process to read data CFIndex index = CFReadStreamRead(stream, buffer, TNET_BUFFER_SIZE); len = index; TSK_DEBUG_INFO("__CFReadStreamClientCallBack --> %u bytes read", len); e = tnet_transport_event_create(event_data, transport->callback_data, sock->fd); e->data = buffer; e->size = len; TSK_RUNNABLE_ENQUEUE_OBJECT(TSK_RUNNABLE(transport), e); break; } case kCFStreamEventEndEncountered: case kCFStreamEventErrorOccurred: { // Get the error code CFErrorRef error = CFReadStreamCopyError(stream); CFIndex index = CFErrorGetCode(error); CFRelease(error); TSK_DEBUG_INFO("__CFReadStreamClientCallBack --> Error %lu", index); TSK_RUNNABLE_ENQUEUE(transport, event_error, transport->callback_data, sock->fd); removeSocket(sock, context); break; } default: { // Not Implemented assert(42 == 0); break; } } /* unlock context */ tsk_safeobj_unlock(context); }
void __CFSocketCallBack(CFSocketRef s, CFSocketCallBackType callbackType, CFDataRef address, const void *data, void *info) { // Extract the context tnet_transport_t *transport = (tnet_transport_t *) info; transport_context_t *context = transport->context; // Extract the native socket int fd = CFSocketGetNative(s); transport_socket_t *sock = (transport_socket_t *) getSocket(context, fd); /* lock context */ tsk_safeobj_lock(context); switch (callbackType) { case kCFSocketReadCallBack: { int ret; tsk_size_t len = 0; void* buffer = 0; tnet_transport_event_t* e; if (tnet_ioctlt(sock->fd, FIONREAD, &len) < 0) { TNET_PRINT_LAST_ERROR("IOCTLT FAILED."); break; } if (!len) { TSK_DEBUG_WARN("IOCTLT returned zero."); TSK_RUNNABLE_ENQUEUE(transport, event_closed, transport->callback_data, sock->fd); removeSocket(sock, context); break; } if (!(buffer = tsk_calloc(len, sizeof(uint8_t)))) { TSK_DEBUG_ERROR("TSK_CALLOC FAILED."); break; } if ((ret = tnet_sockfd_recv(sock->fd, buffer, len, 0)) < 0) { TSK_FREE(buffer); removeSocket(sock, context); TNET_PRINT_LAST_ERROR("recv have failed."); break; } else if ((len != (tsk_size_t)ret) && len) { // useless test ? len = (tsk_size_t)ret; // buffer = tsk_realloc(buffer, len); } TSK_DEBUG_INFO("__CFSocketCallBack -> %u bytes read", len); e = tnet_transport_event_create(event_data, transport->callback_data, sock->fd); e->data = buffer; e->size = len; TSK_RUNNABLE_ENQUEUE_OBJECT(TSK_RUNNABLE(transport), e); break; } case kCFSocketAcceptCallBack: case kCFSocketConnectCallBack: case kCFSocketDataCallBack: case kCFSocketWriteCallBack: default: { // Not Implemented assert(42 == 0); break; } } /* unlock context */ tsk_safeobj_unlock(context); }
static int tdav_speex_denoise_open(tmedia_denoise_t* self, uint32_t frame_size, uint32_t sampling_rate) { tdav_speex_denoise_t *denoiser = (tdav_speex_denoise_t *)self; float f; int i; if(!denoiser->echo_state && TMEDIA_DENOISE(denoiser)->echo_supp_enabled){ TSK_DEBUG_INFO("Init Aec frame_size[%u] filter_length[%u] SampleRate[%u]", (uint32_t)(frame_size* sizeof(spx_int16_t)),TMEDIA_DENOISE(denoiser)->echo_tail*frame_size,sampling_rate); if((denoiser->echo_state = speex_echo_state_init(frame_size, TMEDIA_DENOISE(denoiser)->echo_tail))){ speex_echo_ctl(denoiser->echo_state, SPEEX_ECHO_SET_SAMPLING_RATE, &sampling_rate); } } if(!denoiser->preprocess_state_record && !denoiser->preprocess_state_playback){ denoiser->frame_size = frame_size; if((denoiser->preprocess_state_record = speex_preprocess_state_init(frame_size, sampling_rate)) && (denoiser->preprocess_state_playback = speex_preprocess_state_init(frame_size, sampling_rate)) ){ // Echo suppression if(denoiser->echo_state){ int echo_supp , echo_supp_active = 0; speex_preprocess_ctl(denoiser->preprocess_state_record, SPEEX_PREPROCESS_SET_ECHO_STATE, denoiser->echo_state); TSK_FREE(denoiser->echo_output_frame); denoiser->echo_output_frame = tsk_calloc(denoiser->frame_size, sizeof(spx_int16_t)); speex_preprocess_ctl(denoiser->preprocess_state_record, SPEEX_PREPROCESS_GET_ECHO_SUPPRESS , &echo_supp ); speex_preprocess_ctl(denoiser->preprocess_state_record, SPEEX_PREPROCESS_GET_ECHO_SUPPRESS_ACTIVE , &echo_supp_active ); TSK_DEBUG_INFO("AEC echo_supp level [%d] echo_supp_active level[%d] ", echo_supp , echo_supp_active); echo_supp = -60 ; echo_supp_active = -60 ; speex_preprocess_ctl(denoiser->preprocess_state_record, SPEEX_PREPROCESS_SET_ECHO_SUPPRESS , &echo_supp ); speex_preprocess_ctl(denoiser->preprocess_state_record, SPEEX_PREPROCESS_SET_ECHO_SUPPRESS_ACTIVE , &echo_supp_active ); // TRACES speex_preprocess_ctl(denoiser->preprocess_state_record, SPEEX_PREPROCESS_GET_ECHO_SUPPRESS , &echo_supp ); speex_preprocess_ctl(denoiser->preprocess_state_record, SPEEX_PREPROCESS_GET_ECHO_SUPPRESS_ACTIVE , &echo_supp_active ); TSK_DEBUG_INFO("New aec echo_supp level [%d] echo_supp_active level[%d] ", echo_supp , echo_supp_active); } // Noise suppression if(TMEDIA_DENOISE(denoiser)->noise_supp_enabled){ TSK_DEBUG_INFO("SpeexDSP: Noise supp enabled"); i = 1; speex_preprocess_ctl(denoiser->preprocess_state_record, SPEEX_PREPROCESS_SET_DENOISE, &i); speex_preprocess_ctl(denoiser->preprocess_state_playback, SPEEX_PREPROCESS_SET_DENOISE, &i); i = TMEDIA_DENOISE(denoiser)->noise_supp_level; speex_preprocess_ctl(denoiser->preprocess_state_record, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &i); speex_preprocess_ctl(denoiser->preprocess_state_playback, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &i); } else{ i = 0; speex_preprocess_ctl(denoiser->preprocess_state_record, SPEEX_PREPROCESS_SET_DENOISE, &i); speex_preprocess_ctl(denoiser->preprocess_state_playback, SPEEX_PREPROCESS_SET_DENOISE, &i); } // Automatic gain control if(TMEDIA_DENOISE(denoiser)->agc_enabled){ float agc_level = TMEDIA_DENOISE(denoiser)->agc_level; TSK_DEBUG_INFO("SpeexDSP: AGC enabled"); i = 1; speex_preprocess_ctl(denoiser->preprocess_state_record, SPEEX_PREPROCESS_SET_AGC, &i); speex_preprocess_ctl(denoiser->preprocess_state_record, SPEEX_PREPROCESS_SET_AGC_LEVEL, &agc_level); } else{ i = 0, f = 8000.0f; speex_preprocess_ctl(denoiser->preprocess_state_record, SPEEX_PREPROCESS_SET_AGC, &i); speex_preprocess_ctl(denoiser->preprocess_state_record, SPEEX_PREPROCESS_SET_AGC_LEVEL, &f); } // Voice Activity detection i = TMEDIA_DENOISE(denoiser)->vad_enabled ? 1 : 0; speex_preprocess_ctl(denoiser->preprocess_state_record, SPEEX_PREPROCESS_SET_VAD, &i); return 0; } else{ TSK_DEBUG_ERROR("Failed to create Speex preprocessor state"); return -2; } } return 0; }