code
stringlengths 1
1.05M
| repo_name
stringlengths 6
83
| path
stringlengths 3
242
| language
stringclasses 222
values | license
stringclasses 20
values | size
int64 1
1.05M
|
|---|---|---|---|---|---|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "uvoice_os.h"
#include "uvoice_common.h"
int32_t uvoice_ringbuff_reset(uvoice_ringbuff_t *rb)
{
if (!rb) {
M_LOGE("rb null !\n");
return -1;
}
rb->rd_ptr = rb->buffer;
rb->wr_ptr = rb->buffer;
rb->dirty_size = 0;
rb->free_size = rb->buffer_end - rb->buffer;
return 0;
}
int32_t uvoice_ringbuff_init(uvoice_ringbuff_t *rb,
uint8_t *buffer, int32_t size)
{
if (!rb) {
M_LOGE("rb null !\n");
return -1;
}
if (!buffer) {
M_LOGE("buffer null !\n");
return -1;
}
if (size <= 4) {
M_LOGE("size %d invalid !\n", size);
return -1;
}
rb->buffer = buffer;
rb->buffer_end = rb->buffer + size;
uvoice_ringbuff_reset(rb);
return 0;
}
int32_t uvoice_ringbuff_freesize(uvoice_ringbuff_t *rb)
{
if (!rb) {
M_LOGE("rb null !\n");
return -1;
}
return rb->free_size;
}
int32_t uvoice_ringbuff_dirtysize(uvoice_ringbuff_t *rb)
{
if (!rb) {
M_LOGE("rb null !\n");
return -1;
}
return rb->dirty_size;
}
int32_t uvoice_ringbuff_fill(uvoice_ringbuff_t *rb,
uint8_t *buffer, int32_t size)
{
if (!rb) {
M_LOGE("rb null !\n");
return -1;
}
if (size > rb->free_size || size <= 0) {
M_LOGE("size %d invalid !\n", size);
return -1;
}
if ((rb->buffer_end - rb->wr_ptr >= size &&
rb->wr_ptr >= rb->rd_ptr) ||
rb->wr_ptr < rb->rd_ptr) {
memcpy(rb->wr_ptr, buffer, size);
rb->wr_ptr += size;
rb->dirty_size += size;
rb->free_size -= size;
if (rb->wr_ptr >= rb->buffer_end)
rb->wr_ptr = rb->buffer;
} else if (rb->buffer_end - rb->wr_ptr < size &&
rb->wr_ptr >= rb->rd_ptr) {
int temp = rb->buffer_end - rb->wr_ptr;
memcpy(rb->wr_ptr, buffer, temp);
rb->wr_ptr = rb->buffer;
memcpy(rb->wr_ptr, buffer + temp, size - temp);
rb->dirty_size += size;
rb->free_size -= size;
rb->wr_ptr += size - temp;
} else {
M_LOGE("error ! buffer %08x buffer_end %08x rd_ptr %08x wr_ptr %08x dirty %d free %d\n",
(unsigned int)rb->buffer,
(unsigned int)rb->buffer_end,
(unsigned int)rb->rd_ptr,
(unsigned int)rb->wr_ptr, rb->dirty_size, rb->free_size);
return -1;
}
return size;
}
int32_t uvoice_ringbuff_read(uvoice_ringbuff_t *rb,
uint8_t *buffer, int32_t size)
{
if (!rb) {
M_LOGE("rb null !\n");
return -1;
}
if (size > rb->dirty_size || size <= 0) {
M_LOGE("size %d invalid !\n", size);
return -1;
}
if (rb->rd_ptr < rb->wr_ptr &&
rb->wr_ptr - rb->rd_ptr >= size) {
memcpy(buffer, rb->rd_ptr, size);
rb->dirty_size -= size;
rb->free_size += size;
rb->rd_ptr += size;
} else if (rb->rd_ptr >= rb->wr_ptr) {
if (rb->buffer_end - rb->rd_ptr >= size) {
memcpy(buffer, rb->rd_ptr, size);
rb->dirty_size -= size;
rb->free_size += size;
rb->rd_ptr += size;
if (rb->rd_ptr >= rb->buffer_end)
rb->rd_ptr = rb->buffer;
} else {
int temp = rb->buffer_end - rb->rd_ptr;
memcpy(buffer, rb->rd_ptr, temp);
rb->rd_ptr = rb->buffer;
memcpy(buffer + temp, rb->rd_ptr, size - temp);
rb->dirty_size -= size;
rb->free_size += size;
rb->rd_ptr += size - temp;
}
} else {
M_LOGE("error ! buffer %08x buffer_end %08x rd_ptr %08x wr_ptr %08x dirty %d free %d\n",
(unsigned int)rb->buffer,
(unsigned int)rb->buffer_end,
(unsigned int)rb->rd_ptr,
(unsigned int)rb->wr_ptr, rb->dirty_size, rb->free_size);
return -1;
}
return size;
}
int32_t uvoice_ringbuff_drop(uvoice_ringbuff_t *rb, int32_t size)
{
if (!rb) {
M_LOGE("rb null !\n");
return -1;
}
if (size > rb->dirty_size || size <= 0) {
M_LOGE("size %d invalid !\n", size);
return -1;
}
if (rb->wr_ptr - rb->rd_ptr >= size) {
rb->dirty_size -= size;
rb->free_size += size;
rb->rd_ptr += size;
if (rb->rd_ptr >= rb->buffer_end)
rb->rd_ptr = rb->buffer;
} else if (rb->rd_ptr >= rb->wr_ptr) {
if (rb->buffer_end - rb->rd_ptr >= size) {
rb->dirty_size -= size;
rb->free_size += size;
rb->rd_ptr += size;
if (rb->rd_ptr >= rb->buffer_end)
rb->rd_ptr = rb->buffer;
} else {
rb->rd_ptr = rb->buffer +
(size - (rb->buffer_end - rb->rd_ptr));
rb->dirty_size -= size;
rb->free_size += size;
}
} else {
M_LOGE("error ! buffer %08x buffer_end %08x rd_ptr %08x wr_ptr %08x dirty %d free %d\n",
(unsigned int)rb->buffer,
(unsigned int)rb->buffer_end,
(unsigned int)rb->rd_ptr,
(unsigned int)rb->wr_ptr, rb->dirty_size, rb->free_size);
return -1;
}
return 0;
}
int32_t uvoice_ringbuff_back(uvoice_ringbuff_t *rb, int32_t size)
{
if (!rb) {
M_LOGE("rb null !\n");
return -1;
}
if (size > rb->free_size || size <= 0) {
M_LOGE("size %d invaid !\n", size);
return -1;
}
if (rb->wr_ptr >= rb->rd_ptr) {
if (rb->rd_ptr - rb->buffer >= size) {
rb->rd_ptr -= size;
rb->free_size -= size;
rb->dirty_size += size;
} else {
rb->rd_ptr = rb->buffer_end -
(size - (rb->rd_ptr - rb->buffer));
rb->free_size -= size;
rb->dirty_size += size;
}
} else {
if (rb->rd_ptr - rb->wr_ptr >= size) {
rb->rd_ptr -= size;
rb->free_size -= size;
rb->dirty_size += size;
} else {
M_LOGE("error ! buffer %08x buffer_end %08x rd_ptr %08x wr_ptr %08x dirty %d free %d\n",
(unsigned int)rb->buffer,
(unsigned int)rb->buffer_end,
(unsigned int)rb->rd_ptr,
(unsigned int)rb->wr_ptr, rb->dirty_size, rb->free_size);
return -1;
}
}
return 0;
}
|
YifuLiu/AliOS-Things
|
components/uvoice/common/ringbuffer.c
|
C
|
apache-2.0
| 5,421
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <signal.h>
static char dec2hex(char c)
{
if (0 <= c && c <= 9) {
return c + '0';
} else {
if( 10 <= c && c <= 15 ) {
return c + 'A' - 10;
} else {
return -1;
}
}
}
void uvoice_urlencode(char *url)
{
int i = 0;
int len = strlen( url );
int res_len = 0;
char *res = malloc(len * 3 + 1);
memset(res, 0, len * 3 + 1);
for (i = 0; i < len; ++i) {
char c = url[i];
if (('0' <= c && c <= '9') ||
('a' <= c && c <= 'z') ||
('A' <= c && c <= 'Z') ||
c == '/' || c == '.') {
res[res_len++] = c;
} else {
int j = c;
if (j < 0)
j += 256;
int i1, i0;
i1 = j / 16;
i0 = j - i1 * 16;
res[res_len++] = '%';
res[res_len++] = dec2hex((char)i1);
res[res_len++] = dec2hex((char)i0);
}
}
res[res_len] = '\0';
memcpy(url, res, res_len + 1);
free(res);
}
|
YifuLiu/AliOS-Things
|
components/uvoice/common/urlencode.c
|
C
|
apache-2.0
| 1,155
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <signal.h>
#include <stdlib.h>
#include "uvoice_os.h"
#include "uvoice_ws.h"
#include "nopoll.h"
#include "lwip/netif.h"
#ifdef UVOICE_ON_BK7251
#define NOPOLL_CLIENT_TASK_STACK_SIZE 8192
#else
#define NOPOLL_CLIENT_TASK_STACK_SIZE 4096
#endif
#define NOPOLL_CLIENT_TASK_PRIORITY UVOICE_TASK_PRI_LOWER
#define WAIT_MS_MAX 200
#define WAIT_MS_MIN 20
#define PING_INTERVAL_COUNT 100 /* max: WAIT_MS_MAX * PING_INTERVAL_COUNT < 45 seconds */
#define NOPOLL_PING_PERIOD_SEC 20
#define NOPOLL_PONG_TIMEOUT_MSEC 10000 /* keep NOPOLL_PONG_TIMEOUT_MSEC < NOPOLL_PING_PERIOD_SEC */
#define MERGE_TEXT_FRAME_SUPPORT 1
enum {
NOPOLL_CMD_EXIT,
NOPOLL_CMD_OPEN,
NOPOLL_CMD_SEND_TEXT,
NOPOLL_CMD_SEND_BINARY,
NOPOLL_CMD_CLOSE
};
typedef struct {
int type;
void *data;
} nopoll_msg_t;
typedef struct {
uint8_t *buff;
uint32_t size;
ws_bin_type_t type;
} nopoll_xfer_t;
typedef struct {
char server[128];
char port[8];
char schema[8];
char *cacert;
char *path;
} nopoll_conn_info_t;
typedef struct {
noPollCtx *ctx;
noPollConn *conn;
noPollConnOpts *conn_opts;
nopoll_conn_info_t conn_info;
char *msg_buffer;
int msg_count;
char *prev_text;
int prev_text_size;
uint8_t recv_disable:1;
uint8_t pong_recv:1;
int heartbeat_type;
int prev_recv_type;
os_mutex_t lock;
os_sem_t exit_sem;
os_task_t task;
os_queue_t queue;
ws_cb_ops_t callback;
ws_conn_state_t ws_conn_state;
long long conn_active_time;
} ws_handler_t;
static ws_handler_t *g_ws_handler;
static int nopoll_client_close(ws_handler_t *handler);
static void active_time_update(ws_handler_t *handler)
{
handler->conn_active_time = os_current_time();
}
static int active_time_get(ws_handler_t *handler)
{
return handler->conn_active_time / 1000;
}
static void inline msg_count_add(ws_handler_t *handler)
{
os_mutex_lock(handler->lock, OS_WAIT_FOREVER);
handler->msg_count++;
os_mutex_unlock(handler->lock);
}
static void inline msg_count_dec(ws_handler_t *handler)
{
os_mutex_lock(handler->lock, OS_WAIT_FOREVER);
handler->msg_count--;
os_mutex_unlock(handler->lock);
}
static void nopoll_message_handle(ws_handler_t *handler, noPollMsg *msg)
{
char *content;
noPollOpCode type;
int size;
bool final;
size = nopoll_msg_get_payload_size(msg);
type = nopoll_msg_opcode(msg);
final = nopoll_msg_is_final(msg);
content = (char *)nopoll_msg_get_payload(msg);
#if MERGE_TEXT_FRAME_SUPPORT
if (handler->prev_text_size > 0 && handler->prev_text) {
if (size > 0 && type == NOPOLL_TEXT_FRAME) {
handler->prev_text = snd_realloc(handler->prev_text,
handler->prev_text_size + size, AFM_EXTN);
if (!handler->prev_text) {
M_LOGE("realloc prev text failed !\n");
handler->prev_text_size = 0;
return;
}
memcpy(handler->prev_text + handler->prev_text_size,
content, size);
handler->prev_text_size += size;
if (final) {
handler->callback.recv_text_cb(handler->prev_text,
handler->prev_text_size);
snd_free(handler->prev_text);
handler->prev_text = NULL;
handler->prev_text_size = 0;
}
return;
} else {
M_LOGD("expect text frame, receive type %d\n", type);
handler->callback.recv_text_cb(handler->prev_text,
handler->prev_text_size);
snd_free(handler->prev_text);
handler->prev_text = NULL;
handler->prev_text_size = 0;
}
} else if (size > 0 && type == NOPOLL_TEXT_FRAME && !final) {
if (handler->prev_text) {
snd_free(handler->prev_text);
handler->prev_text_size = 0;
}
handler->prev_text = snd_zalloc(size, AFM_EXTN);
if (!handler->prev_text) {
M_LOGE("alloc prev text buffer failed !\n");
return;
}
handler->prev_text_size = size;
memcpy(handler->prev_text, content, size);
return;
}
#endif
switch (type) {
case NOPOLL_TEXT_FRAME:
handler->prev_recv_type = NOPOLL_TEXT_FRAME;
handler->callback.recv_text_cb(content, size);
break;
case NOPOLL_BINARY_FRAME:
handler->prev_recv_type = NOPOLL_BINARY_FRAME;
if (final) {
handler->callback.recv_binary_cb(content,
size, WS_BIN_DATA_FINISH);
} else {
handler->callback.recv_binary_cb(content,
size, WS_BIN_DATA_START);
}
break;
case NOPOLL_CONTINUATION_FRAME:
if (handler->prev_recv_type == NOPOLL_TEXT_FRAME) {
handler->callback.recv_text_cb(content, size);
} else {
if (final)
handler->callback.recv_binary_cb(content,
size, WS_BIN_DATA_FINISH);
else
handler->callback.recv_binary_cb(content,
size, WS_BIN_DATA_CONTINUE);
}
break;
case NOPOLL_PONG_FRAME:
handler->pong_recv = 1;
break;
default:
break;
}
}
static void __nopoll_conn_open(ws_handler_t *handler,
nopoll_xfer_t *data)
{
nopoll_conn_info_t *conn_info;
if (!handler) {
M_LOGE("ws handler null !\n");
return;
}
handler->conn_opts = nopoll_conn_opts_new();
if (!handler->conn_opts) {
M_LOGE("create connect opts failed !\n");
goto __err_exit;
}
conn_info = &handler->conn_info;
if (!conn_info->cacert) {
if (conn_info->path)
handler->conn = nopoll_conn_new_opts(handler->ctx,
handler->conn_opts,
conn_info->server,
conn_info->port,
NULL,
conn_info->path,
NULL, NULL);
else
handler->conn = nopoll_conn_new(handler->ctx,
conn_info->server,
conn_info->port,
conn_info->server,
NULL, NULL, NULL);
} else {
if (!nopoll_conn_opts_set_ssl_certs(handler->conn_opts,
NULL, 0,
NULL, 0,
NULL, 0,
conn_info->cacert,
strlen(conn_info->cacert) + 1)) {
M_LOGE("set ssl certs failed !\n");
goto __err_exit;
}
nopoll_conn_opts_ssl_peer_verify(handler->conn_opts,
nopoll_false);
handler->conn = nopoll_conn_tls_new(handler->ctx,
handler->conn_opts, conn_info->server,
conn_info->port,
NULL,
conn_info->path,
NULL, NULL);
}
if (!handler->conn) {
M_LOGE("create nopoll connection failed !\n");
handler->conn_opts = NULL;
goto __err_exit;
}
if (!nopoll_conn_wait_until_connection_ready(
handler->conn, 3)) {
M_LOGE("connection timeout !\n");
goto __err_exit;
}
handler->ws_conn_state = WS_CONN_STAT_CONNECTED;
handler->callback.connect_cb();
return;
__err_exit:
nopoll_conn_unref(handler->conn);
nopoll_conn_opts_free(handler->conn_opts);
handler->conn = NULL;
handler->conn_opts = NULL;
handler->ws_conn_state = WS_CONN_STAT_DISCONNECTED;
}
static void __nopoll_conn_close(ws_handler_t *handler, void *data)
{
if (!handler) {
M_LOGE("ws handler null !\n");
return -1;
}
nopoll_conn_close(handler->conn);
handler->conn = NULL;
handler->conn_opts = NULL;
handler->ws_conn_state = WS_CONN_STAT_DISCONNECTED;
handler->callback.disconnect_cb();
}
static int __nopoll_conn_send_continue(noPollConn * conn,
const char *content, long length)
{
return __nopoll_conn_send_common(conn,
content,
length,
nopoll_true,
0,
NOPOLL_CONTINUATION_FRAME);
}
static int __nopoll_conn_send_continue_fragment(noPollConn * conn,
const char *content, long length)
{
return __nopoll_conn_send_common(conn,
content,
length,
nopoll_false,
0,
NOPOLL_CONTINUATION_FRAME);
}
static int __nopoll_conn_complete_pending_write(noPollConn *conn)
{
int try_times = 0;
while (try_times < 5 && errno == NOPOLL_EWOULDBLOCK &&
nopoll_conn_pending_write_bytes(conn) > 0) {
os_msleep(50);
if (nopoll_conn_complete_pending_write(conn) == 0)
return 0;
try_times++;
}
return 1;
}
static void __nopoll_conn_send_text(ws_handler_t *handler,
nopoll_xfer_t *data)
{
int ret;
ret = nopoll_conn_send_text(handler->conn,
(char *)data->buff, data->size);
if (ret != data->size) {
if (__nopoll_conn_complete_pending_write(handler->conn))
M_LOGE("size %u ret %d\n", data->size, ret);
}
snd_free(data->buff);
snd_free(data);
}
static void __nopoll_conn_send_binary(ws_handler_t *handler,
nopoll_xfer_t *data)
{
int ret = 0;
switch (data->type) {
case WS_BIN_DATA_START:
ret = nopoll_conn_send_binary_fragment(handler->conn,
(char *)data->buff, data->size);
break;
case WS_BIN_DATA_CONTINUE:
ret = __nopoll_conn_send_continue_fragment(handler->conn,
(char *)data->buff, data->size);
break;
case WS_BIN_DATA_FINISH:
ret = __nopoll_conn_send_continue(handler->conn,
(char *)data->buff, data->size);
break;
default:
M_LOGE("unknown data type\n");
break;
}
if (ret != data->size) {
if (__nopoll_conn_complete_pending_write(handler->conn))
M_LOGE("size %u, ret %d\n", data->size, ret);
}
snd_free(data->buff);
snd_free(data);
}
static int __nopoll_conn_try_get_msg(ws_handler_t *handler)
{
noPollMsg *msg;
if (handler->recv_disable)
return -1;
if (!nopoll_conn_is_ok(handler->conn)) {
if (handler->ws_conn_state == WS_CONN_STAT_CONNECTED) {
M_LOGE("connect down, close nopoll client\n");
__nopoll_conn_close(handler, NULL);
}
return -1;
}
msg = nopoll_conn_get_msg(handler->conn);
if (!msg)
return -1;
active_time_update(handler);
nopoll_message_handle(handler, msg);
nopoll_msg_unref(msg);
return 0;
}
static int __nopoll_conn_ping_test(ws_handler_t *handler)
{
long long time_active;
long long time_now;
if (!nopoll_conn_is_ok(handler->conn)) {
if (handler->ws_conn_state == WS_CONN_STAT_CONNECTED) {
M_LOGE("connection is closed\n");
__nopoll_conn_close(handler, NULL);
}
return -1;
}
time_now = os_current_time();
time_now /= 1000;
time_active = active_time_get(handler);
if (time_now <= (time_active + NOPOLL_PING_PERIOD_SEC))
return -1;
nopoll_conn_send_ping(handler->conn);
active_time_update(handler);
return 0;
}
static void __nopoll_conn_pong_check(ws_handler_t *handler)
{
if (handler->pong_recv)
return;
M_LOGE("recv pong frame timeout !\n");
__nopoll_conn_close(handler, NULL);
}
static void nopoll_client_task(void *arg)
{
ws_handler_t *handler = (ws_handler_t *)arg;
struct netif *netif;
int wait_time = WAIT_MS_MIN;
int ping_count = 0;
bool ping_sent = false;
int ping_time = 0;
nopoll_msg_t msg;
unsigned int msg_size = 0;
bool task_exit = false;
int ret;
netif = netif_find("en1");
if (!netif) {
M_LOGE("find netif failed !\n");
return;
}
while (!task_exit) {
ret = os_queue_recv(&handler->queue, 30, &msg, &msg_size);
if (ret || msg_size != sizeof(nopoll_msg_t)) {
if (!netif_is_up(netif) || !netif_is_link_up(netif)) {
if (handler->ws_conn_state == WS_CONN_STAT_CONNECTED) {
M_LOGE("netif down ! close connection\n");
__nopoll_conn_close(handler, NULL);
}
}
if (__nopoll_conn_try_get_msg(handler)) {
wait_time <<= 1;
if (wait_time > WAIT_MS_MAX)
wait_time = WAIT_MS_MAX;
} else {
wait_time = WAIT_MS_MIN;
}
if (handler->heartbeat_type != 0) {
if (ping_count++ > PING_INTERVAL_COUNT) {
ping_count = 0;
if (!__nopoll_conn_ping_test(handler)) {
if (handler->heartbeat_type == 2)
ping_sent = true;
handler->pong_recv = 0;
ping_time = 0;
}
}
if (ping_sent) {
if (!handler->recv_disable) {
if (ping_time > NOPOLL_PONG_TIMEOUT_MSEC) {
__nopoll_conn_pong_check(handler);
ping_sent = false;
ping_time = 0;
} else {
ping_time += wait_time;
}
} else {
ping_sent = false;
ping_time = 0;
}
}
}
os_msleep(wait_time);
continue;
}
msg_count_dec(handler);
switch (msg.type) {
case NOPOLL_CMD_EXIT:
task_exit = true;
break;
case NOPOLL_CMD_OPEN:
__nopoll_conn_open(handler, msg.data);
break;
case NOPOLL_CMD_SEND_TEXT:
active_time_update(handler);
__nopoll_conn_send_text(handler, msg.data);
break;
case NOPOLL_CMD_SEND_BINARY:
active_time_update(handler);
__nopoll_conn_send_binary(handler, msg.data);
break;
case NOPOLL_CMD_CLOSE:
__nopoll_conn_close(handler, msg.data);
break;
default:
M_LOGW("unknown msg\n");
break;
}
}
os_sem_signal(handler->exit_sem);
}
static int nopoll_client_open(ws_handler_t *handler,
ws_conn_info_t *info)
{
nopoll_conn_info_t *conn_info;
nopoll_msg_t msg;
int ret;
if (!handler) {
M_LOGE("ws handler null !\n");
return -1;
}
if (!handler->ctx) {
M_LOGE("nopoll ctx null !\n");
return -1;
}
if (handler->conn) {
M_LOGW("conn already open, close it\n");
nopoll_client_close(handler);
}
conn_info = &handler->conn_info;
if (conn_info->cacert) {
snd_free(conn_info->cacert);
conn_info->cacert = NULL;
}
if (conn_info->path) {
snd_free(conn_info->path);
conn_info->path = NULL;
}
memcpy(conn_info->server, info->server,
strlen(info->server) + 1);
snprintf(conn_info->port, sizeof(conn_info->port),
"%u", info->port);
memcpy(conn_info->schema, info->schema,
strlen(info->schema) + 1);
if (info->cacert) {
conn_info->cacert = snd_zalloc(strlen(info->cacert) + 1,
AFM_EXTN);
if (!conn_info->cacert) {
M_LOGE("alloc cacert failed !\n");
return -1;
}
memcpy(conn_info->cacert, info->cacert,
strlen(info->cacert) + 1);
}
if (info->path) {
conn_info->path = snd_zalloc(strlen(info->path) + 1,
AFM_EXTN);
if (!conn_info->path) {
M_LOGE("alloc path failed !\n");
if (conn_info->cacert) {
snd_free(conn_info->cacert);
conn_info->cacert = NULL;
}
return -1;
}
memcpy(conn_info->path, info->path,
strlen(info->path) + 1);
}
memcpy(&handler->callback, &info->callback,
sizeof(ws_cb_ops_t));
msg.type = NOPOLL_CMD_OPEN;
msg.data = NULL;
ret = os_queue_send(&handler->queue, &msg,
sizeof(nopoll_msg_t));
if (ret) {
M_LOGE("send msg failed %d ! msg count %d\n",
ret, handler->msg_count);
return -1;
}
msg_count_add(handler);
return 0;
}
static int nopoll_client_close(ws_handler_t *handler)
{
nopoll_conn_info_t *info;
nopoll_msg_t msg;
int ret;
if (!handler) {
M_LOGE("ws handler null !\n");
return -1;
}
info = &handler->conn_info;
if (info->cacert) {
snd_free(info->cacert);
info->cacert = NULL;
}
if (info->path) {
snd_free(info->path);
info->path = NULL;
}
if (!handler->conn) {
M_LOGW("nopoll not open, ignore\n");
return -1;
}
msg.type = NOPOLL_CMD_CLOSE;
msg.data = NULL;
ret = os_queue_send(&handler->queue, &msg,
sizeof(nopoll_msg_t));
if (ret) {
M_LOGE("send msg failed %d ! msg count %d\n",
ret, handler->msg_count);
return -1;
}
msg_count_add(handler);
return 0;
}
static int nopoll_client_send_text(ws_handler_t *handler,
char *text, int len)
{
nopoll_xfer_t *xfer;
nopoll_msg_t msg;
int ret;
if (!handler) {
M_LOGE("ws handler null !\n");
return -1;
}
if (len <= 0) {
M_LOGE("text len %d invalid !\n", len);
return -1;
}
xfer = snd_zalloc(sizeof(nopoll_xfer_t), AFM_EXTN);
if (!xfer) {
M_LOGE("alloc nopoll xfer failed !\n");
return -1;
}
xfer->buff = snd_zalloc(len, AFM_MAIN);
if (!xfer->buff) {
M_LOGE("alloc buffer failed !\n");
snd_free(xfer);
return -1;
}
memcpy(xfer->buff, text, len);
xfer->size = len;
msg.type = NOPOLL_CMD_SEND_TEXT;
msg.data = xfer;
ret = os_queue_send(&handler->queue, &msg,
sizeof(nopoll_msg_t));
if (ret) {
M_LOGE("send msg failed %d ! msg count %d\n",
ret, handler->msg_count);
snd_free(xfer->buff);
snd_free(xfer);
return -1;
}
msg_count_add(handler);
return 0;
}
static int nopoll_client_send_binary(ws_handler_t *handler,
void *pdata, int len, ws_bin_type_t type)
{
nopoll_xfer_t *xfer;
nopoll_msg_t msg;
int ret;
if (!handler) {
M_LOGE("ws handler null !\n");
return -1;
}
if (len < 0) {
M_LOGE("bin len %d invalid !\n", len);
return -1;
}
xfer = snd_zalloc(sizeof(nopoll_xfer_t), AFM_EXTN);
if (!xfer) {
M_LOGE("alloc nopoll send data failed !\n");
return -1;
}
if (len == 0)
len = 32;
xfer->buff = snd_zalloc(len, AFM_MAIN);
if (!xfer->buff) {
M_LOGE("alloc buffer failed !\n");
snd_free(xfer);
return -1;
}
memcpy(xfer->buff, pdata, len);
xfer->size = len;
xfer->type = type;
msg.type = NOPOLL_CMD_SEND_BINARY;
msg.data = xfer;
ret = os_queue_send(&handler->queue, &msg,
sizeof(nopoll_msg_t));
if (ret) {
M_LOGE("send msg failed %d ! msg count %d\n",
ret, handler->msg_count);
snd_free(xfer->buff);
snd_free(xfer);
return -1;
}
msg_count_add(handler);
return 0;
}
static int nopoll_client_create(ws_handler_t *handler)
{
if (!handler)
return -1;
if (handler->ctx) {
M_LOGW("nopoll client exist, ignore\n");
goto __exit;
}
handler->ctx = nopoll_ctx_new();
if (!handler->ctx) {
M_LOGE("create nopoll ctx failed !\n");
return -1;
}
if (os_task_create(&handler->task,
"nopoll_client_task",
nopoll_client_task,
handler,
NOPOLL_CLIENT_TASK_STACK_SIZE,
NOPOLL_CLIENT_TASK_PRIORITY)) {
M_LOGE("create nopoll client task failed !\n");
return -1;
}
M_LOGI("nopoll client create\n");
__exit:
return 0;
}
static int nopoll_client_release(ws_handler_t *handler)
{
nopoll_msg_t msg;
int ret;
if (!handler) {
M_LOGE("ws handler null !\n");
return -1;
}
nopoll_ctx_unref(handler->ctx);
handler->ctx = NULL;
msg.type = NOPOLL_CMD_EXIT;
msg.data = NULL;
ret = os_queue_send(&handler->queue, &msg,
sizeof(nopoll_msg_t));
if (ret) {
M_LOGE("send msg failed %d ! msg count %d\n",
ret, handler->msg_count);
return -1;
}
msg_count_add(handler);
if (os_sem_wait(handler->exit_sem, 5000)) {
M_LOGE("wait exit sem timeout !\n");
return -1;
}
M_LOGI("nopoll client release\n");
return 0;
}
int uvoice_ws_connect(ws_conn_info_t *info)
{
ws_handler_t *handler = g_ws_handler;
if (!handler) {
M_LOGE("ws handler null !\n");
return -1;
}
if (!info) {
M_LOGE("info null !\n");
return -1;
}
if (!info->server) {
M_LOGE("server info null !\n");
return -1;
}
if (handler->ws_conn_state != WS_CONN_STAT_DISCONNECTED) {
M_LOGW("ws connected or connecting, ignore\n");
goto __exit;
}
handler->ws_conn_state = WS_CONN_STAT_CONNECTING;
M_LOGD("server:%s;port:%u;schema:%s;path:%s\n",
info->server,
info->port,
info->schema ? info->schema : "null",
info->path ? info->path : "null");
if (nopoll_client_create(handler)) {
M_LOGE("create nopoll client failed !\n");
handler->ws_conn_state = WS_CONN_STAT_DISCONNECTED;
return -1;
}
if (nopoll_client_open(handler, info)) {
M_LOGE("open nopoll client failed !\n");
nopoll_client_release(handler);
handler->ws_conn_state = WS_CONN_STAT_DISCONNECTED;
return -1;
}
__exit:
return 0;
}
int uvoice_ws_disconnect(void)
{
ws_handler_t *handler = g_ws_handler;
if (!handler) {
M_LOGE("ws handler null !\n");
return -1;
}
if (handler->ws_conn_state != WS_CONN_STAT_CONNECTED) {
M_LOGE("ws not connected !\n");
return -1;
}
M_LOGD("disconnect ws\n");
nopoll_client_close(handler);
nopoll_client_release(handler);
return 0;
}
int uvoice_ws_conn_state(ws_conn_state_t *state)
{
ws_handler_t *handler = g_ws_handler;
if (!handler) {
M_LOGE("ws handler null !\n");
return -1;
}
if (!state) {
M_LOGE("arg null !\n");
return -1;
}
*state = handler->ws_conn_state;
return 0;
}
int uvoice_ws_send_text(char *text, int len)
{
ws_handler_t *handler = g_ws_handler;
if (!handler) {
M_LOGE("ws handler null !\n");
return -1;
}
if (handler->ws_conn_state != WS_CONN_STAT_CONNECTED) {
M_LOGE("ws not connected !\n");
return -1;
}
return nopoll_client_send_text(handler, text, len);
}
int uvoice_ws_send_binary(char *data, int len, ws_bin_type_t type)
{
ws_handler_t *handler = g_ws_handler;
if (!handler) {
M_LOGE("ws handler null !\n");
return -1;
}
if (handler->ws_conn_state != WS_CONN_STAT_CONNECTED) {
M_LOGE("ws not connected !\n");
return -1;
}
return nopoll_client_send_binary(handler, data, len, type);
}
int uvoice_ws_recv_disable(int disable)
{
ws_handler_t *handler = g_ws_handler;
if (!handler) {
M_LOGE("ws handler null !\n");
return -1;
}
if (disable)
handler->recv_disable = 1;
else
handler->recv_disable = 0;
M_LOGD("set recv_disable %d\n", handler->recv_disable);
return 0;
}
/*
* ping-pong heartbeat type:
* 0 - disable
* 1 - send ping frame but don't check pong frame
* 2 - send ping frame and check pong frame
*/
int uvoice_ws_heartbeat_set(int type)
{
ws_handler_t *handler = g_ws_handler;
if (!handler) {
M_LOGE("ws handler null !\n");
return -1;
}
if (type < 0 || type > 2) {
M_LOGE("type %d invalid !\n", type);
return -1;
}
if (handler->heartbeat_type != type) {
handler->heartbeat_type = type;
M_LOGD("set heartbeat_type %d\n",
handler->heartbeat_type);
}
return 0;
}
int uvoice_ws_init(void)
{
ws_handler_t *handler = g_ws_handler;
int ret;
if (handler)
return 0;
handler = snd_zalloc(sizeof(ws_handler_t), AFM_EXTN);
if (!handler) {
M_LOGE("alloc nopoll handler failed !\n");
return -1;
}
handler->msg_buffer = snd_zalloc(sizeof(nopoll_msg_t) * 8,
AFM_MAIN);
if (!handler->msg_buffer) {
M_LOGE("alloc msg buffer failed !\n");
snd_free(handler);
return -1;
}
ret = os_queue_new(&handler->queue, handler->msg_buffer,
sizeof(nopoll_msg_t) * 8,
sizeof(nopoll_msg_t));
if (ret) {
M_LOGE("create event queue failed %d!\n", ret);
snd_free(handler->msg_buffer);
snd_free(handler);
return -1;
}
handler->exit_sem = os_sem_new(0);
handler->lock = os_mutex_new();
handler->ws_conn_state = WS_CONN_STAT_DISCONNECTED;
g_ws_handler = handler;
M_LOGI("ws init\n");
return 0;
}
int uvoice_ws_deinit(void)
{
ws_handler_t *handler = g_ws_handler;
if (!handler) {
M_LOGE("ws handler null !\n");
return -1;
}
if (handler->ws_conn_state != WS_CONN_STAT_DISCONNECTED)
uvoice_ws_disconnect();
os_mutex_free(handler->lock);
os_sem_free(handler->exit_sem);
os_queue_free(&handler->queue);
snd_free(handler->msg_buffer);
snd_free(handler);
g_ws_handler = NULL;
M_LOGI("ws free\n");
return 0;
}
|
YifuLiu/AliOS-Things
|
components/uvoice/connect/uvoice_ws.c
|
C
|
apache-2.0
| 21,830
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifndef __UVOICE_WS_H__
#define __UVOICE_WS_H__
typedef enum {
WS_BIN_DATA_START,
WS_BIN_DATA_CONTINUE,
WS_BIN_DATA_FINISH,
} ws_bin_type_t;
typedef struct {
void (*connect_cb)(void);
void (*disconnect_cb)(void);
void (*recv_text_cb)(char *text, int size);
void (*recv_binary_cb)(char *data, int size, ws_bin_type_t type);
} ws_cb_ops_t;
typedef struct {
uint16_t port;
char *server;
char *schema;
char *cacert;
char *path;
ws_cb_ops_t callback;
} ws_conn_info_t;
typedef enum {
WS_CONN_STAT_DISCONNECTED = 0,
WS_CONN_STAT_CONNECTING,
WS_CONN_STAT_CONNECTED,
} ws_conn_state_t;
#if (UVOICE_WS_ENABLE == 1)
int uvoice_ws_connect(ws_conn_info_t *info);
int uvoice_ws_disconnect(void);
int uvoice_ws_conn_state(ws_conn_state_t *state);
int uvoice_ws_send_text(char *text, int len);
int uvoice_ws_send_binary(char *data, int len, ws_bin_type_t type);
int uvoice_ws_recv_pause(int pause);
int uvoice_ws_heartbeat_set(int type);
int uvoice_ws_init(void);
int uvoice_ws_deinit(void);
#endif
#endif /*__UVOICE_WS_H__*/
|
YifuLiu/AliOS-Things
|
components/uvoice/connect/uvoice_ws.h
|
C
|
apache-2.0
| 1,125
|
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "k_api.h"
#if AOS_COMP_CLI
#include "aos/cli.h"
#endif
#include "uvoice_init.h"
#include "uvoice_test.h"
static void cmd_play_handler(char *buf, int len, int argc, char **argv)
{
return uvoice_play_test(argc, argv);
}
static void cmd_record_handler(char *buf, int len, int argc, char **argv)
{
return uvoice_record_test(argc, argv);
}
static void cmd_tts_handler(char *buf, int len, int argc, char **argv)
{
extern void test_tts_handle(int argc, char **argv);
return test_tts_handle(argc, argv);
}
#if AOS_COMP_CLI
struct cli_command uvoicedemo_commands[] = {
{"play", "player test", cmd_play_handler},
{"record", "record test", cmd_record_handler},
{"tts", "tts test", cmd_tts_handler}
};
void uvoice_example(int argc, char **argv)
{
static int uvoice_example_inited = 0;
if (uvoice_example_inited == 1) {
printf("uvoice example already initialized !\n");
return;
}
uvoice_example_inited = 1;
uvoice_init();
aos_cli_register_commands(uvoicedemo_commands,
sizeof(uvoicedemo_commands) / sizeof(struct cli_command));
printf("uvoice example initialization succeeded !\n");
return;
}
/* reg args: fun, cmd, description*/
ALIOS_CLI_CMD_REGISTER(uvoice_example, uvoice_example, uvoice test example)
#endif
|
YifuLiu/AliOS-Things
|
components/uvoice/example/uvoice_example.c
|
C
|
apache-2.0
| 1,427
|
#!/usr/bin/env python
import os, sys
print("the script is " + sys.argv[0])
print("current dir is " + os.getcwd())
cur_dir = os.getcwd()
script_dir = sys.path[0]
script1_dir = os.path.join(script_dir, "codec", "opensource", "pvaac")
script2_dir = os.path.join(script_dir, "codec", "opensource", "pvmp3")
os.chdir(script1_dir)
print("Downloading open source of aac...")
ret = os.system("python get_pv_aac.py") >> 8
if ret != 0:
os.chdir(cur_dir)
exit(1)
os.chdir(script2_dir)
print("Downloading open source of mp3...")
ret = os.system("python get_pvmp3.py") >> 8
if ret != 0:
os.chdir(cur_dir)
exit(1)
# result
print("run external script success")
os.chdir(cur_dir)
exit(0)
|
YifuLiu/AliOS-Things
|
components/uvoice/get_open_source.py
|
Python
|
apache-2.0
| 690
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifndef __UVOICE_EVENT_H__
#define __UVOICE_EVENT_H__
/** @defgroup uvoice_event_api uvoice_event
* @ingroup uvoice_aos_api
* @{
*/
#define UVOICE_EV_PLAYER 0x0111
#define UVOICE_CODE_PLAYER_STATE 1
#define UVOICE_CODE_PALYER_CACHE_CPLT 2
#define UVOICE_CODE_PALYER_DLOAD_CPLT 3
#define UVOICE_EV_RECORDER 0x0112
#define UVOICE_CODE_RECORDER_STATE 1
#define UVOICE_EV_SW 0x0113
#define UVOICE_CODE_HEADPHONE 1
#define UVOICE_CODE_HEADSET 2
#define UVOICE_EV_ST 0x0114
#define UVOICE_CODE_VAD_START 1
#define UVOICE_CODE_VAD_END 2
#define UVOICE_CODE_VOICE_WAKEUP 3
#define UVOICE_EV_ASR_RESULT 0x0115
typedef struct {
uint16_t type;
uint16_t code;
int value;
} uvoice_event_t;
typedef void (*uvoice_event_cb)(uvoice_event_t *event, void *data);
int uvoice_event_post(uint16_t type, uint16_t code, int value);
int uvoice_event_register(uint16_t type, uvoice_event_cb cb, void *data);
int uvoice_event_unregister(uint16_t type, uvoice_event_cb cb, void *data);
/**
* @}
*/
#endif /* __UVOICE_EVENT_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/include/uvoice_event.h
|
C
|
apache-2.0
| 1,118
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifndef __UVOICE_INIT_H__
#define __UVOICE_INIT_H__
/** @defgroup uvoice_init_api uvoice_init
* @ingroup uvoice_aos_api
* @{
*/
/**
* Init the uvoice module.
*
* @retrun 0 on success, otherwise will be failed.
*/
int uvoice_init(void);
/**
* DeInit the uvoice module.
*
* @retrun 0 on success, otherwise will be failed.
*/
int uvoice_free(void);
/**
* @}
*/
#endif /* __UVOICE_INIT_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/include/uvoice_init.h
|
C
|
apache-2.0
| 474
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#ifndef __UVOICE_MLIST_H__
#define __UVOICE_MLIST_H__
/** @defgroup uvoice_mlist_api uvoice_mlist
* @ingroup uvoice_aos_api
* @{
*/
/**
* 显示播放列表
*
* @retrun 成功返回0,失败返回非0.
*/
int mlist_source_show(void);
/**
* 扫描本地音频文件,更新播放列表
*
* @retrun 成功返回0,失败返回非0.
*/
int mlist_source_scan(void);
/**
* 获取播放列表
*
* @param[in] index 播放列表中音频文件序号
* @param[out] path 音频文件路径
* @param[in] len 音频文件路径长度
* @retrun 成功返回0,失败返回非0.
*/
int mlist_source_get(int index, char *path, int len);
/**
* 删除播放列表中某个音频文件
*
* @param[in] index 播放列表序号为index的音频文件
* @retrun 成功返回0,失败返回非0.
*/
int mlist_source_del(int index);
/**
* 获取播放列表中正在播放音频文件的列表序号
*
* @param[out] index 播放列表中音频文件序号
* @retrun 成功返回0,失败返回非0.
*/
int mlist_index_get(int *index);
/**
* 设置当前正在播放音频文件的列表序号
*
* @param[in] index 播放列表序号
* @retrun 成功返回0,失败返回非0.
*/
int mlist_index_set(int index);
/**
* @}
*/
#endif /* __UVOICE_MLIST_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/include/uvoice_mlist.h
|
C
|
apache-2.0
| 1,434
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#ifndef __UVOICE_PLAYER_H__
#define __UVOICE_PLAYER_H__
#include "uvoice_types.h"
/** @defgroup uvoice_player_api uvoice_player
* @ingroup uvoice_aos_api
* @{
*/
/** @brief 播放状态 */
typedef enum {
PLAYER_STAT_IDLE = 0,
PLAYER_STAT_READY,
PLAYER_STAT_RUNNING,
PLAYER_STAT_PAUSED,
PLAYER_STAT_RESUME,
PLAYER_STAT_STOP,
PLAYER_STAT_COMPLETE,
PLAYER_STAT_SEEK_CPLT,
PLAYER_STAT_MEDIA_INFO,
PLAYER_STAT_SOURCE_INVALID,
PLAYER_STAT_FORMAT_UNSUPPORT,
PLAYER_STAT_LIST_PLAY_START,
PLAYER_STAT_LIST_PLAY_STOP,
PLAYER_STAT_ERROR,
} player_state_t;
/** @brief 播放接口 */
typedef struct {
int (*start)(void);
int (*stop)(void);
int (*pause)(void);
int (*resume)(void);
int (*complete)(void);
int (*stop_async)(void);
int (*pause_async)(void);
int (*resume_async)(void);
int (*set_source)(char *source);
int (*clr_source)(void);
int (*set_stream)(media_format_t format, int cache_enable, int cache_size);
int (*put_stream)(const uint8_t *buffer, int nbytes);
int (*clr_stream)(int immediate);
int (*play_list)(char **list);
int (*set_pcminfo)(int rate, int channels, int bits, int frames);
int (*get_duration)(int *duration);
int (*get_position)(int *position);
int (*set_volume)(int volume);
int (*get_volume)(int *volume);
int (*volume_range)(int *max, int *min);
int (*seek)(int second);
int (*playback)(char *source);
int (*wait_complete)(void);
int (*download)(char *name);
int (*download_abort)(void);
int (*cache_config)(cache_config_t *config);
int (*set_fade)(int out_period, int in_period);
int (*set_format)(media_format_t format);
int (*set_out_device)(audio_out_device_t device);
int (*set_external_pa)(audio_extpa_info_t *info);
int (*set_standby)(int msec);
int (*eq_enable)(int enable);
int (*state_dump)(void);
int (*pcmdump_enable)(int enable);
int (*get_state)(player_state_t *state);
int (*get_delay)(int *delay_ms);
int (*get_mediainfo)(media_info_t *info);
int (*get_cacheinfo)(int *cache_size);
int (*format_support)(media_format_t format);
void *priv;
} uvoice_player_t;
/**
* 创建播放器
*
* @retrun 成功返回非NULL指针,失败返回NULL.
*/
uvoice_player_t *uvoice_player_create(void);
/**
* 释放播放器.
*
* @param[in] mplayer 创建播放器时返回的指针.
*
* @return 0成功,其他失败.
*/
int uvoice_player_release(uvoice_player_t *mplayer);
/**
* @}
*/
#endif /* __UVOICE_PLAYER_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/include/uvoice_player.h
|
C
|
apache-2.0
| 2,650
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#ifndef __UVOICE_RECORDER_H__
#define __UVOICE_RECORDER_H__
#include "uvoice_types.h"
/** @defgroup uvoice_recoder_api uvoice_recoder
* @ingroup uvoice_aos_api
* @{
*/
/** @brief 录音状态 */
typedef enum {
RECORDER_STAT_IDLE = 0,
RECORDER_STAT_READY,
RECORDER_STAT_RUNNING,
RECORDER_STAT_STOP,
RECORDER_STAT_ERROR,
} recorder_state_t;
/** @brief 录音接口 */
typedef struct {
/** @brief 设置录音参数 */
int (*set_sink)(media_format_t format, int rate, int channels, int bits, int frames, int bitrate, char *sink);
int (*clr_sink)(void);
int (*start)(void);
int (*stop)(void);
int (*get_stream)(uint8_t *buffer, int nbytes);
int (*get_state)(recorder_state_t *state);
int (*get_position)(int *position);
int (*ns_enable)(int enable);
int (*ec_enable)(int enable);
int (*agc_enable)(int enable);
int (*vad_enable)(int enable);
int (*format_support)(media_format_t format);
void *priv;
} uvoice_recorder_t;
/**
* 创建录音handler
*
* @retrun 成功返回非NULL指针,失败返回NULL.
*/
uvoice_recorder_t *uvoice_recorder_create(void);
/**
* 释放录音handler
*
* @param[in] mrecorder 创建录音handler时返回的指针.
*
* @return 0成功,其他失败.
*/
int uvoice_recorder_release(uvoice_recorder_t *mrecorder);
/**
* @}
*/
#endif /* __UVOICE_RECORDER_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/include/uvoice_recorder.h
|
C
|
apache-2.0
| 1,402
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifndef __UVOICE_TEST_H__
#define __UVOICE_TEST_H__
/** @defgroup uvoice_test_api uvoice_test
* @ingroup uvoice_aos_api
* @{
*/
/**
* 播放测试
*
*/
void uvoice_play_test(int argc, char **argv);
/**
* 录音测试
*
*/
void uvoice_record_test(int argc, char **argv);
/**
* TTS测试
*
*/
void test_tts_handle(int argc, char **argv);
void test_swid_handle(int argc, char **argv);
void test_wetalk_handle(int argc, char **argv);
/**
* @}
*/
#endif /* __UVOICE_TEST_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/include/uvoice_test.h
|
C
|
apache-2.0
| 561
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifndef __UVOICE_TYPES_H__
#define __UVOICE_TYPES_H__
/** @defgroup uvoice_aos_api uvoice
* @{
*/
/**
* @}
*/
/** @defgroup uvoice_types_api uvoice_types
* @ingroup uvoice_aos_api
* @ingroup uvoice_aos_api
* @{
*/
typedef enum {
MEDIA_FMT_UNKNOWN = 0,
MEDIA_FMT_PCM,
MEDIA_FMT_WAV,
MEDIA_FMT_MP3,
MEDIA_FMT_AAC,
MEDIA_FMT_M4A,
MEDIA_FMT_OGG,
MEDIA_FMT_OPS,
MEDIA_FMT_SPX,
MEDIA_FMT_WMA,
MEDIA_FMT_AMR,
MEDIA_FMT_AMRWB,
MEDIA_FMT_FLAC,
MEDIA_FMT_COUNT,
} media_format_t;
typedef enum {
AUDIO_OUT_DEVICE_SPEAKER = 1,
AUDIO_OUT_DEVICE_HEADPHONE,
AUDIO_OUT_DEVICE_HEADSET,
AUDIO_OUT_DEVICE_RECEIVER,
AUDIO_OUT_DEVICE_SPEAKER_AND_HEADPHONE,
AUDIO_OUT_DEVICE_SPEAKER_AND_HEADSET,
AUDIO_OUT_DEVICE_MAX,
} audio_out_device_t;
typedef struct {
int used;
int active_high;
int pin;
int delay_ms;
} audio_extpa_info_t;
typedef struct {
char name[32];
char author[32];
char album[32];
char year[8];
int valid;
unsigned char type;
int32_t bitrate;
int32_t media_size;
int32_t duration;
} media_info_t;
typedef struct {
int place; /* 0: none, 1: file, 2: mem */
int mem_size; /* cache memory size in KB */
char file_path[128]; /* cache file full path */
} cache_config_t;
/**
* @}
*/
#endif /* __UVOICE_TYPES_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/include/uvoice_types.h
|
C
|
apache-2.0
| 1,437
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifndef __UVOICE_ALIOS_H__
#define __UVOICE_ALIOS_H__
#include <stdarg.h>
#include <k_api.h>
#include <aos/kernel.h>
#include <aos/errno.h>
#include <aos/kv.h>
#include <aos/vfs.h>
#include <aos/list.h>
#ifdef AOS_LOOP
#include <aos/yloop.h>
#endif
#include <aos/hal/flash.h>
#include "ulog/ulog.h"
typedef aos_dir_t os_dir_t;
typedef aos_dirent_t os_dirent_t;
typedef FILE *os_file_t;
typedef void *os_message_queue_t;
typedef aos_mutex_t *os_mutex_t;
typedef aos_sem_t *os_sem_t;
typedef aos_task_t os_task_t;
typedef aos_timer_t *os_timer_t;
#define OS_SEEK_SET SEEK_SET
#define OS_SEEK_CUR SEEK_CUR
#define OS_SEEK_END SEEK_END
#define OS_F_OK F_OK
#define OS_X_OK X_OK
#define OS_W_OK W_OK
#define OS_R_OK R_OK
#define OS_FILE_OPEN_FAIL(stream) (stream == NULL)
#define OS_FILE_OPENING(stream) (stream != NULL)
#define OS_FILE_CLOSED (NULL)
#define OS_WAIT_FOREVER AOS_WAIT_FOREVER
#define os_container_of aos_container_of
enum {
UVOICE_TASK_PRI_IDLE = RHINO_IDLE_PRI,
UVOICE_TASK_PRI_LOWEST = AOS_DEFAULT_APP_PRI + 5,
UVOICE_TASK_PRI_LOWER = AOS_DEFAULT_APP_PRI + 1,
UVOICE_TASK_PRI_NORMAL = AOS_DEFAULT_APP_PRI,
UVOICE_TASK_PRI_HIGHER = AOS_DEFAULT_APP_PRI - 1,
UVOICE_TASK_PRI_HIGHEST = AOS_DEFAULT_APP_PRI - 5,
UVOICE_TASK_PRI_REALTIME = RHINO_CONFIG_TIMER_TASK_PRI
};
#if (UVOICE_BUILD_RELEASE)
#define M_LOGD(fmt, ...)
#else
#define M_LOGD(fmt, ...) printf("%s: "fmt, __func__, ##__VA_ARGS__)
#endif
#define M_LOGI(fmt, ...) printf("%s: "fmt, __func__, ##__VA_ARGS__)
#define M_LOGW(fmt, ...) printf("%s: "fmt, __func__, ##__VA_ARGS__)
#define M_LOGE(fmt, ...) printf("%s: "fmt, __func__, ##__VA_ARGS__)
#define M_LOGR(fmt, ...) printf(fmt, ##__VA_ARGS__)
#define AFM_MAIN 0x1
#define AFM_EXTN 0x2
static inline void *snd_zalloc(size_t size, int flags)
{
#ifdef UVOICE_ON_BK7251
void *mem = NULL;
if (flags == AFM_MAIN) {
mem = malloc(size);
} else if (flags == AFM_EXTN) {
#ifdef BK7251_IRAM_ENABLE
mem = iram_heap_malloc(size);
#else
mem = malloc(size);
#endif
}
if (mem)
memset(mem, 0, size);
return mem;
#else
void *mem = malloc(size);
if (mem)
memset(mem, 0, size);
return mem;
#endif
}
static inline void snd_free(void *mem)
{
#ifdef UVOICE_ON_BK7251
if (mem >= 0x00400020 && mem <= 0x00440000)
free(mem);
else if (mem >= 0x00900000 && mem <= 0x00940000)
iram_heap_free(mem);
#else
free(mem);
#endif
}
static inline void *snd_realloc(void *old, size_t newsize, int flags)
{
#ifdef UVOICE_ON_BK7251
void *mem = NULL;
if (old >= 0x00400020 && old <= 0x00440000) {
mem = realloc(old, newsize);
} else if (old >= 0x00900000 && old <= 0x00940000) {
iram_heap_free(old);
mem = iram_heap_malloc(newsize);
}
if (mem)
memset(mem, 0, newsize);
return mem;
#else
void *mem = realloc(old, newsize);
if (mem)
memset(mem, 0, newsize);
return mem;
#endif
}
static inline void os_msleep(int msec)
{
aos_msleep(msec);
}
static inline void os_usleep(int usec)
{
if (usec < 1000)
aos_msleep(1);
else
aos_msleep((usec + 600) / 1000);
}
static inline long long os_current_time(void)
{
return aos_now_ms();
}
static inline int os_get_mac_address(char *mac)
{
uint8_t mac_addr[6];
memset(mac_addr, 0, sizeof(mac_addr));
if (hal_wifi_get_mac_addr(NULL, mac_addr))
return -1;
snprintf(mac, 18, "%02X:%02X:%02X:%02X:%02X:%02X",
mac_addr[0], mac_addr[1], mac_addr[2],
mac_addr[3], mac_addr[4], mac_addr[5]);
return 0;
}
static inline int os_kv_get(const char *key, void *buffer, int *len)
{
return aos_kv_get(key, buffer, len);
}
static inline int os_kv_set(const char *key, const void *buffer, int len, int sync)
{
return aos_kv_set(key, buffer, len, sync);
}
static inline int os_mkdir(const char *path)
{
return aos_mkdir(path);
}
static inline os_dir_t *os_opendir(const char *path)
{
return aos_opendir(path);
}
static inline os_dirent_t *os_readdir(os_dir_t *dir)
{
return aos_readdir(dir);
}
static inline int os_closedir(os_dir_t *dir)
{
return aos_closedir(dir);
}
static inline int os_access(const char *filename, int mode)
{
return access(filename, mode);
}
static inline os_file_t os_fopen(const char *filename, const char *mode)
{
FILE *fp = fopen(filename, mode);
return (os_file_t)fp;
}
static inline size_t os_fread(void *buffer, size_t size, size_t count, os_file_t fp)
{
return fread(buffer, size, count, fp);
}
static inline size_t os_fwrite(const void *buffer, size_t size, size_t count, os_file_t fp)
{
return fwrite(buffer, size, count, fp);
}
static inline long os_ftell(os_file_t fp)
{
return ftell(fp);
}
static inline long os_fseek(os_file_t fp, long offset, int whence)
{
return fseek(fp, offset, whence);
}
static inline char *os_fgets(char *buffer, int size, os_file_t fp)
{
return fgets(buffer, size, fp);
}
static inline int os_fprintf(os_file_t fp, const char *format, ...)
{
int ret;
va_list args;
va_start(args, format);
ret = vfprintf(fp, format, args);
va_end(args);
return ret;
}
static inline int os_feof(os_file_t fp)
{
return feof(fp);
}
static inline int os_ferror(os_file_t fp)
{
return ferror(fp);
}
static inline int os_fclose(os_file_t fp)
{
return fclose(fp);
}
static inline int os_remove(const char *filename)
{
return remove(filename);
}
typedef struct {
aos_queue_t queue;
uint8_t *buffer;
int item_size;
} aos_mq_impl_t;
static inline int os_message_queue_send(os_message_queue_t mq, void *msg,
unsigned int size, unsigned int timeout)
{
return aos_queue_send(&((aos_mq_impl_t *)mq)->queue, msg, ((aos_mq_impl_t *)mq)->item_size);
}
static inline int os_message_queue_recv(os_message_queue_t mq, void *msg,
unsigned int size, unsigned int timeout)
{
return aos_queue_recv(&((aos_mq_impl_t *)mq)->queue, timeout, msg, &size);
}
static inline os_message_queue_t os_message_queue_create(int count, int size)
{
aos_mq_impl_t *mq;
int ret;
mq = snd_zalloc(sizeof(aos_mq_impl_t), AFM_MAIN);
if (!mq)
return NULL;
mq->buffer = (uint8_t *)snd_zalloc(count * size, AFM_MAIN);
if (!mq->buffer) {
snd_free(mq);
return NULL;
}
mq->item_size = size;
ret = aos_queue_new(&mq->queue, mq->buffer, count * size, size);
if (ret) {
snd_free(mq->buffer);
snd_free(mq);
return NULL;
}
return mq;
}
static inline int os_message_queue_free(os_message_queue_t mq)
{
aos_queue_free(&((aos_mq_impl_t *)mq)->queue);
snd_free(((aos_mq_impl_t *)mq)->buffer);
snd_free(mq);
return 0;
}
static inline int os_event_post(uint16_t type, uint16_t code, int value)
{
#ifdef AOS_LOOP
return aos_post_event(type, code, value);
#else
return -1;
#endif
}
static inline int os_event_register(uint16_t type, void *cb, void *data)
{
#ifdef AOS_LOOP
return aos_register_event_filter(type, (aos_event_cb)cb, data);
#else
return -1;
#endif
}
static inline int os_event_unregister(uint16_t type, void *cb, void *data)
{
#ifdef AOS_LOOP
return aos_unregister_event_filter(type, (aos_event_cb)cb, data);
#else
return -1;
#endif
}
static inline int os_mutex_lock(os_mutex_t mutex, unsigned int timeout)
{
return aos_mutex_lock(mutex, timeout);
}
static inline int os_mutex_unlock(os_mutex_t mutex)
{
return aos_mutex_unlock(mutex);
}
static inline os_mutex_t os_mutex_new(void)
{
aos_mutex_t *mutex = snd_zalloc(sizeof(aos_mutex_t), AFM_MAIN);
if (!mutex)
return NULL;
if (aos_mutex_new(mutex)) {
snd_free(mutex);
return NULL;
}
return mutex;
}
static inline void os_mutex_free(os_mutex_t mutex)
{
aos_mutex_free(mutex);
snd_free(mutex);
}
static inline int os_sem_is_valid(os_sem_t sem)
{
return aos_sem_is_valid(sem);
}
static inline int os_sem_wait(os_sem_t sem, unsigned int timeout)
{
return aos_sem_wait(sem, timeout);
}
static inline void os_sem_signal(os_sem_t sem)
{
aos_sem_signal(sem);
}
static inline void os_sem_signal_all(os_sem_t sem)
{
aos_sem_signal_all(sem);
}
static inline os_sem_t os_sem_new(int count)
{
aos_sem_t *sem = snd_zalloc(sizeof(aos_sem_t), AFM_MAIN);
if (!sem)
return NULL;
if (aos_sem_new(sem, count)) {
snd_free(sem);
return NULL;
}
return sem;
}
static inline void os_sem_free(os_sem_t sem)
{
aos_sem_free(sem);
snd_free(sem);
}
static inline int os_timer_change(os_timer_t timer, int internal_ms)
{
return aos_timer_change(timer, internal_ms);
}
static inline int os_timer_start(os_timer_t timer)
{
return aos_timer_start(timer);
}
static inline int os_timer_stop(os_timer_t timer)
{
return aos_timer_stop(timer);
}
static inline os_timer_t os_timer_new(void (*func)(void *, void *), void *arg,
int internal_ms, int repeat, unsigned char auto_run)
{
aos_timer_t *timer = snd_zalloc(sizeof(aos_timer_t), AFM_MAIN);
if (!timer)
return NULL;
if (aos_timer_new_ext(timer, func, arg, internal_ms, repeat, auto_run)) {
snd_free(timer);
return NULL;
}
return timer;
}
static inline void os_timer_free(os_timer_t timer)
{
aos_timer_free(timer);
}
static inline int os_task_create(os_task_t *task, const char *name,
void (*fn)(void *), void *arg, int stack_size, int pri)
{
return aos_task_new_ext(task, name, fn, arg, stack_size, pri);
}
static inline int os_task_exit(os_task_t task)
{
return 0;
}
static inline const char *os_partition_name(int pt)
{
hal_logic_partition_t info;
memset(&info, 0, sizeof(info));
if (hal_flash_info_get((hal_partition_t)pt, &info))
return NULL;
return info.partition_description;
}
static inline int os_partition_size(int pt)
{
hal_logic_partition_t info;
memset(&info, 0, sizeof(info));
if (hal_flash_info_get((hal_partition_t)pt, &info))
return NULL;
return info.partition_length;
}
static inline int os_partition_read(int pt, uint32_t *offset, uint8_t *buffer, uint32_t len)
{
return hal_flash_read((hal_partition_t)pt, offset, buffer, len);
}
static inline int os_partition_write(int pt, uint32_t *offset, const uint8_t *buffer , uint32_t len)
{
return hal_flash_write((hal_partition_t)pt, offset, buffer, len);
}
static inline int os_partition_erase(int pt, uint32_t offset, uint32_t len)
{
return hal_flash_erase((hal_partition_t)pt, offset, len);
}
#endif /* __UVOICE_ALIOS_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/internal/uvoice_alios.h
|
C
|
apache-2.0
| 10,925
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifndef __UVOICE_AMP_H__
#define __UVOICE_AMP_H__
#include "amp_platform.h"
#include "amp_kv.h"
#include "amp_fs.h"
#include "amp_defines.h"
#include "amp_system.h"
#include "wrappers_defs.h"
typedef void *os_dir_t;
typedef void *os_dirent_t;
typedef void *os_file_t;
typedef void *os_message_queue_t;
typedef void *os_mutex_t;
typedef void *os_sem_t;
typedef void *os_task_t;
typedef void *os_timer_t;
#define OS_SEEK_SET HAL_SEEK_SET
#define OS_SEEK_CUR HAL_SEEK_CUR
#define OS_SEEK_END HAL_SEEK_END
#define OS_F_OK 0
#define OS_X_OK 1
#define OS_W_OK 2
#define OS_R_OK 3
#define OS_FILE_OPEN_FAIL(stream) (stream == NULL)
#define OS_FILE_OPENING(stream) (stream != NULL)
#define OS_FILE_CLOSED (NULL)
#define OS_WAIT_FOREVER PLATFORM_WAIT_INFINITE
#define os_container_of(ptr, type, member) \
((type *)((char *)(ptr) - offsetof(type, member)))
#define UVOICE_TASK_PRI_DEFAULT (amp_get_default_task_priority() - 1)
#define UVOICE_TASK_PRI_IDLE (amp_get_default_task_priority() - 1)
#define UVOICE_TASK_PRI_LOWEST (amp_get_default_task_priority() - 1)
#define UVOICE_TASK_PRI_LOWER (amp_get_default_task_priority() - 1)
#define UVOICE_TASK_PRI_NORMAL (amp_get_default_task_priority() - 1)
#define UVOICE_TASK_PRI_HIGHER (amp_get_default_task_priority() - 1)
#define UVOICE_TASK_PRI_HIGHEST (amp_get_default_task_priority() - 1)
#define UVOICE_TASK_PRI_REALTIME (amp_get_default_task_priority() - 1)
#ifdef UVOICE_BUILD_RELEASE
#define M_LOGD(fmt, ...)
#else
#define M_LOGD(fmt, ...) amp_printf("%s: "fmt, __func__, ##__VA_ARGS__)
#endif
#define M_LOGI(fmt, ...) amp_printf("%s: "fmt, __func__, ##__VA_ARGS__)
#define M_LOGW(fmt, ...) amp_printf("%s: "fmt, __func__, ##__VA_ARGS__)
#define M_LOGE(fmt, ...) amp_printf("%s: "fmt, __func__, ##__VA_ARGS__)
#define M_LOGR(fmt, ...) amp_printf(fmt, ##__VA_ARGS__)
#define AFM_MAIN 0x1
#define AFM_EXTN 0x2
static inline void *snd_zalloc(size_t size, int flags)
{
void *mem = amp_malloc(size);
if (mem)
memset(mem, 0, size);
return mem;
}
static inline void snd_free(void *mem)
{
amp_free(mem);
}
static inline void *snd_realloc(void *old, size_t newsize, int flags)
{
void *mem = amp_realloc(old, newsize);
if (mem)
memset(mem, 0, newsize);
return mem;
}
static inline void os_msleep(int msec)
{
amp_msleep(msec);
}
static inline void os_usleep(int usec)
{
amp_msleep(usec / 1000);
}
static inline long long os_current_time(void)
{
return amp_uptime();
}
static inline int os_get_mac_address(char *mac)
{
return 0;
}
static inline int os_kv_get(const char *key, void *buffer, int *len)
{
return amp_kv_get(key, buffer, len);
}
static inline int os_kv_set(const char *key, const void *buffer, int len, int sync)
{
return amp_kv_set(key, buffer, len, sync);
}
static inline int os_mkdir(const char *path)
{
return amp_mkdir(path);
}
static inline os_dir_t *os_opendir(const char *path)
{
return -1;
}
static inline os_dirent_t *os_readdir(os_dir_t *dir)
{
return -1;
}
static inline int os_closedir(os_dir_t *dir)
{
return -1;
}
static inline os_file_t os_fopen(const char *filename, const char *mode)
{
return amp_fopen(filename, mode);
}
static inline size_t os_fread(void *buffer, size_t size, size_t count, os_file_t fp)
{
return amp_fread(buffer, size, count, fp);
}
static inline size_t os_fwrite(const void *buffer, size_t size, size_t count, os_file_t fp)
{
return amp_fwrite(buffer, size, count, fp);
}
static inline long os_ftell(os_file_t fp)
{
return amp_ftell(fp);
}
static inline long os_fseek(os_file_t fp, long offset, int whence)
{
int current_pos = -1;
return amp_fseek(fp, offset, whence, ¤t_pos);
}
static inline char *os_fgets(char *buffer, int size, os_file_t fp)
{
return 0;
}
static inline int os_fprintf(os_file_t fp, const char *format, ...)
{
int ret;
va_list args;
va_start(args, format);
ret = vfprintf(fp, format, args);
va_end(args);
return ret;
}
static inline int os_feof(os_file_t fp)
{
return 0;
}
static inline int os_ferror(os_file_t fp)
{
return 0;
}
static inline int os_fclose(os_file_t fp)
{
return amp_fclose(fp);
}
static inline int os_access(const char *filename, int mode)
{
os_file_t fp = os_fopen(filename, "r");
if (!fp)
return -1;
os_fclose(fp);
return 0;
}
static inline int os_remove(const char *filename)
{
return amp_remove(filename);
}
static inline int os_message_queue_send(os_message_queue_t mq, void *msg,
unsigned int size, unsigned int timeout)
{
return amp_queue_send(mq, msg, size, timeout);
}
static inline int os_message_queue_recv(os_message_queue_t mq, void *msg,
unsigned int size, unsigned int timeout)
{
return amp_queue_recv(mq, msg, size, timeout);
}
static inline os_message_queue_t os_message_queue_create(int count, int size)
{
return amp_queue_create(count, size);
}
static inline int os_message_queue_free(os_message_queue_t mq)
{
return amp_queue_delete(mq);
}
static inline int os_event_post(uint16_t type, uint16_t code, int value)
{
return -1;
}
static inline int os_event_register(uint16_t type, void *cb, void *data)
{
return -1;
}
static inline int os_event_unregister(uint16_t type, void *cb, void *data)
{
return -1;
}
static inline int os_mutex_lock(os_mutex_t mutex, unsigned int timeout)
{
amp_mutex_lock(mutex);
return 0;
}
static inline int os_mutex_unlock(os_mutex_t mutex)
{
amp_mutex_unlock(mutex);
return 0;
}
static inline os_mutex_t os_mutex_new(void)
{
return amp_mutex_create();
}
static inline void os_mutex_free(os_mutex_t mutex)
{
amp_mutex_destroy(mutex);
}
static inline int os_sem_is_valid(os_sem_t sem)
{
return 1;
}
static inline int os_sem_wait(os_sem_t sem, unsigned int timeout)
{
return amp_semaphore_wait(sem, timeout);
}
static inline void os_sem_signal(os_sem_t sem)
{
amp_semaphore_post(sem);
}
static inline void os_sem_signal_all(os_sem_t sem)
{
amp_semaphore_post(sem);
}
static inline os_sem_t os_sem_new(int count)
{
return amp_semaphore_create();
}
static inline void os_sem_free(os_sem_t sem)
{
amp_semaphore_destroy(sem);
}
static inline int os_timer_change(os_timer_t timer, int internal_ms)
{
return -1;
}
static inline int os_timer_start(os_timer_t timer)
{
return -1;
}
static inline int os_timer_stop(os_timer_t timer)
{
return -1;
}
static inline os_timer_t os_timer_new(void (*func)(void *, void *), void *arg,
int internal_ms, int repeat, unsigned char auto_run)
{
return NULL;
}
static inline void os_timer_free(os_timer_t timer)
{
}
static inline int os_task_create(os_task_t *task, const char *name,
void *(*fn)(void *), void *arg, int stack_size, int pri)
{
amp_os_thread_param_t task_params = {0};
int stack_used = stack_size;
task_params.name = name;
task_params.priority = pri;
task_params.stack_size = stack_size;
return amp_thread_create(task, fn, arg, &task_params, &stack_used);
}
static inline int os_task_exit(os_task_t task)
{
return amp_thread_delete(task);
}
static inline const char *os_partition_name(int pt)
{
return NULL;
}
static inline int os_partition_size(int pt)
{
return -1;
}
static inline int os_partition_read(int pt, uint32_t *offset, uint8_t *buffer, uint32_t len)
{
return -1;
}
static inline int os_partition_write(int pt, uint32_t *offset, const uint8_t *buffer , uint32_t len)
{
return -1;
}
static inline int os_partition_erase(int pt, uint32_t offset, uint32_t len)
{
return -1;
}
#endif /* __UVOICE_AMP_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/internal/uvoice_amp.h
|
C
|
apache-2.0
| 7,872
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifndef __UVOICE_AOS_H__
#define __UVOICE_AOS_H__
#include <fcntl.h>
#include "aos/kv.h"
#include "aos/vfs.h"
#include <aos/kernel.h>
typedef aos_dir_t os_dir_t;
typedef aos_dirent_t os_dirent_t;
typedef int os_file_t;
typedef aos_queue_t os_message_queue_t;
typedef aos_mutex_t os_mutex_t;
typedef aos_sem_t os_sem_t;
typedef aos_task_t os_task_t;
typedef aos_timer_t os_timer_t;
#define OS_SEEK_SET SEEK_SET
#define OS_SEEK_CUR SEEK_CUR
#define OS_SEEK_END SEEK_END
#define OS_F_OK F_OK
#define OS_X_OK X_OK
#define OS_W_OK W_OK
#define OS_R_OK R_OK
#define OS_FILE_OPEN_FAIL(stream) (stream <= 0)
#define OS_FILE_OPENING(stream) (stream > 0)
#define OS_FILE_CLOSED (0)
#define OS_WAIT_FOREVER AOS_WAIT_FOREVER
#define os_container_of(ptr, type, member) ((type *)((char *)(ptr) - offsetof(type, member)))
enum {
UVOICE_TASK_PRI_LOWEST = AOS_DEFAULT_APP_PRI + 5,
UVOICE_TASK_PRI_LOWER = AOS_DEFAULT_APP_PRI + 1,
UVOICE_TASK_PRI_NORMAL = AOS_DEFAULT_APP_PRI,
UVOICE_TASK_PRI_HIGHER = AOS_DEFAULT_APP_PRI - 1,
UVOICE_TASK_PRI_HIGHEST = AOS_DEFAULT_APP_PRI - 5,
};
#ifdef UVOICE_BUILD_RELEASE
#define M_LOGD(fmt, ...)
#else
#define M_LOGD(fmt, ...) aos_printf("%s: " fmt, __func__, ##__VA_ARGS__)
#endif
#define M_LOGI(fmt, ...) aos_printf("%s: " fmt, __func__, ##__VA_ARGS__)
#define M_LOGW(fmt, ...) aos_printf("%s: " fmt, __func__, ##__VA_ARGS__)
#define M_LOGE(fmt, ...) aos_printf("%s: " fmt, __func__, ##__VA_ARGS__)
#define M_LOGR(fmt, ...) aos_printf(fmt, ##__VA_ARGS__)
#define AFM_MAIN 0x1
#define AFM_EXTN 0x2
static inline void *snd_zalloc(size_t size, int flags)
{
void *mem = aos_malloc(size);
if (mem)
memset(mem, 0, size);
return mem;
}
static inline void snd_free(void *mem)
{
aos_free(mem);
}
static inline void *snd_realloc(void *old, size_t newsize, int flags)
{
void *mem = aos_realloc(old, newsize);
if (mem)
memset(mem, 0, newsize);
return mem;
}
static inline void os_msleep(int msec)
{
aos_msleep(msec);
}
static inline void os_usleep(int usec)
{
aos_msleep(usec / 1000);
}
static inline long long os_current_time(void)
{
return aos_now_ms();
}
static inline int os_get_mac_address(char *mac)
{
return 0;
}
static inline int os_kv_get(const char *key, void *buffer, int *len)
{
return aos_kv_get(key, buffer, len);
}
static inline int os_kv_set(const char *key, const void *buffer, int len, int sync)
{
return aos_kv_set(key, buffer, len, sync);
}
static inline int os_mkdir(const char *path)
{
return aos_mkdir(path);
}
static inline os_dir_t *os_opendir(const char *path)
{
return aos_opendir(path);
}
static inline os_dirent_t *os_readdir(os_dir_t *dir)
{
return aos_readdir(dir);
}
static inline int os_closedir(os_dir_t *dir)
{
return aos_closedir(dir);
}
static inline os_file_t os_fopen(const char *filename, const char *mode)
{
int flags = 0;
if (!strcmp(mode, "r") || !strcmp(mode, "rb")) {
flags = O_RDONLY;
} else if (!strcmp(mode, "w+") || !strcmp(mode, "wb+")) {
flags = O_RDWR | O_CREAT;
}
return aos_open(filename, flags);
}
static inline size_t os_fread(void *buffer, size_t size, size_t count, os_file_t fp)
{
return aos_read(fp, buffer, size * count);
}
static inline size_t os_fwrite(const void *buffer, size_t size, size_t count, os_file_t fp)
{
return aos_write(fp, buffer, size * count);
}
static inline long os_ftell(os_file_t fp)
{
return -1;
}
static inline long os_fseek(os_file_t fp, long offset, int whence)
{
return aos_lseek(fp, offset, whence);
}
static inline char *os_fgets(char *buffer, int size, os_file_t fp)
{
return 0;
}
static inline int os_fprintf(os_file_t fp, const char *format, ...)
{
return 0;
}
static inline int os_feof(os_file_t fp)
{
return 0;
}
static inline int os_ferror(os_file_t fp)
{
return 0;
}
static inline int os_fclose(os_file_t fp)
{
return aos_close(fp);
}
static inline int os_access(const char *filename, int mode)
{
return aos_access(filename, mode);
}
static inline int os_remove(const char *filename)
{
return aos_remove(filename);
}
static inline int os_message_queue_send(os_message_queue_t mq, void *msg, unsigned int size, unsigned int timeout)
{
return aos_queue_send(&mq, msg, size);
}
static inline int os_message_queue_recv(os_message_queue_t mq, void *msg, unsigned int size, unsigned int timeout)
{
return aos_queue_recv(&mq, timeout, msg, &size);
}
static inline os_message_queue_t os_message_queue_create(int count, int size)
{
aos_queue_t q = NULL;
aos_queue_new(&q, NULL, size * count, size);
return q;
}
static inline int os_message_queue_free(os_message_queue_t mq)
{
aos_queue_free(&mq);
return 0;
}
static inline int os_event_post(uint16_t type, uint16_t code, int value)
{
return -1;
}
static inline int os_event_register(uint16_t type, void *cb, void *data)
{
return -1;
}
static inline int os_event_unregister(uint16_t type, void *cb, void *data)
{
return -1;
}
static inline int os_mutex_lock(os_mutex_t mutex, unsigned int timeout)
{
aos_mutex_lock(&mutex, timeout);
return 0;
}
static inline int os_mutex_unlock(os_mutex_t mutex)
{
aos_mutex_unlock(&mutex);
return 0;
}
static inline os_mutex_t os_mutex_new(void)
{
os_mutex_t mutex;
aos_mutex_new(&mutex);
return mutex;
}
static inline void os_mutex_free(os_mutex_t mutex)
{
aos_mutex_free(&mutex);
}
static inline int os_sem_is_valid(os_sem_t sem)
{
return 1;
}
static inline int os_sem_wait(os_sem_t sem, unsigned int timeout)
{
return aos_sem_wait(&sem, timeout);
}
static inline void os_sem_signal(os_sem_t sem)
{
aos_sem_signal(&sem);
}
static inline void os_sem_signal_all(os_sem_t sem)
{
aos_sem_signal_all(&sem);
}
static inline os_sem_t os_sem_new(int count)
{
os_sem_t sem;
aos_sem_new(&sem, 0);
return sem;
}
static inline void os_sem_free(os_sem_t sem)
{
aos_sem_free(&sem);
}
static inline int os_task_create(os_task_t *task, const char *name, void (*fn)(void *), void *arg, int stack_size,
int pri)
{
return aos_task_new_ext(task, name, fn, arg, stack_size, pri);
}
static inline int os_task_exit(os_task_t task)
{
aos_task_exit(0);
return 0;
}
static inline const char *os_partition_name(int pt)
{
return NULL;
}
static inline int os_partition_size(int pt)
{
return -1;
}
static inline int os_partition_read(int pt, uint32_t *offset, uint8_t *buffer, uint32_t len)
{
return -1;
}
static inline int os_partition_write(int pt, uint32_t *offset, const uint8_t *buffer, uint32_t len)
{
return -1;
}
static inline int os_partition_erase(int pt, uint32_t offset, uint32_t len)
{
return -1;
}
#endif /* __UVOICE_AOS_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/internal/uvoice_aos.h
|
C
|
apache-2.0
| 6,875
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifndef __UVOICE_AUDIO_H__
#define __UVOICE_AUDIO_H__
#define VOLUME_LEVEL_MIN 0
#define VOLUME_LEVEL_MAX 10
typedef enum {
SND_DEVICE_NONE = 0,
SND_DEVICE_MIN = SND_DEVICE_NONE,
SND_DEVICE_OUT_BEGIN,
SND_DEVICE_OUT_SPEAKER = SND_DEVICE_OUT_BEGIN,
SND_DEVICE_OUT_HEADPHONE,
SND_DEVICE_OUT_RECEIVER,
SND_DEVICE_OUT_HEADSET,
SND_DEVICE_OUT_SPEAKER_AND_HEADPHONE,
SND_DEVICE_OUT_SPEAKER_AND_HEADSET,
SND_DEVICE_OUT_RECEIVER_AND_HEADPHONE,
SND_DEVICE_OUT_RECEIVER_AND_HEADSET,
SND_DEVICE_OUT_END = SND_DEVICE_OUT_RECEIVER_AND_HEADSET,
SND_DEVICE_IN_BEGIN,
SND_DEVICE_IN_PRIMARY_MIC = SND_DEVICE_IN_BEGIN,
SND_DEVICE_IN_SECONDARY_MIC,
SND_DEVICE_IN_TERTIARY_MIC,
SND_DEVICE_IN_QUATERNARY_MIC,
SND_DEVICE_IN_QUINARY_MIC,
SND_DEVICE_IN_HEADSET_MIC,
SND_DEVICE_IN_END = SND_DEVICE_IN_HEADSET_MIC,
SND_DEVICE_MAX = SND_DEVICE_IN_END,
} snd_device_t;
typedef enum {
PCM_MSG_TX_WAITING = 0,
PCM_MSG_RX_WAITING,
PCM_MSG_WRITE_DONE, /* write buffer copied */
PCM_MSG_READ_DONE, /* read buffer filled */
PCM_MSG_TX_UNDERRUN,
PCM_MSG_TX_OVERRUN,
PCM_MSG_RX_UNDERRUN,
PCM_MSG_RX_OVERRUN,
} pcm_message_t;
enum {
PCM_STATE_CLOSED = 0,
PCM_STATE_SETUP,
PCM_STATE_OPEN,
PCM_STATE_RUNNING,
PCM_STATE_STANDBY,
};
#ifdef UVOICE_ON_XR871
#include "audio/pcm/audio_pcm.h"
#include "audio/manager/audio_manager.h"
#else
#define PCM_OUT 0
#define PCM_IN 1
enum pcm_format {
PCM_FORMAT_INVALID = -1,
PCM_FORMAT_S16_LE = 0, /* 16-bit signed */
PCM_FORMAT_S32_LE, /* 32-bit signed */
PCM_FORMAT_S8, /* 8-bit signed */
PCM_FORMAT_S24_LE, /* 24-bits in 4-bytes */
PCM_FORMAT_S24_3LE, /* 24-bits in 3-bytes */
PCM_FORMAT_MAX,
};
struct pcm_config {
int rate;
int channels;
int period_size;
int period_count;
enum pcm_format format;
};
#endif
struct pcm_device {
struct pcm_config config;
uint8_t dir:1;
uint8_t card:2;
uint8_t state:3;
void *private_data;
};
struct external_pa_info {
int used;
int active_high;
int pin;
int delay_ms;
};
int audio_pcm_notify(pcm_message_t msg);
#ifdef UVOICE_BUILD_RELEASE
#define snd_debug(fmt, ...)
#define snd_info(fmt, ...)
#else
#define snd_debug(fmt, ...) printf(fmt, ##__VA_ARGS__)
#define snd_info(fmt, ...) printf(fmt, ##__VA_ARGS__)
#endif
#define snd_warn(fmt, ...) printf(fmt, ##__VA_ARGS__)
#define snd_err(fmt, ...) printf(fmt, ##__VA_ARGS__)
#endif /* __UVOICE_AUDIO_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/internal/uvoice_audio.h
|
C
|
apache-2.0
| 2,663
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifndef __UVOICE_CODEC_H__
#define __UVOICE_CODEC_H__
int wave_encoder_create(media_encoder_t *mencoder);
int wave_encoder_release(media_encoder_t *mencoder);
int wave_decoder_create(media_decoder_t *mdecoder);
int wave_decoder_release(media_decoder_t *mdecoder);
int mad_decoder_create(media_decoder_t *mdecoder);
int mad_decoder_release(media_decoder_t *mdecoder);
int pvmp3_decoder_create(media_decoder_t *mdecoder);
int pvmp3_decoder_release(media_decoder_t *mdecoder);
int helixmp3_decoder_create(media_decoder_t *mdecoder);
int helixmp3_decoder_release(media_decoder_t *mdecoder);
int helixaac_decoder_create(media_decoder_t *mdecoder);
int helixaac_decoder_release(media_decoder_t *mdecoder);
int ogg_decoder_create(media_decoder_t *mdecoder);
int ogg_decoder_release(media_decoder_t *mdecoder);
int opus_encoder_create(media_encoder_t *mencoder);
int opus_encoder_release(media_encoder_t *mencoder);
int opus_decoder_create(media_decoder_t *mdecoder);
int opus_decoder_release(media_decoder_t *mdecoder);
int spx_encoder_create(media_encoder_t *mencoder);
int spx_encoder_release(media_encoder_t *mencoder);
int spx_decoder_create(media_decoder_t *mdecoder);
int spx_decoder_release(media_decoder_t *mdecoder);
int flac_decoder_create(media_decoder_t *mdecoder);
int flac_decoder_release(media_decoder_t *mdecoder);
int amr_encoder_create(media_encoder_t *mencoder);
int amr_encoder_release(media_encoder_t *mencoder);
int amr_decoder_create(media_decoder_t *mdecoder);
int amr_decoder_release(media_decoder_t *mdecoder);
int amrwb_encoder_create(media_encoder_t *mencoder);
int amrwb_encoder_release(media_encoder_t *mencoder);
int amrwb_decoder_create(media_decoder_t *mdecoder);
int amrwb_decoder_release(media_decoder_t *mdecoder);
#endif /* __UVOICE_CODEC_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/internal/uvoice_codec.h
|
C
|
apache-2.0
| 1,855
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
* SPDX-License-Identifier: Apache-2.0
*
*/
#ifndef __UVOICE_COMMON_H__
#define __UVOICE_COMMON_H__
typedef enum {
MEDIA_TYPE_UNKNOWN = 0,
MEDIA_TYPE_FILE,
MEDIA_TYPE_HTTP,
MEDIA_TYPE_FLASH,
MEDIA_TYPE_MEM,
MEDIA_TYPE_STREAM,
MEDIA_TYPE_COUNT,
} media_type_t;
typedef struct {
int rate;
int channels;
int bits;
int frames;
} media_pcminfo_t;
typedef struct {
uint8_t *buffer;
uint8_t *buffer_end;
uint8_t *rd_ptr;
uint8_t *wr_ptr;
int32_t free_size;
int32_t dirty_size;
} uvoice_ringbuff_t;
#endif /* __UVOICE_COMMON_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/internal/uvoice_common.h
|
C
|
apache-2.0
| 664
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifndef __UVOICE_CONFIG_H__
#define __UVOICE_CONFIG_H__
/* cache type select
* 0 - no cache
* 1 - cache to file (fs required)
* 2 - cache to memory
*/
#define PLAYER_CACHE_TYPE 2
#ifdef __os_linux__
/* set file path for cache type 1 */
#define PLAYER_CACHE_FILE_PATH "./media_cache"
#else
/* set file path for cache type 1 */
#define PLAYER_CACHE_FILE_PATH "/sdcard/media_cache"
#endif
/* set memory size (KB) for cache type 2 */
#ifdef __os_linux__
#define PLAYER_CACHE_MEM_SIZE 80//10240
#else
#ifdef UVOICE_ON_BK7251
#define PLAYER_CACHE_MEM_SIZE 120
#else
#ifdef MUSICBOX_APP
#define PLAYER_CACHE_MEM_SIZE 50
#else
#define PLAYER_CACHE_MEM_SIZE 40
#endif
#endif
#endif /* __os_linux__ */
#ifdef __os_linux__
/* select directory for music download */
#define PLAYER_SOURCE_DLOAD_DIR "../../../../../Music"
/* select directory for music list file */
#define PLAYER_SOURCE_LIST_DIR "../../../../../Music"
#define PLAYER_SOURCE_LIST_NAME "source.list"
/* select directory for temporary use */
#define PLAYER_LOCAL_TEMP_DIR "./temp"
#else
/* select directory for music download */
#define PLAYER_SOURCE_DLOAD_DIR "/sdcard/music"
/* select directory for music list file */
#define PLAYER_SOURCE_LIST_DIR "/sdcard/music"
#define PLAYER_SOURCE_LIST_NAME "source.list"
/* select directory for temporary use */
#define PLAYER_LOCAL_TEMP_DIR "/sdcard/temp"
#endif
/* 0 - disable stere, 1 - enable stere */
#if defined(STORYPLAYER_APP) || defined(VOICELOUDER_APP)
#define PLAYER_STERE_ENABLE 0
#else
#define PLAYER_STERE_ENABLE 1
#endif
#endif /* __UVOICE_CONFIG_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/internal/uvoice_config.h
|
C
|
apache-2.0
| 1,668
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifndef __UVOICE_FORMAT_H__
#define __UVOICE_FORMAT_H__
int mp3_id3v1_parse(media_info_t *info, unsigned char *data, int size);
int format_parse_byname(char *name, media_format_t *format);
bool wav_format_check(char *buffer, int size);
bool mp3_format_check(char *data, int size);
bool aac_format_check(char *buffer, int size);
bool m4a_format_check(char *buffer, int size);
bool ogg_format_check(char *data, int size);
bool wma_format_check(char *buffer, int size);
bool amr_format_check(char *buffer, int size);
bool amrwb_format_check(char *data, int size);
bool flac_format_check(char *buffer, int size);
#endif /* __UVOICE_FORMAT_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/internal/uvoice_format.h
|
C
|
apache-2.0
| 711
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifndef __UVOICE_LINUX_H__
#define __UVOICE_LINUX_H__
#include <stdint.h>
#include <stdio.h>
#include <stddef.h>
#include <stdarg.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <dirent.h>
#include <semaphore.h>
#include <pthread.h>
typedef DIR os_dir_t;
typedef struct dirent os_dirent_t;
typedef FILE * os_file_t;
typedef int os_queue_t;
typedef pthread_mutex_t * os_mutex_t;
typedef sem_t * os_sem_t;
typedef pthread_t os_task_t;
typedef struct timer_list * os_timer_t;
#define OS_SEEK_SET SEEK_SET
#define OS_SEEK_CUR SEEK_CUR
#define OS_SEEK_END SEEK_END
#define OS_F_OK F_OK
#define OS_X_OK X_OK
#define OS_W_OK W_OK
#define OS_R_OK R_OK
#define OS_FILE_OPEN_FAIL(stream) (stream == NULL)
#define OS_FILE_OPENING(stream) (stream != NULL)
#define OS_FILE_CLOSED (NULL)
#define OS_WAIT_FOREVER 0xffffffffu
#define os_container_of(ptr, type, member) \
((type *)((char *)(ptr) - offsetof(type, member)))
enum {
UVOICE_TASK_PRI_DEFAULT = 0,
UVOICE_TASK_PRI_IDLE,
UVOICE_TASK_PRI_LOWEST,
UVOICE_TASK_PRI_LOWER,
UVOICE_TASK_PRI_NORMAL,
UVOICE_TASK_PRI_HIGHER,
UVOICE_TASK_PRI_HIGHEST,
UVOICE_TASK_PRI_REALTIME,
};
#ifdef UVOICE_BUILD_RELEASE
#define M_LOGD(fmt, ...)
#else
#define M_LOGD(fmt, ...) printf("%s: "fmt, __func__, ##__VA_ARGS__)
#endif
#define M_LOGI(fmt, ...) printf("%s: "fmt, __func__, ##__VA_ARGS__)
#define M_LOGW(fmt, ...) printf("%s: "fmt, __func__, ##__VA_ARGS__)
#define M_LOGE(fmt, ...) printf("%s: "fmt, __func__, ##__VA_ARGS__)
#define M_LOGR(fmt, ...) printf(fmt, ##__VA_ARGS__)
#define AFM_MAIN 0x1
#define AFM_EXTN 0x2
static inline void *snd_zalloc(size_t size, int flags)
{
void *mem = malloc(size);
if (mem)
memset(mem, 0, size);
return mem;
}
static inline void snd_free(void *mem)
{
free(mem);
}
static inline void *snd_realloc(void *old, size_t newsize, int flags)
{
void *mem = realloc(old, newsize);
if (mem)
memset(mem, 0, newsize);
return mem;
}
static inline void os_msleep(int msec)
{
usleep(msec * 1000);
}
static inline void os_usleep(int usec)
{
usleep(usec);
}
static inline long long os_current_time(void)
{
struct timeval tt;
gettimeofday(&tt, NULL);
return tt.tv_sec * 1000 + tt.tv_usec / 1000;
}
static inline int os_get_mac_address(char *mac)
{
return 0;
}
static inline int os_kv_get(const char *key, void *buffer, int *len)
{
FILE *fp = fopen(key, "rb");
if (!fp)
return -ENOENT;
fread(buffer, *len, 1, fp);
if (ferror(fp))
return -EIO;
fclose(fp);
return 0;
}
static inline int os_kv_set(const char *key, const void *buffer, int len, int sync)
{
FILE *fp = fopen(key, "wb+");
if (!fp)
return -ENOENT;
fwrite(buffer, len, 1, fp);
if (ferror(fp))
return -EIO;
fclose(fp);
return 0;
}
static inline int os_mkdir(const char *path)
{
return mkdir(path, S_IRWXU); /* posix api, <dirent.h> required */
}
static inline os_dir_t *os_opendir(const char *path)
{
return opendir(path);
}
static inline os_dirent_t *os_readdir(os_dir_t *dir)
{
return readdir(dir);
}
static inline int os_closedir(os_dir_t *dir)
{
return closedir(dir);
}
static inline int os_access(const char *filename, int mode)
{
return access(filename, mode);
}
static inline os_file_t os_fopen(const char *filename, const char *mode)
{
FILE *fp = fopen(filename, mode);
return (os_file_t)fp;
}
static inline size_t os_fread(void *buffer, size_t size, size_t count, os_file_t fp)
{
return fread(buffer, size, count, fp);
}
static inline size_t os_fwrite(const void *buffer, size_t size, size_t count, os_file_t fp)
{
return fwrite(buffer, size, count, fp);
}
static inline long os_ftell(os_file_t fp)
{
return ftell(fp);
}
static inline long os_fseek(os_file_t fp, long offset, int whence)
{
return fseek(fp, offset, whence);
}
static inline char *os_fgets(char *buffer, int size, os_file_t fp)
{
return fgets(buffer, size, fp);
}
static inline int os_fprintf(os_file_t fp, const char *format, ...)
{
int ret;
va_list args;
va_start(args, format);
ret = vfprintf(fp, format, args);
va_end(args);
return ret;
}
static inline int os_feof(os_file_t fp)
{
return feof(fp);
}
static inline int os_ferror(os_file_t fp)
{
return ferror(fp);
}
static inline int os_fclose(os_file_t fp)
{
return fclose(fp);
}
static inline int os_remove(const char *filename)
{
return remove(filename);
}
static inline int os_queue_send(os_queue_t *queue, void *msg, unsigned int size)
{
return -1;
}
static inline int os_queue_recv(os_queue_t *queue, unsigned int ms, void *msg,
unsigned int *size)
{
return -1;
}
static inline int os_queue_new(os_queue_t *queue, void *buffer, unsigned int size, int msg_size)
{
return -1;
}
static inline void os_queue_free(os_queue_t *queue)
{
}
static inline int os_event_post(uint16_t type, uint16_t code, int value)
{
return -1;
}
static inline int os_event_register(uint16_t type, void *cb, void *data)
{
return -1;
}
static inline int os_event_unregister(uint16_t type, void *cb, void *data)
{
return -1;
}
static inline int os_mutex_lock(os_mutex_t mutex, unsigned int timeout)
{
return pthread_mutex_lock(mutex);
}
static inline int os_mutex_unlock(os_mutex_t mutex)
{
return pthread_mutex_unlock(mutex);
}
static inline os_mutex_t os_mutex_new(void)
{
pthread_mutex_t *p_mutex = snd_zalloc(sizeof(pthread_mutex_t), AFM_EXTN);
if (!p_mutex)
return NULL;
if (pthread_mutex_init(p_mutex, NULL)) {
snd_free(p_mutex);
return NULL;
}
return p_mutex;
}
static inline void os_mutex_free(os_mutex_t mutex)
{
pthread_mutex_destroy(mutex);
snd_free(mutex);
}
static inline int os_sem_is_valid(os_sem_t sem)
{
return 1;
}
static inline int os_sem_wait(os_sem_t sem, unsigned int timeout)
{
struct timespec ts;
struct timeval tt;
gettimeofday(&tt, NULL);
ts.tv_sec = tt.tv_sec + timeout / 1000;
ts.tv_nsec = tt.tv_usec * 1000 + (timeout % 1000) * 1000 * 1000;
ts.tv_sec += ts.tv_nsec / (1000 * 1000 * 1000);
ts.tv_nsec %= (1000 * 1000 * 1000);
if (timeout == OS_WAIT_FOREVER)
return sem_wait(sem);
return sem_timedwait(sem, &ts);
}
static inline void os_sem_signal(os_sem_t sem)
{
sem_post(sem);
}
static inline void os_sem_signal_all(os_sem_t sem)
{
//TODO: Fix
sem_post(sem);
}
static inline os_sem_t os_sem_new(int count)
{
sem_t *sem = snd_zalloc(sizeof(sem_t), AFM_MAIN);
if (!sem)
return NULL;
if (sem_init(sem, 0, count)) {
snd_free(sem);
return NULL;
}
return sem;
}
static inline void os_sem_free(os_sem_t sem)
{
sem_destroy(sem);
snd_free(sem);
}
static inline int os_timer_change(os_timer_t timer, int internal_ms)
{
return -1;
}
static inline int os_timer_start(os_timer_t timer)
{
return -1;
}
static inline int os_timer_stop(os_timer_t timer)
{
return -1;
}
static inline os_timer_t os_timer_new(void (*func)(void *, void *), void *arg,
int internal_ms, int repeat, unsigned char auto_run)
{
return NULL;
}
static inline void os_timer_free(os_timer_t timer)
{
}
static inline int os_task_create(os_task_t *task, const char *name,
void *(*fn)(void *), void *arg, int stack_size, int pri)
{
pthread_attr_t attr;
size_t def_stack_size = 0;
int ret;
pthread_attr_init(&attr);
if (!strcmp(name, "uvoice_event_task"))
pthread_attr_setschedpolicy(&attr, SCHED_FIFO);
pthread_attr_getstacksize(&attr, &def_stack_size);
if (def_stack_size < stack_size)
pthread_attr_setstacksize(&attr, stack_size);
ret = pthread_create(task, &attr, fn, arg);
pthread_attr_destroy(&attr);
return ret;
}
static inline int os_task_exit(os_task_t task)
{
pthread_exit(NULL);
}
static inline const char *os_partition_name(int pt)
{
return NULL;
}
static inline int os_partition_size(int pt)
{
return -1;
}
static inline int os_partition_read(int pt, uint32_t *offset, uint8_t *buffer, uint32_t len)
{
return -1;
}
static inline int os_partition_write(int pt, uint32_t *offset, const uint8_t *buffer , uint32_t len)
{
return -1;
}
static inline int os_partition_erase(int pt, uint32_t offset, uint32_t len)
{
return -1;
}
#endif /* __UVOICE_LINUX_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/internal/uvoice_linux.h
|
C
|
apache-2.0
| 8,223
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifndef __UVOICE_LIST_H__
#define __UVOICE_LIST_H__
typedef struct uvoice_list {
struct uvoice_list *prev;
struct uvoice_list *next;
} uvoice_list_t;
#define UVOICE_LIST_INIT(list) \
{&(list), &(list)}
#define uvoice_list_for_each_entry(head, node, type, member) \
for (node = os_container_of((head)->next, type, member); \
&node->member != (head); \
node = os_container_of(node->member.next, type, member))
#define uvoice_list_for_each_entry_safe(head, temp, node, type, member) \
for (node = os_container_of((head)->next, type, member), \
temp = (head)->next ? (head)->next->next : NULL; \
&node->member != (head); \
node = os_container_of(temp, type, member), temp = temp ? temp->next : NULL)
static inline void uvoice_list_add(uvoice_list_t *node, uvoice_list_t *head)
{
uvoice_list_t *next = head->next;
node->next = next;
node->prev = head;
head->next = node;
next->prev = node;
}
static inline void uvoice_list_add_tail(uvoice_list_t *node, uvoice_list_t *head)
{
uvoice_list_t *prev = head->prev;
node->next = head;
node->prev = prev;
prev->next = node;
head->prev = node;
}
static inline int uvoice_list_entry_count(uvoice_list_t *head)
{
uvoice_list_t *pos = head;
int count = 0;
while (pos->next != head) {
pos = pos->next;
count++;
}
return count;
}
static inline int uvoice_list_empty(uvoice_list_t *head)
{
return head->next == head;
}
static inline void uvoice_list_del(uvoice_list_t *node)
{
uvoice_list_t *prev = node->prev;
uvoice_list_t *next = node->next;
prev->next = next;
next->prev = prev;
}
static inline void uvoice_list_init(uvoice_list_t *head)
{
head->next = head->prev = head;
}
#endif /* __UVOICE_LIST_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/internal/uvoice_list.h
|
C
|
apache-2.0
| 1,833
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifndef __UVOICE_MESSAGE_H__
#define __UVOICE_MESSAGE_H__
typedef struct {
char *filename;
int id;
int qid;
int recv_waiting;
os_sem_t recv_sem;
os_mutex_t lock;
} uvoice_msgqueue_t;
int uvoice_msgqueue_recv(uvoice_msgqueue_t *msgqueue, int type, void *msg, int size, int timeout);
int uvoice_msgqueue_send(uvoice_msgqueue_t *msgqueue, void *msg, int size, int block);
uvoice_msgqueue_t *uvoice_msgqueue_create(char *filename, int id);
int uvoice_msgqueue_release(uvoice_msgqueue_t *msgqueue);
#endif /* __UVOICE_MESSAGE_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/internal/uvoice_message.h
|
C
|
apache-2.0
| 604
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifndef __UVOICE_OS_H__
#define __UVOICE_OS_H__
#ifndef __os_linux__
#define __os_alios_things__
#endif
#ifndef MIN
#define MIN(a,b) ((a)<(b) ? (a):(b))
#endif
#ifndef MAX
#define MAX(a,b) ((a)>(b) ? (a):(b))
#endif
#ifndef ARRAY_SIZE
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
#endif
#define UINT32_BIG_2_LIT(val) \
((val&0xFF)<<24) | ((val&0xFF00)<<8) | ((val&0xFF0000)>>8) | ((val&0xFF000000)>>24)
#ifndef bool
#define bool char
#endif
#ifndef true
#define true 1
#endif
#ifndef false
#define false 0
#endif
#define snd_memcpy(dest, src, length) \
{ \
if ((dest) != (src) && length > 0) \
memcpy(dest, src, length); \
}
#define snd_memmove(dest, src, length) \
{ \
if ((dest) != (src)) \
memmove(dest, src, length); \
}
#ifdef __os_alios_things__
#include "uvoice_aos.h"
#elif defined(__os_linux__)
#include "uvoice_linux.h"
#else
#error OS type not specified !
#endif
#endif /* __UVOICE_OS_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/internal/uvoice_os.h
|
C
|
apache-2.0
| 1,036
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifndef __UVOICE_PCM_H__
#define __UVOICE_PCM_H__
/*
* Set volume.
*
* Return:
* 0 -- success or unsupport
* -1 -- failed
*/
int uvoice_set_volume(snd_device_t device, int volume);
/*
* Select audio output/input device, return 0 if device switch unsupported.
*
* Return:
* 0 -- success or unsupport
* -1 -- failed
*/
int uvoice_set_path(struct pcm_device *pcm, snd_device_t device);
/*
* Configure external pa info if used.
*
* Return:
* 0 -- success or no external pa
* -1 -- failed
*/
int uvoice_extpa_config(struct external_pa_info *info);
/*
* Mute audio output/input.
*
* Return:
* 0 -- success or unsupport
* -1 -- failed
*/
int uvoice_dev_mute(struct pcm_device *pcm, snd_device_t device, int mute);
/*
* Called by audio driver to post some message if necessary.
*/
void uvoice_pcm_notify(pcm_message_t msg);
/*
* Update default pcm params to adapt custom hardware.
* you can set write/read buffer length by configure
* pcm->config.period_size
*
* Return:
* 0 -- success
* -1 -- failed
*/
int uvoice_pcm_setup(struct pcm_device *pcm);
/*
* Open pcm device with configured pcm.
*
* Return:
* 0 -- success
* -1 -- failed
*/
int uvoice_pcm_open(struct pcm_device *pcm);
/*
* Read data in. Block reading if data not ready.
*
* Return read length, or negative if failed.
*/
int uvoice_pcm_read(struct pcm_device *pcm, uint8_t *buffer, int nbytes);
/*
* Block write if free dma buffer not ready, otherwise,
* please return after copied.
*
* Return writen length, or negative if failed.
*
*/
int uvoice_pcm_write(struct pcm_device *pcm, uint8_t *buffer, int nbytes);
int uvoice_pcm_silence(struct pcm_device *pcm);
/*
* Flush remaining data in dma buffer
*/
int uvoice_pcm_flush(struct pcm_device *pcm);
/*
* close pcm device, release dma
*
* Return:
* 0 -- success
* -1 -- failed
*
*/
int uvoice_pcm_close(struct pcm_device *pcm);
/*
* Init pcm module
*
* Return:
* 0 -- success
* -1 -- failed
*
*/
int uvoice_pcm_init(void);
#endif
|
YifuLiu/AliOS-Things
|
components/uvoice/internal/uvoice_pcm.h
|
C
|
apache-2.0
| 2,107
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifndef __UVOICE_PLAY_H__
#define __UVOICE_PLAY_H__
typedef enum {
PLAYER_MSG_PCM_INFO = 0,
PLAYER_MSG_MEDIA_INFO,
PLAYER_MSG_SEEK_DONE,
PLAYER_MSG_LOAD_BLOCK,
} player_message_t;
typedef enum {
STREAM_MGR_STAT_IDLE = 0,
STREAM_MGR_STAT_READY,
STREAM_MGR_STAT_RUNNING,
STREAM_MGR_STAT_STOP,
} stream_mgr_state_t;
typedef enum {
FADE_NOP = 0,
FADE_IN_END,
FADE_OUT_END,
FADE_IN,
FADE_OUT,
} fade_state_t;
typedef enum {
SEEK_NOP = 0,
SEEK_PREPARE,
SEEK_START,
SEEK_COMPLETE,
} seek_state_t;
typedef enum {
PLAYER_CLOSE = 0,
PLAYER_PAUSE,
PLAYER_RESUME,
PLAYER_START,
PLAYER_NEXT,
PLAYER_STOP,
PLAYER_COMPLETE,
PLAYER_SEEK_BEGIN,
PLAYER_SEEK,
PLAYER_SEEK_END,
PLAYER_RELOAD,
PLAYER_DLOAD,
PLAYER_DLOAD_ABORT,
PLAYER_UNBLOCK,
PLAYER_CONFIGURE,
STREAM_MGR_START,
STREAM_MGR_STOP,
} player_action_t;
typedef struct {
int dirty_cache_size;
int avail_cache_size;
int seek_forward_limit;
int seek_backward_limit;
} cache_info_t;
typedef struct {
media_format_t format;
uint8_t *buffer_out;
int buffer_out_size;
int unproc_size;
int input_size;
uint8_t initialized:1;
uint8_t running:1;
uint8_t stere_enable:1;
uint8_t pos_rebase:1;
uint32_t rebase_offset;
int (*decode)(void *priv, uint8_t *buffer, int nbytes);
int (*action)(void *priv, player_action_t action, void *arg);
int (*message)(void *priv, player_message_t msg, void *arg);
int (*output)(void *priv, uint8_t *buffer, int nbytes);
int (*reset)(void *priv);
void *decoder;
void *priv;
} media_decoder_t;
typedef struct {
media_type_t type;
uint8_t *buffer;
int buffer_size;
int buffer_dirty_size;
int rebase_request;
int rebase_offset;
int (*read)(void *priv, uint8_t *buffer, int nbytes);
int (*action)(void *priv, player_action_t action, void *arg);
int (*reset)(void *priv);
int (*message)(void *priv, player_message_t msg, void *arg);
int (*get_format)(void *priv, media_format_t *format);
int (*get_mediainfo)(void *priv, media_info_t *info, media_format_t format);
int (*get_cacheinfo)(void *priv, cache_info_t *info);
void *loader;
void *priv;
} media_loader_t;
typedef struct {
uvoice_ringbuff_t rb;
uint8_t *buffer;
uint8_t *stream_pool;
int buffer_size;
int buffer_dirty_size;
int stream_pool_size;
int wr_len;
int rd_len;
uint8_t cache_enable:1;
uint8_t wr_waiting:1;
uint8_t rd_waiting:1;
uint8_t cplt_waiting:1;
uint8_t stop:1;
uint8_t abort:1;
media_format_t format;
os_sem_t cplt_sem;
os_sem_t wr_sem;
os_sem_t rd_sem;
media_decoder_t *mdecoder;
struct out_stream *out;
stream_mgr_state_t state;
os_mutex_t lock;
os_task_t task;
media_pcminfo_t pcm_info;
} stream_mgr_t;
typedef struct {
int out_scope;
int out_period_ms;
int in_scope;
int in_period_ms;
int pos;
int reset;
fade_state_t state;
os_mutex_t lock;
} fade_process_t;
typedef struct {
int offset;
int fade_request;
seek_state_t state;
} seek_process_t;
typedef struct {
int src_channels;
int dst_channels;
int src_bits;
int dst_bits;
int coeff;
uint8_t *buffer;
int buffer_size;
} format_convert_t;
typedef struct {
uint32_t pause:1;
uint32_t stop:1;
uint32_t complete:1;
uint32_t error:1;
uint32_t pcm_reset:1;
uint32_t stream_flowing:1;
uint32_t cplt_waiting:1;
uint32_t start_waiting:1;
uint32_t pause_waiting:1;
uint32_t resume_waiting:1;
uint32_t stop_waiting:1;
uint32_t sw_volume:1;
uint32_t fade_enable:1;
uint32_t fade_ignore:1;
uint32_t blocking:1;
uint32_t deep_cplt:1;
uint32_t frame_skip:1;
uint32_t out_bypass:1;
uint32_t vol_level;
fade_process_t fade;
seek_process_t seek;
media_format_t format;
media_format_t format_preferable;
media_type_t type;
player_state_t state;
long long silent_time;
int consumed_len;
int idle_period;
int standby_msec;
int reference_count;
os_mutex_t lock;
os_mutex_t vol_lock;
os_sem_t start_sem;
os_sem_t pause_sem;
os_sem_t resume_sem;
os_sem_t cplt_sem;
os_sem_t reset_sem;
os_sem_t stop_sem;
format_convert_t *convertor;
media_decoder_t *mdecoder;
media_loader_t *mloader;
stream_mgr_t *stream_mgr;
struct out_stream *out;
void *resampler;
media_info_t *media_info;
media_pcminfo_t pcm_info;
os_task_t task;
} player_t;
int media_loader_reset(media_loader_t *mloader);
media_loader_t *media_loader_create(media_type_t type, char *source);
int media_loader_release(media_loader_t *mloader);
int media_decoder_reset(media_decoder_t *mdecoder);
media_decoder_t *media_decoder_create(media_format_t format);
int media_decoder_release(media_decoder_t *mdecoder);
#endif /* __UVOICE_PLAY_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/internal/uvoice_play.h
|
C
|
apache-2.0
| 4,607
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifndef __UVOICE_RECORD_H__
#define __UVOICE_RECORD_H__
typedef enum {
RECORDER_CLOSE = 0,
RECORDER_PAUSE,
RECORDER_RESUME,
RECORDER_START,
RECORDER_STOP,
RECORDER_UPDATE_HEAD,
} recorder_action_t;
typedef struct {
media_type_t type;
uint32_t size;
int (*pack)(void *priv, uint8_t *buffer, int nbytes);
int (*update)(void *priv, uint8_t *buffer, int nbytes, int pos);
int (*action)(void *priv, recorder_action_t action, void *arg);
void *packer;
} media_packer_t;
typedef struct {
media_format_t format;
void *encoder;
void *header;
void *tail;
int header_size;
int tail_size;
uint8_t initialized:1;
uint8_t header_pack:1;
uint8_t header_cplt:1;
uint8_t running:1;
uint8_t vbr:1;
int rate;
int channels;
int bits;
int frames;
int bitrate;
int (*encode)(void *priv, uint8_t *buffer, int nbytes);
int (*header_gen)(void *priv, void *arg);
int (*header_update)(void *priv, int size);
int (*action)(void *priv, recorder_action_t action, void *arg);
} media_encoder_t;
typedef struct {
uint8_t *buffer;
uint8_t *rec_buffer;
int buffer_size;
int buffer_dirty_size;
int record_len;
int reference_count;
media_format_t format;
media_type_t type;
recorder_state_t state;
uint8_t stop:1;
uint8_t error:1;
uint8_t ns_enable:1;
uint8_t ec_enable:1;
uint8_t agc_enable:1;
uint8_t vad_enable:1;
os_mutex_t lock;
os_sem_t cplt_sem;
int src_rate;
int dst_rate;
void *resampler;
media_encoder_t *mencoder;
media_packer_t *mpacker;
struct in_stream *in;
os_task_t task;
media_pcminfo_t pcm_info;
} recorder_t;
media_packer_t *media_packer_create(char *sink, media_type_t type);
int media_packer_release(media_packer_t *mpacker);
int media_encoder_header_gen(media_encoder_t *mencoder, media_pcminfo_t *pcminfo);
media_encoder_t *media_encoder_create(media_format_t format);
int media_encoder_release(media_encoder_t *mencoder);
#endif /* __UVOICE_RECORD_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/internal/uvoice_record.h
|
C
|
apache-2.0
| 1,974
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifndef __UVOICE_RESAMPLER_H__
#define __UVOICE_RESAMPLER_H__
int uvoice_resampler_process(void *resampler, uint8_t *input, int input_len, uint8_t **output, int *output_len);
int uvoice_resampler_update(void *resampler, int src_rate, int dst_rate, int channels, int sbits);
int uvoice_resampler_create(void **resampler, int src_rate, int dst_rate, int channels, int sbits);
int uvoice_resampler_release(void *resampler);
#endif /* __UVOICE_RESAMPLER_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/internal/uvoice_resampler.h
|
C
|
apache-2.0
| 525
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifndef __UVOICE_RINGBUFFER_H__
#define __UVOICE_RINGBUFFER_H__
int32_t uvoice_ringbuff_reset(uvoice_ringbuff_t *rb);
int32_t uvoice_ringbuff_init(uvoice_ringbuff_t *rb, uint8_t *buffer, int32_t size);
int32_t uvoice_ringbuff_freesize(uvoice_ringbuff_t *rb);
int32_t uvoice_ringbuff_dirtysize(uvoice_ringbuff_t *rb);
int32_t uvoice_ringbuff_fill(uvoice_ringbuff_t *rb, uint8_t *buffer, int32_t size);
int32_t uvoice_ringbuff_read(uvoice_ringbuff_t *rb, uint8_t *buffer, int32_t size);
int32_t uvoice_ringbuff_drop(uvoice_ringbuff_t *rb, int32_t size);
int32_t uvoice_ringbuff_back(uvoice_ringbuff_t *rb, int32_t size);
#endif /* __UVOICE_RINGBUFFER_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/internal/uvoice_ringbuffer.h
|
C
|
apache-2.0
| 725
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifndef __UVOICE_EXTRACTOR_H__
#define __UVOICE_EXTRACTOR_H__
int file_loader_create(media_loader_t *mloader, char *source);
int file_loader_release(media_loader_t *mloader);
int file_packer_create(media_packer_t *mpacker, char *sink);
int file_packer_release(media_packer_t *mpacker);
int http_loader_create(media_loader_t *mloader, char *source);
int http_loader_release(media_loader_t *mloader);
int partition_loader_create(media_loader_t *mloader, char *source);
int partition_loader_release(media_loader_t *mloader);
int partition_packer_create(media_packer_t *mpacker, char *sink);
int partition_packer_release(media_packer_t *mpacker);
#endif /* __UVOICE_EXTRACTOR_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/internal/uvoice_stream.h
|
C
|
apache-2.0
| 749
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#ifndef __UVOICE_WAVE_H__
#define __UVOICE_WAVE_H__
#define ID_RIFF 0x46464952 /* 'F' 'F' 'I' 'R' */
#define ID_WAVE 0x45564157 /* 'E' 'V' 'A' 'W' */
#define ID_FMT 0x20746d66 /* ' ' 't' 'm' 'f' */
#define ID_DATA 0x61746164 /* 'a' 't' 'a' 'd' */
#define WAVE_FMT_PCM 0x0001 /* linear pcm */
#define WAVE_FMT_IEEE_FLOAT 0x0003
#define WAVE_FMT_G711_ALAW 0x0006
#define WAVE_FMT_G711_ULAW 0x0007
#define WAVE_FMT_EXTENSIBLE 0xfffe
struct riff_wave_header {
uint32_t riff_id;
uint32_t riff_sz;
uint32_t wave_id;
};
struct chunk_header {
uint32_t id;
uint32_t sz;
};
struct chunk_fmt {
uint16_t audio_format;
uint16_t num_channels;
uint32_t sample_rate;
uint32_t byte_rate;
uint16_t block_align;
uint16_t bits_per_sample;
};
struct wav_header {
uint32_t riff_id;
uint32_t riff_sz;
uint32_t riff_fmt;
uint32_t fmt_id;
uint32_t fmt_sz;
uint16_t audio_format;
uint16_t num_channels;
uint32_t sample_rate;
uint32_t byte_rate;
uint16_t block_align;
uint16_t bits_per_sample;
uint32_t data_id;
uint32_t data_sz;
};
/*int wave_encoder_create(media_encoder_t *mencoder);
int wave_encoder_release(media_encoder_t *mencoder);
int wave_decoder_create(media_decoder_t *mdecoder);
int wave_decoder_release(media_decoder_t *mdecoder);*/
#endif /* __UVOICE_WAVE_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/internal/uvoice_wave.h
|
C
|
apache-2.0
| 1,365
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdarg.h>
#include "uvoice_os.h"
#include "uvoice_types.h"
#include "uvoice_player.h"
#include "uvoice_recorder.h"
#include "uvoice_config.h"
#include "uvoice_common.h"
#include "uvoice_play.h"
#include "uvoice_record.h"
#include "uvoice_codec.h"
#define MP3_DECODER_BUFF_SIZE 1200
#define AAC_DECODER_BUFF_SIZE 4096
#define M4A_DECODER_BUFF_SIZE 6144
static int mp3_decoder_create(media_decoder_t *mdecoder)
{
if (!mdecoder) {
M_LOGE("mdecoder null !\n");
return -1;
}
mdecoder->input_size = MP3_DECODER_BUFF_SIZE;
#ifdef DECODER_MAD_ENABLE
if (mdecoder->stere_enable)
mdecoder->buffer_out_size = 1152 * sizeof(int16_t) * 2;
else
mdecoder->buffer_out_size = 1152 * sizeof(int16_t);
#else
mdecoder->buffer_out_size = 1152 * sizeof(int16_t) * 2;
#endif
mdecoder->buffer_out = snd_zalloc(
mdecoder->buffer_out_size, AFM_EXTN);
if (!mdecoder->buffer_out) {
M_LOGE("alloc out buffer failed !\n");
goto __exit;
}
#ifdef DECODER_MAD_ENABLE
if (mad_decoder_create(mdecoder)) {
M_LOGE("create mad decoder failed !\n");
goto __exit1;
}
#elif (DECODER_PV_MP3_ENABLE == 1)
if (pvmp3_decoder_create(mdecoder)) {
M_LOGE("create pvmp3 decoder failed !\n");
goto __exit1;
}
#elif defined(DECODER_HELIX_MP3_ENABLE)
if (helixmp3_decoder_create(mdecoder)) {
M_LOGE("create helixmp3 decoder failed !\n");
goto __exit1;
}
#else
M_LOGW("MP3 decoder not enable !\n");
goto __exit1;
#endif
return 0;
__exit1:
mdecoder->buffer_out_size = 0;
snd_free(mdecoder->buffer_out);
mdecoder->buffer_out = NULL;
__exit:
mdecoder->input_size = 0;
return -1;
}
static int mp3_decoder_release(media_decoder_t *mdecoder)
{
if (!mdecoder) {
M_LOGE("mdecoder null !\n");
return -1;
}
#ifdef DECODER_MAD_ENABLE
mad_decoder_release(mdecoder);
#elif (DECODER_PV_MP3_ENABLE == 1)
pvmp3_decoder_release(mdecoder);
#elif defined(DECODER_HELIX_MP3_ENABLE)
helixmp3_decoder_release(mdecoder);
#endif
snd_free(mdecoder->buffer_out);
mdecoder->buffer_out = NULL;
mdecoder->buffer_out_size = 0;
mdecoder->input_size = 0;
return 0;
}
static int aac_decoder_create(media_decoder_t *mdecoder)
{
if (!mdecoder) {
M_LOGE("mdecoder null !\n");
return -1;
}
mdecoder->input_size = AAC_DECODER_BUFF_SIZE;
#ifndef DECODER_FAAD2_AAC_ENABLE
mdecoder->buffer_out_size = 2048 * sizeof(int16_t);
mdecoder->buffer_out = snd_zalloc(
mdecoder->buffer_out_size, AFM_EXTN);
if (!mdecoder->buffer_out) {
M_LOGE("alloc out buffer failed !\n");
mdecoder->input_size = 0;
goto __exit;
}
#endif
#ifdef DECODER_FAAD2_AAC_ENABLE
if (faad2aac_decoder_create(mdecoder)) {
M_LOGE("create faad2 aac decoder failed !\n");
goto __exit;
}
#elif defined(DECODER_HELIX_AAC_ENABLE)
if (helixaac_decoder_create(mdecoder)) {
M_LOGE("create helix aac decoder failed !\n");
goto __exit1;
}
#else
M_LOGE("AAC decoder not enable !\n");
goto __exit1;
#endif
return 0;
__exit1:
mdecoder->buffer_out_size = 0;
snd_free(mdecoder->buffer_out);
mdecoder->buffer_out = NULL;
__exit:
mdecoder->input_size = 0;
return -1;
}
static int aac_decoder_release(media_decoder_t *mdecoder)
{
if (!mdecoder) {
M_LOGE("mdecoder null !\n");
return -1;
}
#ifdef DECODER_FAAD2_AAC_ENABLE
faad2aac_decoder_release(mdecoder);
#elif defined(DECODER_HELIX_AAC_ENABLE)
helixaac_decoder_release(mdecoder);
#endif
#ifndef DECODER_FAAD2_AAC_ENABLE
snd_free(mdecoder->buffer_out);
mdecoder->buffer_out = NULL;
mdecoder->buffer_out_size = 0;
#endif
mdecoder->input_size = 0;
return 0;
}
static int m4a_decoder_create(media_decoder_t *mdecoder)
{
if (!mdecoder) {
M_LOGE("mdecoder null !\n");
return -1;
}
mdecoder->input_size = M4A_DECODER_BUFF_SIZE;
#ifndef DECODER_FAAD2_M4A_ENABLE
if (mdecoder->stere_enable)
mdecoder->buffer_out_size = 1024 * sizeof(int16_t) * 2;
else
mdecoder->buffer_out_size = 1024 * sizeof(int16_t);
mdecoder->buffer_out = snd_zalloc(
mdecoder->buffer_out_size, AFM_EXTN);
if (!mdecoder->buffer_out) {
M_LOGE("alloc out buffer failed !\n");
mdecoder->input_size = 0;
goto __exit;
}
#endif
#ifdef DECODER_FAAD2_M4A_ENABLE
if (faad2m4a_decoder_create(mdecoder)) {
M_LOGE("create faad2m4a decoder failed !\n");
goto __exit;
}
#elif defined(DECODER_HELIX_M4A_ENABLE)
if (helixm4a_decoder_create(mdecoder)) {
M_LOGE("create helixm4a decoder failed !\n");
goto __exit1;
}
#elif (DECODER_PV_M4A_ENABLE == 1)
if (pvm4a_decoder_create(mdecoder)) {
M_LOGE("create pvm4a decoder failed !\n");
goto __exit1;
}
printf("func %s, line %d: mdecoder->action is 0x%p\n", __FUNCTION__, __LINE__, mdecoder->action);
#else
M_LOGE("M4A decoder not enable !\n");
goto __exit1;
#endif
M_LOGD("M4A decoder create\n");
return 0;
__exit1:
mdecoder->buffer_out_size = 0;
snd_free(mdecoder->buffer_out);
mdecoder->buffer_out = NULL;
__exit:
mdecoder->input_size = 0;
return -1;
}
static int m4a_decoder_release(media_decoder_t *mdecoder)
{
if (!mdecoder) {
M_LOGE("mdecoder null !\n");
return -1;
}
#ifdef DECODER_FAAD2_M4A_ENABLE
faad2m4a_decoder_release(mdecoder);
#elif defined(DECODER_HELIX_M4A_ENABLE)
helixm4a_decoder_release(mdecoder);
#elif (DECODER_PV_M4A_ENABLE == 1)
pvm4a_decoder_release(mdecoder);
#endif
snd_free(mdecoder->buffer_out);
#ifndef DECODER_FAAD2_M4A_ENABLE
mdecoder->buffer_out = NULL;
mdecoder->buffer_out_size = 0;
#endif
mdecoder->input_size = 0;
M_LOGD("M4A decoder release\n");
return 0;
}
int media_decoder_reset(media_decoder_t *mdecoder)
{
if (!mdecoder) {
M_LOGE("mdecoder null !\n");
return -1;
}
if (mdecoder->reset && mdecoder->reset(mdecoder))
M_LOGW("reset decoder failed\n");
mdecoder->unproc_size = 0;
mdecoder->running = 0;
return 0;
}
media_decoder_t *media_decoder_create(media_format_t format)
{
media_decoder_t *mdecoder = snd_zalloc(
sizeof(media_decoder_t), AFM_EXTN);
if (!mdecoder) {
M_LOGE("alloc mdecoder failed !\n");
return NULL;
}
mdecoder->stere_enable = PLAYER_STERE_ENABLE;
switch (format) {
case MEDIA_FMT_MP3:
if (mp3_decoder_create(mdecoder)) {
M_LOGE("create mp3 decoder failed !\n");
snd_free(mdecoder);
return NULL;
}
mdecoder->initialized = 1;
break;
case MEDIA_FMT_WAV:
if (wave_decoder_create(mdecoder)) {
M_LOGE("create wav decoder failed !\n");
snd_free(mdecoder);
return NULL;
}
mdecoder->initialized = 1;
break;
case MEDIA_FMT_AAC:
if (aac_decoder_create(mdecoder)) {
M_LOGE("create aac decoder failed !\n");
snd_free(mdecoder);
return NULL;
}
mdecoder->initialized = 1;
break;
case MEDIA_FMT_M4A:
if (m4a_decoder_create(mdecoder)) {
M_LOGE("create m4a decoder failed !\n");
snd_free(mdecoder);
return NULL;
}
mdecoder->initialized = 1;
break;
case MEDIA_FMT_SPX:
#ifdef DECODER_SPEEX_ENABLE
if (spx_decoder_create(mdecoder)) {
M_LOGE("create spx decoder failed !\n");
snd_free(mdecoder);
return NULL;
}
mdecoder->initialized = 1;
break;
#else
M_LOGE("spx decoder not enable !\n");
snd_free(mdecoder);
return NULL;
#endif
case MEDIA_FMT_OGG:
#ifdef DECODER_OGG_ENABLE
if (ogg_decoder_create(mdecoder)) {
M_LOGE("create ogg decoder failed !\n");
snd_free(mdecoder);
return NULL;
}
mdecoder->initialized = 1;
break;
#else
M_LOGE("ogg decoder not enable !\n");
snd_free(mdecoder);
return NULL;
#endif
case MEDIA_FMT_WMA:
#ifdef DECODER_WMA_ENABLE
if (wma_decoder_create(mdecoder)) {
M_LOGE("create wma decoder failed !\n");
snd_free(mdecoder);
return NULL;
}
mdecoder->initialized = 1;
break;
#else
M_LOGE("wma decoder not enable!\n");
snd_free(mdecoder);
return NULL;
#endif
case MEDIA_FMT_OPS:
#ifdef DECODER_OPUS_ENABLE
if (opus_decode_create(mdecoder)) {
M_LOGE("create opus decoder failed !\n");
snd_free(mdecoder);
return NULL;
}
mdecoder->initialized = 1;
break;
#else
M_LOGE("opus decoder not enable !\n");
snd_free(mdecoder);
return NULL;
#endif
case MEDIA_FMT_FLAC:
#ifdef DECODER_FLAC_ENABLE
if (flac_decoder_create(mdecoder)) {
M_LOGE("create flac decoder failed !\n");
snd_free(mdecoder);
return NULL;
}
mdecoder->initialized = 1;
break;
#else
M_LOGE("flac decoder not enable !\n");
snd_free(mdecoder);
return NULL;
#endif
case MEDIA_FMT_AMR:
#ifdef DECODER_AMR_ENABLE
if (amr_decoder_create(mdecoder)) {
M_LOGE("create amr decoder failed !\n");
snd_free(mdecoder);
return NULL;
}
mdecoder->initialized = 1;
break;
#else
M_LOGE("amr decoder not enable !\n");
snd_free(mdecoder);
return NULL;
#endif
case MEDIA_FMT_AMRWB:
#ifdef DECODER_AMRWB_ENABLE
if (amrwb_decoder_create(mdecoder)) {
M_LOGE("create amrwb decoder failed !\n");
snd_free(mdecoder);
return NULL;
}
mdecoder->initialized = 1;
break;
#else
M_LOGE("amrwb decoder not enable !\n");
snd_free(mdecoder);
return NULL;
#endif
case MEDIA_FMT_PCM:
mdecoder->input_size = 2048;
break;
default:
M_LOGE("unknown format %d\n", format);
snd_free(mdecoder);
return NULL;
}
mdecoder->format = format;
return mdecoder;
}
int media_decoder_release(media_decoder_t *mdecoder)
{
if (!mdecoder) {
M_LOGE("mdecoder null !\n");
return -1;
}
switch (mdecoder->format) {
case MEDIA_FMT_MP3:
mp3_decoder_release(mdecoder);
break;
case MEDIA_FMT_WAV:
wave_decoder_release(mdecoder);
break;
case MEDIA_FMT_AAC:
aac_decoder_release(mdecoder);
break;
case MEDIA_FMT_M4A:
m4a_decoder_release(mdecoder);
break;
case MEDIA_FMT_SPX:
#ifdef DECODER_SPEEX_ENABLE
spx_decoder_release(mdecoder);
#endif
break;
case MEDIA_FMT_OGG:
#ifdef DECODER_OGG_ENABLE
ogg_decoder_release(mdecoder);
#endif
break;
case MEDIA_FMT_WMA:
#ifdef DECODER_WMA_ENABLE
wma_decoder_release(mdecoder);
#endif
break;
case MEDIA_FMT_OPS:
#ifdef DECODER_OPUS_ENABLE
opus_decode_release(mdecoder);
#endif
break;
case MEDIA_FMT_FLAC:
#ifdef DECODER_FLAC_ENABLE
flac_decoder_release(mdecoder);
#endif
break;
case MEDIA_FMT_AMR:
#ifdef DECODER_AMR_ENABLE
amr_decoder_release(mdecoder);
#endif
break;
case MEDIA_FMT_AMRWB:
#ifdef DECODER_AMRWB_ENABLE
amrwb_decoder_release(mdecoder);
#endif
break;
default:
break;
}
snd_free(mdecoder);
return 0;
}
int media_encoder_header_gen(media_encoder_t *mencoder,
media_pcminfo_t *pcminfo)
{
if (!mencoder) {
M_LOGE("mencoder null !\n");
return -1;
}
if (!pcminfo) {
M_LOGE("pcminfo null !\n");
return -1;
}
if (mencoder->header_gen &&
mencoder->header_gen(mencoder, pcminfo)) {
M_LOGE("generate header failed !\n");
return -1;
}
return 0;
}
media_encoder_t *media_encoder_create(media_format_t format)
{
media_encoder_t *mencoder = snd_zalloc(
sizeof(media_encoder_t), AFM_EXTN);
if (!mencoder) {
M_LOGE("alloc media encoder failed !\n");
return NULL;
}
switch (format) {
case MEDIA_FMT_WAV:
if (wave_encoder_create(mencoder)) {
M_LOGE("create wave encoder failed !\n");
snd_free(mencoder);
return NULL;
}
mencoder->initialized = 1;
break;
case MEDIA_FMT_SPX:
#ifdef ENCODER_SPEEX_ENABLE
if (spx_encoder_create(mencoder)) {
M_LOGE("create speex encoder failed !\n");
snd_free(mencoder);
return NULL;
}
mencoder->initialized = 1;
break;
#else
M_LOGE("speex encoder not enable !\n");
snd_free(mencoder);
return NULL;
#endif
case MEDIA_FMT_OPS:
#ifdef ENCODER_OPUS_ENABLE
if (opus_encode_create(mencoder)) {
M_LOGE("create opus encoder failed !\n");
snd_free(mencoder);
return NULL;
}
mencoder->initialized = 1;
break;
#else
M_LOGE("opus encoder not enable !\n");
snd_free(mencoder);
return NULL;
#endif
case MEDIA_FMT_AMR:
#ifdef ENCODER_AMR_ENABLE
if (amr_encoder_create(mencoder)) {
M_LOGE("create amr encoder failed !\n");
snd_free(mencoder);
return NULL;
}
mencoder->initialized = 1;
break;
#else
M_LOGE("amr encoder not enable !\n");
snd_free(mencoder);
return NULL;
#endif
case MEDIA_FMT_AMRWB:
#ifdef ENCODER_AMRWB_ENABLE
if (amrwb_encoder_create(mencoder)) {
M_LOGE("create amrwb encoder failed !\n");
snd_free(mencoder);
return NULL;
}
mencoder->initialized = 1;
break;
#else
M_LOGE("amrwb encoder not enable !\n");
snd_free(mencoder);
return NULL;
#endif
case MEDIA_FMT_AAC:
#ifdef ENCODER_FAAC_ENABLE
if (faac_encoder_create(mencoder)) {
M_LOGE("create faac encoder failed !\n");
snd_free(mencoder);
return NULL;
}
mencoder->initialized = 1;
break;
#else
M_LOGE("faac encoder not enable !\n");
snd_free(mencoder);
return NULL;
#endif
case MEDIA_FMT_MP3:
#ifdef ENCODER_LAME_ENABLE
if (lame_encoder_create(mencoder)) {
M_LOGE("create lame encoder failed !\n");
snd_free(mencoder->buffer_out);
snd_free(mencoder);
return NULL;
}
mencoder->initialized = 1;
break;
#else
M_LOGE("MP3 encoder not enable !\n");
snd_free(mencoder);
return NULL;
#endif
default:
break;
}
mencoder->format = format;
return mencoder;
}
int media_encoder_release(media_encoder_t *mencoder)
{
if (!mencoder) {
M_LOGW("mencoder null\n");
return -1;
}
switch (mencoder->format) {
case MEDIA_FMT_WAV:
wave_encoder_release(mencoder);
mencoder->initialized = 0;
break;
case MEDIA_FMT_SPX:
#ifdef ENCODER_SPEEX_ENABLE
spx_encoder_release(mencoder);
mencoder->initialized = 0;
#endif
break;
case MEDIA_FMT_MP3:
#ifdef ENCODER_LAME_ENABLE
lame_encoder_release(mencoder);
mencoder->initialized = 0;
#endif
break;
case MEDIA_FMT_AAC:
#ifdef ENCODER_FAAC_ENABLE
faac_encoder_release(mencoder);
mencoder->initialized = 0;
#endif
break;
case MEDIA_FMT_AMR:
#ifdef ENCODER_AMR_ENABLE
amr_encoder_release(mencoder);
mencoder->initialized = 0;
#endif
break;
case MEDIA_FMT_AMRWB:
#ifdef ENCODER_AMRWB_ENABLE
amrwb_encoder_release(mencoder);
mencoder->initialized = 0;
#endif
break;
case MEDIA_FMT_OPS:
#ifdef ENCODER_OPUS_ENABLE
opus_encode_release(mencoder);
mencoder->initialized = 0;
#endif
break;
default:
break;
}
snd_free(mencoder);
return 0;
}
|
YifuLiu/AliOS-Things
|
components/uvoice/media/uvoice_codec.c
|
C
|
apache-2.0
| 14,156
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#include <stdlib.h>
#include <stdint.h>
int fade_out_proc_8bit(uint8_t *buffer, int nbytes,
int *pos, int scope, int channels)
{
char *ptr = (char *)buffer;
int sample_pos = *pos;
int samples;
int sample_index;
int channel_index;
double sample_val;
samples = nbytes / channels;
for (sample_index = 0; sample_index < samples; sample_index++) {
for (channel_index = 0; channel_index < channels;
channel_index++) {
sample_val = (double)*ptr;
sample_val *= (double)sample_pos;
sample_val /= (double)scope;
*ptr = (uint8_t)sample_val;
ptr++;
}
if (sample_pos > 0)
sample_pos--;
}
*pos = sample_pos;
return 0;
}
int fade_in_proc_8bit(uint8_t *buffer, int nbytes,
int *pos, int scope, int channels)
{
char *ptr = (char *)buffer;
int sample_pos = *pos;
int samples;
int sample_index;
int channel_index;
double sample_val;
if (sample_pos >= scope)
goto __exit;
samples = nbytes / channels;
for (sample_index = 0; sample_index < samples; sample_index++) {
for (channel_index = 0; channel_index < channels;
channel_index++) {
sample_val = (double)*ptr;
sample_val *= (double)sample_pos;
sample_val /= (double)scope;
*ptr = (uint8_t)sample_val;
ptr++;
}
if (sample_pos < scope)
sample_pos++;
if (sample_pos >= scope)
break;
}
*pos = sample_pos;
__exit:
return 0;
}
int fade_out_proc_16bit(uint8_t *buffer, int nbytes,
int *pos, int scope, int channels)
{
short *ptr = (short *)buffer;
int sample_pos = *pos;
int samples;
int sample_index;
int channel_index;
double sample_val;
samples = nbytes / (channels * 2);
for (sample_index = 0; sample_index < samples; sample_index++) {
for (channel_index = 0; channel_index < channels;
channel_index++) {
sample_val = (double)*ptr;
sample_val *= (double)sample_pos;
sample_val /= (double)scope;
*ptr = (short)sample_val;
ptr++;
}
if (sample_pos > 0)
sample_pos--;
}
*pos = sample_pos;
return 0;
}
int fade_in_proc_16bit(uint8_t *buffer, int nbytes,
int *pos, int scope, int channels)
{
short *ptr = (short *)buffer;
int sample_pos = *pos;
int samples;
int sample_index;
int channel_index;
double sample_val;
if (sample_pos >= scope)
goto __exit;
samples = nbytes / (channels * 2);
for (sample_index = 0; sample_index < samples; sample_index++) {
for (channel_index = 0; channel_index < channels;
channel_index++) {
sample_val = (double)*ptr;
sample_val *= (double)sample_pos;
sample_val /= (double)scope;
*ptr = (short)sample_val;
ptr++;
}
if (sample_pos < scope)
sample_pos++;
if (sample_pos >= scope)
break;
}
*pos = sample_pos;
__exit:
return 0;
}
|
YifuLiu/AliOS-Things
|
components/uvoice/media/uvoice_fade.c
|
C
|
apache-2.0
| 2,748
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <signal.h>
#include "uvoice_os.h"
#include "uvoice_types.h"
#include "uvoice_player.h"
#include "uvoice_recorder.h"
#include "uvoice_common.h"
#include "uvoice_play.h"
#include "uvoice_record.h"
#include "uvoice_wave.h"
#define MP3_HEADER_MASK 0xfffe0c00
#define MP3_HEADER_SIZE 4
#define MP3_HEADER_PACK(ptr) \
((ptr)[0] << 24 | (ptr)[1] << 16 | (ptr)[2] << 8 | (ptr)[3])
struct mp3_id3v2_desc {
char label[3];
char version;
char revision;
char flag;
char size[4];
};
struct mp3_id3v2_frame_header {
char id[4];
char size[4];
unsigned short flag;
};
int mp3_id3v1_parse(media_info_t *info, unsigned char *data, int size)
{
unsigned char *ptr;
if (!data || !info) {
M_LOGE("arg null !\n");
return -1;
}
ptr = data;
if (memcmp(ptr, "TAG", 3)) {
M_LOGD("no tag\n");
return -1;
}
ptr += 3;
memcpy(info->name, ptr, 30);
ptr += 30;
memcpy(info->author, ptr, 30);
ptr += 30;
memcpy(info->album, ptr, 30);
ptr += 30;
memcpy(info->year, ptr, 4);
ptr += 4;
ptr += 30;
memcpy(&info->type, ptr, 1);
info->valid = 1;
M_LOGD("name: %s, author: %s, album: %s, year: %s, type: %u\n",
info->name,
info->author,
info->album, info->year, info->type);
return 0;
}
static int mp3_id3v2_parse(media_info_t *info, char *data, int size)
{
struct mp3_id3v2_desc ID3;
struct mp3_id3v2_frame_header header;
int id3v2_frame_size;
if (!info || !data || size < sizeof(ID3)) {
M_LOGE("param invalid !\n");
return -1;
}
memcpy(&ID3, data, sizeof(ID3));
if (ID3.version != 3) {
M_LOGW("ID3 not version 3\n");
return -1;
}
//M_LOGD("label %s\n", ID3.label);
//M_LOGD("version %d\n", ID3.version);
//M_LOGD("revision %d\n", ID3.revision);
//M_LOGD("flag %d\n", ID3.flag);
id3v2_frame_size = ((ID3.size[0] & 0x7f) << 21) |
((ID3.size[1] & 0x7f) << 14) |
((ID3.size[2] & 0x7f) << 7) |
(ID3.size[3] & 0x7f);
//M_LOGD("size %d\n", id3v2_frame_size);
unsigned int pos = sizeof(struct mp3_id3v2_desc);
unsigned int frame_size = 0;
unsigned int frame_pos = 0;
unsigned int copy_size = 0;
unsigned int end = MIN(id3v2_frame_size, size - pos);
int i, j;
if (pos + sizeof(struct mp3_id3v2_frame_header) <= end) {
M_LOGW("mp3 id3v2 frame formate invalid \n");
return -1;
}
while (pos <= end) {
memcpy(&header, data + pos ,
sizeof(struct mp3_id3v2_frame_header));
frame_size = header.size[0] << 24 |
header.size[1] << 16 |
header.size[2] << 8 |
header.size[3];
if (frame_size == 0) {
pos++;
continue;
}
if (frame_size + sizeof(struct mp3_id3v2_frame_header) < frame_size) {
M_LOGW("mp3 id3v2 frame size %d invalid \n", frame_size);
return -1;
}
if (!memcmp(header.id, "TIT2", 4)) {
pos += frame_size + sizeof(struct mp3_id3v2_frame_header);
if (pos > end)
break;
frame_pos = pos - frame_size;
copy_size = MIN(sizeof(info->name) - 1, frame_size);
for (i = 0, j = 0; i < copy_size; i++) {
if (*(data + frame_pos + i) == '\0')
continue;
info->name[j++] = *(data + frame_pos + i);
}
info->name[j] = '\0';
//M_LOGD("name: %s\n", info->name);
} else if (!memcmp(header.id, "TPE1", 4)) {
pos += frame_size + sizeof(struct mp3_id3v2_frame_header);
if (pos > end)
break;
frame_pos = pos - frame_size;
copy_size = MIN(sizeof(info->author) - 1, frame_size);
for (i = 0, j = 0; i < copy_size; i++) {
if (*(data + frame_pos + i) == '\0')
continue;
info->author[j++] = *(data + frame_pos + i);
}
info->author[j] = '\0';
//M_LOGD("author: %s\n", info->author);
} else if (!memcmp(header.id, "TALB", 4)) {
pos += frame_size + sizeof(struct mp3_id3v2_frame_header);
if (pos > end)
break;
frame_pos = pos - frame_size;
copy_size = MIN(sizeof(info->album) - 1, frame_size);
for (i = 0, j = 0; i < copy_size; i++) {
if (*(data + frame_pos + i) == '\0')
continue;
info->album[j++] = *(data + frame_pos + i);
}
info->album[j] = '\0';
//M_LOGD("album: %s\n", info->album);
} else if (!memcmp(header.id, "TYER", 4)) {
pos += frame_size + sizeof(struct mp3_id3v2_frame_header);
if (pos > end)
break;
frame_pos = pos - frame_size;
copy_size = MIN(sizeof(info->year) - 1, frame_size);
for (i = 0, j = 0; i < copy_size; i++) {
if (*(data + frame_pos + i) == '\0')
continue;
info->year[j++] = *(data + frame_pos + i);
}
info->year[j] = '\0';
//M_LOGD("year: %s\n", info->year);
} else if (!memcmp(header.id, "TCON", 4)) {
pos += frame_size + sizeof(struct mp3_id3v2_frame_header);
if (pos > end)
break;
frame_pos = pos - frame_size;
char type[32];
memset(type, 0, sizeof(type));
copy_size = MIN(sizeof(type) - 1, frame_size);
for (i = 0, j = 0; i < copy_size; i++) {
if (*(data + frame_pos + i) == '\0')
continue;
type[j++] = *(data + frame_pos + i);
}
type[j] = '\0';
//M_LOGD("type: %s\n", type);
} else if (!memcmp(header.id, "TSSE", 4)) {
pos += frame_size + sizeof(struct mp3_id3v2_frame_header);
if (pos > end)
break;
frame_pos = pos - frame_size;
char tsse[32];
memset(tsse, 0, sizeof(tsse));
copy_size = MIN(sizeof(tsse) - 1, frame_size);
for (i = 0, j = 0; i < copy_size; i++) {
if (*(data + frame_pos + i) == '\0')
continue;
tsse[j++] = *(data + frame_pos + i);
}
tsse[j] = '\0';
//M_LOGD("tsse: %s\n", tsse);
} else {
pos++;
continue;
}
//M_LOGD("frame id %s frame_size %u frame_pos %d\n",
// header.id, frame_size, frame_pos);
}
return 0;
}
bool wav_format_check(char *buffer, int size)
{
struct riff_wave_header riff_wave_header;
if (buffer && size >= sizeof(riff_wave_header)) {
memcpy(&riff_wave_header, buffer,
sizeof(riff_wave_header));
if (riff_wave_header.riff_id == ID_RIFF &&
riff_wave_header.wave_id == ID_WAVE)
return true;
}
return false;
}
bool mp3_format_check(char *data, int size)
{
if (!data || size < sizeof(struct mp3_id3v2_desc)) {
M_LOGE("arg invalid !\n");
return false;
}
if (!memcmp(data, "ID3", strlen("ID3"))) {
struct mp3_id3v2_desc ID3;
memcpy(&ID3, data, sizeof(struct mp3_id3v2_desc));
M_LOGD("ID3 found, version %d\n", ID3.version);
if (ID3.version != 3 && ID3.version != 4)
return false;
media_info_t info;
memset(&info, 0, sizeof(info));
mp3_id3v2_parse(&info, data, size);
return true;
}
return false;
}
bool aac_format_check(char *buffer, int size)
{
return false;
}
bool m4a_format_check(char *buffer, int size)
{
if (!buffer || size < 8) {
M_LOGE("arg invalid !\n");
return false;
}
return !memcmp(buffer + 4, "ftyp", strlen("ftyp"));
}
bool ogg_format_check(char *buffer, int size)
{
if (!buffer || size < 4) {
M_LOGE("arg invalid !\n");
return false;
}
return !memcmp(buffer, "OggS", strlen("OggS"));
}
bool wma_format_check(char *buffer, int size)
{
if (!buffer || size < 4) {
M_LOGE("arg invalid !\n");
return false;
}
return !memcmp(buffer, "MAC ", strlen("MAC "));
}
bool amr_format_check(char *buffer, int size)
{
if (!buffer || size < 6) {
M_LOGE("arg invalid !\n");
return false;
}
return !memcmp(buffer, "#!AMR\n", strlen("#!AMR\n"));
}
bool amrwb_format_check(char *buffer, int size)
{
if (!buffer || size < strlen("#!AMR-WB\n")) {
M_LOGE("arg invalid !\n");
return false;
}
return !memcmp(buffer, "#!AMR-WB\n", strlen("#!AMR-WB\n"));
}
bool ape_format_check(char *buffer, int size)
{
return false;
}
bool flac_format_check(char *buffer, int size)
{
if (!buffer || size < 4) {
M_LOGE("arg invalid !\n");
return false;
}
return !memcmp(buffer, "fLaC", strlen("fLaC"));
}
static bool suffix_assert(char *str, char *suffix)
{
bool ret = false;
if (!str || !suffix || strlen(str) < strlen(suffix))
return ret;
ret = !memcmp((str + strlen(str) - strlen(suffix)),
suffix, strlen(suffix));
if (!ret) {
if (!strncmp(str, "http://", strlen("http://")) ||
!strncmp(str, "https://", strlen("https://")))
ret = !!strstr(str, suffix);
}
return ret;
}
int format_parse_byname(char *name, media_format_t *format)
{
if (!name || !format) {
M_LOGE("arg null !\n");
return -1;
}
if (suffix_assert(name, ".mp3") || suffix_assert(name, ".MP3"))
*format = MEDIA_FMT_MP3;
else if (suffix_assert(name, ".wav") || suffix_assert(name, ".WAV"))
*format = MEDIA_FMT_WAV;
else if (suffix_assert(name, ".aac") || suffix_assert(name, ".AAC"))
*format = MEDIA_FMT_AAC;
else if (suffix_assert(name, ".m4a") || suffix_assert(name, ".M4A"))
*format = MEDIA_FMT_M4A;
else if (suffix_assert(name, ".pcm") || suffix_assert(name, ".PCM"))
*format = MEDIA_FMT_PCM;
else if (suffix_assert(name, ".spx") || suffix_assert(name, ".SPX"))
*format = MEDIA_FMT_SPX;
else if (suffix_assert(name, ".ogg") || suffix_assert(name, ".OGG"))
*format = MEDIA_FMT_OGG;
else if (suffix_assert(name, ".wma") || suffix_assert(name, ".WMA"))
*format = MEDIA_FMT_WMA;
else if (suffix_assert(name, ".amrwb") || suffix_assert(name, ".AMRWB"))
*format = MEDIA_FMT_AMRWB;
else if (suffix_assert(name, ".amr") || suffix_assert(name, ".AMR"))
*format = MEDIA_FMT_AMR;
else if (suffix_assert(name, ".opus") || suffix_assert(name, ".OPUS"))
*format = MEDIA_FMT_OPS;
else if (suffix_assert(name, ".flac") || suffix_assert(name, ".FLAC"))
*format = MEDIA_FMT_FLAC;
return 0;
}
|
YifuLiu/AliOS-Things
|
components/uvoice/media/uvoice_format.c
|
C
|
apache-2.0
| 9,454
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
#include "uvoice_os.h"
#include "uvoice_types.h"
#include "uvoice_mlist.h"
#include "uvoice_config.h"
#define SOURCE_LIST_INDEX_KEY "mlist_index"
typedef struct {
int count;
int index;
char source[128];
os_mutex_t lock;
} mlist_t;
static mlist_t *g_src_list;
int mlist_source_show(void)
{
mlist_t *src_list = g_src_list;
char *listpath;
os_file_t *list_fp;
char file_name[128];
int index = 0;
char *ptr = NULL;
int len;
if (!src_list) {
M_LOGE("src_list null !\n");
return -1;
}
os_mutex_lock(src_list->lock, OS_WAIT_FOREVER);
len = strlen(PLAYER_SOURCE_LIST_DIR) +
strlen(PLAYER_SOURCE_LIST_NAME) + 4;
listpath = snd_zalloc(len, AFM_EXTN);
if (!listpath) {
M_LOGE("alloc list path failed !\n");
os_mutex_unlock(src_list->lock);
return -1;
}
snprintf(listpath, len, "%s/%s",
PLAYER_SOURCE_LIST_DIR, PLAYER_SOURCE_LIST_NAME);
list_fp = os_fopen(listpath, "r");
if (!list_fp) {
M_LOGE("list not found, please scan\n");
snd_free(listpath);
os_mutex_unlock(src_list->lock);
return -1;
}
while (!os_feof(list_fp)) {
memset(file_name, 0, sizeof(file_name));
os_fgets(file_name, sizeof(file_name), list_fp);
if (file_name[strlen(file_name) - 1] == '\n')
file_name[strlen(file_name) - 1] = '\0';
ptr = strchr(file_name, '/');
if (!ptr)
continue;
ptr += 1;
index = atoi(ptr);
ptr = strchr(ptr, '/');
if (!ptr)
continue;
ptr += 1;
M_LOGI("No.%d %s\n", index, ptr);
}
os_fclose(list_fp);
snd_free(listpath);
os_mutex_unlock(src_list->lock);
return 0;
}
int mlist_source_scan(void)
{
mlist_t *src_list = g_src_list;
char *listpath;
int listpath_len;
os_file_t *list_fp;
os_dir_t *dir;
os_dirent_t *content = NULL;
media_format_t format = MEDIA_FMT_UNKNOWN;
int index = 0;
bool curr_source_found = false;
int ret;
if (!src_list) {
M_LOGE("src_list null !\n");
return -1;
}
os_mutex_lock(src_list->lock, OS_WAIT_FOREVER);
ret = access(PLAYER_SOURCE_LIST_DIR, F_OK);
if (ret) {
ret = os_mkdir(PLAYER_SOURCE_LIST_DIR);
if (ret) {
M_LOGE("create %s failed %d!\n",
PLAYER_SOURCE_LIST_DIR, ret);
os_mutex_unlock(src_list->lock);
return -1;
}
M_LOGD("create dir: %s\n", PLAYER_SOURCE_LIST_DIR);
}
listpath_len = strlen(PLAYER_SOURCE_LIST_DIR) +
strlen(PLAYER_SOURCE_LIST_NAME) + 2;
listpath = snd_zalloc(listpath_len, AFM_EXTN);
if (!listpath) {
M_LOGE("alloc list path failed !\n");
os_mutex_unlock(src_list->lock);
return -1;
}
snprintf(listpath, listpath_len, "%s/%s",
PLAYER_SOURCE_LIST_DIR, PLAYER_SOURCE_LIST_NAME);
list_fp = os_fopen(listpath, "w+");
if (!list_fp) {
M_LOGE("open %s failed !\n", listpath);
snd_free(listpath);
os_mutex_unlock(src_list->lock);
return -1;
}
dir = os_opendir(PLAYER_SOURCE_LIST_DIR);
if (!dir) {
M_LOGE("open %s failed !\n", PLAYER_SOURCE_LIST_DIR);
os_fclose(list_fp);
snd_free(listpath);
os_mutex_unlock(src_list->lock);
return -1;
}
while (1) {
content = os_readdir(dir);
if (!content)
break;
#ifdef __os_alios_things__
if (content->d_type & (AM_DIR | AM_HID | AM_ARC | AM_SYS))
continue;
#else
if (!(content->d_type & (DT_REG)))
continue;
#endif
format = MEDIA_FMT_UNKNOWN;
format_parse_byname(content->d_name, &format);
if (format == MEDIA_FMT_UNKNOWN)
continue;
if (strlen(content->d_name) + strlen("fs:") +
strlen(PLAYER_SOURCE_LIST_DIR) > 126)
continue;
index++;
if (os_fprintf(list_fp, "/%d/%s\n", index, content->d_name) < 0) {
M_LOGE("write list failed !\n");
index--;
continue;
}
if (src_list->index > 0) {
if (strlen(src_list->source) <=
(strlen("fs:") + strlen(PLAYER_SOURCE_LIST_DIR) + 1)) {
M_LOGE("source name invalid\n");
continue;
}
if (!strncmp(content->d_name, (char *)src_list->source +
strlen("fs:") + strlen(PLAYER_SOURCE_LIST_DIR) + 1,
strlen(content->d_name))) {
curr_source_found = true;
if (src_list->index != index) {
M_LOGI("update index %d\n", index);
src_list->index = index;
ret = os_kv_set(SOURCE_LIST_INDEX_KEY,
&src_list->index,
sizeof(src_list->index), 0);
if (ret) {
M_LOGW("kv set failed %d!\n", ret);
ret = -1;
goto __exit;
}
}
}
}
//M_LOGD("No.%d %s\n", index, content->d_name);
}
if (src_list->count != index)
src_list->count = index;
M_LOGD("list count %d\n", src_list->count);
__exit:
os_closedir(dir);
os_fclose(list_fp);
snd_free(listpath);
if (!curr_source_found && src_list->index > 0) {
M_LOGD("set default index\n");
src_list->index = 0;
os_mutex_unlock(src_list->lock);
if (mlist_index_set(1)) {
M_LOGE("set index failed !\n");
ret = -1;
}
} else {
os_mutex_unlock(src_list->lock);
}
return ret;
}
int mlist_source_get(int index, char *path, int len)
{
mlist_t *src_list = g_src_list;
char file_name[128];
int listpath_len;
char *listpath;
os_file_t *list_fp;
char *ptr = NULL;
int file_index = 0;
int ret = -1;
if (!src_list) {
M_LOGE("src_list null !\n");
return -1;
}
if (!path) {
M_LOGE("path null !\n");
return -1;
}
if (len < 0) {
M_LOGE("len %d invalid!\n", len);
return -1;
}
os_mutex_lock(src_list->lock, OS_WAIT_FOREVER);
if (index <= 0 || index > src_list->count) {
M_LOGE("index %d count %d\n",
index, src_list->count);
os_mutex_unlock(src_list->lock);
return -1;
}
listpath_len = strlen(PLAYER_SOURCE_LIST_DIR) +
strlen(PLAYER_SOURCE_LIST_NAME) + 4;
listpath = snd_zalloc(listpath_len, AFM_EXTN);
if (!listpath) {
M_LOGE("alloc list path failed !\n");
os_mutex_unlock(src_list->lock);
return -1;
}
snprintf(listpath, listpath_len, "%s/%s",
PLAYER_SOURCE_LIST_DIR, PLAYER_SOURCE_LIST_NAME);
list_fp = os_fopen(listpath, "r");
if (!list_fp) {
M_LOGE("open %s failed !\n", listpath);
snd_free(listpath);
os_mutex_unlock(src_list->lock);
return -1;
}
while (!os_feof(list_fp)) {
memset(file_name, 0, sizeof(file_name));
os_fgets(file_name, sizeof(file_name), list_fp);
if (file_name[strlen(file_name) - 1] == '\n')
file_name[strlen(file_name) - 1] = '\0';
ptr = strchr(file_name, '/');
if (!ptr)
continue;
ptr += 1;
file_index = atoi(ptr);
if (file_index <= 0)
continue;
//M_LOGD("index %d, name: %s\n", file_index, file_name);
if (file_index == index) {
ptr = strchr(ptr, '/');
if (!ptr)
continue;
ptr += 1;
if (strchr(ptr, '/'))
continue;
if (strlen(ptr) + strlen("fs:") +
strlen(PLAYER_SOURCE_LIST_DIR) + 2 > len) {
M_LOGE("name %s length %d too long !\n",
ptr, strlen(ptr));
ret = -1;
break;
}
snprintf(path, len, "fs:%s/%s",
PLAYER_SOURCE_LIST_DIR, ptr);
//M_LOGD("found /%d/%s\n", index, path);
ret = 0;
break;
}
}
os_fclose(list_fp);
snd_free(listpath);
os_mutex_unlock(src_list->lock);
return ret;
}
int mlist_source_del(int index)
{
mlist_t *src_list = g_src_list;
char file_path[128];
int ret = 0;
if (!src_list) {
M_LOGE("src_list null !\n");
return -1;
}
memset(file_path, 0, sizeof(file_path));
if (mlist_source_get(index, file_path, sizeof(file_path))) {
M_LOGE("get source name failed !\n");
return -1;
}
if (strncmp(file_path, "fs:", strlen("fs:"))) {
M_LOGE("source path invalid !\n");
return -1;
}
if (unlink((char *)file_path + strlen("fs:"))) {
M_LOGE("delete %s failed !\n", file_path);
return -1;
}
os_mutex_lock(src_list->lock, OS_WAIT_FOREVER);
if (src_list->index == index && index != 1) {
M_LOGD("set default index\n");
src_list->index = 1;
ret = os_kv_set(SOURCE_LIST_INDEX_KEY,
&src_list->index,
sizeof(src_list->index), 0);
if (ret) {
M_LOGE("kv set failed %d!\n", ret);
os_mutex_unlock(src_list->lock);
return -1;
}
memset(src_list->source, 0, sizeof(src_list->source));
os_mutex_unlock(src_list->lock);
if (mlist_source_get(src_list->index,
src_list->source,
sizeof(src_list->source))) {
M_LOGE("get source name failed !\n");
return -1;
}
} else {
os_mutex_unlock(src_list->lock);
}
if (mlist_source_scan()) {
M_LOGE("scan source failed !\n");
return -1;
}
M_LOGI("%s delete\n", file_path);
return 0;
}
int mlist_index_get(int *index)
{
mlist_t *src_list = g_src_list;
int kv_len;
int ret = 0;
if (!src_list) {
M_LOGE("src_list null !\n");
return -1;
}
os_mutex_lock(src_list->lock, OS_WAIT_FOREVER);
kv_len = sizeof(src_list->index);
if (src_list->index == 0) {
ret = os_kv_get(SOURCE_LIST_INDEX_KEY,
&src_list->index, &kv_len);
os_mutex_unlock(src_list->lock);
if (ret == -ENOENT) {
M_LOGD("set default index\n");
if (mlist_index_set(1)) {
M_LOGE("set source index failed !\n");
return -1;
}
} else if (ret) {
M_LOGE("kv get failed %d!\n", ret);
return -1;
}
} else {
os_mutex_unlock(src_list->lock);
}
if (strlen(src_list->source) <= 0) {
if (mlist_source_get(src_list->index,
src_list->source, sizeof(src_list->source))) {
M_LOGE("get source name failed !\n");
return -1;
}
}
*index = src_list->index;
M_LOGD("No.%d %s\n", *index,
(char *)src_list->source + strlen("fs:") +
strlen(PLAYER_SOURCE_LIST_DIR) + 1);
return 0;
}
int mlist_index_set(int index)
{
mlist_t *src_list = g_src_list;
int kv_len;
int ret = 0;
if (!src_list) {
M_LOGE("src_list null !\n");
return -1;
}
os_mutex_lock(src_list->lock, OS_WAIT_FOREVER);
kv_len = sizeof(src_list->index);
if (src_list->index != index) {
src_list->index = index;
ret = os_kv_set(SOURCE_LIST_INDEX_KEY,
&src_list->index,
sizeof(src_list->index), 0);
if (ret) {
M_LOGE("kv set failed %d!\n", ret);
os_mutex_unlock(src_list->lock);
return -1;
}
M_LOGI("update source index %d\n", src_list->index);
os_mutex_unlock(src_list->lock);
memset(src_list->source, 0, sizeof(src_list->source));
if (mlist_source_get(index, src_list->source,
sizeof(src_list->source))) {
M_LOGE("get source name failed !\n");
return -1;
}
} else {
os_mutex_unlock(src_list->lock);
}
return 0;
}
int mlist_init(void)
{
mlist_t *src_list;
int index = 0;
src_list = snd_zalloc(sizeof(mlist_t), AFM_EXTN);
if (!src_list) {
M_LOGE("alloc src list failed !\n");
return -1;
}
src_list->lock = os_mutex_new();
g_src_list = src_list;
if (mlist_source_scan()) {
M_LOGE("scan source failed !\n");
return -1;
}
if (mlist_index_get(&index)) {
M_LOGE("get source index failed !\n");
return -1;
}
M_LOGD("mlist init\n");
return 0;
}
int mlist_deinit(void)
{
mlist_t *src_list = g_src_list;
if (!src_list) {
M_LOGE("src_list null !\n");
return -1;
}
os_mutex_free(src_list->lock);
snd_free(src_list);
g_src_list = NULL;
M_LOGD("mlist free\n");
return 0;
}
|
YifuLiu/AliOS-Things
|
components/uvoice/media/uvoice_mlist.c
|
C
|
apache-2.0
| 10,938
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdarg.h>
#include <signal.h>
#include <errno.h>
#include "uvoice_types.h"
#include "uvoice_event.h"
#include "uvoice_player.h"
#include "uvoice_os.h"
#include "uvoice_config.h"
#include "uvoice_list.h"
#include "uvoice_audio.h"
#include "uvoice_common.h"
#include "uvoice_ringbuffer.h"
#include "uvoice_play.h"
#include "uvoice_resampler.h"
#include "audio_common.h"
#include "audio_stream.h"
#define PLAYER_VOLUME_LEVEL_KEY "player_volume_level"
#define PLAYER_VOLUME_LEVEL_DEFAULT 40
#define FADE_OUT_PERIOD_DEFAULT 10
#define FADE_IN_PERIOD_DEFAULT 20
#define PLAYER_FADE_PROC_ENABLE 1
#ifdef __os_linux__
#define PLAYER_SW_VOLUME_ENABLE 1
#else
#define PLAYER_SW_VOLUME_ENABLE 0
#endif
#define PLAYER_TRACE(fmt, ...) printf("%s: "fmt, __func__, ##__VA_ARGS__)
static uvoice_player_t *g_mplayer;
static int player_clr_source(void);
int http_cache_config(cache_config_t *config);
static inline bool player_can_set_source(player_t *player)
{
if (player->state == PLAYER_STAT_IDLE ||
player->state == PLAYER_STAT_COMPLETE)
return true;
return false;
}
static inline bool player_can_clr_source(player_t *player)
{
if (player->state == PLAYER_STAT_STOP ||
player->state == PLAYER_STAT_READY)
return true;
return false;
}
static inline bool player_can_set_config(player_t *player)
{
if (!player->stream_flowing &&
(player->state == PLAYER_STAT_READY ||
player->state == PLAYER_STAT_COMPLETE))
return true;
if (player->stream_mgr &&
player->stream_mgr->state == STREAM_MGR_STAT_READY)
return true;
return false;
}
static inline bool player_can_pause(player_t *player)
{
if (player->state == PLAYER_STAT_RUNNING ||
player->state == PLAYER_STAT_COMPLETE)
return true;
return false;
}
static inline bool player_can_resume(player_t *player)
{
if (player->state == PLAYER_STAT_PAUSED ||
player->state == PLAYER_STAT_RUNNING ||
player->state == PLAYER_STAT_COMPLETE)
return true;
return false;
}
static inline bool player_can_complete(player_t *player)
{
if (player->state == PLAYER_STAT_RUNNING)
return true;
return false;
}
static inline bool player_can_seek(player_t *player)
{
if (player->state == PLAYER_STAT_RUNNING ||
player->state == PLAYER_STAT_PAUSED)
return true;
return false;
}
static inline bool player_can_download(player_t *player)
{
if (player->state == PLAYER_STAT_RUNNING ||
player->state == PLAYER_STAT_PAUSED)
return true;
return false;
}
static inline bool player_can_wait_complete(player_t *player)
{
if (player->state == PLAYER_STAT_COMPLETE &&
!player->complete)
return true;
if (player->state == PLAYER_STAT_RUNNING)
return true;
return false;
}
static inline bool player_can_stop(player_t *player)
{
if (player->state == PLAYER_STAT_RUNNING ||
player->state == PLAYER_STAT_PAUSED ||
player->state == PLAYER_STAT_COMPLETE)
return true;
return false;
}
static inline bool player_can_set_stream(player_t *player)
{
if (player->state == PLAYER_STAT_IDLE ||
player->state == PLAYER_STAT_PAUSED ||
player->state == PLAYER_STAT_STOP)
return true;
return false;
}
static int player_state_post(player_t *player, player_state_t state)
{
return uvoice_event_post(UVOICE_EV_PLAYER,
UVOICE_CODE_PLAYER_STATE, state);
}
static int player_pcminfo_update(player_t *player,
media_pcminfo_t *info)
{
media_pcminfo_t *pcminfo;
int changed = 0;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
if (!info) {
M_LOGE("info null !\n");
return -1;
}
if (player->stream_flowing)
pcminfo = &player->stream_mgr->pcm_info;
else
pcminfo = &player->pcm_info;
if (pcm_rate_valid(info->rate) &&
pcminfo->rate != info->rate) {
if (pcm_rate_valid(pcminfo->rate))
changed = 1;
pcminfo->rate = info->rate;
player->fade.out_scope = (pcminfo->rate / 100) *
player->fade.out_period_ms;
player->fade.in_scope = (pcminfo->rate / 100) *
player->fade.in_period_ms;
}
if (pcm_channel_valid(info->channels) &&
pcminfo->channels != info->channels) {
if (pcm_channel_valid(pcminfo->channels))
changed = 1;
pcminfo->channels = info->channels;
}
if (pcm_bits_valid(info->bits) &&
pcminfo->bits != info->bits) {
if (pcm_bits_valid(pcminfo->bits))
changed = 1;
pcminfo->bits = info->bits;
}
if (info->frames > 0 &&
pcminfo->frames != info->frames)
pcminfo->frames = info->frames;
M_LOGD("rate %d channels %d bits %d frames %d changed %d\n",
pcminfo->rate,
pcminfo->channels,
pcminfo->bits, pcminfo->frames, changed);
return changed;
}
static int player_mediainfo_update(player_t *player,
media_info_t *info)
{
media_info_t *media_info;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
if (!info) {
M_LOGE("info null !\n");
return -1;
}
media_info = player->media_info;
if (!media_info) {
M_LOGE("player media info null !\n");
return -1;
}
if (strlen(info->name) > 0)
memcpy(media_info->name,
info->name, strlen(info->name) + 1);
if (strlen(info->author) > 0)
memcpy(media_info->author,
info->author, strlen(info->author) + 1);
if (strlen(info->album) > 0)
memcpy(media_info->album,
info->album, strlen(info->album) + 1);
if (info->media_size > 0)
media_info->media_size = info->media_size;
if (info->duration > 0)
media_info->duration = info->duration;
if (media_info->media_size > 0 && media_info->duration > 0)
media_info->bitrate = (media_info->media_size /
media_info->duration) * 8;
if (info->bitrate > 0)
media_info->bitrate = info->bitrate;
if (media_info->bitrate > 0 && media_info->media_size > 0)
player_state_post(player, PLAYER_STAT_MEDIA_INFO);
M_LOGD("bitrate %d media_size %d\n",
media_info->bitrate, media_info->media_size);
return 0;
}
static int player_message_handle(void *priv,
player_message_t msg, void *arg)
{
player_t *player = (player_t *)priv;
int ret;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
switch (msg) {
case PLAYER_MSG_PCM_INFO:
ret = player_pcminfo_update(player, arg);
if (ret < 0) {
M_LOGE("update pcm info failed !\n");
return -1;
}
player->pcm_reset = !!ret;
break;
case PLAYER_MSG_MEDIA_INFO:
if (!player->stream_flowing) {
if (player_mediainfo_update(player, arg)) {
M_LOGE("update media info failed !\n");
return -1;
}
}
break;
case PLAYER_MSG_SEEK_DONE:
if (player->seek.state == SEEK_START)
player->seek.state = SEEK_COMPLETE;
player->consumed_len += (int)arg;
player_state_post(player, PLAYER_STAT_SEEK_CPLT);
break;
case PLAYER_MSG_LOAD_BLOCK:
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
player->blocking = (int)arg;
os_mutex_unlock(player->lock);
break;
default:
break;
}
return 0;
}
static int player_ampl_coeff(player_t *player, uint8_t *buffer,
int nbytes)
{
media_pcminfo_t *pcminfo;
int coeff = 0;
int step = 0;
int channels;
static int curr_coeff = -1;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
if (player->stream_flowing)
pcminfo = &player->stream_mgr->pcm_info;
else
pcminfo = &player->pcm_info;
channels = pcminfo->channels;
os_mutex_lock(player->vol_lock, OS_WAIT_FOREVER);
coeff = player->vol_level * 100;
if (player->vol_level <= 30 && player->vol_level > 0)
coeff -= 80;
else if (player->vol_level <= 50)
coeff -= 50;
else if (player->vol_level <= 80)
coeff -= 20;
os_mutex_unlock(player->vol_lock);
if (coeff != curr_coeff) {
if (curr_coeff != -1)
step = coeff > curr_coeff ? 1 : -1;
else
curr_coeff = coeff;
}
if (pcminfo->bits == 32 || pcminfo->bits == 24) {
int *temp_buffer = (int *)buffer;
double temp_value;
int sample_count = nbytes / 4;
for (int sample_idx = 0; sample_idx < sample_count;
sample_idx += channels) {
if (curr_coeff != coeff)
curr_coeff += step;
for (int channel_idx = 0; channel_idx < channels;
channel_idx++) {
temp_value = temp_buffer[sample_idx + channel_idx];
temp_value *= curr_coeff;
temp_value /= 10000;
temp_buffer[sample_idx + channel_idx] = (int)temp_value;
}
}
} else if (pcminfo->bits == 16) {
short *temp_buffer = (short *)buffer;
double temp_value;
int sample_count = nbytes / 2;
for (int sample_idx = 0; sample_idx < sample_count;
sample_idx += channels) {
if (curr_coeff != coeff)
curr_coeff += step;
for (int channel_idx = 0; channel_idx < channels;
channel_idx++) {
temp_value = temp_buffer[sample_idx + channel_idx];
temp_value *= curr_coeff;
temp_value /= 10000;
temp_buffer[sample_idx + channel_idx] = (short)temp_value;
}
}
} else if (pcminfo->bits == 8) {
double temp_value;
for (int sample_idx = 0; sample_idx < nbytes;
sample_idx += channels) {
if (curr_coeff != coeff)
curr_coeff += step;
for (int channel_idx = 0; channel_idx < channels;
channel_idx++) {
temp_value = buffer[sample_idx + channel_idx];
temp_value *= curr_coeff;
temp_value /= 10000;
buffer[sample_idx + channel_idx] = (char)temp_value;
}
}
}
return 0;
}
static int player_fade_config_unlock(player_t *player,
int out_period, int in_period)
{
fade_process_t *fade;
media_pcminfo_t *pcminfo;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
fade = &player->fade;
if (in_period != FADE_IN_PERIOD_DEFAULT ||
out_period != FADE_OUT_PERIOD_DEFAULT)
fade->reset = 1;
if (fade->in_period_ms == in_period &&
fade->out_period_ms == out_period) {
M_LOGD("fade period no change\n");
return 0;
}
if (player->stream_flowing)
pcminfo = &player->stream_mgr->pcm_info;
else
pcminfo = &player->pcm_info;
fade->in_period_ms = in_period;
fade->out_period_ms = out_period;
fade->out_scope = (pcminfo->rate / 100) *
fade->out_period_ms;
fade->in_scope = (pcminfo->rate / 100) *
fade->in_period_ms;
return 0;
}
static int player_fade_config(player_t *player, int out_period,
int in_period)
{
if (!player) {
M_LOGE("player null !\n");
return -1;
}
os_mutex_lock(player->fade.lock, OS_WAIT_FOREVER);
if (!player->fade_enable) {
M_LOGW("fade process not enable\n");
os_mutex_unlock(player->fade.lock);
return -1;
}
player_fade_config_unlock(player, out_period, in_period);
os_mutex_unlock(player->fade.lock);
return 0;
}
static int player_fade_process(player_t *player,
uint8_t *buffer, int nbytes)
{
media_pcminfo_t *pcminfo;
fade_process_t *fade;
fade = &player->fade;
os_mutex_lock(fade->lock, OS_WAIT_FOREVER);
if (player->stream_flowing)
pcminfo = &player->stream_mgr->pcm_info;
else
pcminfo = &player->pcm_info;
if (fade->state == FADE_OUT) {
if (fade->out_scope > 0) {
if (pcminfo->bits == 16)
fade_out_proc_16bit(buffer, nbytes,
&fade->pos,
fade->out_scope, pcminfo->channels);
else if (pcminfo->bits == 8)
fade_out_proc_8bit(buffer, nbytes,
&fade->pos,
fade->out_scope, pcminfo->channels);
else
fade->pos = 0;
if (fade->pos == 0) {
M_LOGD("fade out end\n");
fade->state = FADE_OUT_END;
if (fade->reset) {
player_fade_config_unlock(player,
FADE_OUT_PERIOD_DEFAULT, FADE_IN_PERIOD_DEFAULT);
fade->reset = 0;
}
}
} else {
fade->state = FADE_OUT_END;
M_LOGD("fade out end\n");
if (fade->reset) {
player_fade_config_unlock(player,
FADE_OUT_PERIOD_DEFAULT, FADE_IN_PERIOD_DEFAULT);
fade->reset = 0;
}
}
} else if (fade->state == FADE_IN) {
if (fade->in_scope > 0) {
if (pcminfo->bits == 16)
fade_in_proc_16bit(buffer, nbytes, &fade->pos,
fade->in_scope, pcminfo->channels);
else if (pcminfo->bits == 8)
fade_in_proc_8bit(buffer, nbytes, &fade->pos,
fade->in_scope, pcminfo->channels);
else
fade->pos = fade->in_scope;
if (fade->pos >= fade->in_scope) {
M_LOGD("fade in end\n");
fade->state = FADE_NOP;
if (fade->reset) {
player_fade_config_unlock(player,
FADE_OUT_PERIOD_DEFAULT, FADE_IN_PERIOD_DEFAULT);
fade->reset = 0;
}
}
} else {
fade->state = FADE_NOP;
M_LOGD("fade in end\n");
if (fade->reset) {
player_fade_config_unlock(player,
FADE_OUT_PERIOD_DEFAULT, FADE_IN_PERIOD_DEFAULT);
fade->reset = 0;
}
}
}
os_mutex_unlock(fade->lock);
return 0;
}
static int player_data_detect(player_t *player,
uint8_t *buffer, int nbytes)
{
int sample_count = nbytes / sizeof(short);
short *pdata = (short *)buffer;
short ampl_prev = 0;
short ampl_curr = 0;
short ampl_next = 0;
int i;
for (i = 0; i < sample_count; i += 2) {
ampl_curr = pdata[i];
ampl_next = i < sample_count - 2 ? pdata[i + 2] : -1;
if (ampl_curr == 0 && ampl_prev != 0 && ampl_next != 0)
M_LOGI("%d, %d, %d\n", ampl_prev, ampl_curr, ampl_next);
ampl_prev = ampl_curr;
}
return 0;
}
static int player_data_format_init(player_t *player,
int src_ch, int dst_ch, int src_bits, int dst_bits)
{
int dst;
int src;
if (src_ch == dst_ch && src_bits == dst_bits) {
if (player->convertor) {
snd_free(player->convertor);
player->convertor = NULL;
}
return 0;
}
if (player->convertor) {
snd_free(player->convertor);
player->convertor = NULL;
}
player->convertor = snd_zalloc(sizeof(format_convert_t), AFM_EXTN);
if (!player->convertor) {
M_LOGE("alloc format convertor failed !\n");
return -1;
}
player->convertor->src_bits = src_bits;
player->convertor->dst_bits = dst_bits;
player->convertor->src_channels = src_ch;
player->convertor->dst_channels = dst_ch;
dst = dst_ch * dst_bits;
src = src_ch * src_bits;
if (dst <= src)
player->convertor->coeff = 1;
else
player->convertor->coeff = (dst / src) + ((dst % src) > 0) ? 1 : 0;
player->convertor->coeff = player->convertor->coeff > 0 ?
player->convertor->coeff : 1;
return 0;
}
static int player_data_format_proc(player_t *player,
uint8_t *input, int input_size, uint8_t **output, int *output_size)
{
format_convert_t *convertor;
int buffer_size;
convertor = player->convertor;
if (!convertor) {
*output = input;
*output_size = input_size;
return 0;
}
buffer_size = input_size * convertor->coeff;
if (convertor->buffer_size < buffer_size) {
if (convertor->buffer) {
snd_free(convertor->buffer);
convertor->buffer = NULL;
}
}
if (!convertor->buffer) {
convertor->buffer = snd_zalloc(buffer_size, AFM_MAIN);
if (!convertor->buffer) {
convertor->buffer_size = 0;
M_LOGE("alloc buffer failed !\n");
return -1;
}
convertor->buffer_size = buffer_size;
}
if (convertor->src_channels == 2 && convertor->dst_channels == 1) {
short *out_data = (short *)convertor->buffer;
short *in_data = (short *)input;
int samples = input_size / 4;
int i;
for (i = 0; i < samples; i++)
out_data[i] = in_data[i * 2];
*output = convertor->buffer;
*output_size = input_size / 2;
} else if (convertor->src_channels == 1 && convertor->dst_channels == 2) {
short *out_data = (short *)convertor->buffer;
short *in_data = (short *)input;
int samples = input_size / 2;
int i;
for (i = 0; i < samples; i++) {
out_data[i * 2] = in_data[i];
out_data[i * 2 + 1] = in_data[i];
}
*output = convertor->buffer;
*output_size = input_size;
}
return 0;
}
static int player_data_format_free(player_t *player)
{
if (player->convertor) {
snd_free(player->convertor);
player->convertor = NULL;
}
return 0;
}
static int player_output_render(void *priv, uint8_t *buffer,
int nbytes)
{
player_t *player = (player_t *)priv;
uint8_t *resampler_data;
uint8_t *format_data;
int resampler_data_size;
int format_data_size;
void *out;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
if (player->stream_flowing)
out = player->stream_mgr->out;
else
out = player->out;
if (player->pcm_reset) {
out_stream_reset(player->out);
player->pcm_reset = 0;
}
if (!out_stream_configured(out)) {
media_pcminfo_t *info;
media_pcminfo_t pcminfo;
if (player->stream_flowing)
info = &player->stream_mgr->pcm_info;
else
info = &player->pcm_info;
memcpy(&pcminfo, info, sizeof(pcminfo));
if (out_stream_configure(out, &pcminfo)) {
M_LOGE("configure stream failed !\n");
return -1;
}
if (pcminfo.rate != info->rate) {
#ifdef UVOICE_RESAMPLE_ENABLE
if (!player->resampler) {
uvoice_resampler_create(&player->resampler, info->rate,
pcminfo.rate, info->channels, info->bits);
if (!player->resampler) {
M_LOGE("create resampler failed !\n");
return -1;
}
} else {
uvoice_resampler_update(player->resampler, info->rate,
pcminfo.rate, info->channels, info->bits);
}
#else
M_LOGE("resampler not enable !\n");
return -1;
#endif
} else {
#ifdef UVOICE_RESAMPLE_ENABLE
if (player->resampler) {
uvoice_resampler_release(player->resampler);
player->resampler = NULL;
}
#endif
}
player_data_format_init(player, info->channels, pcminfo.channels,
info->bits, pcminfo.bits);
player->idle_period = out_stream_period_duration(out);
if (player->idle_period < 0) {
M_LOGE("get idle period failed !\n");
return -1;
}
M_LOGD("idle period %d\n", player->idle_period);
}
if (player->sw_volume)
player_ampl_coeff(player, buffer, nbytes);
if (player->fade_enable)
player_fade_process(player, buffer, nbytes);
if (!player->out_bypass) {
#ifdef UVOICE_RESAMPLE_ENABLE
if (uvoice_resampler_process(player->resampler, buffer, nbytes,
&resampler_data, &resampler_data_size)) {
M_LOGE("resample error\n");
}
if (resampler_data_size <= 0) {
M_LOGE("resampler_data_size err %d\n", resampler_data_size);
return -1;
}
#else
resampler_data = buffer;
resampler_data_size = nbytes;
#endif
format_data = resampler_data;
format_data_size = resampler_data_size;
player_data_format_proc(player, resampler_data, resampler_data_size,
&format_data, &format_data_size);
if (out_stream_write(out, format_data, format_data_size)) {
M_LOGE("output render failed, size %d !\n", format_data_size);
return -1;
}
} else {
M_LOGD("bypass %d\n", nbytes);
}
os_mutex_lock(player->fade.lock, OS_WAIT_FOREVER);
if (player->fade.state == FADE_OUT_END && !player->out_bypass) {
/* fade out complete, discard remaining output */
player->out_bypass = 1;
}
os_mutex_unlock(player->fade.lock);
return 0;
}
static int player_decode_default(void *priv, uint8_t *buffer,
int nbytes)
{
media_decoder_t *mdecoder = (media_decoder_t *)priv;
if (!mdecoder) {
M_LOGE("mdecoder null !\n");
return -1;
}
if (mdecoder->output(mdecoder->priv, buffer, nbytes)) {
M_LOGE("output failed !\n");
return -1;
}
return 0;
}
static int player_action_default(void *priv,
player_action_t action, void *arg)
{
return 0;
}
static media_type_t player_type_parse(char *source)
{
if (!source)
return MEDIA_TYPE_UNKNOWN;
else if (!strncmp(source, "http://", strlen("http://")))
return MEDIA_TYPE_HTTP;
else if (!strncmp(source, "https://", strlen("https://")))
return MEDIA_TYPE_HTTP;
else if (!strncmp(source, "fs:", strlen("fs:")))
return MEDIA_TYPE_FILE;
else if (!strncmp(source, "pt:", strlen("pt:")))
return MEDIA_TYPE_FLASH;
return MEDIA_TYPE_UNKNOWN;
}
static bool player_format_assert(media_format_t format)
{
switch (format) {
case MEDIA_FMT_MP3:
case MEDIA_FMT_WAV:
case MEDIA_FMT_PCM:
case MEDIA_FMT_AAC:
case MEDIA_FMT_SPX:
case MEDIA_FMT_M4A:
case MEDIA_FMT_OGG:
case MEDIA_FMT_WMA:
case MEDIA_FMT_AMR:
case MEDIA_FMT_AMRWB:
case MEDIA_FMT_OPS:
case MEDIA_FMT_FLAC:
return true;
default:
return false;
}
return false;
}
static int player_stack_size(media_format_t format)
{
int size = 8192;
switch (format) {
case MEDIA_FMT_AAC:
#ifdef DECODER_FAAD2_AAC_ENABLE
size = 48 * 1024;
#endif
break;
case MEDIA_FMT_M4A:
#ifdef DECODER_FAAD2_M4A_ENABLE
size = 48 * 1024;
#endif
break;
default:
break;
}
#ifdef UVOICE_RESAMPLE_ENABLE
size += 20 * 1024;
#endif
return size;
}
static void player_reset(player_t *player)
{
player->silent_time = 0;
player->consumed_len = 0;
player->pause = 0;
player->stop = 0;
player->error = 0;
player->blocking = 0;
player->fade_ignore = 0;
player->frame_skip = 0;
player->complete = 0;
player->pcm_reset = 0;
player->out_bypass = 0;
player->fade.state = FADE_NOP;
player->fade.pos = 0;
player->fade.reset = 0;
player->seek.state = SEEK_NOP;
player->seek.fade_request = 0;
player->seek.offset = 0;
player->type = MEDIA_TYPE_UNKNOWN;
player->format = MEDIA_FMT_UNKNOWN;
player->format_preferable = MEDIA_FMT_UNKNOWN;
memset(&player->pcm_info, 0, sizeof(player->pcm_info));
}
static void player_task(void *arg)
{
player_t *player = (player_t *)arg;
media_decoder_t *mdecoder;
media_loader_t *mloader;
int ret = 0;
if (!player) {
M_LOGE("player null !\n");
return;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->state != PLAYER_STAT_READY &&
player->state != PLAYER_STAT_STOP) {
M_LOGE("player can't start ! state %d\n",
player->state);
os_mutex_unlock(player->lock);
return;
}
mdecoder = player->mdecoder;
if (!mdecoder) {
M_LOGE("mdecoder null !\n");
os_mutex_unlock(player->lock);
return;
}
mloader = player->mloader;
if (!mloader) {
M_LOGE("mloader null !\n");
os_mutex_unlock(player->lock);
return;
}
if (mloader->action(mloader, PLAYER_START, NULL)) {
M_LOGE("start mloader failed !\n");
if (player->start_waiting) {
os_sem_signal(player->start_sem);
player->start_waiting = 0;
}
player_state_post(player, PLAYER_STAT_ERROR);
os_mutex_unlock(player->lock);
player_clr_source();
return;
}
if (mdecoder->action(mdecoder, PLAYER_START, NULL)) {
M_LOGE("start mdecoder failed !\n");
if (player->start_waiting) {
os_sem_signal(player->start_sem);
player->start_waiting = 0;
}
player_state_post(player, PLAYER_STAT_ERROR);
mloader->action(mloader, PLAYER_STOP, NULL);
os_mutex_unlock(player->lock);
player_clr_source();
return;
}
if (player->state == PLAYER_STAT_READY)
PLAYER_TRACE("ready->running\n");
else
PLAYER_TRACE("stop->running\n");
player->state = PLAYER_STAT_RUNNING;
player_state_post(player, player->state);
mloader->buffer_dirty_size = 0;
if (player->start_waiting) {
os_sem_signal(player->start_sem);
player->start_waiting = 0;
}
os_mutex_unlock(player->lock);
while (1) {
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->pause && !player->stop &&
player->fade.state != FADE_OUT) {
if (player->state == PLAYER_STAT_RUNNING) {
if (player->fade_enable && !player->fade_ignore) {
if (player->fade.state == FADE_NOP ||
player->fade.state == FADE_IN ||
player->fade.state == FADE_IN_END) {
if (player->fade.state == FADE_NOP)
player->fade.pos = player->fade.out_scope;
else
player_fade_config(player,
player->fade.in_period_ms,
player->fade.in_period_ms);
player->fade.state = FADE_OUT;
M_LOGD("fade out start, pos %d\n",
player->fade.pos);
os_mutex_unlock(player->lock);
continue;
}
}
if (mdecoder->action(mdecoder, PLAYER_PAUSE, NULL)) {
M_LOGE("pause mdecoder failed !\n");
player->stop = 1;
player->error = 1;
player->pause = 0;
if (player->pause_waiting) {
player->pause_waiting = 0;
os_sem_signal(player->pause_sem);
}
os_mutex_unlock(player->lock);
continue;
}
if (mloader->action(mloader, PLAYER_PAUSE, NULL)) {
M_LOGE("pause mloader failed !\n");
player->stop = 1;
player->error = 1;
player->pause = 0;
if (player->pause_waiting) {
player->pause_waiting = 0;
os_sem_signal(player->pause_sem);
}
os_mutex_unlock(player->lock);
continue;
}
if (player->frame_skip) {
out_stream_mute(player->out, 1);
player->frame_skip = 0;
}
out_stream_stop(player->out);
out_stream_release(player->out);
media_decoder_release(mdecoder);
#ifdef UVOICE_RESAMPLE_ENABLE
uvoice_resampler_release(player->resampler);
#endif
player_data_format_free(player);
player->mdecoder = NULL;
player->resampler = NULL;
player->out = NULL;
player->out_bypass = 0;
player->fade_ignore = 0;
player->fade.state = FADE_NOP;
if (player->seek.state != SEEK_NOP) {
player->seek.state = SEEK_NOP;
if (player->fade_enable && player->fade.reset) {
player_fade_config(player,
FADE_OUT_PERIOD_DEFAULT,
FADE_IN_PERIOD_DEFAULT);
player->fade.reset = 0;
}
}
if (player->seek.offset)
player->seek.offset = 0;
player->state = PLAYER_STAT_PAUSED;
player_state_post(player, player->state);
PLAYER_TRACE("running->pause\n");
if (player->pause_waiting) {
player->pause_waiting = 0;
os_sem_signal(player->pause_sem);
}
}
if (player->state == PLAYER_STAT_PAUSED && !player->stop) {
os_mutex_unlock(player->lock);
os_msleep(50);
continue;
}
} else if (player->state == PLAYER_STAT_PAUSED &&
!player->stop) {
player->out = out_stream_create();
if (!player->out) {
M_LOGE("alloc out stream failed !\n");
player->stop = 1;
if (player->resume_waiting) {
player->resume_waiting = 0;
os_sem_signal(player->resume_sem);
}
os_mutex_unlock(player->lock);
continue;
}
mdecoder = media_decoder_create(player->format);
if (!mdecoder) {
M_LOGE("create mdecoder failed !\n");
out_stream_release(player->out);
player->out = NULL;
player->stop = 1;
if (player->resume_waiting) {
player->resume_waiting = 0;
os_sem_signal(player->resume_sem);
}
os_mutex_unlock(player->lock);
continue;
}
mdecoder->output = player_output_render;
mdecoder->message = player_message_handle;
mdecoder->priv = player;
if (!mdecoder->initialized) {
mdecoder->decode = player_decode_default;
mdecoder->action = player_action_default;
mdecoder->initialized = 1;
}
player->mdecoder = mdecoder;
if (mloader->action(mloader, PLAYER_RESUME, NULL)) {
M_LOGE("mloader resume failed !\n");
media_decoder_release(mdecoder);
out_stream_release(player->out);
player->mdecoder = NULL;
player->out = NULL;
player->stop = 1;
if (player->resume_waiting) {
player->resume_waiting = 0;
os_sem_signal(player->resume_sem);
}
os_mutex_unlock(player->lock);
continue;
}
if (mdecoder->action(mdecoder, PLAYER_RESUME, NULL)) {
M_LOGE("mdecoder resume failed !\n");
media_decoder_release(player->mdecoder);
out_stream_release(player->out);
player->mdecoder = NULL;
player->out = NULL;
player->stop = 1;
if (player->resume_waiting) {
player->resume_waiting = 0;
os_sem_signal(player->resume_sem);
}
os_mutex_unlock(player->lock);
continue;
}
if (player->fade_enable) {
if (player->fade.state == FADE_NOP) {
player->fade.state = FADE_IN;
player->fade.pos = 0;
M_LOGD("fade in start\n");
} else if (player->fade.state == FADE_IN_END) {
player->fade.state = FADE_NOP;
}
}
player->state = PLAYER_STAT_RUNNING;
player_state_post(player, player->state);
PLAYER_TRACE("pause->resume\n");
if (player->resume_waiting) {
player->resume_waiting = 0;
os_sem_signal(player->resume_sem);
}
}
if (player->stop && player->fade.state != FADE_OUT) {
if (player->state == PLAYER_STAT_RUNNING) {
if (player->fade_enable && !player->fade_ignore &&
!player->error) {
if (player->fade.state == FADE_NOP) {
player->fade.state = FADE_OUT;
player->fade.pos = player->fade.out_scope;
M_LOGD("fade out start\n");
os_mutex_unlock(player->lock);
continue;
}
}
mdecoder->action(mdecoder, PLAYER_STOP, NULL);
mloader->action(mloader, PLAYER_STOP, NULL);
mloader->buffer_dirty_size = 0;
if (player->frame_skip) {
out_stream_mute(player->out, 1);
player->frame_skip = 0;
}
out_stream_stop(player->out);
#ifdef UVOICE_RESAMPLE_ENABLE
uvoice_resampler_release(player->resampler);
player->resampler = NULL;
#endif
media_decoder_reset(mdecoder);
player->consumed_len = 0;
player->out_bypass = 0;
player->fade.state = FADE_NOP;
if (player->seek.state != SEEK_NOP) {
player->seek.state = SEEK_NOP;
if (player->fade_enable && player->fade.reset) {
player_fade_config(player,
FADE_OUT_PERIOD_DEFAULT,
FADE_IN_PERIOD_DEFAULT);
player->fade.reset = 0;
}
}
if (player->seek.offset)
player->seek.offset = 0;
player->stop = 0;
if (player->pause)
player->pause = 0;
player->fade_ignore = 0;
player->state = PLAYER_STAT_STOP;
player_state_post(player, player->state);
if (player->cplt_waiting) {
os_sem_signal_all(player->cplt_sem);
player->cplt_waiting = 0;
}
os_mutex_unlock(player->lock);
PLAYER_TRACE("running->stop\n");
if (player->error) {
M_LOGI("player error, release it\n");
player_clr_source();
}
break;
} else if (player->state == PLAYER_STAT_PAUSED) {
mloader->action(mloader, PLAYER_STOP, NULL);
snd_free(mloader->buffer);
media_loader_release(mloader);
snd_free(player->media_info);
player->mloader = NULL;
player->media_info = NULL;
player_reset(player);
player->state = PLAYER_STAT_IDLE;
player_state_post(player, player->state);
if (player->cplt_waiting) {
os_sem_signal_all(player->cplt_sem);
player->cplt_waiting = 0;
}
os_mutex_unlock(player->lock);
PLAYER_TRACE("pause->idle\n");
break;
} else if (player->state == PLAYER_STAT_COMPLETE) {
out_stream_stop(player->out);
player->stop = 0;
player->complete = 0;
player->consumed_len = 0;
player->state = PLAYER_STAT_STOP;
player_state_post(player, player->state);
os_mutex_unlock(player->lock);
PLAYER_TRACE("complete->stop\n");
if (player->error)
player_clr_source();
if (player->cplt_waiting) {
os_sem_signal_all(player->cplt_sem);
player->cplt_waiting = 0;
}
break;
} else {
player->stop = 0;
M_LOGE("stop failed !\n");
}
}
if (player->complete && player->fade.state != FADE_OUT &&
player->state == PLAYER_STAT_RUNNING) {
mdecoder->action(mdecoder, PLAYER_COMPLETE, NULL);
mloader->action(mloader, PLAYER_COMPLETE, NULL);
mloader->buffer_dirty_size = 0;
if (player->frame_skip)
player->frame_skip = 0;
if (player->deep_cplt) {
media_decoder_release(mdecoder);
if (mloader->buffer)
snd_free(mloader->buffer);
media_loader_release(mloader);
player->mdecoder = NULL;
player->mloader = NULL;
}
player->fade.state = FADE_NOP;
player->fade_ignore = 0;
player->format_preferable = MEDIA_FMT_UNKNOWN;
player->state = PLAYER_STAT_COMPLETE;
player_state_post(player, player->state);
player->silent_time = os_current_time();
if (player->cplt_waiting) {
os_sem_signal_all(player->cplt_sem);
player->cplt_waiting = 0;
}
PLAYER_TRACE("running->complete\n");
} else if (!player->complete &&
player->state == PLAYER_STAT_COMPLETE) {
if (mloader != player->mloader) {
mloader = player->mloader;
M_LOGD("mloader update\n");
}
if (mdecoder != player->mdecoder) {
mdecoder = player->mdecoder;
M_LOGD("mdecoder update\n");
}
#ifdef ALIGENIE_ENABLE
if (mloader->action(mloader, PLAYER_START, NULL)) {
M_LOGE("mloader start failed !\n");
player->stop = 1;
player->error = 1;
if (player->start_waiting) {
player->start_waiting = 0;
os_sem_signal_all(player->start_sem);
}
os_mutex_unlock(player->lock);
continue;
}
if (mdecoder->action(mdecoder, PLAYER_START, NULL)) {
M_LOGE("mdecoder start failed !\n");
mloader->action(mloader, PLAYER_STOP, NULL);
player->stop = 1;
player->error = 1;
if (player->start_waiting) {
player->start_waiting = 0;
os_sem_signal_all(player->start_sem);
}
os_mutex_unlock(player->lock);
continue;
}
#endif
player->consumed_len = 0;
player->state = PLAYER_STAT_RUNNING;
player_state_post(player, player->state);
if (player->start_waiting) {
player->start_waiting = 0;
os_sem_signal_all(player->start_sem);
}
PLAYER_TRACE("complete->running\n");
if (player->pause || player->stop) {
os_mutex_unlock(player->lock);
continue;
}
}
if (player->state == PLAYER_STAT_RUNNING) {
if (player->seek.state == SEEK_PREPARE) {
if (player->seek.fade_request &&
player->fade_enable) {
if (player->fade.state == FADE_NOP) {
player->fade.state = FADE_OUT;
player->fade.pos = player->fade.out_scope;
M_LOGD("fade out start\n");
}
if (player->fade.state == FADE_OUT_END) {
player->seek.state = SEEK_START;
player->fade.state = FADE_IN;
player->fade.pos = 0;
mloader->action(mloader, PLAYER_SEEK,
(void *)player->seek.offset);
M_LOGD("fade in start\n");
}
} else {
player->seek.state = SEEK_START;
mloader->action(mloader, PLAYER_SEEK,
(void *)player->seek.offset);
}
} else if (player->seek.state == SEEK_COMPLETE &&
player->fade.state == FADE_NOP) {
M_LOGD("seek complete\n");
player->seek.state = SEEK_NOP;
if (player->fade_enable) {
player_fade_config(player,
FADE_OUT_PERIOD_DEFAULT,
FADE_IN_PERIOD_DEFAULT);
player->fade.reset = 0;
}
}
os_mutex_unlock(player->lock);
ret = mloader->read(mloader,
mloader->buffer + mloader->buffer_dirty_size,
mloader->buffer_size - mloader->buffer_dirty_size);
if (ret < 0) {
M_LOGE("load failed %d!\n", ret);
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
player->stop = 1;
player->error = 1;
os_mutex_unlock(player->lock);
continue;
} else if (ret == 0) {
if (mdecoder->pos_rebase) {
mloader->action(mloader, PLAYER_RELOAD, (void *)mdecoder->rebase_offset);
mdecoder->pos_rebase = 0;
mloader->buffer_dirty_size = 0;
player->consumed_len = (int)mdecoder->rebase_offset;
mdecoder->unproc_size = 0;
continue;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->pause || player->stop) {
if (player->fade.state == FADE_OUT)
player->fade.state = FADE_OUT_END;
if (player->fade.state == FADE_IN)
player->fade.state = FADE_IN_END;
os_mutex_unlock(player->lock);
continue;
}
if (mloader->buffer_dirty_size < mloader->buffer_size) {
M_LOGD("play complete\n");
player->complete = 1;
if (player->fade.state == FADE_OUT) {
M_LOGD("cancel fade out\n");
player->fade.state = FADE_NOP;
}
os_mutex_unlock(player->lock);
continue;
}
os_mutex_unlock(player->lock);
} else if (ret !=
mloader->buffer_size - mloader->buffer_dirty_size) {
M_LOGD("load %d ret %d\n",
mloader->buffer_size - mloader->buffer_dirty_size, ret);
}
mloader->buffer_dirty_size += ret;
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->frame_skip) {
M_LOGD("frame skipping\n");
os_mutex_unlock(player->lock);
continue;
}
os_mutex_unlock(player->lock);
if (mdecoder->decode(mdecoder,
mloader->buffer, mloader->buffer_dirty_size)) {
M_LOGE("decode failed !\n");
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
player->stop = 1;
player->error = 1;
os_mutex_unlock(player->lock);
continue;
}
player->consumed_len += mloader->buffer_dirty_size -
mdecoder->unproc_size;
if (mdecoder->unproc_size >= mloader->buffer_dirty_size) {
M_LOGD("decoder maybe error\n");
mdecoder->unproc_size = 0;
}
if (mdecoder->unproc_size > 0) {
snd_memmove(mloader->buffer,
mloader->buffer +
mloader->buffer_dirty_size - mdecoder->unproc_size,
mdecoder->unproc_size);
mloader->buffer_dirty_size = mdecoder->unproc_size;
mdecoder->unproc_size = 0;
} else {
mloader->buffer_dirty_size = 0;
}
if (player->out_bypass)
player->out_bypass = 0;
continue;
} else if (player->state == PLAYER_STAT_COMPLETE) {
if (os_current_time() - player->silent_time >
player->standby_msec) {
M_LOGD("standby end\n");
player->fade.state = FADE_NOP;
player->stop = 1;
player->error = 1;
os_mutex_unlock(player->lock);
continue;
}
if (out_stream_silent(player->out)) {
M_LOGE("standby failed !\n");
player->stop = 1;
player->error = 1;
os_mutex_unlock(player->lock);
continue;
}
}
os_mutex_unlock(player->lock);
os_msleep(player->idle_period);
}
if (player->stop_waiting) {
player->stop_waiting = 0;
os_sem_signal(player->stop_sem);
}
M_LOGD("exit\n");
}
static int player_start(void)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->stream_flowing) {
M_LOGE("player stream flowing !\n");
os_mutex_unlock(player->lock);
return -1;
}
if (player->state == PLAYER_STAT_READY ||
player->state == PLAYER_STAT_STOP) {
os_task_create(&player->task,
"uvoice_play_task",
player_task, player,
player_stack_size(player->format),
UVOICE_TASK_PRI_HIGHER);
player->start_waiting = 1;
os_mutex_unlock(player->lock);
os_sem_wait(player->start_sem, OS_WAIT_FOREVER);
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->state != PLAYER_STAT_RUNNING) {
M_LOGE("player start failed !\n");
os_mutex_unlock(player->lock);
return -1;
}
} else if (player->state == PLAYER_STAT_RUNNING &&
player->stop) {
player->stop = 0;
if (player->frame_skip)
player->frame_skip = 0;
if (player->fade_ignore)
player->fade_ignore = 0;
if (player->stop_waiting) {
M_LOGD("cancel stop waiting\n");
player->stop_waiting = 0;
os_sem_signal(player->stop_sem);
}
os_mutex_lock(player->fade.lock, OS_WAIT_FOREVER);
if (player->fade.state == FADE_OUT ||
player->fade.state == FADE_OUT_END) {
M_LOGD("fade out cancel, fade in start, pos %d\n",
player->fade.pos);
player->fade.state = FADE_IN;
player_fade_config_unlock(player,
player->fade.out_period_ms,
player->fade.out_period_ms);
}
os_mutex_unlock(player->fade.lock);
} else if (player->state == PLAYER_STAT_COMPLETE && !player->stop) {
#ifdef ALIGENIE_ENABLE
player->complete = 0;
#else
os_mutex_unlock(player->lock);
if (player->mloader->action(player->mloader,
PLAYER_START, NULL)) {
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
M_LOGE("mloader start failed !\n");
if (player->start_waiting) {
player->start_waiting = 0;
os_sem_signal(player->start_sem);
}
os_mutex_unlock(player->lock);
return -1;
}
if (player->mdecoder->action(player->mdecoder,
PLAYER_START, NULL)) {
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
M_LOGE("mdecoder start failed !\n");
player->mloader->action(player->mloader, PLAYER_STOP, NULL);
if (player->start_waiting) {
player->start_waiting = 0;
os_sem_signal(player->start_sem);
}
os_mutex_unlock(player->lock);
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
player->complete = 0;
player->start_waiting = 1;
os_mutex_unlock(player->lock);
os_sem_wait(player->start_sem, OS_WAIT_FOREVER);
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->state != PLAYER_STAT_RUNNING) {
M_LOGE("player not running !\n");
os_mutex_unlock(player->lock);
return -1;
}
#endif
}
os_mutex_unlock(player->lock);
return 0;
}
static int player_complete(void)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->stream_flowing) {
os_mutex_unlock(player->lock);
return -1;
}
if (!player_can_complete(player)) {
os_mutex_unlock(player->lock);
return -1;
}
if (player->complete) {
os_mutex_unlock(player->lock);
return -1;
}
if (player->pause_waiting || player->pause) {
M_LOGW("pause pending\n");
os_mutex_unlock(player->lock);
return -1;
}
if (player->stop_waiting || player->stop) {
M_LOGW("stop pending\n");
os_mutex_unlock(player->lock);
return -1;
}
player->complete = 1;
player->cplt_waiting = 1;
if (player->state == PLAYER_STAT_RUNNING) {
if (player->blocking) {
M_LOGI("cancel blocking\n");
player->fade_ignore = 1;
player->frame_skip = 1;
player->mloader->action(player->mloader,
PLAYER_UNBLOCK, NULL);
}
}
os_mutex_lock(player->fade.lock, OS_WAIT_FOREVER);
if (player->fade_enable && !player->fade_ignore &&
player->fade.state == FADE_NOP) {
player->fade.state = FADE_OUT;
player->fade.pos = player->fade.out_scope;
M_LOGD("fade out start\n");
}
os_mutex_unlock(player->fade.lock);
os_mutex_unlock(player->lock);
os_sem_wait(player->cplt_sem, OS_WAIT_FOREVER);
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->state != PLAYER_STAT_COMPLETE &&
player->state != PLAYER_STAT_RUNNING &&
player->state != PLAYER_STAT_STOP &&
player->state != PLAYER_STAT_IDLE) {
M_LOGE("player complete failed ! state %d\n",
player->state);
os_mutex_unlock(player->lock);
return -1;
} else {
M_LOGD("player complete\n");
}
os_mutex_unlock(player->lock);
if (player_clr_source()) {
M_LOGE("clr source failed !\n");
return -1;
}
return 0;
}
static int player_pause(void)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->stream_flowing) {
os_mutex_unlock(player->lock);
return -1;
}
if (!player_can_pause(player)) {
os_mutex_unlock(player->lock);
return -1;
}
if (player->pause || player->stop) {
os_mutex_unlock(player->lock);
return -1;
}
if (player->state == PLAYER_STAT_COMPLETE) {
M_LOGD("play complete, stop\n");
if (!player->stop) {
player->stop = 1;
player->error = 1;
player->cplt_waiting = 1;
os_mutex_unlock(player->lock);
if (os_sem_wait(player->cplt_sem, 5000)) {
M_LOGE("wait stop timeout !\n");
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->state == PLAYER_STAT_STOP) {
M_LOGD("player stop\n");
} else if (player->state == PLAYER_STAT_IDLE) {
M_LOGD("player idle\n");
} else {
M_LOGE("player stop failed ! state %d\n",
player->state);
os_mutex_unlock(player->lock);
return -1;
}
}
} else if (player->state == PLAYER_STAT_RUNNING) {
if (!player->pause) {
player->pause = 1;
player->pause_waiting = 1;
if (player->blocking) {
M_LOGI("cancel blocking\n");
player->fade_ignore = 1;
player->frame_skip = 1;
player->mloader->action(player->mloader,
PLAYER_UNBLOCK, NULL);
}
os_mutex_unlock(player->lock);
if (os_sem_wait(player->pause_sem, 20000)) {
M_LOGE("wait pause timeout !\n");
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->state != PLAYER_STAT_PAUSED) {
M_LOGE("pause failed ?!\n");
os_mutex_unlock(player->lock);
return -1;
} else {
M_LOGD("player pause\n");
}
}
}
os_mutex_unlock(player->lock);
return 0;
}
static int player_resume(void)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
bool resume_sync = false;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->stream_flowing) {
os_mutex_unlock(player->lock);
return -1;
}
if (!player_can_resume(player)) {
os_mutex_unlock(player->lock);
return -1;
}
if (!player->pause) {
os_mutex_unlock(player->lock);
return -1;
}
if (player->state == PLAYER_STAT_PAUSED)
resume_sync = true;
if (player->frame_skip)
player->frame_skip = 0;
if (player->fade_ignore)
player->fade_ignore = 0;
os_mutex_lock(player->fade.lock, OS_WAIT_FOREVER);
if (player->fade.state == FADE_OUT ||
player->fade.state == FADE_OUT_END) {
M_LOGD("fade out cancel, fade in start, pos %d\n",
player->fade.pos);
player->fade.state = FADE_IN;
player_fade_config_unlock(player,
player->fade.out_period_ms,
player->fade.out_period_ms);
}
os_mutex_unlock(player->fade.lock);
player->pause = 0;
if (player->pause_waiting) {
M_LOGI("cancel pause waiting\n");
player->pause_waiting = 0;
os_sem_signal(player->pause_sem);
}
if (resume_sync) {
player->resume_waiting = 1;
os_mutex_unlock(player->lock);
if (os_sem_wait(player->resume_sem, OS_WAIT_FOREVER)) {
M_LOGE("wait resume timeout !\n");
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->state != PLAYER_STAT_RUNNING &&
player->state != PLAYER_STAT_COMPLETE) {
M_LOGE("player resume failed ! state %d\n",
player->state);
os_mutex_unlock(player->lock);
return -1;
} else {
M_LOGD("player resume\n");
}
}
os_mutex_unlock(player->lock);
return 0;
}
static int player_stop(void)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (!player_can_stop(player)) {
os_mutex_unlock(player->lock);
return -1;
}
if (player->stop) {
os_mutex_unlock(player->lock);
return -1;
}
player->stop = 1;
player->stop_waiting = 1;
if (player->state == PLAYER_STAT_RUNNING) {
if (player->blocking) {
M_LOGI("cancel blocking\n");
player->fade_ignore = 1;
player->frame_skip = 1;
player->mloader->action(player->mloader,
PLAYER_UNBLOCK, NULL);
}
}
os_mutex_unlock(player->lock);
if (os_sem_wait(player->stop_sem, 5000)) {
M_LOGE("wait stop timeout !\n");
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->state == PLAYER_STAT_STOP) {
M_LOGD("player stop\n");
} else if (player->state == PLAYER_STAT_IDLE) {
M_LOGD("player idle\n");
} else {
M_LOGE("player stop failed ! state %d\n",
player->state);
os_mutex_unlock(player->lock);
return -1;
}
os_mutex_unlock(player->lock);
if (player_clr_source()) {
M_LOGE("clr source failed !\n");
return -1;
}
return 0;
}
static int player_pause_async(void)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (!player_can_pause(player)) {
os_mutex_unlock(player->lock);
return -1;
}
if (player->pause || player->stop) {
os_mutex_unlock(player->lock);
return -1;
}
if (player->state == PLAYER_STAT_RUNNING) {
player->pause = 1;
if (player->blocking) {
M_LOGI("cancel blocking\n");
player->fade_ignore = 1;
player->frame_skip = 1;
player->mloader->action(player->mloader,
PLAYER_UNBLOCK, NULL);
}
} else if (player->state == PLAYER_STAT_COMPLETE) {
player->stop = 1;
player->error = 1;
}
os_mutex_unlock(player->lock);
return 0;
}
static int player_resume_async(void)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (!player_can_resume(player)) {
os_mutex_unlock(player->lock);
return -1;
}
if (!player->pause) {
os_mutex_unlock(player->lock);
return -1;
}
player->pause = 0;
if (player->pause_waiting) {
M_LOGI("cancel pause waiting\n");
player->pause_waiting = 0;
os_sem_signal(player->pause_sem);
}
os_mutex_unlock(player->lock);
return 0;
}
static int player_stop_async(void)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (!player_can_stop(player)) {
os_mutex_unlock(player->lock);
return -1;
}
if (!player->stop) {
player->stop = 1;
if (player->state == PLAYER_STAT_RUNNING) {
if (player->blocking) {
M_LOGI("cancel blocking\n");
player->fade_ignore = 1;
player->frame_skip = 1;
player->mloader->action(player->mloader,
PLAYER_UNBLOCK, NULL);
}
}
}
os_mutex_unlock(player->lock);
return 0;
}
static void player_stream_task(void *arg)
{
stream_mgr_t *mgr = (stream_mgr_t *)arg;
media_decoder_t *mdecoder;
int rd_size = 0;
int ret = 0;
if (!mgr) {
M_LOGE("mgr null !\n");
return;
}
mdecoder = mgr->mdecoder;
if (!mdecoder) {
M_LOGE("mdecoder null !\n");
return;
}
if (mdecoder->action(mdecoder, STREAM_MGR_START, NULL)) {
M_LOGE("start mdecoder failed !\n");
return;
}
mgr->buffer_dirty_size = 0;
M_LOGD("start\n");
while (1) {
os_mutex_lock(mgr->lock, OS_WAIT_FOREVER);
if (mgr->abort) {
mdecoder->action(mdecoder, STREAM_MGR_STOP, NULL);
out_stream_stop(mgr->out);
os_mutex_unlock(mgr->lock);
M_LOGD("stream abort\n");
goto __exit;
}
rd_size = mgr->buffer_size - mgr->buffer_dirty_size;
while (uvoice_ringbuff_dirtysize(&mgr->rb) < rd_size) {
if (mgr->abort) {
mdecoder->action(mdecoder, STREAM_MGR_STOP, NULL);
out_stream_stop(mgr->out);
os_mutex_unlock(mgr->lock);
M_LOGD("stream abort\n");
goto __exit;
}
if (mgr->stop) {
rd_size = uvoice_ringbuff_dirtysize(&mgr->rb);
if (rd_size > 0) {
ret = uvoice_ringbuff_read(&mgr->rb,
mgr->buffer + mgr->buffer_dirty_size,
rd_size);
if (ret != rd_size)
M_LOGW("read %d ret %d\n", rd_size, ret);
mgr->buffer_dirty_size += ret;
M_LOGD("flush %d\n", mgr->buffer_dirty_size);
os_mutex_unlock(mgr->lock);
if (mdecoder->decode(mdecoder,
mgr->buffer, mgr->buffer_dirty_size))
M_LOGE("decode error !\n");
os_mutex_lock(mgr->lock, OS_WAIT_FOREVER);
}
mdecoder->action(mdecoder, STREAM_MGR_STOP, NULL);
out_stream_stop(mgr->out);
os_mutex_unlock(mgr->lock);
M_LOGD("stream end\n");
goto __exit;
}
mgr->rd_waiting = 1;
mgr->rd_len = rd_size;
if (mgr->wr_waiting) {
os_sem_signal(mgr->wr_sem);
mgr->wr_waiting = 0;
}
os_mutex_unlock(mgr->lock);
M_LOGD("waiting data %d dirtysize %d freesize %d\n",
mgr->rd_len,
uvoice_ringbuff_dirtysize(&mgr->rb),
uvoice_ringbuff_freesize(&mgr->rb));
os_sem_wait(mgr->rd_sem, OS_WAIT_FOREVER);
os_mutex_lock(mgr->lock, OS_WAIT_FOREVER);
mgr->rd_waiting = 0;
}
if (mgr->abort) {
mdecoder->action(mdecoder, STREAM_MGR_STOP, NULL);
out_stream_stop(mgr->out);
os_mutex_unlock(mgr->lock);
M_LOGD("stream abort\n");
goto __exit;
}
ret = uvoice_ringbuff_read(&mgr->rb,
mgr->buffer + mgr->buffer_dirty_size, rd_size);
if (ret < 0) {
M_LOGE("read failed !\n");
os_mutex_unlock(mgr->lock);
goto __exit;
} else if (ret != rd_size) {
M_LOGW("read %d ret %d\n", rd_size, ret);
}
if (mgr->wr_waiting &&
uvoice_ringbuff_freesize(&mgr->rb) >= mgr->wr_len) {
mgr->wr_waiting = 0;
os_sem_signal(mgr->wr_sem);
}
mgr->buffer_dirty_size += ret;
os_mutex_unlock(mgr->lock);
if (mdecoder->decode(mdecoder,
mgr->buffer, mgr->buffer_dirty_size)) {
M_LOGE("decode failed !\n");
break;
}
if (mdecoder->unproc_size >= mgr->buffer_dirty_size) {
M_LOGW("decoder error\n");
mdecoder->unproc_size = 0;
}
if (mdecoder->unproc_size > 0) {
snd_memmove(mgr->buffer,
mgr->buffer + mgr->buffer_dirty_size - mdecoder->unproc_size,
mdecoder->unproc_size);
mgr->buffer_dirty_size = mdecoder->unproc_size;
mdecoder->unproc_size = 0;
} else {
mgr->buffer_dirty_size = 0;
}
}
__exit:
if (mgr->wr_waiting) {
M_LOGD("wake up wr waiting\n");
os_sem_signal(mgr->wr_sem);
mgr->wr_waiting = 0;
} else {
mgr->stop = 0;
mgr->abort = 0;
if (mgr->cplt_waiting) {
mgr->cplt_waiting = 0;
os_sem_signal(mgr->cplt_sem);
}
}
M_LOGD("exit\n");
}
static int player_stream_fill(stream_mgr_t *mgr,
const uint8_t *buffer, int nbytes)
{
if (!mgr) {
M_LOGE("mgr null !\n");
return -1;
}
os_mutex_lock(mgr->lock, OS_WAIT_FOREVER);
if (mgr->stop || mgr->abort) {
os_mutex_unlock(mgr->lock);
return -1;
}
while (uvoice_ringbuff_freesize(&mgr->rb) < nbytes) {
if (mgr->rd_waiting) {
M_LOGD("wake rd waiting, nbytes %d dirtysize %d freesize %d\n",
nbytes,
uvoice_ringbuff_dirtysize(&mgr->rb),
uvoice_ringbuff_freesize(&mgr->rb));
os_sem_signal(mgr->rd_sem);
mgr->rd_waiting = 0;
}
mgr->wr_waiting = 1;
mgr->wr_len = nbytes;
if (mgr->state == STREAM_MGR_STAT_READY) {
mgr->state = STREAM_MGR_STAT_RUNNING;
os_task_create(&mgr->task,
"uvoice_stream_task",
player_stream_task, mgr,
player_stack_size(mgr->format),
UVOICE_TASK_PRI_HIGHER);
}
os_mutex_unlock(mgr->lock);
os_sem_wait(mgr->wr_sem, OS_WAIT_FOREVER);
os_mutex_lock(mgr->lock, OS_WAIT_FOREVER);
mgr->wr_waiting = 0;
if (mgr->stop || mgr->abort) {
M_LOGD("stop\n");
if (mgr->state != STREAM_MGR_STAT_RUNNING) {
if (mgr->cplt_waiting) {
mgr->cplt_waiting = 0;
os_sem_signal(mgr->cplt_sem);
}
} else {
if (mgr->rd_waiting) {
mgr->rd_waiting = 0;
os_sem_signal(mgr->rd_sem);
}
}
goto __exit;
}
}
if (uvoice_ringbuff_fill(&mgr->rb, buffer, nbytes) < 0) {
M_LOGE("fill failed !\n");
os_mutex_unlock(mgr->lock);
return -1;
}
if (mgr->rd_waiting &&
uvoice_ringbuff_dirtysize(&mgr->rb) >= mgr->rd_len) {
mgr->rd_waiting = 0;
os_sem_signal(mgr->rd_sem);
}
__exit:
os_mutex_unlock(mgr->lock);
return 0;
}
static int player_stream_handle(stream_mgr_t *mgr,
const uint8_t *buffer, int nbytes)
{
media_decoder_t *mdecoder;
int remaining_size = nbytes;
int avail_size;
int copy_size;
if (!mgr) {
M_LOGE("mgr null !\n");
return -1;
}
mdecoder = mgr->mdecoder;
if (!mdecoder) {
M_LOGE("mdecoder null !\n");
return -1;
}
avail_size = remaining_size + mgr->buffer_dirty_size;
if (avail_size < mgr->buffer_size) {
snd_memcpy(mgr->buffer + mgr->buffer_dirty_size,
buffer, remaining_size);
mgr->buffer_dirty_size += remaining_size;
goto __exit;
}
while (1) {
if (avail_size < mgr->buffer_size) {
if (remaining_size > 0) {
snd_memcpy(mgr->buffer + mgr->buffer_dirty_size,
buffer + nbytes - remaining_size,
remaining_size);
mgr->buffer_dirty_size += remaining_size;
}
break;
}
copy_size = MIN(remaining_size,
mgr->buffer_size - mgr->buffer_dirty_size);
snd_memcpy(mgr->buffer + mgr->buffer_dirty_size,
buffer + nbytes - remaining_size, copy_size);
remaining_size -= copy_size;
mgr->buffer_dirty_size += copy_size;
if (mdecoder->decode(mdecoder,
mgr->buffer, mgr->buffer_dirty_size)) {
M_LOGE("decode failed !\n");
return -1;
}
if (mdecoder->unproc_size >= mgr->buffer_dirty_size) {
M_LOGW("decoder error\n");
mdecoder->unproc_size = 0;
}
if (mdecoder->unproc_size > 0) {
snd_memmove(mgr->buffer,
mgr->buffer +
mgr->buffer_dirty_size - mdecoder->unproc_size,
mdecoder->unproc_size);
mgr->buffer_dirty_size = mdecoder->unproc_size;
mdecoder->unproc_size = 0;
} else {
mgr->buffer_dirty_size = 0;
}
avail_size = remaining_size + mgr->buffer_dirty_size;
}
__exit:
if (mgr->state == STREAM_MGR_STAT_READY) {
M_LOGD("stream handle running\n");
mgr->state = STREAM_MGR_STAT_RUNNING;
}
return 0;
}
static int player_put_stream(const uint8_t *buffer, int nbytes)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
stream_mgr_t *mgr;
const uint8_t *pbuffer = buffer;
bool need_split = false;
int remaining_size;
int ret;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
if (!buffer) {
M_LOGE("buffer null !\n");
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->state == PLAYER_STAT_RUNNING ||
player->state == PLAYER_STAT_COMPLETE) {
M_LOGE("player conflict !\n");
os_mutex_unlock(player->lock);
return -1;
}
if (!player->stream_flowing) {
M_LOGW("stream mgr not running\n");
os_mutex_unlock(player->lock);
return -1;
}
mgr = player->stream_mgr;
if (!mgr) {
M_LOGE("stream mgr not initialized !\n");
os_mutex_unlock(player->lock);
return -1;
}
os_mutex_unlock(player->lock);
os_mutex_lock(mgr->lock, OS_WAIT_FOREVER);
if (mgr->state == STREAM_MGR_STAT_IDLE ||
mgr->state == STREAM_MGR_STAT_STOP) {
M_LOGE("stream mgr released/stop !\n");
os_mutex_unlock(mgr->lock);
return -1;
}
if (mgr->stop || mgr->abort) {
M_LOGE("drop %d\n", nbytes);
os_mutex_unlock(mgr->lock);
return -1;
}
if (!mgr->cache_enable) {
ret = player_stream_handle(mgr, buffer, nbytes);
os_mutex_unlock(mgr->lock);
return ret;
}
remaining_size = nbytes;
if (remaining_size > (mgr->stream_pool_size / 2))
need_split = true;
os_mutex_unlock(mgr->lock);
if (need_split) {
while (remaining_size >= mgr->buffer_size) {
player_stream_fill(mgr, pbuffer, mgr->buffer_size);
pbuffer += mgr->buffer_size;
remaining_size -= mgr->buffer_size;
}
}
if (remaining_size > 0)
player_stream_fill(mgr, pbuffer, remaining_size);
return 0;
}
static int player_wait_complete(void)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->stream_flowing) {
os_mutex_unlock(player->lock);
return -1;
}
if (player->state == PLAYER_STAT_READY ||
player->state == PLAYER_STAT_STOP) {
os_mutex_unlock(player->lock);
os_msleep(100);
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
}
if (!player_can_wait_complete(player)) {
M_LOGE("state %d can't wait complete !\n",
player->state);
os_mutex_unlock(player->lock);
return -1;
}
player->cplt_waiting = 1;
os_mutex_unlock(player->lock);
os_sem_wait(player->cplt_sem, OS_WAIT_FOREVER);
M_LOGD("player complete\n");
return 0;
}
static int player_set_source(char *source)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
media_format_t format = MEDIA_FMT_UNKNOWN;
media_type_t type;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
if (!source) {
M_LOGE("source null !\n");
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->stream_flowing || player->stop || player->pause) {
os_mutex_unlock(player->lock);
return -1;
}
if (!player_can_set_source(player)) {
M_LOGE("state %d can't set source !\n", player->state);
os_mutex_unlock(player->lock);
return -1;
}
M_LOGD("source %s\n", source);
type = player_type_parse(source);
if (type == MEDIA_TYPE_UNKNOWN) {
M_LOGE("media type unsupport !\n");
player_state_post(player, PLAYER_STAT_FORMAT_UNSUPPORT);
os_mutex_unlock(player->lock);
return -1;
}
if (player->type != type) {
if (player->mloader) {
M_LOGD("release prev mloader\n");
M_LOGD("free prev mloader buffer %d\n",
player->mloader->buffer_size);
snd_free(player->mloader->buffer);
media_loader_release(player->mloader);
player->mloader = NULL;
} else if (player->type != MEDIA_TYPE_UNKNOWN) {
M_LOGE("prev mloader null !\n");
player->type = MEDIA_TYPE_UNKNOWN;
os_mutex_unlock(player->lock);
return -1;
}
player->type = type;
}
if (!player->mloader) {
player->mloader = media_loader_create(player->type, source);
if (!player->mloader) {
M_LOGE("create mloader failed !\n");
player->type = MEDIA_TYPE_UNKNOWN;
os_mutex_unlock(player->lock);
return -1;
}
player->mloader->message = player_message_handle;
player->mloader->priv = player;
} else {
media_loader_reset(player->mloader);
if (player->mloader->action(player->mloader,
PLAYER_NEXT, source)) {
M_LOGE("mloader update failed !\n");
os_mutex_unlock(player->lock);
return -1;
}
}
if (!player_format_assert(player->format_preferable)) {
format_parse_byname(source, &format);
if (format == MEDIA_FMT_UNKNOWN) {
if (player->mloader->get_format(player->mloader,
&format)) {
M_LOGE("mloader get source format failed !\n");
if (player->state == PLAYER_STAT_IDLE)
goto __exit;
os_mutex_unlock(player->lock);
return -1;
}
}
if (!player_format_assert(format)) {
M_LOGE("unknown format !\n");
player_state_post(player, PLAYER_STAT_FORMAT_UNSUPPORT);
if (player->state == PLAYER_STAT_IDLE)
goto __exit;
os_mutex_unlock(player->lock);
return -1;
}
} else {
format = player->format_preferable;
}
if (player->format != format) {
if (player->mdecoder) {
media_decoder_release(player->mdecoder);
player->mdecoder = NULL;
} else if (player->format != MEDIA_FMT_UNKNOWN) {
M_LOGE("prev mdecoder null !\n");
goto __exit;
}
player->format = format;
}
if (!player->mdecoder) {
player->mdecoder = media_decoder_create(player->format);
if (!player->mdecoder) {
M_LOGE("create mdecoder failed !\n");
if (player->state == PLAYER_STAT_IDLE)
goto __exit;
os_mutex_unlock(player->lock);
return -1;
}
player->mdecoder->output = player_output_render;
player->mdecoder->message = player_message_handle;
player->mdecoder->priv = player;
if (!player->mdecoder->initialized) {
player->mdecoder->decode = player_decode_default;
player->mdecoder->action = player_action_default;
player->mdecoder->initialized = 1;
}
if (!player->mloader->buffer ||
player->mloader->buffer_size != player->mdecoder->input_size) {
if (player->mloader->buffer) {
M_LOGD("free prev mloader buffer %d\n",
player->mloader->buffer_size);
snd_free(player->mloader->buffer);
}
player->mloader->buffer_size = player->mdecoder->input_size;
player->mloader->buffer = snd_zalloc(
player->mloader->buffer_size, AFM_MAIN);
if (!player->mloader->buffer) {
M_LOGE("alloc mloader buffer failed !\n");
if (player->state == PLAYER_STAT_IDLE)
goto __exit1;
os_mutex_unlock(player->lock);
return -1;
}
}
} else {
media_decoder_reset(player->mdecoder);
if (!player->mloader->buffer) {
M_LOGD("alloc mloader buffer %d\n",
player->mdecoder->input_size);
player->mloader->buffer_size = player->mdecoder->input_size;
player->mloader->buffer = snd_zalloc(
player->mloader->buffer_size, AFM_MAIN);
if (!player->mloader->buffer) {
M_LOGE("alloc mloader buffer failed !\n");
os_mutex_unlock(player->lock);
return -1;
}
}
}
if (!player->out) {
player->out = out_stream_create();
if (!player->out) {
M_LOGE("alloc out stream failed !\n");
goto __exit2;
}
}
if (!player->media_info) {
player->media_info = snd_zalloc(
sizeof(media_info_t), AFM_EXTN);
if (!player->media_info) {
M_LOGE("alloc media info failed !\n");
goto __exit3;
}
} else {
memset(player->media_info, 0, sizeof(media_info_t));
}
player->mloader->get_mediainfo(player->mloader,
player->media_info, player->format);
if (player->state == PLAYER_STAT_IDLE) {
player->state = PLAYER_STAT_READY;
player_state_post(player, player->state);
PLAYER_TRACE("idle->ready\n");
} else if (player->state == PLAYER_STAT_COMPLETE) {
os_mutex_unlock(player->lock);
player_start();
return 0;
}
os_mutex_unlock(player->lock);
return 0;
__exit3:
out_stream_release(player->out);
player->out = NULL;
__exit2:
snd_free(player->mloader->buffer);
__exit1:
media_decoder_release(player->mdecoder);
player->mdecoder = NULL;
__exit:
media_loader_release(player->mloader);
player->mloader = NULL;
player_reset(player);
player->state = PLAYER_STAT_IDLE;
player_state_post(player, player->state);
os_mutex_unlock(player->lock);
return -1;
}
static int player_clr_source(void)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->state == PLAYER_STAT_IDLE) {
os_mutex_unlock(player->lock);
return -1;
}
if (!player_can_clr_source(player)) {
M_LOGE("state %d can't clr source !\n", player->state);
os_mutex_unlock(player->lock);
return -1;
}
out_stream_release(player->out);
snd_free(player->media_info);
player->media_info = NULL;
player->out = NULL;
#ifdef UVOICE_RESAMPLE_ENABLE
if (player->resampler) {
uvoice_resampler_release(player->resampler);
player->resampler = NULL;
}
#endif
if (player->mdecoder) {
media_decoder_release(player->mdecoder);
player->mdecoder = NULL;
}
if (player->mloader) {
if (player->mloader->buffer)
snd_free(player->mloader->buffer);
media_loader_release(player->mloader);
player->mloader = NULL;
}
player_data_format_free(player);
player_reset(player);
if (player->state == PLAYER_STAT_READY)
PLAYER_TRACE("ready->idle\n");
else
PLAYER_TRACE("stop->idle\n");
player->state = PLAYER_STAT_IDLE;
player_state_post(player, player->state);
os_mutex_unlock(player->lock);
return 0;
}
static int player_set_stream(media_format_t format,
int cache_enable, int cache_size)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
stream_mgr_t *mgr;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
if (!player_format_assert(format)) {
M_LOGE("format unsupport !\n");
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->stream_flowing) {
os_mutex_unlock(player->lock);
return -1;
}
if (!player_can_set_stream(player)) {
M_LOGE("player conflict ! state %d\n", player->state);
os_mutex_unlock(player->lock);
return -1;
}
if (player->stream_mgr) {
M_LOGE("stream mgr not release !\n");
os_mutex_unlock(player->lock);
return -1;
}
mgr = snd_zalloc(sizeof(stream_mgr_t), AFM_EXTN);
if (!mgr) {
M_LOGE("alloc stream mgr failed !\n");
os_mutex_unlock(player->lock);
return -1;
}
mgr->format = format;
M_LOGD("format %d\n", mgr->format);
mgr->out = out_stream_create();
if (!mgr->out) {
M_LOGE("create out stream failed !\n");
goto __exit;
}
mgr->mdecoder = media_decoder_create(mgr->format);
if (!mgr->mdecoder) {
M_LOGE("create mdecoder failed !\n");
goto __exit1;
}
mgr->mdecoder->output = player_output_render;
mgr->mdecoder->message = player_message_handle;
mgr->mdecoder->priv = player;
if (!mgr->mdecoder->initialized) {
mgr->mdecoder->decode = player_decode_default;
mgr->mdecoder->action = player_action_default;
mgr->mdecoder->initialized = 1;
}
mgr->buffer_size = mgr->mdecoder->input_size;
mgr->buffer = snd_zalloc(mgr->buffer_size, AFM_MAIN);
if (!mgr->buffer) {
M_LOGE("alloc buffer failed !\n");
goto __exit2;
}
mgr->cache_enable = cache_enable;
if (mgr->cache_enable) {
mgr->stream_pool_size = MAX(mgr->buffer_size, cache_size);
if (mgr->stream_pool_size < mgr->buffer_size * 2) {
M_LOGE("stream pool size %d not enough !\n",
mgr->stream_pool_size);
goto __exit3;
}
M_LOGD("stream pool size %d\n", mgr->stream_pool_size);
mgr->stream_pool = snd_zalloc(mgr->stream_pool_size + 4,
AFM_EXTN);
if (!mgr->stream_pool) {
M_LOGE("alloc stream pool failed !\n");
goto __exit3;
}
if (uvoice_ringbuff_init(&mgr->rb,
mgr->stream_pool, mgr->stream_pool_size)) {
M_LOGE("init stream pool failed !\n");
goto __exit4;
}
}
mgr->cplt_sem = os_sem_new(0);
mgr->wr_sem = os_sem_new(0);
mgr->rd_sem = os_sem_new(0);
mgr->lock = os_mutex_new();
player->stream_mgr = mgr;
player->stream_flowing = 1;
mgr->state = STREAM_MGR_STAT_READY;
os_mutex_unlock(player->lock);
M_LOGI("stream mgr ready\n");
return 0;
__exit4:
snd_free(mgr->stream_pool);
__exit3:
snd_free(mgr->buffer);
__exit2:
media_decoder_release(mgr->mdecoder);
mgr->mdecoder = NULL;
__exit1:
out_stream_release(mgr->out);
__exit:
snd_free(mgr);
os_mutex_unlock(player->lock);
return -1;
}
static int player_clr_stream(int immediate)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
stream_mgr_t *mgr;
media_decoder_t *mdecoder;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
mgr = player->stream_mgr;
if (!mgr) {
M_LOGI("no stream mgr\n");
goto __exit;
}
os_mutex_lock(mgr->lock, OS_WAIT_FOREVER);
mdecoder = mgr->mdecoder;
if (!mdecoder) {
M_LOGE("mdecoder null !\n");
os_mutex_unlock(mgr->lock);
os_mutex_unlock(player->lock);
return -1;
}
if (mgr->cache_enable) {
if (mgr->state == STREAM_MGR_STAT_READY &&
uvoice_ringbuff_dirtysize(&mgr->rb) > 0) {
if (!immediate) {
os_task_create(&mgr->task,
"uvoice_stream_task",
player_stream_task, mgr,
player_stack_size(mgr->format),
UVOICE_TASK_PRI_HIGHER);
mgr->state = STREAM_MGR_STAT_RUNNING;
}
}
if (mgr->state == STREAM_MGR_STAT_RUNNING) {
if (immediate)
mgr->abort = 1;
else
mgr->stop = 1;
if (mgr->rd_waiting) {
os_sem_signal(mgr->rd_sem);
mgr->rd_waiting = 0;
}
if (mgr->wr_waiting) {
os_sem_signal(mgr->wr_sem);
mgr->wr_waiting = 0;
}
mgr->cplt_waiting = 1;
os_mutex_unlock(mgr->lock);
M_LOGD("waiting stream stop\n");
os_sem_wait(mgr->cplt_sem, OS_WAIT_FOREVER);
M_LOGD("stream stop\n");
os_mutex_lock(mgr->lock, OS_WAIT_FOREVER);
if (uvoice_ringbuff_dirtysize(&mgr->rb) > 0)
M_LOGW("not flush %d\n",
uvoice_ringbuff_dirtysize(&mgr->rb));
}
} else {
mdecoder->action(mdecoder, STREAM_MGR_STOP, NULL);
out_stream_stop(mgr->out);
}
player->stream_flowing = 0;
player->stream_mgr = NULL;
os_mutex_unlock(mgr->lock);
out_stream_release(mgr->out);
media_decoder_release(mgr->mdecoder);
#ifdef UVOICE_RESAMPLE_ENABLE
uvoice_resampler_release(player->resampler);
player->resampler = NULL;
#endif
player_data_format_free(player);
os_sem_free(mgr->rd_sem);
os_sem_free(mgr->wr_sem);
os_sem_free(mgr->cplt_sem);
os_mutex_free(mgr->lock);
snd_free(mgr->buffer);
if (mgr->stream_pool)
snd_free(mgr->stream_pool);
snd_free(mgr);
M_LOGI("stream mgr release\n");
__exit:
os_mutex_unlock(player->lock);
return 0;
}
static int player_set_pcminfo(int rate, int channels, int bits,
int frames)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
media_pcminfo_t *pcminfo;
int changed = 0;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
if (!pcm_rate_valid(rate)) {
M_LOGE("rate %d invalid !\n", rate);
return -1;
}
if (!pcm_channel_valid(channels)) {
M_LOGE("channels %d invalid !\n", channels);
return -1;
}
if (!pcm_bits_valid(bits)) {
M_LOGE("bits %d invalid !\n", bits);
return -1;
}
if (frames <= 0) {
M_LOGE("frames %d invalid !\n", frames);
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (!player_can_set_config(player)) {
M_LOGE("can't set config !\n");
os_mutex_unlock(player->lock);
return -1;
}
if (player->stream_mgr)
pcminfo = &player->stream_mgr->pcm_info;
else
pcminfo = &player->pcm_info;
if (pcminfo->rate != rate) {
if (pcm_rate_valid(pcminfo->rate))
changed = 1;
pcminfo->rate = rate;
}
if (pcminfo->channels != channels) {
if (pcm_channel_valid(pcminfo->channels))
changed = 1;
pcminfo->channels = channels;
}
if (pcminfo->bits != bits) {
if (pcm_bits_valid(pcminfo->bits))
changed = 1;
pcminfo->bits = bits;
}
if (!player->stream_flowing &&
player->state == PLAYER_STAT_COMPLETE)
player->pcm_reset = changed;
pcminfo->frames = frames;
if (player->mdecoder && player->mdecoder->action)
player->mdecoder->action(player->mdecoder,
PLAYER_CONFIGURE, pcminfo);
if (player->stream_mgr &&
player->stream_mgr->mdecoder &&
player->stream_mgr->mdecoder->action) {
player->stream_mgr->mdecoder->action(
player->stream_mgr->mdecoder,
PLAYER_CONFIGURE, pcminfo);
}
M_LOGI("rate %d channels %d bits %d frames %d change %u\n",
pcminfo->rate,
pcminfo->channels,
pcminfo->bits, pcminfo->frames, player->pcm_reset);
os_mutex_unlock(player->lock);
return 0;
}
static int player_set_fade(int out_period, int in_period)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
if (out_period < 0 || out_period > 100) {
M_LOGE("out_period %d invalid !\n", out_period);
return -1;
}
if (in_period < 0 || in_period > 100) {
M_LOGE("in_period %d invalid !\n", in_period);
return -1;
}
player_fade_config(player, out_period, in_period);
return 0;
}
static int player_set_format(media_format_t format)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
if (!player_format_assert(format)) {
M_LOGE("format %d unsupport !\n", format);
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->format_preferable != format)
player->format_preferable = format;
os_mutex_unlock(player->lock);
return 0;
}
static int player_set_outdevice(audio_out_device_t device)
{
snd_device_t _device = SND_DEVICE_NONE;
switch (device) {
case AUDIO_OUT_DEVICE_SPEAKER:
_device = SND_DEVICE_OUT_SPEAKER;
break;
case AUDIO_OUT_DEVICE_HEADPHONE:
_device = SND_DEVICE_OUT_HEADPHONE;
break;
case AUDIO_OUT_DEVICE_HEADSET:
_device = SND_DEVICE_OUT_HEADSET;
break;
case AUDIO_OUT_DEVICE_RECEIVER:
_device = SND_DEVICE_OUT_RECEIVER;
break;
case AUDIO_OUT_DEVICE_SPEAKER_AND_HEADPHONE:
_device = SND_DEVICE_OUT_SPEAKER_AND_HEADPHONE;
break;
case AUDIO_OUT_DEVICE_SPEAKER_AND_HEADSET:
_device = SND_DEVICE_OUT_SPEAKER_AND_HEADSET;
break;
default:
return -1;
}
return out_device_set(_device);
}
static int player_set_external_pa(audio_extpa_info_t *info)
{
return out_extpa_set(info);
}
static int player_set_standby(int msec)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
if (msec < 0) {
M_LOGE("arg %d invalid !\n", msec);
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->standby_msec != msec)
player->standby_msec = msec;
os_mutex_unlock(player->lock);
return 0;
}
static int player_get_state(player_state_t *state)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
if (!state) {
M_LOGE("arg null !\n");
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
*state = player->state;
os_mutex_unlock(player->lock);
return 0;
}
static int player_get_delay(int *delay_ms)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
if (!delay_ms) {
M_LOGE("arg null !\n");
return -1;
}
*delay_ms = player->idle_period;
return 0;
}
static int player_get_mediainfo(media_info_t *info)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
if (!info) {
M_LOGE("arg null !\n");
return -1;
}
if (!player->media_info) {
M_LOGE("media info not found\n");
return -1;
}
if (player->media_info->valid) {
memcpy(info, player->media_info, sizeof(media_info_t));
} else {
if (!player->mloader) {
M_LOGW("mloader released, ignore\n");
return -1;
}
player->mloader->get_mediainfo(player->mloader,
player->media_info, player->format);
if (player->media_info->valid)
memcpy(info, player->media_info, sizeof(media_info_t));
}
return 0;
}
static int player_get_cacheinfo(int *cache_size)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
media_loader_t *mloader;
cache_info_t cache_info;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
if (!cache_size) {
M_LOGE("arg null !\n");
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->type == MEDIA_TYPE_HTTP) {
mloader = player->mloader;
if (!mloader) {
M_LOGE("mloader null !\n");
os_mutex_unlock(player->lock);
return -1;
}
memset(&cache_info, 0, sizeof(cache_info));
if (mloader->get_cacheinfo &&
mloader->get_cacheinfo(mloader, &cache_info)) {
M_LOGE("get cache info failed !\n");
os_mutex_unlock(player->lock);
return -1;
}
*cache_size = cache_info.avail_cache_size;
}
os_mutex_unlock(player->lock);
return 0;
}
static int player_get_duration(int *duration)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
if (!duration) {
M_LOGE("arg null !\n");
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->state == PLAYER_STAT_RUNNING ||
player->state == PLAYER_STAT_PAUSED ||
player->state == PLAYER_STAT_COMPLETE ||
player->state == PLAYER_STAT_STOP) {
if (player->media_info) {
if (player->media_info->duration > 0)
*duration = player->media_info->duration;
else if (player->media_info->bitrate > 0)
*duration = (player->media_info->media_size * 8) /
player->media_info->bitrate;
}
}
os_mutex_unlock(player->lock);
return 0;
}
static int player_get_position(int *position)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
if (!position) {
M_LOGE("arg null !\n");
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->state == PLAYER_STAT_RUNNING ||
player->state == PLAYER_STAT_PAUSED ||
player->state == PLAYER_STAT_COMPLETE) {
if (player->media_info &&
player->media_info->bitrate > 0) {
*position = (player->consumed_len * 8) /
player->media_info->bitrate;
if (player->state == PLAYER_STAT_COMPLETE) {
int duration = (player->media_info->media_size * 8) /
player->media_info->bitrate;
if (abs(*position - duration) < 3)
*position = duration;
}
}
}
os_mutex_unlock(player->lock);
return 0;
}
static int player_set_volume(int volume)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
int ret;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
if (player->sw_volume) {
if (volume > 100 && player->vol_level < 100)
volume = 100;
if (volume < 0 || volume > 100) {
M_LOGE("volume %d invalid !\n", volume);
return -1;
}
os_mutex_lock(player->vol_lock, OS_WAIT_FOREVER);
if (player->vol_level != volume) {
player->vol_level = volume;
ret = os_kv_set(PLAYER_VOLUME_LEVEL_KEY,
&player->vol_level,
sizeof(player->vol_level), 0);
if (ret) {
M_LOGE("kv set failed %d!\n", ret);
os_mutex_unlock(player->vol_lock);
return -1;
}
}
os_mutex_unlock(player->vol_lock);
} else {
if (out_volume_set(volume)) {
M_LOGE("set volume failed !\n");
return -1;
}
}
return 0;
}
static int player_get_volume(int *volume)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
int vol;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
if (!volume) {
M_LOGE("arg null !\n");
return -1;
}
if (player->sw_volume) {
os_mutex_lock(player->vol_lock, OS_WAIT_FOREVER);
*volume = player->vol_level;
os_mutex_unlock(player->vol_lock);
} else {
vol = out_volume_get();
if (vol < 0) {
M_LOGE("get volume failed !\n");
return -1;
}
*volume = vol;
}
return 0;
}
static int player_cache_config(cache_config_t *config)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
if (!config) {
M_LOGE("config null !\n");
return -1;
}
if (config->place < 0 || config->place > 2) {
M_LOGE("place %d unsupport !\n", config->place);
return -1;
}
if ((config->place == 1) ||
(config->place == 2 && config->mem_size < 40)) {
M_LOGE("config invalid !\n");
return -1;
}
#ifdef UVOICE_HTTP_ENABLE
http_cache_config(config);
#endif
return 0;
}
static int player_volume_range(int *max, int *min)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
if (player->sw_volume) {
if (min)
*min = 0;
if (max)
*max = 100;
} else {
out_volume_range(max, min);
}
return 0;
}
static int player_playback(char *source)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
int standby_ms;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->stream_flowing) {
M_LOGE("player stream flowing !\n");
os_mutex_unlock(player->lock);
return -1;
}
if (player->state != PLAYER_STAT_IDLE) {
M_LOGE("player state not idle !\n");
os_mutex_unlock(player->lock);
return -1;
}
standby_ms = player->standby_msec;
player->standby_msec = -1;
os_mutex_unlock(player->lock);
if (player_set_source(source)) {
M_LOGE("set source failed !\n");
return -1;
}
player_task(player);
player->standby_msec = standby_ms;
return 0;
}
static int player_seek(int position)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
media_loader_t *mloader;
media_info_t *media_info;
cache_info_t cache_info;
int seek_interval;
int seek_offset;
int val = 0;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
if (position < 0) {
M_LOGE("arg %d invalid !\n", position);
return -1;
}
if (player_get_duration(&val)) {
M_LOGE("get duration failed !\n");
return -1;
}
if (val <= 0) {
M_LOGE("not seekable\n");
return -1;
}
if (position >= val) {
M_LOGE("arg %d overrange !\n", position);
return -1;
}
val = 0;
if (player_get_position(&val)) {
M_LOGE("get position failed !\n");
return -1;
}
seek_interval = position - val;
if (seek_interval == 0) {
M_LOGW("no seek interval\n");
goto __exit;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (!player_can_seek(player)) {
M_LOGE("player state %d can't seek\n",
player->state);
os_mutex_unlock(player->lock);
return -1;
}
if (player->seek.state != SEEK_NOP) {
M_LOGE("seek state %d can't seek\n",
player->seek.state);
os_mutex_unlock(player->lock);
return -1;
}
mloader = player->mloader;
if (!mloader) {
M_LOGE("mloader null\n");
os_mutex_unlock(player->lock);
return -1;
}
media_info = player->media_info;
if (!media_info) {
M_LOGE("media info null\n");
os_mutex_unlock(player->lock);
return -1;
}
seek_offset = (media_info->bitrate / 8) * seek_interval;
if (seek_offset == 0) {
M_LOGW("not seekable\n");
os_mutex_unlock(player->lock);
return -1;
}
if (!mloader->get_cacheinfo) {
M_LOGD("seek %ds offset %d\n", seek_interval, seek_offset);
if (player->state == PLAYER_STAT_RUNNING &&
player->fade_enable) {
player_fade_config(player, 30, 60);
player->fade.reset = 0;
player->seek.fade_request = 1;
} else {
player->seek.fade_request = 0;
}
player->seek.state = SEEK_PREPARE;
player->seek.offset = seek_offset;
os_mutex_unlock(player->lock);
goto __exit;
}
os_mutex_unlock(player->lock);
memset(&cache_info, 0, sizeof(cache_info));
if (mloader->get_cacheinfo(mloader, &cache_info)) {
M_LOGE("get cache info failed\n");
return -1;
}
M_LOGD("seek %ds offset %d\n", seek_interval, seek_offset);
M_LOGD("avail_cache_size %d dirty_cache_size %d\n",
cache_info.avail_cache_size, cache_info.dirty_cache_size);
if ((seek_offset > 0 &&
cache_info.avail_cache_size >= seek_offset) ||
(seek_offset < 0 &&
cache_info.dirty_cache_size >= abs(seek_offset))) {
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (player->state == PLAYER_STAT_RUNNING &&
player->fade_enable) {
player_fade_config(player, 30, 60);
player->fade.reset = 0;
player->seek.fade_request = 1;
} else {
player->seek.fade_request = 0;
}
player->seek.state = SEEK_PREPARE;
player->seek.offset = seek_offset;
os_mutex_unlock(player->lock);
goto __exit;
} else {
if ((seek_offset > 0 &&
cache_info.seek_forward_limit >= seek_offset) ||
(seek_offset < 0 &&
cache_info.seek_backward_limit >= abs(seek_offset))) {
if (player->state == PLAYER_STAT_RUNNING) {
mloader->action(mloader,
PLAYER_SEEK_BEGIN, NULL);
player_pause();
mloader->action(mloader,
PLAYER_SEEK, (void *)seek_offset);
player_resume();
mloader->action(mloader,
PLAYER_SEEK_END, NULL);
} else if (player->state == PLAYER_STAT_PAUSED) {
mloader->action(mloader,
PLAYER_SEEK, (void *)seek_offset);
}
} else {
M_LOGW("avail_cache_size %d dirty_cache_size %d\n",
cache_info.avail_cache_size,
cache_info.dirty_cache_size);
M_LOGW("forward_limit %d backward_limit %d\n",
cache_info.seek_forward_limit,
cache_info.seek_backward_limit);
}
}
__exit:
return 0;
}
static int player_eq_enable(int enable)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
int ret = 0;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
if (enable)
ret = audio_param_set(PARAM_KEY_EFFECT_EQUALIZER,
PARAM_VAL_ENABLE);
else
ret = audio_param_set(PARAM_KEY_EFFECT_EQUALIZER,
PARAM_VAL_DISABLE);
return ret;
}
int player_pcmdump_enable(int enable)
{
int val = enable ? PARAM_VAL_ENABLE : PARAM_VAL_DISABLE;
return audio_param_set(PARAM_KEY_OUT_PCM_DUMP, val);
}
static int player_state_dump(void)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
M_LOGI("state %d\n", player->state);
M_LOGI("pause %u\n", player->pause);
M_LOGI("stop %u\n", player->stop);
M_LOGI("complete %u\n", player->complete);
M_LOGI("pcm_reset %u\n", player->pcm_reset);
M_LOGI("error %u\n", player->error);
M_LOGI("stream_flowing %u\n", player->stream_flowing);
M_LOGI("cplt_waiting %u\n", player->cplt_waiting);
M_LOGI("start_waiting %u\n", player->start_waiting);
M_LOGI("pause_waiting %u\n", player->pause_waiting);
M_LOGI("resume_waiting %u\n", player->resume_waiting);
M_LOGI("stop_waiting %u\n", player->stop_waiting);
M_LOGI("blocking %u\n", player->blocking);
M_LOGI("deep_cplt %u\n", player->deep_cplt);
M_LOGI("frame_skip %u\n", player->frame_skip);
M_LOGI("sw_volume %u\n", player->sw_volume);
M_LOGI("out_bypass %u\n", player->out_bypass);
M_LOGI("type %d format %d\n", player->type, player->format);
M_LOGI("format_preferable %d\n", player->format_preferable);
M_LOGI("silent_time %lld\n", player->silent_time);
M_LOGI("consumed_len %d\n", player->consumed_len);
M_LOGI("idle_period %d\n", player->idle_period);
M_LOGI("standby_msec %d\n", player->standby_msec);
M_LOGI("reference_count %d\n", player->reference_count);
M_LOGI("seek state %d\n", player->seek.state);
M_LOGI("seek offset %d\n", player->seek.offset);
M_LOGI("seek fade_request %d\n", player->seek.fade_request);
M_LOGI("fade_enable %d\n", player->fade_enable);
M_LOGI("fade_ignore %d\n", player->fade_ignore);
M_LOGI("fade state %d\n", player->fade.state);
M_LOGI("fade pos %d\n", player->fade.pos);
M_LOGI("fade out_scope %d out_period_ms %d\n",
player->fade.out_scope, player->fade.out_period_ms);
M_LOGI("fade in_scope %d in_period_ms %d\n",
player->fade.in_scope, player->fade.in_period_ms);
M_LOGI("pcm rate %d\n", player->pcm_info.rate);
M_LOGI("pcm bits %d\n", player->pcm_info.bits);
M_LOGI("pcm channels %d\n", player->pcm_info.channels);
M_LOGI("pcm frames %d\n", player->pcm_info.frames);
M_LOGI("out stream 0x%x\n", (uint32_t)player->out);
M_LOGI("mloader 0x%x\n", (uint32_t)player->mloader);
M_LOGI("mdecoder 0x%x\n", (uint32_t)player->mdecoder);
if (player->stream_mgr) {
os_mutex_lock(player->stream_mgr->lock, OS_WAIT_FOREVER);
M_LOGI("stream mgr state %d\n",
player->stream_mgr->state);
M_LOGI("stream mgr cache_enable %u\n",
player->stream_mgr->cache_enable);
M_LOGI("stream mgr buffer_size %d\n",
player->stream_mgr->buffer_size);
M_LOGI("stream mgr buffer_dirty_size %d\n",
player->stream_mgr->buffer_dirty_size);
M_LOGI("stream mgr wr_len %d\n",
player->stream_mgr->wr_len);
M_LOGI("stream mgr rd_len %d\n",
player->stream_mgr->rd_len);
M_LOGI("stream mgr wr_waiting %u\n",
player->stream_mgr->wr_waiting);
M_LOGI("stream mgr rd_waiting %u\n",
player->stream_mgr->rd_waiting);
M_LOGI("stream mgr stop %u\n",
player->stream_mgr->stop);
M_LOGI("stream mgr abort %u\n",
player->stream_mgr->abort);
M_LOGI("stream mgr format %d\n",
player->stream_mgr->format);
M_LOGI("stream mgr pcm rate %d\n",
player->stream_mgr->pcm_info.rate);
M_LOGI("stream mgr pcm bits %d\n",
player->stream_mgr->pcm_info.bits);
M_LOGI("stream mgr pcm channels %d\n",
player->stream_mgr->pcm_info.channels);
M_LOGI("stream mgr pcm frames %d\n",
player->stream_mgr->pcm_info.frames);
os_mutex_unlock(player->stream_mgr->lock);
}
os_mutex_unlock(player->lock);
return 0;
}
static int player_download(char *name)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
media_loader_t *mloader;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (!player_can_download(player)) {
os_mutex_unlock(player->lock);
return -1;
}
mloader = player->mloader;
if (!mloader) {
M_LOGE("mloader null !\n");
os_mutex_unlock(player->lock);
return -1;
}
if (mloader->action(mloader, PLAYER_DLOAD, name)) {
M_LOGE("download failed !\n");
os_mutex_unlock(player->lock);
return -1;
}
os_mutex_unlock(player->lock);
return 0;
}
static int player_download_abort(void)
{
player_t *player = g_mplayer ? g_mplayer->priv : NULL;
media_loader_t *mloader;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
os_mutex_lock(player->lock, OS_WAIT_FOREVER);
if (!player_can_download(player)) {
os_mutex_unlock(player->lock);
return -1;
}
mloader = player->mloader;
if (!mloader) {
M_LOGE("mloader null !\n");
os_mutex_unlock(player->lock);
return -1;
}
os_mutex_unlock(player->lock);
if (mloader->action(mloader, PLAYER_DLOAD_ABORT, NULL)) {
M_LOGE("abort download failed !\n");
return -1;
}
return 0;
}
static int player_format_support(media_format_t format)
{
return player_format_assert(format);
}
static int player_volume_init(player_t *player)
{
int kv_len;
int ret;
if (!player) {
M_LOGE("player null !\n");
return -1;
}
out_volume_set(8);
kv_len = sizeof(player->vol_level);
ret = os_kv_get(PLAYER_VOLUME_LEVEL_KEY,
&player->vol_level, &kv_len);
if (ret == -ENOENT) {
player->vol_level = PLAYER_VOLUME_LEVEL_DEFAULT;
M_LOGW("set default volume %d\n", player->vol_level);
} else if (ret) {
M_LOGE("get %s failed !\n", PLAYER_VOLUME_LEVEL_KEY);
return -1;
}
player->vol_lock = os_mutex_new();
return 0;
}
static int player_volume_deinit(player_t *player)
{
if (!player) {
M_LOGE("player null !\n");
return -1;
}
os_mutex_free(player->vol_lock);
return 0;
}
static int player_reference(player_t *player)
{
if (!player)
return -1;
player->reference_count++;
return player->reference_count;
}
static int player_dereference(player_t *player)
{
if (!player)
return -1;
player->reference_count--;
return player->reference_count;
}
static player_t *player_init(void)
{
player_t *player;
player = snd_zalloc(sizeof(player_t), AFM_EXTN);
if (!player) {
M_LOGE("alloc player failed !\n");
return NULL;
}
#if (UVOICE_MLIST_ENABLE == 1)
mlist_init();
#endif
player->sw_volume = PLAYER_SW_VOLUME_ENABLE;
if (player->sw_volume) {
M_LOGD("sw volume enable\n");
player_volume_init(player);
}
player->cplt_sem = os_sem_new(0);
player->resume_sem = os_sem_new(0);
player->pause_sem = os_sem_new(0);
player->start_sem = os_sem_new(0);
player->reset_sem = os_sem_new(0);
player->stop_sem = os_sem_new(0);
player->lock = os_mutex_new();
player->fade.lock = os_mutex_new();
#ifdef UVOICE_DEEP_COMPLETE
player->deep_cplt = 1;
#endif
player->fade.out_period_ms = FADE_OUT_PERIOD_DEFAULT;
player->fade.in_period_ms = FADE_IN_PERIOD_DEFAULT;
player->fade_enable = PLAYER_FADE_PROC_ENABLE;
player_reset(player);
player->standby_msec = 5000;
player->reference_count = 1;
player->state = PLAYER_STAT_IDLE;
return player;
}
static int player_deinit(player_t *player)
{
if (!player) {
M_LOGE("player null !\n");
return -1;
}
if (player->state != PLAYER_STAT_IDLE) {
M_LOGE("player not release !\n");
return -1;
}
#if (UVOICE_MLIST_ENABLE == 1)
mlist_deinit();
#endif
if (player->sw_volume)
player_volume_deinit(player);
os_mutex_free(player->fade.lock);
os_mutex_free(player->lock);
os_sem_free(player->stop_sem);
os_sem_free(player->reset_sem);
os_sem_free(player->start_sem);
os_sem_free(player->pause_sem);
os_sem_free(player->resume_sem);
os_sem_free(player->cplt_sem);
snd_free(player);
return 0;
}
uvoice_player_t *uvoice_player_create(void)
{
uvoice_player_t *mplayer = g_mplayer;
if (mplayer) {
if (player_reference(mplayer->priv) < 0) {
M_LOGE("get uvoice player failed !\n");
return NULL;
}
return mplayer;
}
mplayer = snd_zalloc(sizeof(uvoice_player_t), AFM_EXTN);
if (!mplayer) {
M_LOGE("alloc uvoice player failed !\n");
return NULL;
}
mplayer->priv = player_init();
if (!mplayer->priv) {
M_LOGE("init player failed !\n");
snd_free(mplayer);
return NULL;
}
g_mplayer = mplayer;
mplayer->start = player_start;
mplayer->stop = player_stop;
mplayer->pause = player_pause;
mplayer->resume = player_resume;
mplayer->complete = player_complete;
mplayer->playback = player_playback;
mplayer->stop_async = player_stop_async;
mplayer->pause_async = player_pause_async;
mplayer->resume_async = player_resume_async;
mplayer->set_source = player_set_source;
mplayer->clr_source = player_clr_source;
mplayer->set_stream = player_set_stream;
mplayer->put_stream = player_put_stream;
mplayer->clr_stream = player_clr_stream;
mplayer->set_pcminfo = player_set_pcminfo;
mplayer->get_position = player_get_position;
mplayer->get_duration = player_get_duration;
mplayer->wait_complete = player_wait_complete;
mplayer->get_mediainfo = player_get_mediainfo;
mplayer->get_cacheinfo = player_get_cacheinfo;
mplayer->get_state = player_get_state;
mplayer->get_delay = player_get_delay;
mplayer->set_fade = player_set_fade;
mplayer->seek = player_seek;
mplayer->set_format = player_set_format;
mplayer->set_out_device = player_set_outdevice;
mplayer->set_external_pa = player_set_external_pa;
mplayer->set_standby = player_set_standby;
mplayer->eq_enable = player_eq_enable;
mplayer->set_volume = player_set_volume;
mplayer->get_volume = player_get_volume;
mplayer->cache_config = player_cache_config;
mplayer->volume_range = player_volume_range;
mplayer->state_dump = player_state_dump;
mplayer->pcmdump_enable = player_pcmdump_enable;
mplayer->download = player_download;
mplayer->download_abort = player_download_abort;
mplayer->format_support = player_format_support;
M_LOGI("uvoice player create\n");
return mplayer;
}
int uvoice_player_release(uvoice_player_t *mplayer)
{
if (!mplayer) {
M_LOGE("uvoice player null !\n");
return -1;
}
if (mplayer != g_mplayer) {
M_LOGE("uvoice player invalid !\n");
return -1;
}
if (player_dereference(mplayer->priv) == 0) {
if (player_deinit(mplayer->priv)) {
M_LOGE("free player failed !\n");
return -1;
}
snd_free(mplayer);
g_mplayer = NULL;
M_LOGI("uvoice player release\n");
}
return 0;
}
|
YifuLiu/AliOS-Things
|
components/uvoice/media/uvoice_player.c
|
C
|
apache-2.0
| 116,712
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "uvoice_types.h"
#include "uvoice_event.h"
#include "uvoice_recorder.h"
#include "uvoice_os.h"
#include "uvoice_config.h"
#include "uvoice_common.h"
#include "uvoice_audio.h"
#include "uvoice_record.h"
#include "uvoice_resampler.h"
#include "audio_common.h"
#include "audio_stream.h"
static uvoice_recorder_t *g_mrecorder;
static int recorder_clr_sink(void);
static int recorder_state_post(recorder_t *recorder,
recorder_state_t state)
{
return 0;//uvoice_event_post(UVOICE_EV_RECORDER,
// UVOICE_CODE_RECORDER_STATE, state);
}
static void recorder_reset(recorder_t *recorder)
{
recorder->stop = 0;
recorder->error = 0;
recorder->record_len = 0;
}
static int recorder_encode_default(void *priv,
uint8_t *buffer, int nbytes)
{
return nbytes;
}
static int recorder_action_default(void *priv,
recorder_action_t action, void *arg)
{
return 0;
}
static media_type_t recorder_type_parse(char *sink)
{
if (!sink)
return MEDIA_TYPE_UNKNOWN;
else if (!strncmp(sink, "fs:", strlen("fs:")))
return MEDIA_TYPE_FILE;
else if (!strncmp(sink, "pt:", strlen("pt:")))
return MEDIA_TYPE_FLASH;
return MEDIA_TYPE_UNKNOWN;
}
static bool recorder_format_assert(media_format_t format)
{
switch (format) {
case MEDIA_FMT_WAV:
case MEDIA_FMT_PCM:
case MEDIA_FMT_SPX:
case MEDIA_FMT_AMR:
case MEDIA_FMT_AMRWB:
case MEDIA_FMT_OPS:
return true;
default:
return false;
}
return false;
}
static int recorder_stack_size(media_format_t format)
{
recorder_t *recorder = g_mrecorder ? g_mrecorder->priv : NULL;
int size = 4096;
if (!recorder)
return size;
switch (format) {
case MEDIA_FMT_OPS:
size = 32768;
break;
case MEDIA_FMT_SPX:
size = 8192;
break;
case MEDIA_FMT_AMR:
case MEDIA_FMT_AMRWB:
size = 20 * 1024;
}
if (recorder->ns_enable || recorder->ec_enable)
size = 12 * 1024;
if (recorder->agc_enable)
size = 10 * 1024;
return size;
}
static int recorder_bitrate_default(media_format_t format)
{
if (format == MEDIA_FMT_MP3)
return 128000;
else if (format == MEDIA_FMT_OPS)
return 27800;
return 100000;
}
static int recorder_param_set(media_pcminfo_t *info,
int rate, int channels, int bits, int frames)
{
if (!info) {
M_LOGE("info null !\n");
return -1;
}
if (!pcm_rate_valid(rate)) {
M_LOGE("sample rate invalid !\n");
return -1;
}
if (!pcm_bits_valid(bits)) {
M_LOGE("bits invalid !\n");
return -1;
}
if (!pcm_channel_valid(channels)) {
M_LOGE("channels invalid !\n");
return -1;
}
if (frames < 0) {
M_LOGE("frames invalid !\n");
return -1;
}
info->rate = rate;
info->channels = channels;
info->bits = bits;
info->frames = frames;
return 0;
}
static void recorder_task(void *arg)
{
recorder_t *recorder = (recorder_t *)arg;
media_encoder_t *mencoder;
media_packer_t *mpacker;
uint8_t *data_buffer;
int data_buffer_size;
int ret;
if (!recorder) {
M_LOGE("recorder null !\n");
return;
}
mencoder = recorder->mencoder;
if (!mencoder) {
M_LOGE("mencoder null !\n");
return;
}
mpacker = recorder->mpacker;
if (!mpacker) {
M_LOGE("mpacker null !\n");
return;
}
os_mutex_lock(recorder->lock, OS_WAIT_FOREVER);
if (recorder->state == RECORDER_STAT_READY ||
recorder->state == RECORDER_STAT_STOP) {
if (mencoder->action(mencoder, RECORDER_START, NULL)) {
M_LOGE("start encoder failed !\n");
os_mutex_unlock(recorder->lock);
return;
}
if (recorder->state == RECORDER_STAT_STOP)
M_LOGI("stop->running\n");
else
M_LOGI("ready->running\n");
recorder->state = RECORDER_STAT_RUNNING;
recorder_state_post(recorder, recorder->state);
}
if (recorder->state != RECORDER_STAT_RUNNING) {
M_LOGE("recorder not running ! state %d\n",
recorder->state);
os_mutex_unlock(recorder->lock);
return;
}
os_mutex_unlock(recorder->lock);
while (1) {
os_mutex_lock(recorder->lock, OS_WAIT_FOREVER);
if (recorder->stop) {
if (recorder->state == RECORDER_STAT_RUNNING) {
mencoder->action(mencoder, RECORDER_STOP, NULL);
if (mpacker->action)
mpacker->action(mpacker, RECORDER_STOP, NULL);
in_stream_stop(recorder->in);
recorder->state = RECORDER_STAT_STOP;
recorder->stop = 0;
recorder_state_post(recorder, recorder->state);
M_LOGI("running->stop\n");
os_mutex_unlock(recorder->lock);
if (recorder->error) {
M_LOGE("recorder error, release it\n");
recorder_clr_sink();
}
break;
}
}
if (!in_stream_configured(recorder->in)) {
media_pcminfo_t *info = &recorder->pcm_info;
media_pcminfo_t temp_info;
memcpy(&temp_info, info, sizeof(temp_info));
if (in_stream_configure(recorder->in, &temp_info)) {
M_LOGE("configure stream failed !\n");
recorder->stop = 1;
recorder->error = 1;
os_mutex_unlock(recorder->lock);
continue;
}
recorder->src_rate = temp_info.rate;
if (temp_info.rate != info->rate) {
#ifdef UVOICE_RESAMPLE_ENABLE
if (!recorder->resampler) {
uvoice_resampler_create(&recorder->resampler, recorder->src_rate,
recorder->dst_rate, temp_info.channels, temp_info.bits);
if (!recorder->resampler) {
M_LOGE("create resampler failed !\n");
recorder->stop = 1;
recorder->error = 1;
os_mutex_unlock(recorder->lock);
continue;
}
} else {
uvoice_resampler_update(recorder->resampler, recorder->src_rate,
recorder->dst_rate, temp_info.channels, temp_info.bits);
}
#endif
}
}
ret = in_stream_read(recorder->in, recorder->buffer,
recorder->buffer_size);
if (ret <= 0) {
M_LOGE("read failed %d!\n", ret);
recorder->stop = 1;
recorder->error = 1;
os_mutex_unlock(recorder->lock);
continue;
} else if (ret != recorder->buffer_size) {
M_LOGW("read %d ret %d\n",
recorder->buffer_size, ret);
}
data_buffer_size = ret;
data_buffer = recorder->buffer;
#ifdef UVOICE_RESAMPLE_ENABLE
if (uvoice_resampler_process(recorder->resampler, recorder->buffer, ret,
&data_buffer, &data_buffer_size)) {
M_LOGE("resample error\n");
}
#endif
if (data_buffer_size <= 0) {
M_LOGE("data_buffer_size err %d\n", data_buffer_size);
os_mutex_unlock(recorder->lock);
continue;
}
recorder->buffer_dirty_size = data_buffer_size;
recorder->record_len += data_buffer_size;
if (!mencoder->header_pack) {
if (mencoder->header_gen &&
mencoder->header_gen(mencoder, &recorder->pcm_info)) {
M_LOGE("init header failed !\n");
recorder->stop = 1;
recorder->error = 1;
os_mutex_unlock(recorder->lock);
continue;
}
if (mencoder->header && mencoder->header_size > 0) {
M_LOGD("header pack\n");
ret = mpacker->pack(mpacker,
mencoder->header, mencoder->header_size);
if (ret < 0) {
M_LOGE("pack header failed !\n");
snd_free(mencoder->header);
mencoder->header = NULL;
mencoder->header_size = 0;
recorder->stop = 1;
os_mutex_unlock(recorder->lock);
continue;
} else if (ret != mencoder->header_size) {
M_LOGW("pack %d ret %d\n", mencoder->header_size, ret);
}
if (mencoder->header_cplt) {
snd_free(mencoder->header);
mencoder->header = NULL;
mencoder->header_size = 0;
}
}
mencoder->header_pack = 1;
}
os_mutex_unlock(recorder->lock);
ret = mencoder->encode(mencoder,
data_buffer, recorder->buffer_dirty_size);
if (ret <= 0) {
M_LOGE("encode failed %d!\n", ret);
os_mutex_lock(recorder->lock, OS_WAIT_FOREVER);
recorder->stop = 1;
recorder->error = 1;
os_mutex_unlock(recorder->lock);
continue;
}
recorder->buffer_dirty_size = ret;
ret = mpacker->pack(mpacker, data_buffer,
recorder->buffer_dirty_size);
if (ret < 0) {
M_LOGE("pack failed %d!\n", ret);
os_mutex_lock(recorder->lock, OS_WAIT_FOREVER);
recorder->stop = 1;
recorder->error = 1;
os_mutex_unlock(recorder->lock);
} else if (ret == 0) {
M_LOGW("pack end\n");
os_mutex_lock(recorder->lock, OS_WAIT_FOREVER);
recorder->stop = 1;
os_mutex_unlock(recorder->lock);
} else if (ret != recorder->buffer_dirty_size) {
M_LOGW("pack %d ret %d\n",
recorder->buffer_dirty_size, ret);
}
}
os_sem_signal(recorder->cplt_sem);
M_LOGD("exit\n");
}
static int recorder_get_stream(uint8_t *buffer, int nbytes)
{
recorder_t *recorder = g_mrecorder ? g_mrecorder->priv : NULL;
media_encoder_t *mencoder;
uint8_t *data_buffer;
uint8_t *data_ptr;
int data_size;
int ret;
if (!recorder) {
M_LOGE("recorder null !\n");
return -1;
}
if (!buffer) {
M_LOGE("buffer null !\n");
return -1;
}
os_mutex_lock(recorder->lock, OS_WAIT_FOREVER);
mencoder = recorder->mencoder;
if (!mencoder) {
M_LOGE("mencoder null !\n");
os_mutex_unlock(recorder->lock);
return -1;
}
if (recorder->state == RECORDER_STAT_READY ||
recorder->state == RECORDER_STAT_STOP) {
if (mencoder->action(mencoder, RECORDER_START, NULL)) {
M_LOGE("start encoder failed !\n");
os_mutex_unlock(recorder->lock);
return -1;
}
if (recorder->state == RECORDER_STAT_STOP)
M_LOGI("stop->running\n");
else
M_LOGI("ready->running\n");
recorder->state = RECORDER_STAT_RUNNING;
}
if (recorder->state != RECORDER_STAT_RUNNING) {
M_LOGE("recorder not running ! state %d\n",
recorder->state);
os_mutex_unlock(recorder->lock);
return -1;
}
if (!in_stream_configured(recorder->in)) {
media_pcminfo_t *info = &recorder->pcm_info;
media_pcminfo_t temp_info;
if (info->frames <= 0) {
info->frames = nbytes / (info->channels * (info->bits >> 3));
mencoder->frames = info->frames;
}
memcpy(&temp_info, info, sizeof(temp_info));
in_stream_configure(recorder->in, &temp_info);
recorder->src_rate = temp_info.rate;
if (temp_info.rate != info->rate) {
#ifdef UVOICE_RESAMPLE_ENABLE
uvoice_resampler_create(&recorder->resampler, recorder->src_rate,
recorder->dst_rate, temp_info.channels, temp_info.bits);
if (!recorder->resampler) {
M_LOGE("create resampler failed !\n");
os_mutex_unlock(recorder->lock);
return -1;
}
#endif
}
}
data_size = (nbytes * recorder->src_rate) / recorder->dst_rate;
if (data_size > nbytes) {
if (!recorder->rec_buffer) {
recorder->rec_buffer = snd_zalloc(data_size, AFM_MAIN);
if (!recorder->rec_buffer) {
M_LOGE("alloc record buffer failed !\n");
os_mutex_unlock(recorder->lock);
return -1;
}
}
data_buffer = recorder->rec_buffer;
} else {
data_buffer = buffer;
}
ret = in_stream_read(recorder->in, data_buffer, data_size);
if (ret <= 0) {
M_LOGE("read failed !\n");
os_mutex_unlock(recorder->lock);
return -1;
} else if (ret != data_size) {
M_LOGW("read %d ret %d\n", data_size, ret);
}
data_ptr = data_buffer;
data_size = ret;
#ifdef UVOICE_RESAMPLE_ENABLE
if (uvoice_resampler_process(recorder->resampler, data_buffer, ret,
&data_ptr, &data_size)) {
M_LOGE("resample error\n");
}
if (data_size <= 0) {
M_LOGE("data_size err %d\n", data_size);
os_mutex_unlock(recorder->lock);
return -1;
}
#endif
recorder->buffer_dirty_size = data_size;
ret = mencoder->encode(mencoder,
data_ptr, recorder->buffer_dirty_size);
if (ret <= 0) {
M_LOGE("encode failed !\n");
os_mutex_unlock(recorder->lock);
return -1;
}
if (data_ptr != buffer)
memcpy(buffer, data_ptr, ret);
os_mutex_unlock(recorder->lock);
return ret;
}
static int recorder_start(void)
{
recorder_t *recorder = g_mrecorder ? g_mrecorder->priv : NULL;
if (!recorder) {
M_LOGE("recorder null !\n");
return -1;
}
os_mutex_lock(recorder->lock, OS_WAIT_FOREVER);
if (recorder->type == MEDIA_TYPE_STREAM) {
M_LOGE("media type stream !\n");
os_mutex_unlock(recorder->lock);
return -1;
}
if (recorder->state != RECORDER_STAT_READY &&
recorder->state != RECORDER_STAT_STOP) {
M_LOGE("recorder not ready/stop !\n");
os_mutex_unlock(recorder->lock);
return -1;
}
os_mutex_unlock(recorder->lock);
M_LOGD("start record task\n");
os_task_create(&recorder->task,
"uvoice_record_task",
recorder_task,
recorder,
recorder_stack_size(recorder->format),
UVOICE_TASK_PRI_HIGHER);
return 0;
}
static int recorder_stop(void)
{
recorder_t *recorder = g_mrecorder ? g_mrecorder->priv : NULL;
if (!recorder) {
M_LOGE("recorder null !\n");
return -1;
}
os_mutex_lock(recorder->lock, OS_WAIT_FOREVER);
if (recorder->type == MEDIA_TYPE_STREAM) {
M_LOGE("stream stop not required !\n");
os_mutex_unlock(recorder->lock);
return -1;
}
if (recorder->state != RECORDER_STAT_RUNNING) {
M_LOGE("recorder can't stop ! state %d\n",
recorder->state);
os_mutex_unlock(recorder->lock);
return -1;
}
if (!recorder->stop) {
recorder->stop = 1;
os_mutex_unlock(recorder->lock);
if (os_sem_wait(recorder->cplt_sem, 5000)) {
M_LOGE("wait stop timeout !\n");
return -1;
}
os_mutex_lock(recorder->lock, OS_WAIT_FOREVER);
if (recorder->state != RECORDER_STAT_STOP) {
M_LOGE("recorder stop failed ! state %d\n",
recorder->state);
os_mutex_unlock(recorder->lock);
return -1;
} else {
M_LOGD("recorder stop\n");
}
}
os_mutex_unlock(recorder->lock);
return 0;
}
static int recorder_get_state(recorder_state_t *state)
{
recorder_t *recorder = g_mrecorder ? g_mrecorder->priv : NULL;
if (!recorder) {
M_LOGE("recorder null !\n");
return -1;
}
if (!state) {
M_LOGE("arg null !\n");
return -1;
}
os_mutex_lock(recorder->lock, OS_WAIT_FOREVER);
*state = recorder->state;
os_mutex_unlock(recorder->lock);
return 0;
}
static int recorder_get_position(int *position)
{
recorder_t *recorder = g_mrecorder ? g_mrecorder->priv : NULL;
media_pcminfo_t *info;
if (!recorder) {
M_LOGE("recorder null !\n");
return -1;
}
if (!position) {
M_LOGE("arg null !\n");
return -1;
}
info = &recorder->pcm_info;
os_mutex_lock(recorder->lock, OS_WAIT_FOREVER);
if (recorder->state == RECORDER_STAT_RUNNING ||
recorder->state == RECORDER_STAT_STOP) {
*position = (recorder->record_len /
(info->channels * (info->bits >> 3))) / info->rate;
}
os_mutex_unlock(recorder->lock);
return 0;
}
static int recorder_set_sink(media_format_t format,
int rate, int channels,
int bits, int frames, int bitrate, char *sink)
{
recorder_t *recorder = g_mrecorder ? g_mrecorder->priv : NULL;
if (!recorder) {
M_LOGE("recorder null !\n");
return -1;
}
os_mutex_lock(recorder->lock, OS_WAIT_FOREVER);
if (recorder->state != RECORDER_STAT_IDLE) {
M_LOGE("recorder not released !\n");
goto __exit;
}
M_LOGD("sink %s\n", sink ? sink : "null");
recorder->dst_rate = rate;
recorder->src_rate = rate;
if (frames <= 0 && sink)
frames = 640;
if (recorder_param_set(&recorder->pcm_info, recorder->dst_rate,
channels, bits, frames)) {
M_LOGE("set record param failed !\n");
goto __exit;
}
if (sink) {
if (format_parse_byname(sink, &recorder->format)) {
M_LOGE("parse format failed !\n");
goto __exit;
}
if (!recorder_format_assert(recorder->format)) {
M_LOGE("format unsupport !\n");
goto __exit;
}
} else {
recorder->format = format;
}
if (recorder->format == MEDIA_FMT_UNKNOWN) {
M_LOGE("format unsupport !\n");
goto __exit;
}
recorder->mencoder = media_encoder_create(recorder->format);
if (!recorder->mencoder) {
M_LOGE("create media encoder failed !\n");
goto __exit;
}
if (!recorder->mencoder->initialized) {
recorder->mencoder->encode = recorder_encode_default;
recorder->mencoder->action = recorder_action_default;
recorder->mencoder->initialized = 1;
}
recorder->mencoder->frames = frames;
recorder->mencoder->rate = recorder->dst_rate;
recorder->mencoder->channels = channels;
recorder->mencoder->bits = bits;
recorder->mencoder->bitrate = bitrate > 0 ? bitrate :
recorder_bitrate_default(recorder->format);
if (sink) {
recorder->type = recorder_type_parse(sink);
if (recorder->type == MEDIA_TYPE_UNKNOWN) {
M_LOGE("media type unsupport !\n");
goto __exit2;
}
recorder->mpacker = media_packer_create(
sink, recorder->type);
if (!recorder->mpacker) {
M_LOGE("create media packer fail !\n");
goto __exit3;
}
#if (BOARD_HAASEDUK1 == 1)
recorder->buffer_size = frames * channels * (bits >> 3) + 512; // avoid crash when use frames = 1024
#else
recorder->buffer_size = frames * channels * (bits >> 3);
#endif
M_LOGD("alloc record buffer %d\n", recorder->buffer_size);
recorder->buffer = snd_zalloc(
recorder->buffer_size, AFM_MAIN);
if (!recorder->buffer) {
M_LOGE("alloc record buffer failed !\n");
goto __exit4;
}
} else {
recorder->type = MEDIA_TYPE_STREAM;
}
recorder->in = in_stream_create();
if (!recorder->in) {
M_LOGE("create in stream failed !\n");
if (recorder->buffer) {
snd_free(recorder->buffer);
recorder->buffer = NULL;
}
goto __exit4;
}
recorder->state = RECORDER_STAT_READY;
M_LOGI("idle->ready\n");
os_mutex_unlock(recorder->lock);
return 0;
__exit4:
media_packer_release(recorder->mpacker);
__exit3:
recorder->type = MEDIA_TYPE_UNKNOWN;
__exit2:
#ifdef UVOICE_RESAMPLE_ENABLE
uvoice_resampler_release(recorder->resampler);
recorder->resampler = NULL;
#else
M_LOGI("resampler not enable\n");
#endif
__exit1:
media_encoder_release(recorder->mencoder);
recorder->mencoder = NULL;
__exit:
os_mutex_unlock(recorder->lock);
return -1;
}
static int recorder_clr_sink(void)
{
recorder_t *recorder = g_mrecorder ? g_mrecorder->priv : NULL;
media_encoder_t *mencoder = NULL;
media_packer_t *mpacker = NULL;
int ret;
if (!recorder) {
M_LOGE("recorder null !\n");
return -1;
}
os_mutex_lock(recorder->lock, OS_WAIT_FOREVER);
if (recorder->state == RECORDER_STAT_IDLE) {
M_LOGW("recorder is idle\n");
os_mutex_unlock(recorder->lock);
return -1;
}
if (recorder->type != MEDIA_TYPE_STREAM) {
if (recorder->state != RECORDER_STAT_STOP &&
recorder->state != RECORDER_STAT_READY) {
M_LOGE("state %d can't clr sink\n", recorder->state);
os_mutex_unlock(recorder->lock);
return -1;
}
}
mencoder = recorder->mencoder;
if (!mencoder) {
M_LOGE("mencoder null !\n");
os_mutex_unlock(recorder->lock);
return -1;
}
if (recorder->type == MEDIA_TYPE_STREAM) {
if (recorder->state == RECORDER_STAT_RUNNING) {
mencoder->action(mencoder, RECORDER_STOP, NULL);
in_stream_stop(recorder->in);
recorder->state = RECORDER_STAT_STOP;
M_LOGI("running->stop\n");
}
} else {
mpacker = recorder->mpacker;
if (!mpacker) {
M_LOGE("mpacker null !\n");
os_mutex_unlock(recorder->lock);
return -1;
}
}
if (recorder->state != RECORDER_STAT_STOP &&
recorder->state != RECORDER_STAT_READY) {
M_LOGE("recorder can't clr sink ! state %d\n",
recorder->state);
os_mutex_unlock(recorder->lock);
return -1;
}
if (recorder->type != MEDIA_TYPE_STREAM) {
if (!mencoder->header_cplt &&
mencoder->header_update && mpacker->update) {
if (mencoder->header && mencoder->header_size > 0) {
M_LOGD("header update\n");
mencoder->header_update(mencoder, mpacker->size);
ret = mpacker->update(mpacker,
mencoder->header, mencoder->header_size, 0);
if (ret < 0)
M_LOGE("pack header failed !\n");
snd_free(mencoder->header);
mencoder->header = NULL;
mencoder->header_size = 0;
}
}
}
#ifdef UVOICE_RESAMPLE_ENABLE
uvoice_resampler_release(recorder->resampler);
#endif
media_encoder_release(mencoder);
media_packer_release(mpacker);
if (recorder->buffer) {
snd_free(recorder->buffer);
recorder->buffer = NULL;
}
if (recorder->rec_buffer) {
snd_free(recorder->rec_buffer);
recorder->rec_buffer = NULL;
}
in_stream_release(recorder->in);
recorder->resampler = NULL;
recorder->mencoder = NULL;
recorder->mpacker = NULL;
recorder->in = NULL;
recorder_reset(recorder);
recorder->format = MEDIA_FMT_UNKNOWN;
recorder->type = MEDIA_TYPE_UNKNOWN;
if (recorder->state == RECORDER_STAT_STOP)
M_LOGI("stop->idle\n");
else
M_LOGI("ready->idle\n");
recorder->state = RECORDER_STAT_IDLE;
os_mutex_unlock(recorder->lock);
return 0;
}
static int recorder_format_support(media_format_t format)
{
if (recorder_format_assert(format))
return 1;
return 0;
}
static int recorder_ns_enable(int enable)
{
recorder_t *recorder = g_mrecorder ? g_mrecorder->priv : NULL;
int ret = 0;
if (!recorder) {
M_LOGE("recorder null !\n");
return -1;
}
enable = !!enable;
if (recorder->ns_enable != enable) {
recorder->ns_enable = enable;
if (recorder->ns_enable)
ret = audio_param_set(PARAM_KEY_NOISE_SUPPRESSION,
PARAM_VAL_ENABLE);
else
ret = audio_param_set(PARAM_KEY_NOISE_SUPPRESSION,
PARAM_VAL_DISABLE);
}
return ret;
}
static int recorder_ec_enable(int enable)
{
recorder_t *recorder = g_mrecorder ? g_mrecorder->priv : NULL;
int ret = 0;
if (!recorder) {
M_LOGE("recorder null !\n");
return -1;
}
enable = !!enable;
if (recorder->ec_enable != enable) {
recorder->ec_enable = enable;
if (recorder->ec_enable)
ret = audio_param_set(PARAM_KEY_ECHO_CANCELLATION,
PARAM_VAL_ENABLE);
else
ret = audio_param_set(PARAM_KEY_ECHO_CANCELLATION,
PARAM_VAL_DISABLE);
}
return ret;
}
static int recorder_agc_enable(int enable)
{
recorder_t *recorder = g_mrecorder ? g_mrecorder->priv : NULL;
int ret = 0;
if (!recorder) {
M_LOGE("recorder null !\n");
return -1;
}
enable = !!enable;
if (recorder->agc_enable != enable) {
recorder->agc_enable = enable;
if (recorder->agc_enable)
ret = audio_param_set(PARAM_KEY_AUTO_GAIN_CONTROL,
PARAM_VAL_ENABLE);
else
ret = audio_param_set(PARAM_KEY_AUTO_GAIN_CONTROL,
PARAM_VAL_DISABLE);
}
return ret;
}
static int recorder_vad_enable(int enable)
{
recorder_t *recorder = g_mrecorder ? g_mrecorder->priv : NULL;
int ret = 0;
if (!recorder) {
M_LOGE("recorder null !\n");
return -1;
}
enable = !!enable;
if (recorder->vad_enable != enable) {
recorder->vad_enable = enable;
if (recorder->vad_enable)
ret = audio_param_set(PARAM_KEY_VOICE_ACTIVE_DETECT,
PARAM_VAL_ENABLE);
else
ret = audio_param_set(PARAM_KEY_VOICE_ACTIVE_DETECT,
PARAM_VAL_DISABLE);
}
return ret;
}
static int recorder_reference(recorder_t *recorder)
{
if (!recorder)
return -1;
recorder->reference_count++;
return recorder->reference_count;
}
static int recorder_dereference(recorder_t *recorder)
{
if (!recorder)
return -1;
recorder->reference_count--;
return recorder->reference_count;
}
static recorder_t *recorder_init(void)
{
recorder_t *recorder = snd_zalloc(sizeof(recorder_t), AFM_EXTN);
if (!recorder) {
M_LOGE("alloc recorder failed !\n");
return NULL;
}
recorder->cplt_sem = os_sem_new(0);
recorder->lock = os_mutex_new();
recorder->reference_count = 1;
recorder->format = MEDIA_FMT_UNKNOWN;
recorder->type = MEDIA_TYPE_UNKNOWN;
return recorder;
}
static int recorder_deinit(recorder_t *recorder)
{
if (!recorder) {
M_LOGE("recorder null !\n");
return -1;
}
if (recorder->state != RECORDER_STAT_IDLE) {
M_LOGE("recorder not released !\n");
return -1;
}
os_mutex_free(recorder->lock);
os_sem_free(recorder->cplt_sem);
snd_free(recorder);
return 0;
}
uvoice_recorder_t *uvoice_recorder_create(void)
{
uvoice_recorder_t *mrecorder = g_mrecorder;
if (mrecorder) {
if (recorder_reference(mrecorder->priv) < 0) {
M_LOGE("get uvoice recorder failed !\n");
return NULL;
}
return mrecorder;
}
mrecorder = snd_zalloc(sizeof(uvoice_recorder_t), AFM_EXTN);
if (!mrecorder) {
M_LOGE("alloc uvoice recorder failed !\n");
return NULL;
}
mrecorder->priv = recorder_init();
if (!mrecorder->priv) {
M_LOGE("init recoder failed !\n");
snd_free(mrecorder);
return NULL;
}
mrecorder->start = recorder_start;
mrecorder->stop = recorder_stop;
mrecorder->get_stream = recorder_get_stream;
mrecorder->set_sink = recorder_set_sink;
mrecorder->clr_sink = recorder_clr_sink;
mrecorder->get_state = recorder_get_state;
mrecorder->get_position = recorder_get_position;
mrecorder->ns_enable = recorder_ns_enable;
mrecorder->ec_enable = recorder_ec_enable;
mrecorder->agc_enable = recorder_agc_enable;
mrecorder->vad_enable = recorder_vad_enable;
mrecorder->format_support = recorder_format_support;
g_mrecorder = mrecorder;
M_LOGI("uvoice recorder create\n");
return mrecorder;
}
int uvoice_recorder_release(uvoice_recorder_t *mrecorder)
{
if (!mrecorder) {
M_LOGE("uvoice recorder null !\n");
return -1;
}
if (mrecorder != g_mrecorder) {
M_LOGE("uvoice recorder invalid !\n");
return -1;
}
if (recorder_dereference(mrecorder->priv) == 0) {
if (recorder_deinit(mrecorder->priv)) {
M_LOGE("free recorder failed !\n");
return -1;
}
snd_free(mrecorder);
g_mrecorder = NULL;
M_LOGI("uvoice recorder release\n");
}
return 0;
}
|
YifuLiu/AliOS-Things
|
components/uvoice/media/uvoice_recorder.c
|
C
|
apache-2.0
| 29,659
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "uvoice_os.h"
#include "uvoice_types.h"
#include "uvoice_player.h"
#include "uvoice_recorder.h"
#include "uvoice_config.h"
#include "uvoice_common.h"
#include "uvoice_play.h"
#include "uvoice_record.h"
#include "uvoice_stream.h"
int media_loader_reset(media_loader_t *mloader)
{
if (!mloader) {
M_LOGE("mloader null !\n");
return -1;
}
if (mloader->reset && mloader->reset(mloader)) {
M_LOGE("reset loader failed !\n");
return -1;
}
return 0;
}
media_loader_t *media_loader_create(media_type_t type, char *source)
{
media_loader_t *mloader;
if (!source) {
M_LOGE("source null !\n");
return NULL;
}
mloader = snd_zalloc(sizeof(media_loader_t), AFM_EXTN);
if (!mloader) {
M_LOGE("alloc mloader failed !\n");
return NULL;
}
if (type == MEDIA_TYPE_HTTP) {
#ifdef UVOICE_HTTP_ENABLE
if (http_loader_create(mloader, source)) {
M_LOGE("init http loader failed !\n");
snd_free(mloader);
return NULL;
}
#else
M_LOGE("http load not enable !\n");
snd_free(mloader);
return NULL;
#endif
} else if (type == MEDIA_TYPE_FILE) {
#ifdef UVOICE_FILE_ENABLE
if (file_loader_create(mloader, source)) {
M_LOGE("init file loader failed !\n");
snd_free(mloader);
return NULL;
}
#else
M_LOGE("file load not enable !\n");
snd_free(mloader);
return NULL;
#endif
} else if (type == MEDIA_TYPE_FLASH) {
#ifdef UVOICE_PARTITION_ENABLE
if (partition_loader_create(mloader, source)) {
M_LOGE("init flash loader failed !\n");
snd_free(mloader);
return NULL;
}
#else
M_LOGE("flash load not enable !\n");
snd_free(mloader);
return NULL;
#endif
} else {
M_LOGE("type unsupport !\n");
snd_free(mloader);
return NULL;
}
mloader->type = type;
return mloader;
}
int media_loader_release(media_loader_t *mloader)
{
if (!mloader) {
M_LOGE("mloader null !\n");
return -1;
}
if (mloader->type == MEDIA_TYPE_HTTP) {
#ifdef UVOICE_HTTP_ENABLE
http_loader_release(mloader);
#endif
} else if (mloader->type == MEDIA_TYPE_FILE) {
#ifdef UVOICE_FILE_ENABLE
file_loader_release(mloader);
#endif
} else if (mloader->type == MEDIA_TYPE_FLASH) {
#ifdef UVOICE_PARTITION_ENABLE
partition_loader_release(mloader);
#endif
}
snd_free(mloader);
return 0;
}
media_packer_t *media_packer_create(char *sink, media_type_t type)
{
media_packer_t *mpacker;
if (!sink) {
M_LOGE("sink null !\n");
return NULL;
}
mpacker = snd_zalloc(sizeof(media_packer_t), AFM_EXTN);
if (!mpacker) {
M_LOGE("alloc media packer failed !\n");
return NULL;
}
if (type == MEDIA_TYPE_FILE) {
#ifdef UVOICE_FILE_ENABLE
if (file_packer_create(mpacker, sink)) {
M_LOGE("init file packer failed !\n");
snd_free(mpacker);
return NULL;
}
#else
M_LOGE("file pack not enable !\n");
snd_free(mpacker);
return NULL;
#endif
} else if (type == MEDIA_TYPE_FLASH) {
#ifdef UVOICE_PARTITION_ENABLE
if (partition_packer_create(mpacker, sink)) {
M_LOGE("init flash packer failed !\n");
snd_free(mpacker);
return NULL;
}
#else
M_LOGE("flash pack not enable !\n");
snd_free(mpacker);
return NULL;
#endif
} else {
M_LOGE("type unsupport !\n");
snd_free(mpacker);
return NULL;
}
mpacker->type = type;
return mpacker;
}
int media_packer_release(media_packer_t *mpacker)
{
if (!mpacker)
return -1;
if (mpacker->type == MEDIA_TYPE_FILE) {
#ifdef UVOICE_FILE_ENABLE
file_packer_release(mpacker);
#endif
} else if (mpacker->type == MEDIA_TYPE_FLASH) {
#ifdef UVOICE_PARTITION_ENABLE
partition_packer_release(mpacker);
#endif
}
snd_free(mpacker);
return 0;
}
|
YifuLiu/AliOS-Things
|
components/uvoice/media/uvoice_stream.c
|
C
|
apache-2.0
| 3,765
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <signal.h>
#include "uvoice_types.h"
#include "uvoice_player.h"
#include "uvoice_recorder.h"
#include "uvoice_os.h"
#include "uvoice_common.h"
#include "uvoice_play.h"
#include "uvoice_record.h"
#include "uvoice_wave.h"
typedef struct {
int rate;
int bits;
int channels;
uint16_t audio_format;
} wave_decoder_t;
static int wave_header_init(struct wav_header *header, int rate,
int channels, int bits)
{
if (!header) {
M_LOGE("header null !\n");
return -1;
}
header->riff_id = ID_RIFF;
header->riff_fmt = ID_WAVE;
header->fmt_id = ID_FMT;
header->fmt_sz = 16;
header->audio_format = WAVE_FMT_PCM;
header->num_channels = channels;
header->sample_rate = rate;
header->bits_per_sample = bits;
header->byte_rate = (header->bits_per_sample / 8) * channels * rate;
header->block_align = channels * (header->bits_per_sample / 8);
header->data_id = ID_DATA;
return 0;
}
static int wave_info_parse(media_decoder_t *mdecoder, uint8_t *buffer,
int nbytes)
{
struct riff_wave_header riff_wave_header;
struct chunk_header chunk_header;
struct chunk_fmt chunk_fmt;
int more_chunks = 1;
int remaining_bytes = nbytes;
uint8_t *ptr = buffer;
wave_decoder_t *wave;
media_pcminfo_t pcm_info;
media_info_t media_info;
if (!mdecoder) {
M_LOGE("mdecoder null !\n");
return -1;
}
if (!ptr) {
M_LOGE("buffer null !\n");
return -1;
}
wave = mdecoder->decoder;
if (!wave) {
M_LOGE("wave decoder null !\n");
return -1;
}
if (remaining_bytes >= sizeof(struct riff_wave_header)) {
memcpy(&riff_wave_header,
ptr, sizeof(struct riff_wave_header));
remaining_bytes -= sizeof(struct riff_wave_header);
ptr += sizeof(struct riff_wave_header);
} else {
M_LOGE("parse riff wave header failed !\n");
return -1;
}
if ((riff_wave_header.riff_id != ID_RIFF) ||
(riff_wave_header.wave_id != ID_WAVE)) {
M_LOGE("not riff/wave file !\n");
return -1;
}
memset(&chunk_fmt, 0, sizeof(struct chunk_fmt));
do {
if (remaining_bytes >= sizeof(struct chunk_header)) {
memcpy(&chunk_header, ptr, sizeof(struct chunk_header));
remaining_bytes -= sizeof(struct chunk_header);
ptr += sizeof(struct chunk_header);
} else {
M_LOGE("parse chunk header failed !\n");
return -1;
}
switch (chunk_header.id) {
case ID_FMT:
if (remaining_bytes >= sizeof(struct chunk_fmt)) {
memcpy(&chunk_fmt, ptr, sizeof(struct chunk_fmt));
remaining_bytes -= sizeof(struct chunk_fmt);
ptr += sizeof(struct chunk_fmt);
} else {
M_LOGE("parse chunk fmt failed !\n");
return -1;
}
if (chunk_header.sz > sizeof(struct chunk_fmt)) {
remaining_bytes -= (chunk_header.sz - sizeof(chunk_fmt));
ptr += chunk_header.sz - sizeof(chunk_fmt);
}
M_LOGD("sample_rate %u\n", chunk_fmt.sample_rate);
M_LOGD("channels %u\n", chunk_fmt.num_channels);
M_LOGD("byte_rate %u\n", chunk_fmt.byte_rate);
M_LOGD("audio_format %u\n", chunk_fmt.audio_format);
M_LOGD("bits_per_sample %u\n", chunk_fmt.bits_per_sample);
M_LOGD("block_align %u\n", chunk_fmt.block_align);
break;
case ID_DATA:
more_chunks = 0;
break;
default:
remaining_bytes -= chunk_header.sz;
ptr += chunk_header.sz;
}
} while (more_chunks);
memset(&pcm_info, 0, sizeof(pcm_info));
pcm_info.rate = chunk_fmt.sample_rate;
if (mdecoder->stere_enable)
pcm_info.channels = chunk_fmt.num_channels;
else
pcm_info.channels = 1;
pcm_info.bits = chunk_fmt.bits_per_sample;
pcm_info.frames = mdecoder->input_size /
(pcm_info.channels * (pcm_info.bits >> 3));
wave->rate = chunk_fmt.sample_rate;
wave->channels = chunk_fmt.num_channels;
wave->bits = chunk_fmt.bits_per_sample;
wave->audio_format = chunk_fmt.audio_format;
mdecoder->message(mdecoder->priv,
PLAYER_MSG_PCM_INFO, &pcm_info);
memset(&media_info, 0, sizeof(media_info));
media_info.bitrate = chunk_fmt.byte_rate * 8;
mdecoder->message(mdecoder->priv,
PLAYER_MSG_MEDIA_INFO, &media_info);
if (remaining_bytes >= 0)
memset(buffer, 0, nbytes - remaining_bytes);
M_LOGD("remaining_bytes %d\n", remaining_bytes);
return remaining_bytes;
}
static int wave_decode_process(void *priv, uint8_t *buffer,
int nbytes)
{
media_decoder_t *mdecoder = (media_decoder_t *)priv;
wave_decoder_t *wave;
short *out_buffer = (short *)buffer;
int out_samples;
int i;
if (!mdecoder) {
M_LOGE("mdecoder null !\n");
return -1;
}
wave = mdecoder->decoder;
if (!wave) {
M_LOGE("wave decoder null !\n");
return -1;
}
if (!mdecoder->running) {
if (wave_info_parse(mdecoder, buffer, nbytes) < 0) {
M_LOGE("parse wave info failed !\n");
return -1;
}
mdecoder->running = 1;
}
if (wave->channels == 2 && !mdecoder->stere_enable) {
out_samples = (nbytes / (wave->bits >> 3)) / 2;
for (i = 0; i < out_samples; i++)
out_buffer[i] = out_buffer[2 * i];
nbytes /= 2;
}
if (mdecoder->output(mdecoder->priv, buffer, nbytes)) {
M_LOGE("output failed !\n");
return -1;
}
return 0;
}
static int wave_decode_action(void *priv, player_action_t action,
void *arg)
{
media_decoder_t *mdecoder = (media_decoder_t *)priv;
wave_decoder_t *wave;
static int wave_bits = 0;
static int wave_channels = 0;
static int wave_sample_rate = 0;
static uint16_t audio_format = 0;
if (!mdecoder) {
M_LOGE("mdecoder null !\n");
return -1;
}
wave = mdecoder->decoder;
if (!wave) {
M_LOGE("wave decoder null !\n");
return -1;
}
switch (action) {
case PLAYER_PAUSE:
audio_format = wave->audio_format;
wave_sample_rate = wave->rate;
wave_channels = wave->channels;
wave_bits = wave->bits;
break;
case PLAYER_RESUME:
wave->audio_format = audio_format;
wave->rate = wave_sample_rate;
wave->channels = wave_channels;
wave->bits = wave_bits;
mdecoder->running = 1;
break;
default:
break;
}
return 0;
}
int wave_decoder_create(media_decoder_t *mdecoder)
{
wave_decoder_t *wave;
if (!mdecoder) {
M_LOGE("mdecoder null !\n");
return -1;
}
wave = snd_zalloc(sizeof(wave_decoder_t), AFM_EXTN);
if (!wave) {
M_LOGE("alloc wave decoder failed !\n");
return -1;
}
mdecoder->decode = wave_decode_process;
mdecoder->action = wave_decode_action;
mdecoder->decoder = wave;
mdecoder->input_size = 2048;
M_LOGD("wav decoder create\n");
return 0;
}
int wave_decoder_release(media_decoder_t *mdecoder)
{
if (!mdecoder) {
M_LOGE("mdecoder null !\n");
return -1;
}
snd_free(mdecoder->decoder);
mdecoder->decoder = NULL;
mdecoder->decode = NULL;
mdecoder->action = NULL;
M_LOGD("wav decoder release\n");
return 0;
}
static int wave_encode_process(void *priv, uint8_t *buffer, int nbytes)
{
return nbytes;
}
static int wave_encode_action(void *priv,
recorder_action_t action, void *arg)
{
return 0;
}
static int wave_encode_header_gen(void *priv, void *arg)
{
media_encoder_t *mencoder = (media_encoder_t *)priv;
media_pcminfo_t *pcminfo;
struct wav_header *header;
if (!mencoder) {
M_LOGE("mencoder null !\n");
return -1;
}
pcminfo = arg;
if (!pcminfo) {
M_LOGE("pcminfo null !\n");
return -1;
}
mencoder->header_size = sizeof(struct wav_header);
header = snd_zalloc(mencoder->header_size, AFM_EXTN);
if (!header) {
M_LOGE("alloc header failed !\n");
return -1;
}
M_LOGD("rate %d channels %d bits %d\n",
pcminfo->rate,
pcminfo->channels, pcminfo->bits);
if (wave_header_init(header, pcminfo->rate,
pcminfo->channels, pcminfo->bits)) {
M_LOGE("init wave header failed !\n");
snd_free(header);
mencoder->header_size = 0;
return -1;
}
mencoder->header_cplt = 0;
mencoder->header = header;
return 0;
}
static int wave_encode_header_update(void *priv, int size)
{
media_encoder_t *mencoder = (media_encoder_t *)priv;
struct wav_header *header;
if (!mencoder) {
M_LOGE("mencoder null !\n");
return -1;
}
header = mencoder->header;
if (!header) {
M_LOGE("header null !\n");
return -1;
}
header->riff_sz = size - 8;
header->data_sz = size - sizeof(struct wav_header);
mencoder->header_cplt = 1;
return 0;
}
int wave_encoder_create(media_encoder_t *mencoder)
{
if (!mencoder) {
M_LOGE("mencoder null !\n");
return -1;
}
mencoder->encode = wave_encode_process;
mencoder->action = wave_encode_action;
mencoder->header_gen = wave_encode_header_gen;
mencoder->header_update = wave_encode_header_update;
M_LOGD("wav encoder create\n");
return 0;
}
int wave_encoder_release(media_encoder_t *mencoder)
{
if (!mencoder) {
M_LOGE("mencoder null !\n");
return -1;
}
mencoder->encode = NULL;
mencoder->action = NULL;
mencoder->header_gen = NULL;
M_LOGD("wav encoder release\n");
return 0;
}
|
YifuLiu/AliOS-Things
|
components/uvoice/media/uvoice_wave.c
|
C
|
apache-2.0
| 8,750
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "uvoice_types.h"
#include "uvoice_player.h"
#include "uvoice_os.h"
#include "uvoice_config.h"
#include "uvoice_common.h"
#include "uvoice_ringbuffer.h"
#include "uvoice_play.h"
#include "uvoice_format.h"
#include "uvoice_cache.h"
#if (PLAYER_CACHE_TYPE != 0) && (PLAYER_CACHE_TYPE != 1) && \
(PLAYER_CACHE_TYPE != 2)
#error "cache type unsupport ! please choose from 0, 1, 2"
#endif
#ifdef MUSICBOX_APP
#define NET_CACHE_TASK_PRIORITY UVOICE_TASK_PRI_HIGHEST
#else
#define NET_CACHE_TASK_PRIORITY UVOICE_TASK_PRI_HIGHER
#endif
#ifndef PLAYER_CACHE_MEM_SIZE
#define PLAYER_CACHE_MEM_SIZE 40
#endif
#define NET_CACHE_REBUILD_ENABLE 1
#define NET_CACHE_FILE_ENABLE 1
static int net_cache_file(net_cache_t *nc)
{
#if NET_CACHE_FILE_ENABLE
struct cache_file *cache;
int load_size = 0;
int rd_ret = 0;
int ret;
if (!nc) {
M_LOGE("nc null !\n");
return -1;
}
os_mutex_lock(nc->lock, OS_WAIT_FOREVER);
nc->cache_running = 1;
cache = nc->cache;
if (!cache) {
M_LOGE("cache null !\n");
os_mutex_unlock(nc->lock);
return -1;
}
if (cache->fp) {
os_fclose(cache->fp);
cache->fp = NULL;
M_LOGD("cache file close\n");
}
cache->fp = os_fopen(nc->cache_config.file_path, "wb+");
if (OS_FILE_OPEN_FAIL(cache->fp)) {
M_LOGE("open %s failed !\n", nc->cache_config.file_path);
nc->cache_running = 0;
os_mutex_unlock(nc->lock);
return -1;
}
M_LOGD("cache file open\n");
cache->wr_pos = 0;
(void)os_fseek(cache->fp, cache->wr_pos, OS_SEEK_SET);
if (nc->head_data_size > 0) {
ret = os_fwrite(nc->buffer, 1, nc->head_data_size, cache->fp);
if (os_ferror(cache->fp) || ret != nc->head_data_size) {
M_LOGE("write head data failed %d!\n",
os_ferror(cache->fp));
nc->cache_running = 0;
os_mutex_unlock(nc->lock);
return -1;
}
cache->wr_pos += nc->head_data_size;
nc->load_length += nc->head_data_size;
nc->head_data_size = 0;
}
load_size = MIN(nc->buffer_size,
nc->content_length - cache->wr_pos);
M_LOGD("start\n");
os_mutex_unlock(nc->lock);
while (1) {
rd_ret = nc->cache_load(nc->priv, nc->buffer, load_size);
if (rd_ret < 0) {
M_LOGE("load failed !\n");
nc->cache_cplt = 1;
break;
} else if (rd_ret == 0) {
M_LOGD("load end\n");
nc->cache_cplt = 1;
break;
} else if (rd_ret != load_size) {
M_LOGW("load %d ret %d\n", load_size, rd_ret);
}
os_mutex_lock(nc->lock, OS_WAIT_FOREVER);
(void)os_fseek(cache->fp, cache->wr_pos, OS_SEEK_SET);
ret = os_fwrite(nc->buffer, 1, rd_ret, cache->fp);
if (os_ferror(cache->fp) || ret != rd_ret) {
M_LOGE("cache wr failed %d!\n", os_ferror(cache->fp));
nc->cache_cplt = 1;
os_mutex_unlock(nc->lock);
break;
}
cache->wr_pos += rd_ret;
if (cache->rd_waiting &&
cache->wr_pos - cache->rd_pos >= cache->rd_len) {
os_sem_signal(cache->rd_sem);
cache->rd_waiting = 0;
}
nc->load_length += rd_ret;
if (nc->cache_stop) {
if (cache->rd_waiting) {
os_sem_signal(cache->rd_sem);
cache->rd_waiting = 0;
}
nc->cache_stop = 0;
nc->cache_cplt = 1;
os_mutex_unlock(nc->lock);
M_LOGD("cache stop\n");
break;
}
load_size = MIN(load_size,
nc->content_length - nc->load_length);
if (load_size <= 0) {
if (!nc->sequence) {
M_LOGD("load end\n");
nc->cache_cplt = 1;
os_mutex_unlock(nc->lock);
break;
} else {
M_LOGD("request next segment, wr_pos %u load_length %u\n",
cache->wr_pos, nc->load_length);
os_mutex_unlock(nc->lock);
if (nc->event(nc->priv, CACHE_EV_CACHE_CPLT, NULL)) {
M_LOGD("request next segment failed !\n");
nc->cache_cplt = 1;
break;
}
os_mutex_lock(nc->lock, OS_WAIT_FOREVER);
if (nc->head_data_size > 0) {
ret = os_fwrite(nc->buffer,
1, nc->head_data_size, cache->fp);
if (os_ferror(cache->fp) || ret != nc->head_data_size) {
M_LOGE("write head data failed %d!\n",
os_ferror(cache->fp));
if (nc->cplt_waiting) {
nc->cplt_waiting = 0;
os_sem_signal(nc->cplt_sem);
}
nc->cache_running = 0;
os_mutex_unlock(nc->lock);
return -1;
}
cache->wr_pos += nc->head_data_size;
nc->load_length += nc->head_data_size;
M_LOGD("cache seq head data %u\n",
nc->head_data_size);
M_LOGD("cache next segment, wr_pos %u load_length %u\n",
cache->wr_pos, nc->load_length);
nc->head_data_size = 0;
}
load_size = MIN(nc->buffer_size,
nc->content_length - nc->load_length);
if (load_size <= 0) {
M_LOGD("load end\n");
nc->cache_cplt = 1;
os_mutex_unlock(nc->lock);
break;
}
}
}
os_mutex_unlock(nc->lock);
}
os_mutex_lock(nc->lock, OS_WAIT_FOREVER);
M_LOGD("complete %d/%d\n",
nc->load_length, nc->content_length);
if (!nc->sequence)
nc->event(nc->priv, CACHE_EV_CACHE_CPLT, NULL);
if (nc->cplt_waiting) {
nc->cplt_waiting = 0;
os_sem_signal(nc->cplt_sem);
}
nc->cache_running = 0;
os_mutex_unlock(nc->lock);
return 0;
#else
return -1;
#endif
}
static int net_cache_file_read(void *priv, unsigned char *buffer, int nbytes)
{
#if NET_CACHE_FILE_ENABLE
net_cache_t *nc = (net_cache_t *)priv;
struct cache_file *cache;
int ret = 0;
if (!nc) {
M_LOGE("nc null !\n");
return -1;
}
os_mutex_lock(nc->lock, OS_WAIT_FOREVER);
cache = nc->cache;
if (!cache) {
M_LOGE("cache null !\n");
os_mutex_unlock(nc->lock);
return -1;
}
if (!cache->rd_start) {
cache->rd_len = MIN(nbytes * 10, nc->content_length);
cache->rd_start = 1;
M_LOGD("read start\n");
} else {
cache->rd_len = nbytes;
}
if (nc->seek_offset != 0) {
if (nc->seek_offset > 0) {
if (nc->seek_offset <= cache->wr_pos - cache->rd_pos) {
cache->rd_pos += nc->seek_offset;
nc->event(nc->priv, CACHE_EV_SEEK_DONE,
(void *)nc->seek_offset);
M_LOGD("seek %d bytes\n", nc->seek_offset);
}
} else {
if (abs(nc->seek_offset) <= cache->rd_pos) {
cache->rd_pos += nc->seek_offset;
nc->event(nc->priv, CACHE_EV_SEEK_DONE,
(void *)nc->seek_offset);
M_LOGD("seek %d bytes\n", nc->seek_offset);
}
}
nc->seek_offset = 0;
}
while (cache->wr_pos <= cache->rd_pos ||
cache->wr_pos - cache->rd_pos < cache->rd_len ||
!cache->fp) {
if (nc->cache_cplt) {
M_LOGD("cache cplt, stop waiting\n");
break;
}
M_LOGD("wait cache, rd_len %u rd_pos %u wr_pos %u\n",
cache->rd_len, cache->rd_pos, cache->wr_pos);
cache->rd_waiting = 1;
os_mutex_unlock(nc->lock);
if (os_sem_wait(cache->rd_sem, 30000)) {
os_mutex_lock(nc->lock, OS_WAIT_FOREVER);
M_LOGE("wait timeout ! rd_len %u rd_pos %u wr_pos %u\n",
cache->rd_len, cache->rd_pos, cache->wr_pos);
cache->rd_waiting = 0;
goto __exit;
}
os_mutex_lock(nc->lock, OS_WAIT_FOREVER);
cache->rd_waiting = 0;
M_LOGD("wait exit, rd_len %u rd_pos %u wr_pos %u\n",
cache->rd_len, cache->rd_pos, cache->wr_pos);
}
if (!cache->fp) {
M_LOGE("cache file not open !\n");
os_mutex_unlock(nc->lock);
return -1;
}
if (nc->cache_cplt) {
if (os_feof(cache->fp) || cache->rd_pos >= cache->wr_pos) {
nbytes = 0;
M_LOGD("read end\n");
goto __exit;
} else if (cache->wr_pos - cache->rd_pos < nbytes) {
nbytes = cache->wr_pos - cache->rd_pos;
M_LOGD("read tail %d\n", nbytes);
}
}
(void)os_fseek(cache->fp, cache->rd_pos, OS_SEEK_SET);
ret = os_fread(buffer, 1, nbytes, cache->fp);
if (os_ferror(cache->fp) || ret != nbytes) {
M_LOGE("read failed %d!\n", os_ferror(cache->fp));
os_mutex_unlock(nc->lock);
return -1;
}
cache->rd_pos += nbytes;
ret = nbytes;
__exit:
os_mutex_unlock(nc->lock);
return ret;
#else
return -1;
#endif
}
static int net_cache_file_mediainfo(struct cache_file *cache,
media_info_t *info, media_format_t format)
{
#if NET_CACHE_FILE_ENABLE
if (!cache) {
M_LOGW("cache not enable\n");
return -1;
}
if (!cache->fp) {
M_LOGE("cache file not open !\n");
return -1;
}
if (format == MEDIA_FMT_MP3) {
char buffer[128];
memset(buffer, 0, sizeof(buffer));
(void)os_fseek(cache->fp, -128, OS_SEEK_END);
int ret = os_fread(buffer, 1, 128, cache->fp);
if (ret != 128) {
M_LOGE("read failed %d!\n", ret);
return -1;
}
mp3_id3v1_parse(info, buffer, 128);
}
return 0;
#else
return -1;
#endif
}
static int net_cache_file_reset(struct cache_file *cache)
{
#if NET_CACHE_FILE_ENABLE
if (!cache) {
M_LOGE("cache null !\n");
return -1;
}
if (cache->fp) {
os_fclose(cache->fp);
cache->fp = NULL;
M_LOGD("cache file close\n");
}
cache->rd_pos = 0;
cache->wr_pos = 0;
cache->rd_waiting = 0;
cache->rd_start = 0;
cache->rd_len = 0;
M_LOGD("file cache reset\n");
return 0;
#else
return -1;
#endif
}
static int net_cache_file_init(net_cache_t *nc)
{
#if NET_CACHE_FILE_ENABLE
struct cache_file *cache = snd_zalloc(
sizeof(struct cache_file), AFM_EXTN);
if (!cache) {
M_LOGE("alloc cache file failed !\n");
return -1;
}
cache->rd_sem = os_sem_new(0);
nc->cache_read = net_cache_file_read;
nc->cache = cache;
return 0;
#else
return -1;
#endif
}
static int net_cache_file_deinit(net_cache_t *nc)
{
#if NET_CACHE_FILE_ENABLE
struct cache_file *cache;
if (!nc) {
M_LOGE("nc null !\n");
return -1;
}
cache = nc->cache;
if (!cache) {
M_LOGE("cache null !\n");
return -1;
}
net_cache_file_reset(cache);
os_sem_free(cache->rd_sem);
snd_free(cache);
nc->cache_read = NULL;
nc->cache = NULL;
return 0;
#else
return -1;
#endif
}
static int net_cache_mem(net_cache_t *nc)
{
struct cache_mem *cache;
int load_size;
int rd_ret = 0;
int wr_ret = 0;
if (!nc) {
M_LOGE("nc null !\n");
return -1;
}
os_mutex_lock(nc->lock, OS_WAIT_FOREVER);
nc->cache_running = 1;
cache = nc->cache;
if (!cache) {
M_LOGE("cache null !\n");
os_mutex_unlock(nc->lock);
return -1;
}
if (nc->head_data_size > 0) {
if (uvoice_ringbuff_freesize(&cache->rb) < nc->head_data_size) {
if (cache->rd_waiting) {
os_sem_signal(cache->rd_sem);
cache->rd_waiting = 0;
}
cache->wr_len = nc->head_data_size;
cache->wr_waiting = 1;
os_mutex_unlock(nc->lock);
os_sem_wait(cache->wr_sem, OS_WAIT_FOREVER);
os_mutex_lock(nc->lock, OS_WAIT_FOREVER);
cache->wr_waiting = 0;
if (nc->cache_stop) {
nc->cache_stop = 0;
nc->cache_cplt = 1;
M_LOGD("cache stop\n");
os_mutex_unlock(nc->lock);
goto __exit;
}
}
wr_ret = uvoice_ringbuff_fill(&cache->rb,
nc->buffer, nc->head_data_size);
if (wr_ret < 0) {
M_LOGE("fill head data %u failed !\n",
nc->head_data_size);
nc->cache_running = 0;
os_mutex_unlock(nc->lock);
return -1;
} else if (wr_ret != nc->head_data_size) {
M_LOGW("cache head data %u ret %d\n",
nc->buffer_size, wr_ret);
}
nc->load_length += nc->head_data_size;
nc->head_data_size = 0;
}
load_size = MIN(nc->buffer_size,
nc->content_length - nc->load_length);
if (nc->load_length >= nc->content_length) {
nc->cache_cplt = 1;
goto __exit;
}
M_LOGD("start\n");
os_mutex_unlock(nc->lock);
while (1) {
rd_ret = nc->cache_load(nc->priv, nc->buffer + nc->offset,
load_size);
if (rd_ret < 0) {
M_LOGE("load failed !\n");
nc->cache_cplt = 1;
nc->load_length -= nc->offset;
break;
} else if (rd_ret == 0) {
M_LOGD("load end\n");
nc->cache_cplt = 1;
nc->load_length -= nc->offset;
break;
} else if (rd_ret != load_size) {
M_LOGW("load %d ret %u\n", load_size, rd_ret);
}
os_mutex_lock(nc->lock, OS_WAIT_FOREVER);
if (nc->cache_stop) {
nc->cache_stop = 0;
nc->cache_cplt = 1;
nc->load_length -= nc->offset;
M_LOGD("cache stop\n");
os_mutex_unlock(nc->lock);
goto __exit;
}
while (uvoice_ringbuff_freesize(&cache->rb) <
rd_ret + nc->offset) {
if (cache->rd_waiting) {
os_sem_signal(cache->rd_sem);
cache->rd_waiting = 0;
}
cache->wr_len = rd_ret + nc->offset;
cache->wr_waiting = 1;
os_mutex_unlock(nc->lock);
os_sem_wait(cache->wr_sem, OS_WAIT_FOREVER);
os_mutex_lock(nc->lock, OS_WAIT_FOREVER);
cache->wr_waiting = 0;
if (nc->cache_stop) {
nc->cache_stop = 0;
nc->cache_cplt = 1;
nc->load_length -= nc->offset;
M_LOGD("cache stop\n");
os_mutex_unlock(nc->lock);
goto __exit;
}
}
wr_ret = uvoice_ringbuff_fill(&cache->rb,
nc->buffer, rd_ret + nc->offset);
if (wr_ret < 0) {
M_LOGE("fill failed %d!\n", wr_ret);
nc->cache_cplt = 1;
nc->load_length -= nc->offset;
os_mutex_unlock(nc->lock);
break;
} else if (wr_ret != rd_ret + nc->offset) {
M_LOGW("fill %u ret %d\n", rd_ret + nc->offset, wr_ret);
}
nc->load_length += rd_ret;
if (nc->offset > 0)
nc->offset = 0;
if (cache->rd_waiting &&
uvoice_ringbuff_dirtysize(&cache->rb) >= cache->rd_len) {
cache->rd_waiting = 0;
os_sem_signal(cache->rd_sem);
}
if (nc->cache_stop) {
nc->cache_stop = 0;
nc->cache_cplt = 1;
M_LOGD("stop\n");
os_mutex_unlock(nc->lock);
break;
}
load_size = MIN(nc->buffer_size,
nc->content_length - nc->load_length);
if (load_size <= 0) {
if (!nc->sequence) {
M_LOGD("load end\n");
nc->cache_cplt = 1;
os_mutex_unlock(nc->lock);
break;
} else {
M_LOGD("request next segment\n");
os_mutex_unlock(nc->lock);
if (nc->event(nc->priv, CACHE_EV_CACHE_CPLT, NULL)) {
M_LOGD("request next segment failed !\n");
nc->cache_cplt = 1;
break;
}
os_mutex_lock(nc->lock, OS_WAIT_FOREVER);
load_size = MIN(nc->buffer_size,
nc->content_length - nc->load_length);
if (load_size <= 0) {
M_LOGD("load end\n");
nc->cache_cplt = 1;
os_mutex_unlock(nc->lock);
break;
}
if (nc->head_data_size > 0) {
nc->offset = nc->head_data_size;
load_size -= nc->offset;
nc->load_length += nc->offset;
M_LOGD("cache head data %u\n", nc->offset);
nc->head_data_size = 0;
}
}
}
os_mutex_unlock(nc->lock);
}
__exit:
os_mutex_lock(nc->lock, OS_WAIT_FOREVER);
M_LOGD("complete %d/%d\n",
nc->load_length, nc->content_length);
if (cache->rd_waiting) {
M_LOGD("wake rd wait\n");
cache->rd_waiting = 0;
os_sem_signal(cache->rd_sem);
}
if (nc->cplt_waiting) {
nc->cplt_waiting = 0;
os_sem_signal(nc->cplt_sem);
}
nc->cache_running = 0;
os_mutex_unlock(nc->lock);
return 0;
}
static int net_cache_mem_read(void *priv, unsigned char *buffer,
int nbytes)
{
net_cache_t *nc = (net_cache_t *)priv;
struct cache_mem *cache;
int ret = 0;
if (!nc) {
M_LOGE("nc null !\n");
return -1;
}
os_mutex_lock(nc->lock, OS_WAIT_FOREVER);
if (nbytes <= 0)
goto __exit;
cache = nc->cache;
if (!cache) {
M_LOGE("cache null !\n");
ret = -1;
goto __exit;
}
if (!cache->rd_start) {
#ifdef UVOICE_IOTNLP_ENABLE
cache->rd_len = nbytes;
#else
if (nc->cache_cplt)
cache->rd_len = MIN(cache->pool_size,
MIN(nbytes, nc->content_length));
else
cache->rd_len = MIN(cache->pool_size,
MIN(nbytes * 4, nc->content_length - nc->load_length));
if (nbytes > cache->rd_len) {
nbytes = cache->rd_len;
M_LOGD("update read bytes %d\n", nbytes);
}
#endif
cache->rd_start = 1;
} else {
cache->rd_len = nbytes;
}
if (nc->cache_cplt) {
if (uvoice_ringbuff_dirtysize(&cache->rb) <= 0) {
M_LOGD("data end\n");
goto __exit;
} else if (uvoice_ringbuff_dirtysize(&cache->rb) < nbytes) {
nbytes = uvoice_ringbuff_dirtysize(&cache->rb);
cache->rd_len = nbytes;
M_LOGD("cache cplt, read %d\n", nbytes);
}
}
if (nc->seek_offset != 0) {
if (nc->seek_offset > 0) {
if (nc->seek_offset <= uvoice_ringbuff_dirtysize(&cache->rb)) {
uvoice_ringbuff_drop(&cache->rb, nc->seek_offset);
nc->event(nc->priv, CACHE_EV_SEEK_DONE,
(void *)nc->seek_offset);
}
} else {
if (abs(nc->seek_offset) <= uvoice_ringbuff_freesize(&cache->rb)) {
uvoice_ringbuff_back(&cache->rb, abs(nc->seek_offset));
nc->event(nc->priv, CACHE_EV_SEEK_DONE,
(void *)nc->seek_offset);
}
}
M_LOGD("seek %d bytes\n", nc->seek_offset);
nc->seek_offset = 0;
}
if (uvoice_ringbuff_dirtysize(&cache->rb) < cache->rd_len) {
cache->rd_waiting = 1;
if (cache->wr_waiting) {
os_sem_signal(cache->wr_sem);
cache->wr_waiting = 0;
}
if (cache->rd_len == nbytes && !nc->sequence)
cache->rd_len = MIN(cache->pool_size / 2,
nc->content_length - nc->load_length);
if (cache->rd_len <= 0) {
M_LOGD("content end\n");
cache->rd_waiting = 0;
goto __exit;
}
nbytes = MIN(nbytes, cache->rd_len);
nc->event(nc->priv, CACHE_EV_READ_BLOCK, (void *)1);
M_LOGD("wait cache, rd_len %u dirtysize %d freesize %d\n",
cache->rd_len,
uvoice_ringbuff_dirtysize(&cache->rb),
uvoice_ringbuff_freesize(&cache->rb));
os_mutex_unlock(nc->lock);
if (os_sem_wait(cache->rd_sem, 60000)) {
os_mutex_lock(nc->lock, OS_WAIT_FOREVER);
M_LOGE("wait timeout ! rd_len %u dirtysize %d freesize %d\n",
cache->rd_len,
uvoice_ringbuff_dirtysize(&cache->rb),
uvoice_ringbuff_freesize(&cache->rb));
cache->rd_waiting = 0;
goto __exit;
}
os_mutex_lock(nc->lock, OS_WAIT_FOREVER);
M_LOGD("wait exit, rd_len %u dirtysize %d freesize %d\n",
cache->rd_len,
uvoice_ringbuff_dirtysize(&cache->rb),
uvoice_ringbuff_freesize(&cache->rb));
nc->event(nc->priv, CACHE_EV_READ_BLOCK, 0);
cache->rd_waiting = 0;
}
if (nc->cache_cplt) {
if (uvoice_ringbuff_dirtysize(&cache->rb) <= 0) {
M_LOGD("read end\n");
goto __exit;
} else if (uvoice_ringbuff_dirtysize(&cache->rb) <
nbytes) {
nbytes = uvoice_ringbuff_dirtysize(&cache->rb);
cache->rd_len = nbytes;
M_LOGD("cache cplt, read %d\n", nbytes);
}
}
ret = uvoice_ringbuff_read(&cache->rb, buffer, nbytes);
if (ret < 0) {
M_LOGE("read %d failed %d!\n", nbytes, ret);
ret = -1;
goto __exit;
} else if (ret != nbytes) {
M_LOGW("read %d ret %d\n", nbytes, ret);
}
if (cache->wr_waiting &&
uvoice_ringbuff_freesize(&cache->rb) >= cache->wr_len) {
os_sem_signal(cache->wr_sem);
cache->wr_waiting = 0;
}
__exit:
os_mutex_unlock(nc->lock);
return ret;
}
static int net_cache_mem_reset(struct cache_mem *cache)
{
if (!cache) {
M_LOGE("cache null !\n");
return -1;
}
cache->rd_start = 0;
cache->wr_waiting = 0;
cache->rd_waiting = 0;
cache->rd_len = 0;
cache->wr_len = 0;
memset(cache->pool, 0, cache->pool_size);
uvoice_ringbuff_reset(&cache->rb);
M_LOGD("mem cache reset\n");
return 0;
}
static int net_cache_mem_init(net_cache_t *nc)
{
struct cache_mem *cache;
if (!nc) {
M_LOGE("nc null !\n");
return -1;
}
cache = snd_zalloc(sizeof(struct cache_mem), AFM_EXTN);
if (!cache) {
M_LOGE("alloc cache mem failed !\n");
return -1;
}
cache->pool_size = nc->cache_config.mem_size * 1024;
if (nc->sequence && nc->cache_config.mem_size > 40)
cache->pool_size = 40 * 1024;
cache->pool = snd_zalloc(cache->pool_size + 4, AFM_EXTN);
if (!cache->pool) {
M_LOGE("alloc cache pool failed !\n");
snd_free(cache);
return -1;
}
M_LOGD("alloc cache pool %u\n", cache->pool_size);
if (uvoice_ringbuff_init(&cache->rb,
cache->pool, cache->pool_size)) {
M_LOGE("init ring buffer failed !\n");
snd_free(cache->pool);
snd_free(cache);
return -1;
}
cache->wr_sem = os_sem_new(0);
cache->rd_sem = os_sem_new(0);
nc->cache_read = net_cache_mem_read;
nc->cache = cache;
return 0;
}
static int net_cache_mem_deinit(net_cache_t *nc)
{
struct cache_mem *cache;
if (!nc) {
M_LOGE("nc null !\n");
return -1;
}
cache = nc->cache;
if (!cache) {
M_LOGE("cache null !\n");
return -1;
}
os_sem_free(cache->wr_sem);
os_sem_free(cache->rd_sem);
snd_free(cache->pool);
snd_free(cache);
nc->cache_read = NULL;
nc->cache = NULL;
return 0;
}
static void net_cache_task(void *arg)
{
net_cache_t *nc = (net_cache_t *)arg;
if (!nc) {
M_LOGE("nc null !\n");
return;
}
if (nc->cache_config.place == CACHE_FILE)
net_cache_file(nc);
else if (nc->cache_config.place == CACHE_MEM)
net_cache_mem(nc);
}
int net_get_cacheinfo(net_cache_t *nc, cache_info_t *info)
{
if (!nc) {
M_LOGE("nc null !\n");
return -1;
}
if (!info) {
M_LOGE("info null !\n");
return -1;
}
os_mutex_lock(nc->lock, OS_WAIT_FOREVER);
if (nc->cache_config.place == CACHE_FILE) {
struct cache_file *cache = nc->cache;
info->dirty_cache_size = cache->rd_pos;
info->avail_cache_size = cache->wr_pos - cache->rd_pos;
} else if (nc->cache_config.place == CACHE_MEM) {
struct cache_mem *cache = nc->cache;
info->dirty_cache_size = 0;
info->avail_cache_size =
uvoice_ringbuff_dirtysize(&cache->rb);
}
os_mutex_unlock(nc->lock);
return 0;
}
int net_get_mediainfo(net_cache_t *nc,
media_info_t *info, media_format_t format)
{
if (!nc) {
M_LOGE("nc null !\n");
return -1;
}
if (!info) {
M_LOGE("info null !\n");
return -1;
}
os_mutex_lock(nc->lock, OS_WAIT_FOREVER);
switch (nc->cache_config.place) {
case CACHE_FILE:
if (!nc->cache_cplt)
break;
if (net_cache_file_mediainfo(nc->cache,
info, format)) {
M_LOGE("get file mediainfo failed !\n");
os_mutex_unlock(nc->lock);
return -1;
}
break;
default:
break;
}
os_mutex_unlock(nc->lock);
return 0;
}
int net_cache_reset(net_cache_t *nc)
{
if (!nc) {
M_LOGE("nc null !\n");
return -1;
}
if (nc->cache_config.place == CACHE_NONE) {
M_LOGD("cache disabled\n");
goto __exit;
}
if (!nc->cache_cplt && nc->cache_running) {
M_LOGE("cache not cplt !\n");
return -1;
}
nc->cache_running = 0;
nc->load_length = 0;
nc->cache_cplt = 0;
nc->seek_offset = 0;
nc->rebuild = 0;
switch (nc->cache_config.place) {
case CACHE_FILE:
if (net_cache_file_reset(nc->cache)) {
M_LOGE("reset file cache failed !\n");
return -1;
}
break;
case CACHE_MEM:
if (net_cache_mem_reset(nc->cache)) {
M_LOGE("reset mem cache failed !\n");
return -1;
}
break;
default:
break;
}
__exit:
return 0;
}
int net_cache_seek(net_cache_t *nc, int offset)
{
if (!nc) {
M_LOGE("nc null !\n");
return -1;
}
if (offset != 0) {
os_mutex_lock(nc->lock, OS_WAIT_FOREVER);
nc->seek_offset = offset;
os_mutex_unlock(nc->lock);
}
return 0;
}
int net_cache_start(net_cache_t *nc)
{
if (!nc) {
M_LOGE("nc null !\n");
return -1;
}
if (nc->load_length >= nc->content_length) {
M_LOGD("load cplt, ignore\n");
nc->cache_cplt = 1;
goto __exit;
}
if (nc->cache_config.place != CACHE_NONE) {
nc->cache_cplt = 0;
os_task_create(&nc->cache_task, "uvoice_cache_task",
net_cache_task, nc,
2048, NET_CACHE_TASK_PRIORITY);
}
__exit:
return 0;
}
int net_cache_pause(net_cache_t *nc)
{
if (!nc) {
M_LOGE("nc null !\n");
return -1;
}
if (nc->cache_config.place == CACHE_MEM ||
nc->cache_config.place == CACHE_NONE) {
M_LOGD("rebuild cache\n");
nc->rebuild = NET_CACHE_REBUILD_ENABLE;
/* sequece stream rebuild forcibly */
if (nc->sequence)
nc->rebuild = 1;
}
return 0;
}
int net_cache_resume(net_cache_t *nc)
{
if (!nc) {
M_LOGE("nc null !\n");
return -1;
}
return 0;
}
int net_cache_stop(net_cache_t *nc)
{
if (!nc) {
M_LOGE("nc null !\n");
return -1;
}
if (!nc->cache_running) {
M_LOGD("cache not running, ignore\n");
goto __exit;
}
if (nc->cache_cplt) {
M_LOGD("cache cplt already, ignore\n");
goto __exit;
}
if (nc->cache_config.place != CACHE_NONE) {
os_mutex_lock(nc->lock, OS_WAIT_FOREVER);
if (!nc->cache_cplt) {
M_LOGD("wait cache cplt\n");
if (nc->cache_config.place == CACHE_MEM) {
struct cache_mem *cache = nc->cache;
nc->cache_stop = 1;
if (cache->wr_waiting) {
M_LOGD("wake wr waiting\n");
os_sem_signal(cache->wr_sem);
cache->wr_waiting = 0;
}
cache->rd_start = 0;
} else if (nc->cache_config.place == CACHE_FILE) {
struct cache_file *cache = nc->cache;
nc->cache_stop = 1;
cache->rd_start = 0;
}
nc->cplt_waiting = 1;
os_mutex_unlock(nc->lock);
if (os_sem_wait(nc->cplt_sem, 15000)) {
nc->cplt_waiting = 0;
M_LOGW("wait cache cplt timeout !\n");
}
M_LOGD("cache cplt and stop\n");
} else {
nc->cache_cplt = 0;
os_mutex_unlock(nc->lock);
}
}
__exit:
return 0;
}
net_cache_t *net_cache_create(int read_size,
cache_config_t *config, bool sequence)
{
net_cache_t *nc;
nc = snd_zalloc(sizeof(net_cache_t), AFM_EXTN);
if (!nc) {
M_LOGE("alloc net cache failed !\n");
return NULL;
}
memcpy(&nc->cache_config, config, sizeof(cache_config_t));
nc->buffer_size = read_size;
nc->buffer = snd_zalloc(nc->buffer_size, AFM_MAIN);
if (!nc->buffer) {
M_LOGE("alloc buffer failed !\n");
snd_free(nc);
return NULL;
}
nc->lock = os_mutex_new();
nc->cplt_sem = os_sem_new(0);
if (sequence)
nc->sequence = 1;
if (nc->cache_config.place == CACHE_FILE) {
if (net_cache_file_init(nc)) {
M_LOGE("init file cache failed !\n");
snd_free(nc->buffer);
snd_free(nc);
return NULL;
}
} else if (nc->cache_config.place == CACHE_MEM) {
if (net_cache_mem_init(nc)) {
M_LOGE("init mem cache failed !\n");
snd_free(nc->buffer);
snd_free(nc);
return NULL;
}
}
M_LOGD("net cache create\n");
return nc;
}
int net_cache_release(net_cache_t *nc)
{
int ret = 0;
if (!nc) {
M_LOGE("nc null !\n");
return -1;
}
if (nc->cache_config.place == CACHE_FILE)
ret = net_cache_file_deinit(nc);
else if (nc->cache_config.place == CACHE_MEM)
ret = net_cache_mem_deinit(nc);
if (ret) {
M_LOGE("cache deinit failed !\n");
return -1;
}
os_sem_free(nc->cplt_sem);
os_mutex_free(nc->lock);
snd_free(nc->buffer);
snd_free(nc);
M_LOGD("net cache release\n");
return 0;
}
|
YifuLiu/AliOS-Things
|
components/uvoice/stream/uvoice_cache.c
|
C
|
apache-2.0
| 31,809
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#ifndef __NET_CACHE_H__
#define __NET_CACHE_H__
enum cache_type {
CACHE_NONE = 0,
CACHE_FILE,
CACHE_MEM,
};
enum cache_event {
CACHE_EV_CACHE_CPLT = 0,
CACHE_EV_SEEK_DONE,
CACHE_EV_READ_BLOCK,
};
struct cache_file {
os_file_t fp;
uint32_t wr_pos;
uint32_t rd_pos;
uint32_t rd_len;
uint8_t rd_waiting:1;
uint8_t rd_start:1;
os_sem_t rd_sem;
};
struct cache_mem {
uvoice_ringbuff_t rb;
uint8_t *pool;
int pool_size;
int wr_len;
int rd_len;
uint8_t wr_waiting:1;
uint8_t rd_waiting:1;
uint8_t rd_start:1;
os_sem_t wr_sem;
os_sem_t rd_sem;
};
typedef struct {
uint8_t *buffer;
int32_t buffer_size;
int32_t head_data_size;
int32_t offset;
cache_config_t cache_config;
uint8_t cache_running:1;
uint8_t cache_stop:1;
uint8_t cache_cplt:1;
uint8_t cplt_waiting:1;
uint8_t rebuild:1;
uint8_t download:1;
uint8_t sequence:1;
char filename[64];
int32_t content_length;
int32_t load_length;
int32_t seek_offset;
void *cache;
int (*cache_load)(void *priv, uint8_t *buffer, int nbytes);
int (*cache_read)(void *priv, uint8_t *buffer, int nbytes);
int (*event)(void *priv, enum cache_event event, void *arg);
void *priv;
os_sem_t cplt_sem;
os_mutex_t lock;
os_task_t cache_task;
} net_cache_t;
int net_get_cacheinfo(net_cache_t *nc, cache_info_t *info);
int net_get_mediainfo(net_cache_t *nc, media_info_t *info, media_format_t format);
int net_cache_reset(net_cache_t *nc);
int net_cache_seek(net_cache_t *nc, int offset);
int net_cache_pause(net_cache_t *nc);
int net_cache_resume(net_cache_t *nc);
int net_cache_start(net_cache_t *nc);
int net_cache_stop(net_cache_t *nc);
net_cache_t *net_cache_create(int read_size, cache_config_t *config, bool sequence);
int net_cache_release(net_cache_t *nc);
#endif /* __NET_CACHE_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/stream/uvoice_cache.h
|
C
|
apache-2.0
| 1,838
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "uvoice_os.h"
#include "uvoice_types.h"
#include "uvoice_player.h"
#include "uvoice_config.h"
#include "uvoice_common.h"
#include "uvoice_play.h"
#include "uvoice_cache.h"
int net_download_work(net_cache_t *nc)
{
int filepath_len;
char *filepath;
os_file_t fp;
int rd_ret = 0;
int load_size;
int i = 0;
int ret;
if (!nc) {
M_LOGE("nc null !\n");
return -1;
}
os_mutex_lock(nc->lock, OS_WAIT_FOREVER);
ret = os_access(PLAYER_SOURCE_DLOAD_DIR, OS_F_OK);
if (ret != 0) {
ret = os_mkdir(PLAYER_SOURCE_DLOAD_DIR);
if (ret) {
M_LOGE("create %s failed %d!\n",
PLAYER_SOURCE_DLOAD_DIR, ret);
os_mutex_unlock(nc->lock);
return -1;
}
M_LOGD("create dir: %s\n", PLAYER_SOURCE_DLOAD_DIR);
}
filepath_len = strlen(PLAYER_SOURCE_DLOAD_DIR) +
strlen(nc->filename) + 4;
filepath = snd_zalloc(filepath_len, AFM_EXTN);
if (!filepath) {
M_LOGE("alloc file path failed !\n");
os_mutex_unlock(nc->lock);
return -1;
}
snprintf(filepath, filepath_len, "%s/%s",
PLAYER_SOURCE_DLOAD_DIR, nc->filename);
M_LOGI("download to %s\n", filepath);
ret = os_access(filepath, OS_W_OK | OS_R_OK | OS_F_OK);
if (ret == 0) {
M_LOGW("file exist\n");
snd_free(filepath);
os_mutex_unlock(nc->lock);
goto __exit;
}
fp = os_fopen(filepath, "wb+");
if (OS_FILE_OPEN_FAIL(fp)) {
M_LOGE("open %s failed !\n", filepath);
snd_free(filepath);
os_mutex_unlock(nc->lock);
return -1;
}
if (nc->head_data_size > 0) {
ret = os_fwrite(nc->buffer, 1, nc->head_data_size, fp);
if (os_ferror(fp) || ret != nc->head_data_size) {
M_LOGE("write head data failed %d!\n", os_ferror(fp));
os_fclose(fp);
snd_free(filepath);
nc->head_data_size = 0;
os_mutex_unlock(nc->lock);
return -1;
}
M_LOGD("save head data %u\n", nc->head_data_size);
nc->load_length += nc->head_data_size;
nc->head_data_size = 0;
}
load_size = MIN(nc->buffer_size,
nc->content_length - nc->load_length);
nc->download = 1;
os_mutex_unlock(nc->lock);
while (load_size > 0) {
rd_ret = nc->cache_load(nc->priv, nc->buffer, load_size);
if (rd_ret < 0) {
M_LOGE("read failed !\n");
break;
} else if (rd_ret == 0) {
M_LOGD("read end\n");
break;
}
os_mutex_lock(nc->lock, OS_WAIT_FOREVER);
ret = os_fwrite(nc->buffer, 1, rd_ret, fp);
if (os_ferror(fp) || ret != rd_ret) {
M_LOGE("write failed %d!\n", os_ferror(fp));
os_mutex_unlock(nc->lock);
break;
}
nc->load_length += rd_ret;
load_size = MIN(load_size,
nc->content_length - nc->load_length);
if (++i == 50) {
M_LOGI("download %d/%d\n",
nc->load_length, nc->content_length);
i = 0;
}
if (!nc->download) {
M_LOGI("download abort\n");
os_mutex_unlock(nc->lock);
break;
}
os_mutex_unlock(nc->lock);
}
os_mutex_lock(nc->lock, OS_WAIT_FOREVER);
os_fclose(fp);
if (!nc->download) {
ret = os_remove(filepath);
if (ret)
M_LOGE("delete failed %d!\n", ret);
else
M_LOGD("file delete\n");
} else {
M_LOGI("download %d/%d\n",
nc->load_length, nc->content_length);
M_LOGI("download complete\n");
}
snd_free(filepath);
if (nc->cplt_waiting) {
nc->cplt_waiting = 0;
os_sem_signal(nc->cplt_sem);
}
os_mutex_unlock(nc->lock);
__exit:
return 0;
}
int new_download_abort(net_cache_t *nc)
{
if (!nc) {
M_LOGW("nc null\n");
return -1;
}
os_mutex_lock(nc->lock, OS_WAIT_FOREVER);
if (nc->download) {
nc->download = 0;
nc->cplt_waiting = 1;
M_LOGD("wait cplt\n");
os_mutex_unlock(nc->lock);
if (os_sem_wait(nc->cplt_sem, 15000)) {
M_LOGE("wait cplt timeout !\n");
nc->cplt_waiting = 0;
return -1;
}
M_LOGD("download abort\n");
} else {
M_LOGW("no download\n");
os_mutex_unlock(nc->lock);
}
return 0;
}
net_cache_t *net_download_create(void)
{
net_cache_t *nc = snd_zalloc(sizeof(net_cache_t), AFM_EXTN);
if (!nc) {
M_LOGE("alloc net cache failed !\n");
return NULL;
}
nc->cache_config.place = CACHE_NONE;
nc->buffer_size = 2048;
nc->buffer = snd_zalloc(nc->buffer_size, AFM_MAIN);
if (!nc->buffer) {
M_LOGE("alloc buffer failed !\n");
snd_free(nc);
return NULL;
}
nc->lock = os_mutex_new();
nc->cplt_sem = os_sem_new(0);
return nc;
}
int net_download_release(net_cache_t *nc)
{
if (!nc) {
M_LOGE("nc null !\n");
return -1;
}
os_sem_free(nc->cplt_sem);
os_mutex_free(nc->lock);
snd_free(nc->buffer);
snd_free(nc);
return 0;
}
|
YifuLiu/AliOS-Things
|
components/uvoice/stream/uvoice_download.c
|
C
|
apache-2.0
| 5,413
|
#ifndef __NET_DOWNLOAD_H__
#define __NET_DOWNLOAD_H__
int net_download_work(net_cache_t *nc);
int new_download_abort(net_cache_t *nc);
net_cache_t *net_download_create(void);
int net_download_release(net_cache_t *nc);
#endif
|
YifuLiu/AliOS-Things
|
components/uvoice/stream/uvoice_download.h
|
C
|
apache-2.0
| 229
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "uvoice_types.h"
#include "uvoice_player.h"
#include "uvoice_recorder.h"
#include "uvoice_os.h"
#include "uvoice_common.h"
#include "uvoice_play.h"
#include "uvoice_record.h"
#include "uvoice_format.h"
struct file_loader {
char filename[256];
os_file_t stream;
int file_length;
int rd_pos;
long seek_offset;
os_mutex_t lock;
};
struct file_packer {
os_file_t stream;
os_mutex_t lock;
};
static int file_get_format(void *priv, media_format_t *format)
{
media_loader_t *mloader = (media_loader_t *)priv;
struct file_loader *loader;
uint8_t *head_buffer;
int buffer_size;
int file_pos;
int ret;
if (!mloader) {
M_LOGE("mloader null !\n");
return -1;
}
loader = mloader->loader;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
os_mutex_lock(loader->lock, OS_WAIT_FOREVER);
if (!OS_FILE_OPENING(loader->stream)) {
M_LOGE("file not open !\n");
os_mutex_unlock(loader->lock);
return -1;
}
buffer_size = MIN(512, loader->file_length);
head_buffer = snd_zalloc(buffer_size, AFM_EXTN);
if (!head_buffer) {
M_LOGE("alloc buffer failed !\n");
os_mutex_unlock(loader->lock);
return -1;
}
file_pos = os_ftell(loader->stream);
if (file_pos < 0)
file_pos = loader->rd_pos;
(void)os_fseek(loader->stream, 0, OS_SEEK_SET);
ret = os_fread(head_buffer, 1, buffer_size, loader->stream);
if (ret != buffer_size) {
M_LOGE("read failed %d!\n", ret);
(void)os_fseek(loader->stream, file_pos, OS_SEEK_SET);
snd_free(head_buffer);
os_mutex_unlock(loader->lock);
return -1;
}
(void)os_fseek(loader->stream, file_pos, OS_SEEK_SET);
os_mutex_unlock(loader->lock);
if (flac_format_check(head_buffer, buffer_size)) {
*format = MEDIA_FMT_FLAC;
M_LOGD("format FLAC\n");
} else if (mp3_format_check(head_buffer, buffer_size)) {
*format = MEDIA_FMT_MP3;
M_LOGD("format MP3\n");
} else if (wav_format_check(head_buffer, buffer_size)) {
*format = MEDIA_FMT_WAV;
M_LOGD("format WAV\n");
} else if (aac_format_check(head_buffer, buffer_size)) {
*format = MEDIA_FMT_AAC;
M_LOGD("format AAC\n");
} else if (m4a_format_check(head_buffer, buffer_size)) {
*format = MEDIA_FMT_M4A;
M_LOGD("format M4A\n");
} else if (ogg_format_check(head_buffer, buffer_size)) {
*format = MEDIA_FMT_OGG;
M_LOGD("format OGG\n");
} else if (wma_format_check(head_buffer, buffer_size)) {
*format = MEDIA_FMT_WMA;
M_LOGD("format WMA\n");
} else if (amrwb_format_check(head_buffer, buffer_size)) {
*format = MEDIA_FMT_AMRWB;
M_LOGD("format AMR-WB\n");
} else if (amr_format_check(head_buffer, buffer_size)) {
*format = MEDIA_FMT_AMR;
M_LOGD("format AMR\n");
}
snd_free(head_buffer);
return 0;
}
static int file_get_mediainfo(void *priv, media_info_t *info,
media_format_t format)
{
media_loader_t *mloader = (media_loader_t *)priv;
struct file_loader *loader;
if (!mloader) {
M_LOGE("mloader null !\n");
return -1;
}
loader = mloader->loader;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
os_mutex_lock(loader->lock, OS_WAIT_FOREVER);
if (!OS_FILE_OPENING(loader->stream)) {
M_LOGE("file not open !\n");
os_mutex_unlock(loader->lock);
return -1;
}
if (format == MEDIA_FMT_MP3) {
if (loader->file_length < 128) {
M_LOGE("file too short !\n");
os_mutex_unlock(loader->lock);
return -1;
}
char buffer[128];
memset(buffer, 0, sizeof(buffer));
int file_pos = os_ftell(loader->stream);
if (file_pos < 0)
file_pos = loader->rd_pos;
(void)os_fseek(loader->stream, -128, OS_SEEK_END);
int ret = os_fread(buffer, 1, 128, loader->stream);
if (ret != 128) {
M_LOGE("read failed %d!\n", ret);
(void)os_fseek(loader->stream, file_pos, OS_SEEK_SET);
os_mutex_unlock(loader->lock);
return -1;
}
(void)os_fseek(loader->stream, file_pos, OS_SEEK_SET);
mp3_id3v1_parse(info, buffer, 128);
}
os_mutex_unlock(loader->lock);
return 0;
}
static int file_loader_reset(void *priv)
{
media_loader_t *mloader = (media_loader_t *)priv;
struct file_loader *loader;
if (!mloader) {
M_LOGE("mloader null !\n");
return -1;
}
loader = mloader->loader;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
os_mutex_lock(loader->lock, OS_WAIT_FOREVER);
if (OS_FILE_OPENING(loader->stream)) {
M_LOGE("file load not stop !\n");
os_mutex_unlock(loader->lock);
return -1;
}
loader->rd_pos = 0;
loader->seek_offset = 0;
loader->file_length = 0;
os_mutex_unlock(loader->lock);
M_LOGD("file load reset\n");
return 0;
}
static int file_loader_update(struct file_loader *loader, char *sink)
{
int ret;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
if (!sink) {
M_LOGE("sink null!\n");
return -1;
}
if (loader->stream) {
M_LOGE("prev file not close !\n");
return -1;
}
if (strncmp(sink, "fs:", strlen("fs:"))) {
M_LOGE("filename invalid !\n");
return -1;
}
sink += strlen("fs:");
if (strlen(sink) + 1 > sizeof(loader->filename)) {
M_LOGE("filename length overrange !\n");
return -1;
}
memset(loader->filename, 0, sizeof(loader->filename));
memcpy(loader->filename, sink, strlen(sink) + 1);
loader->stream = os_fopen(loader->filename, "rb");
if (OS_FILE_OPEN_FAIL(loader->stream)) {
M_LOGE("open %s failed !\n", loader->filename);
return -1;
}
ret = (int)os_fseek(loader->stream, 0, OS_SEEK_END);
loader->file_length = os_ftell(loader->stream);
if (loader->file_length < 0)
loader->file_length = ret;
(void)os_fseek(loader->stream, 0, OS_SEEK_SET);
loader->rd_pos = 0;
loader->seek_offset = 0;
return 0;
}
static int file_loader_read(void *priv, uint8_t *buffer, int nbytes)
{
media_loader_t *mloader = (media_loader_t *)priv;
struct file_loader *loader;
int ret;
if (!mloader) {
M_LOGE("mloader null !\n");
return -1;
}
loader = mloader->loader;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
if (mloader->rebase_request) {
mloader->rebase_request = 0;
loader->seek_offset = loader->rd_pos - mloader->rebase_offset;
M_LOGI("read pos rebase %d\n", mloader->rebase_offset);
}
os_mutex_lock(loader->lock, OS_WAIT_FOREVER);
if (loader->seek_offset != 0) {
if (loader->seek_offset > 0) {
if (loader->seek_offset <=
loader->file_length - loader->rd_pos) {
(void)os_fseek(loader->stream, loader->seek_offset,
OS_SEEK_CUR);
ret = os_ftell(loader->stream);
if (ret < 0)
loader->rd_pos += loader->seek_offset;
else
loader->rd_pos = ret;
if (mloader->message)
mloader->message(mloader->priv,
PLAYER_MSG_SEEK_DONE, (void *)loader->seek_offset);
}
} else {
if (abs(loader->seek_offset) <= loader->rd_pos) {
(void)os_fseek(loader->stream, loader->seek_offset,
OS_SEEK_CUR);
ret = os_ftell(loader->stream);
if (ret < 0)
loader->rd_pos += loader->seek_offset;
else
loader->rd_pos = ret;
if (mloader->message)
mloader->message(mloader->priv,
PLAYER_MSG_SEEK_DONE, (void *)loader->seek_offset);
}
}
loader->seek_offset = 0;
}
if (os_feof(loader->stream) ||
loader->rd_pos >= loader->file_length) {
nbytes = 0;
M_LOGD("read end\n");
goto __exit;
} else if (loader->file_length - loader->rd_pos < nbytes) {
nbytes = loader->file_length - loader->rd_pos;
M_LOGD("read tail %d\n", nbytes);
}
ret = os_fread(buffer, 1, nbytes, loader->stream);
if (os_ferror(loader->stream) || ret != nbytes) {
M_LOGE("read failed %d!\n", os_ferror(loader->stream));
os_mutex_unlock(loader->lock);
return -1;
}
loader->rd_pos += nbytes;
__exit:
os_mutex_unlock(loader->lock);
return nbytes;
}
static int file_loader_action(void *priv, player_action_t action, void *arg)
{
media_loader_t *mloader = (media_loader_t *)priv;
struct file_loader *loader;
int ret;
if (!mloader) {
M_LOGE("mloader null !\n");
return -1;
}
loader = mloader->loader;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
if (action == PLAYER_START) {
os_mutex_lock(loader->lock, OS_WAIT_FOREVER);
if (!OS_FILE_OPENING(loader->stream)) {
M_LOGD("open %s\n", loader->filename);
loader->stream = os_fopen(loader->filename, "rb");
if (OS_FILE_OPEN_FAIL(loader->stream)) {
M_LOGE("open %s failed !\n", loader->filename);
os_mutex_unlock(loader->lock);
return -1;
}
ret = (int)os_fseek(loader->stream, 0, OS_SEEK_END);
loader->file_length = os_ftell(loader->stream);
if (loader->file_length < 0)
loader->file_length = ret;
(void)os_fseek(loader->stream, 0, OS_SEEK_SET);
loader->rd_pos = 0;
loader->seek_offset = 0;
M_LOGI("file_length %d\n", loader->file_length);
}
if (mloader->message) {
media_info_t media_info;
memset(&media_info, 0, sizeof(media_info_t));
media_info.media_size = loader->file_length;
mloader->message(mloader->priv,
PLAYER_MSG_MEDIA_INFO, &media_info);
}
os_mutex_unlock(loader->lock);
} else if (action == PLAYER_STOP) {
os_mutex_lock(loader->lock, OS_WAIT_FOREVER);
if (OS_FILE_OPENING(loader->stream)) {
M_LOGD("file close\n");
os_fclose(loader->stream);
loader->stream = NULL;
}
os_mutex_unlock(loader->lock);
} else if (action == PLAYER_RELOAD) {
os_mutex_lock(loader->lock, OS_WAIT_FOREVER);
if (!OS_FILE_OPENING(loader->stream)) {
M_LOGD("file not open\n");
os_mutex_unlock(loader->lock);
return -1;
}
M_LOGD("reload from %x\n", (uint32_t)arg);
loader->seek_offset = 0;
loader->rd_pos = (int)arg;
(void)os_fseek(loader->stream, (long)arg, OS_SEEK_SET);
os_mutex_unlock(loader->lock);
} else if (action == PLAYER_SEEK) {
os_mutex_lock(loader->lock, OS_WAIT_FOREVER);
loader->seek_offset = (long)arg;
os_mutex_unlock(loader->lock);
} else if (action == PLAYER_COMPLETE) {
os_mutex_lock(loader->lock, OS_WAIT_FOREVER);
if (OS_FILE_OPENING(loader->stream)) {
M_LOGD("file close\n");
os_fclose(loader->stream);
loader->stream = OS_FILE_CLOSED;
} else {
M_LOGW("file not open !\n");
}
os_mutex_unlock(loader->lock);
} else if (action == PLAYER_NEXT) {
os_mutex_lock(loader->lock, OS_WAIT_FOREVER);
if (file_loader_update(loader, (char *)arg)) {
M_LOGE("update failed !\n");
os_mutex_unlock(loader->lock);
return -1;
}
os_mutex_unlock(loader->lock);
}
return 0;
}
int file_loader_create(media_loader_t *mloader, char *source)
{
struct file_loader *loader;
int ret;
if (!mloader) {
M_LOGE("mloader null !\n");
return -1;
}
if (!source) {
M_LOGE("source null !\n");
return -1;
}
if (strncmp(source, "fs:", strlen("fs:"))) {
M_LOGE("filename invalid !\n");
return -1;
}
source += strlen("fs:");
loader = snd_zalloc(sizeof(struct file_loader), AFM_EXTN);
if (!loader) {
M_LOGE("alloc file loader failed !\n");
return -1;
}
if (strlen(source) + 1 > sizeof(loader->filename)) {
M_LOGE("filename length overrange !\n");
snd_free(loader);
return -1;
}
memcpy(loader->filename, source, strlen(source) + 1);
loader->stream = os_fopen(loader->filename, "rb");
if (OS_FILE_OPEN_FAIL(loader->stream)) {
M_LOGE("open %s failed !\n", loader->filename);
snd_free(loader);
return -1;
}
ret = os_fseek(loader->stream, 0, OS_SEEK_END);
loader->file_length = os_ftell(loader->stream);
if (loader->file_length < 0)
loader->file_length = ret;
(void)os_fseek(loader->stream, 0, OS_SEEK_SET);
if (loader->file_length <= 0) {
M_LOGE("file lenth %u invalid !\n", loader->file_length);
os_fclose(loader->stream);
snd_free(loader);
return -1;
}
loader->lock = os_mutex_new();
loader->seek_offset = 0;
loader->rd_pos = 0;
mloader->read = file_loader_read;
mloader->action = file_loader_action;
mloader->get_format = file_get_format;
mloader->get_mediainfo = file_get_mediainfo;
mloader->get_cacheinfo = NULL;
mloader->reset = file_loader_reset;
mloader->loader = loader;
M_LOGD("file loader create\n");
return 0;
}
int file_loader_release(media_loader_t *mloader)
{
struct file_loader *loader;
if (!mloader) {
M_LOGE("mloader null !\n");
return -1;
}
loader = mloader->loader;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
if (OS_FILE_OPENING(loader->stream)) {
M_LOGD("file close\n");
os_fclose(loader->stream);
loader->stream = OS_FILE_CLOSED;
}
os_mutex_free(loader->lock);
snd_free(loader);
mloader->loader = NULL;
M_LOGD("file loader release\n");
return 0;
}
static int file_packer_write(void *priv, uint8_t *buffer, int nbytes)
{
media_packer_t *mpacker = (media_packer_t *)priv;
struct file_packer *packer;
int ret;
if (!mpacker) {
M_LOGE("mpacker null !\n");
return -1;
}
packer = mpacker->packer;
if (!packer) {
M_LOGE("packer null !\n");
return -1;
}
os_mutex_lock(packer->lock, OS_WAIT_FOREVER);
ret = os_fwrite(buffer, 1, nbytes, packer->stream);
if (os_ferror(packer->stream) || ret != nbytes) {
M_LOGE("write failed %d!\n", os_ferror(packer->stream));
os_mutex_unlock(packer->lock);
return -1;
}
mpacker->size += nbytes;
os_mutex_unlock(packer->lock);
return nbytes;
}
static int file_packer_update(void *priv, uint8_t *buffer,
int nbytes, int pos)
{
media_packer_t *mpacker = (media_packer_t *)priv;
struct file_packer *packer;
int file_pos;
int ret;
if (!mpacker) {
M_LOGE("mpacker null !\n");
return -1;
}
packer = mpacker->packer;
if (!packer) {
M_LOGE("packer null !\n");
return -1;
}
os_mutex_lock(packer->lock, OS_WAIT_FOREVER);
file_pos = os_ftell(packer->stream);
if (file_pos < 0)
file_pos = mpacker->size;
(void)os_fseek(packer->stream, pos, OS_SEEK_SET);
ret = os_fwrite(buffer, 1, nbytes, packer->stream);
if (os_ferror(packer->stream) || ret != nbytes) {
M_LOGE("write failed %d!\n", os_ferror(packer->stream));
os_mutex_unlock(packer->lock);
return -1;
}
(void)os_fseek(packer->stream, file_pos, OS_SEEK_SET);
os_mutex_unlock(packer->lock);
return 0;
}
static int file_packer_action(void *priv, recorder_action_t action, void *arg)
{
media_packer_t *mpacker = (media_packer_t *)priv;
struct file_packer *packer;
if (!mpacker) {
M_LOGE("mpacker null !\n");
return -1;
}
packer = mpacker->packer;
if (!packer) {
M_LOGE("packer null !\n");
return -1;
}
if (action == RECORDER_STOP)
M_LOGD("pack size %d\n", mpacker->size);
return 0;
}
int file_packer_create(media_packer_t *mpacker, char *sink)
{
struct file_packer *packer;
if (!mpacker) {
M_LOGE("mpacker null !\n");
return -1;
}
if (!sink) {
M_LOGE("sink null !\n");
return -1;
}
if (strncmp(sink, "fs:", strlen("fs:"))) {
M_LOGE("filename invalid !\n");
return -1;
}
sink += strlen("fs:");
packer = snd_zalloc(sizeof(struct file_packer), AFM_EXTN);
if (!packer) {
M_LOGE("alloc file packer failed !\n");
return -1;
}
packer->stream = os_fopen(sink, "wb+");
if (OS_FILE_OPEN_FAIL(packer->stream)) {
M_LOGE("open %s failed !\n", sink);
snd_free(packer);
return -1;
}
(void)os_fseek(packer->stream, 0, OS_SEEK_SET);
packer->lock = os_mutex_new();
mpacker->packer = packer;
mpacker->pack = file_packer_write;
mpacker->update = file_packer_update;
mpacker->action = file_packer_action;
M_LOGD("file packer create\n");
return 0;
}
int file_packer_release(media_packer_t *mpacker)
{
struct file_packer *packer;
if (!mpacker) {
M_LOGE("mpacker null !\n");
return -1;
}
packer = mpacker->packer;
if (!packer) {
M_LOGE("packer null !\n");
return -1;
}
if (OS_FILE_OPENING(packer->stream)) {
M_LOGD("file close\n");
os_fclose(packer->stream);
}
os_mutex_free(packer->lock);
snd_free(packer);
mpacker->packer = NULL;
M_LOGD("file packer release\n");
return 0;
}
|
YifuLiu/AliOS-Things
|
components/uvoice/stream/uvoice_file.c
|
C
|
apache-2.0
| 18,379
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "uvoice_types.h"
#include "uvoice_player.h"
#include "uvoice_os.h"
#include "uvoice_common.h"
#include "uvoice_play.h"
#include "uvoice_cache.h"
#include "uvoice_http.h"
#include "uvoice_hls.h"
//#define HTTP_LIST_FILE_LOAD
#define HTTP_LIVE_STREAM_ENABLE 1
int http_loader_start(http_loader_t *loader);
int http_loader_stop(http_loader_t *loader);
static int hls_index_get(char *desc)
{
int len;
char *ptr;
bool found = false;
if (!desc) {
M_LOGE("desc null !\n");
return -1;
}
len = strlen(desc);
if (len <= 0) {
M_LOGE("desc invalid !\n");
return -1;
}
ptr = strstr(desc, ".aac");
if (!ptr) {
ptr = strstr(desc, ".AAC");
if (!ptr) {
M_LOGE("seg info not found !\n");
return -1;
}
}
for (ptr--; ptr > desc; ptr--) {
if (*ptr < '0' || *ptr > '9') {
found = true;
ptr++;
break;
}
}
if (!found) {
M_LOGE("seg index not found !\n");
return -1;
}
return atoi(ptr);
}
int uvoice_hls_index_update(http_loader_t *loader, int index)
{
hls_t *hls;
int target_index;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
hls = loader->hls;
if (!hls) {
M_LOGE("hls null !\n");
return -1;
}
os_mutex_lock(hls->lock, OS_WAIT_FOREVER);
if (index < 0 || index >= hls->seg_count) {
M_LOGE("index %d invalid !\n", index);
os_mutex_unlock(hls->lock);
return -1;
}
if (index == hls->seg_index) {
M_LOGD("seg index not change\n");
goto __exit;
}
hls->seg_index = index;
target_index = index + hls->seg_begin;
#ifdef HTTP_LIST_FILE_LOAD
if (!hls->fp) {
M_LOGE("no hls file !\n");
os_mutex_unlock(hls->lock);
return -1;
}
fseek(hls->fp, 0, SEEK_SET);
#else
if (!hls->content) {
M_LOGE("no hls content !\n");
os_mutex_unlock(hls->lock);
return -1;
}
hls->pos = hls->content;
#endif
char item_desc[128];
char *ptr;
char *ptr_temp;
int i = 0;
while (1) {
#ifdef HTTP_LIST_FILE_LOAD
if (os_feof(hls->fp)) {
M_LOGD("hls file end\n");
break;
}
memset(item_desc, 0, sizeof(item_desc));
os_fgets(item_desc, sizeof(item_desc), hls->fp);
if (item_desc[strlen(item_desc) - 1] == '\n')
item_desc[strlen(item_desc) - 1] = '\0';
#else
if (hls->pos - hls->content >= hls->len) {
M_LOGD("hls content end\n");
break;
}
ptr = strchr(hls->pos, '\n');
if (!ptr) {
M_LOGD("hls end\n");
break;
}
memset(item_desc, 0, sizeof(item_desc));
memcpy(item_desc, hls->pos, ptr - hls->pos);
item_desc[ptr - hls->pos] = '\0';
ptr++;
hls->pos = ptr;
#endif
ptr = (char *)item_desc;
if (!strncmp(ptr, "#EXTINF:", strlen("#EXTINF:"))) {
#ifdef HTTP_LIST_FILE_LOAD
memset(item_desc, 0, sizeof(item_desc));
ptr = os_fgets(item_desc, sizeof(item_desc), hls->fp);
if (!ptr) {
M_LOGE("read list file failed !\n");
os_mutex_unlock(hls->lock);
return -1;
}
if (item_desc[strlen(item_desc) - 1] == '\n')
item_desc[strlen(item_desc) - 1] = '\0';
#else
ptr = strchr(hls->pos, '\n');
if (!ptr) {
M_LOGD("hls end\n");
break;
}
memset(item_desc, 0, sizeof(item_desc));
memcpy(item_desc, hls->pos, ptr - hls->pos);
item_desc[ptr - hls->pos] = '\0';
ptr++;
hls->pos = ptr;
#endif
if (i++ < target_index)
continue;
ptr = (char *)item_desc;
// while (*ptr == '/')
// ptr++;
ptr_temp = ptr + strlen(ptr) - 1;
while (*ptr_temp == '\\') {
*ptr_temp = '\0';
ptr_temp--;
}
memset(hls->seg_desc, 0, sizeof(hls->seg_desc));
memcpy(hls->seg_desc, ptr, strlen(ptr) + 1);
break;
} else if (!strncmp(item_desc, "#EXT-X-ENDLIST",
strlen("#EXT-X-ENDLIST"))) {
M_LOGD("hls end\n");
break;
}
}
if (strlen(hls->seg_desc) + 1 >
HTTP_URL_LEN - (hls->sub - loader->url)) {
M_LOGE("seg desc length overrange !\n");
os_mutex_unlock(hls->lock);
return -1;
}
memset(hls->sub, 0,
HTTP_URL_LEN - (hls->sub - loader->url));
memcpy(hls->sub, hls->seg_desc,
strlen(hls->seg_desc) + 1);
M_LOGI("seg url %s\n", loader->url);
__exit:
os_mutex_unlock(hls->lock);
return 0;
}
int uvoice_hls_file_next(http_loader_t *loader)
{
hls_t *hls;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
hls = loader->hls;
if (!hls) {
M_LOGE("hls null !\n");
return -1;
}
os_mutex_lock(hls->lock, OS_WAIT_FOREVER);
#ifdef HTTP_LIST_FILE_LOAD
if (!hls->fp) {
M_LOGE("no hls file !\n");
os_mutex_unlock(hls->lock);
return -1;
}
#else
if (!hls->content) {
M_LOGE("no hls content !\n");
os_mutex_unlock(hls->lock);
return -1;
}
#endif
__repeat:
hls->seg_index++;
if (hls->seg_index >= hls->seg_count) {
M_LOGD("hls file end\n");
// goto __exit;
if (strlen(hls->base) > 0) {
hls->seg_current = hls_index_get(hls->seg_desc);
M_LOGD("current seg %d\n", hls->seg_current);
if (http_loader_stop(loader)) {
M_LOGE("stop http load failed !\n");
os_mutex_unlock(hls->lock);
return -1;
}
memset(loader->url, 0, sizeof(loader->url));
memcpy(loader->url, hls->base,
strlen(hls->base) + 1);
if (uvoice_hls_build(loader)) {
M_LOGE("build hls failed !\n");
os_mutex_unlock(hls->lock);
return -1;
}
goto __skip;
} else {
goto __exit;
}
}
char item_desc[128];
char *ptr;
char *ptr_temp;
while (1) {
#ifdef HTTP_LIST_FILE_LOAD
if (os_feof(hls->fp)) {
M_LOGD("hls file end\n");
break;
}
memset(item_desc, 0, sizeof(item_desc));
os_fgets(item_desc, sizeof(item_desc), hls->fp);
if (item_desc[strlen(item_desc) - 1] == '\n')
item_desc[strlen(item_desc) - 1] = '\0';
#else
if (hls->pos - hls->content >= hls->len) {
M_LOGD("hls content end\n");
goto __repeat;
}
ptr = strchr(hls->pos, '\n');
if (!ptr) {
M_LOGD("hls end\n");
goto __repeat;
}
memset(item_desc, 0, sizeof(item_desc));
memcpy(item_desc, hls->pos, ptr - hls->pos);
item_desc[ptr - hls->pos] = '\0';
ptr++;
hls->pos = ptr;
#endif
ptr = (char *)item_desc;
if (!strncmp(ptr, "#EXTINF:", strlen("#EXTINF:"))) {
#ifdef HTTP_LIST_FILE_LOAD
memset(item_desc, 0, sizeof(item_desc));
os_fgets(item_desc, sizeof(item_desc), hls->fp);
if (item_desc[strlen(item_desc) - 1] == '\n')
item_desc[strlen(item_desc) - 1] = '\0';
#else
memset(item_desc, 0, sizeof(item_desc));
ptr = strchr(hls->pos, '\n');
if (ptr) {
memcpy(item_desc, hls->pos, ptr - hls->pos);
item_desc[ptr - hls->pos] = '\0';
} else {
memcpy(item_desc, hls->pos,
hls->len - (hls->pos - hls->content));
item_desc[hls->len - (hls->pos - hls->content)] = '\0';
}
ptr++;
hls->pos = ptr;
#endif
ptr = (char *)item_desc;
if (!strncmp(hls->seg_desc, ptr, strlen(ptr) + 1)) {
M_LOGW("seg desc no change\n");
goto __repeat;
}
// while (*ptr == '/')
// ptr++;
ptr_temp = ptr + strlen(ptr) - 1;
while (*ptr_temp == '\\') {
*ptr_temp = '\0';
ptr_temp--;
}
memset(hls->seg_desc, 0, sizeof(hls->seg_desc));
memcpy(hls->seg_desc, ptr, strlen(ptr) + 1);
break;
} else if (!strncmp(item_desc, "#EXT-X-ENDLIST",
strlen("#EXT-X-ENDLIST"))) {
M_LOGD("hls end\n");
goto __repeat;
}
}
if (strlen(hls->seg_desc) + 1 >
HTTP_URL_LEN - (hls->sub - loader->url)) {
M_LOGE("seg desc length overrange !\n");
os_mutex_unlock(hls->lock);
return -1;
}
memset(hls->sub, 0,
HTTP_URL_LEN - (hls->sub - loader->url));
memcpy(hls->sub, hls->seg_desc,
strlen(hls->seg_desc) + 1);
M_LOGD("seg url %s\n", loader->url);
if (hls->seg_offset) {
hls->seg_offset[hls->seg_index] =
hls->seg_offset[hls->seg_index - 1] +
loader->content_length;
M_LOGD("set seg_offset[%d] %d\n",
hls->seg_index,
hls->seg_offset[loader->hls->seg_index]);
}
if (http_loader_stop(loader)) {
M_LOGE("stop http load failed !\n");
os_mutex_unlock(hls->lock);
return -1;
}
__skip:
loader->breakpoint_pos = 0;
loader->redirect = 0;
memset(loader->host_name, 0, sizeof(loader->host_name));
memset(loader->uri, 0, sizeof(loader->uri));
memset(loader->redirect_url, 0, sizeof(loader->redirect_url));
if (http_loader_start(loader)) {
M_LOGE("start http load failed !\n");
os_mutex_unlock(hls->lock);
return -1;
}
__exit:
os_mutex_unlock(hls->lock);
return 0;
}
int uvoice_hls_build(http_loader_t *loader)
{
net_cache_t *nc;
char *ptr;
char *ptr_temp;
int ret;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
nc = loader->nc;
if (!nc) {
M_LOGE("nc null !\n");
return -1;
}
ptr = strstr(loader->url, ".m3u8");
if (!ptr) {
if (loader->hls) {
if (loader->hls->fp)
os_fclose(loader->hls->fp);
if (loader->hls->content)
snd_free(loader->hls->content);
if (loader->hls->seg_offset)
snd_free(loader->hls->seg_offset);
os_mutex_free(loader->hls->lock);
snd_free(loader->hls);
loader->hls = NULL;
nc->sequence = 0;
M_LOGD("hls free\n");
}
goto __exit;
}
hls_t *hls = loader->hls;
if (hls) {
if (hls->fp) {
os_fclose(hls->fp);
hls->fp = NULL;
}
if (hls->content) {
snd_free(hls->content);
hls->content = NULL;
}
if (hls->seg_offset) {
snd_free(hls->seg_offset);
hls->seg_offset = NULL;
}
os_mutex_free(hls->lock);
hls->len = 0;
hls->pos = NULL;
hls->seg_begin = 0;
hls->seg_count = 0;
hls->seg_index = 0;
M_LOGD("hls reset\n");
} else {
hls = snd_zalloc(sizeof(hls_t), AFM_EXTN);
if (!hls) {
M_LOGE("alloc hls failed !\n");
return -1;
}
hls->live_stream = HTTP_LIVE_STREAM_ENABLE;
M_LOGD("alloc hls\n");
}
char *ptr_name;
for (ptr_name = ptr - 1;
ptr_name >= loader->url; ptr_name--) {
if (*ptr_name == '/') {
ptr_name++;
break;
}
}
if ((ptr_name - loader->url) <= strlen("http://") ||
ptr_name == ptr) {
M_LOGE("find hls name failed !\n");
snd_free(hls);
if (loader->hls)
loader->hls = NULL;
return -1;
}
if (http_loader_start(loader)) {
M_LOGE("start http load failed !\n");
snd_free(hls);
if (loader->hls)
loader->hls = NULL;
return -1;
}
#ifdef HTTP_LIST_FILE_LOAD
if (access(PLAYER_LOCAL_TEMP_DIR, F_OK)) {
if (mkdir(PLAYER_LOCAL_TEMP_DIR, S_IRWXU)) {
M_LOGE("create %s failed %d!\n",
PLAYER_LOCAL_TEMP_DIR);
http_loader_stop(loader);
snd_free(hls);
if (loader->hls)
loader->hls = NULL;
return -1;
}
M_LOGD("create dir: %s\n", PLAYER_LOCAL_TEMP_DIR);
}
int temp_name_len = strlen(PLAYER_LOCAL_TEMP_DIR) +
strlen("temp.m3u8") + 2;
char *temp_name = snd_zalloc(temp_name_len, AFM_EXTN);
if (!temp_name) {
M_LOGE("alloc temp name failed !\n");
http_loader_stop(loader);
snd_free(hls);
if (loader->hls)
loader->hls = NULL;
return -1;
}
memcpy(temp_name, PLAYER_LOCAL_TEMP_DIR,
strlen(PLAYER_LOCAL_TEMP_DIR) + 1);
if (*(temp_name + strlen(PLAYER_LOCAL_TEMP_DIR) - 1) == '/')
snprintf(temp_name + strlen(PLAYER_LOCAL_TEMP_DIR),
temp_name_len - strlen(PLAYER_LOCAL_TEMP_DIR),
"temp.m3u8");
else
snprintf(temp_name + strlen(PLAYER_LOCAL_TEMP_DIR),
temp_name_len - strlen(PLAYER_LOCAL_TEMP_DIR),
"/temp.m3u8");
M_LOGD("open %s\n", temp_name);
hls->fp = os_fopen(temp_name, "w+");
if (!hls->fp) {
M_LOGE("open %s failed !\n", temp_name);
http_loader_stop(loader);
snd_free(temp_name);
snd_free(hls);
if (loader->hls)
loader->hls = NULL;
return -1;
}
snd_free(temp_name);
#else
if (loader->content_length > 4096) {
M_LOGE("hls length %d overrange !\n",
loader->content_length);
http_loader_stop(loader);
snd_free(hls);
if (loader->hls)
loader->hls = NULL;
return -1;
}
hls->len = loader->content_length;
hls->content = snd_zalloc(hls->len, AFM_EXTN);
if (!hls->content) {
M_LOGE("alloc hls content failed !\n");
http_loader_stop(loader);
snd_free(hls);
if (loader->hls)
loader->hls = NULL;
return -1;
}
hls->pos = hls->content;
M_LOGD("hls content len %d\n", hls->len);
#endif
if (nc->head_data_size > 0) {
#ifdef HTTP_LIST_FILE_LOAD
if (os_fwrite(nc->buffer, 1, nc->head_data_size, hls->fp) !=
nc->head_data_size) {
M_LOGE("write head data failed %d!\n");
os_fclose(hls->fp);
snd_free(hls);
if (loader->hls)
loader->hls = NULL;
nc->head_data_size = 0;
return -1;
}
#else
memcpy(hls->pos, nc->buffer, nc->head_data_size);
hls->pos += nc->head_data_size;
#endif
M_LOGD("save head data %u\n", nc->head_data_size);
nc->load_length += nc->head_data_size;
nc->head_data_size = 0;
}
int load_size = MIN(nc->buffer_size,
nc->content_length - nc->load_length);
int rd_ret;
while (load_size > 0) {
rd_ret = nc->cache_load(nc->priv,
nc->buffer, load_size);
if (rd_ret < 0) {
M_LOGE("read failed !\n");
break;
} else if (rd_ret == 0) {
M_LOGD("read end\n");
break;
}
#ifdef HTTP_LIST_FILE_LOAD
ret = os_fwrite(nc->buffer, 1, rd_ret, hls->fp);
if (ret != rd_ret) {
M_LOGE("write failed %d!\n", os_ferror(hls->fp));
break;
}
#else
if (hls->pos + rd_ret - hls->content > hls->len) {
M_LOGE("content length overrange !\n");
break;
}
memcpy(hls->pos, nc->buffer, rd_ret);
#endif
hls->pos += rd_ret;
nc->load_length += rd_ret;
load_size = MIN(load_size,
nc->content_length - nc->load_length);
}
nc->sequence = 1;
nc->load_length = 0;
http_loader_stop(loader);
char item_desc[128];
float duration_max;
float duration = 0.001;
float duration_sum = 0.0;
bool seg_found = false;
int pos_bak;
int seg_current;
int seg_index = 0;
#ifdef HTTP_LIST_FILE_LOAD
os_fseek(hls->fp, 0, OS_SEEK_SET);
#else
hls->pos = hls->content;
#endif
hls->seg_begin = -1;
while (1) {
#ifdef HTTP_LIST_FILE_LOAD
if (os_feof(hls->fp)) {
M_LOGD("hls file end\n");
break;
}
memset(item_desc, 0, sizeof(item_desc));
os_fgets(item_desc, sizeof(item_desc), hls->fp);
if (item_desc[strlen(item_desc) - 1] == '\n')
item_desc[strlen(item_desc) - 1] = '\0';
#else
if (hls->pos - hls->content >= hls->len) {
M_LOGD("hls content end\n");
break;
}
ptr = strchr(hls->pos, '\n');
if (!ptr) {
M_LOGD("hls end\n");
break;
}
memset(item_desc, 0, sizeof(item_desc));
memcpy(item_desc, hls->pos, ptr - hls->pos);
item_desc[ptr - hls->pos] = '\0';
ptr++;
hls->pos = ptr;
#endif
ptr = (char *)item_desc;
if (!strncmp(ptr, "#EXTINF:", strlen("#EXTINF:"))) {
ptr += strlen("#EXTINF:");
duration = atof(ptr);
if (duration_max > 0.01 && duration > duration_max) {
M_LOGE("duration invalid !\n");
continue;
}
if (!seg_found) {
#ifdef HTTP_LIST_FILE_LOAD
memset(item_desc, 0, sizeof(item_desc));
os_fgets(item_desc, sizeof(item_desc), hls->fp);
ptr = (char *)item_desc;
if (*(ptr + strlen(ptr) - 1) == '\n')
*(ptr + strlen(ptr) - 1) = '\0';
pos_bak = os_ftell(hls->fp);
#else
ptr = strchr(hls->pos, '\n');
if (!ptr) {
M_LOGD("seg desc not found\n");
continue;
}
if (ptr - hls->pos >= sizeof(item_desc)) {
M_LOGW("seg desc overrange\n");
continue;
}
memset(item_desc, 0, sizeof(item_desc));
memcpy(item_desc, hls->pos, ptr - hls->pos);
item_desc[ptr - hls->pos] = '\0';
ptr++;
hls->pos = ptr;
pos_bak = (int)hls->pos;
ptr = (char *)item_desc;
#endif
ptr_temp = ptr + strlen(ptr) - 1;
while (*ptr_temp == '\\') {
*ptr_temp = '\0';
ptr_temp--;
}
memset(hls->seg_desc, 0, sizeof(hls->seg_desc));
memcpy(hls->seg_desc, ptr, strlen(ptr) + 1);
if (hls->seg_current > 0) {
seg_current = hls_index_get(hls->seg_desc);
M_LOGD("index %d current %d\n",
seg_current, hls->seg_current);
if (seg_current <= hls->seg_current) {
seg_index++;
continue;
}
}
hls->seg_index = seg_index;
seg_found = true;
}
duration_sum += duration;
hls->seg_count++;
} else if (!strncmp(ptr, "#EXT-X-MEDIA-SEQUENCE:",
strlen("#EXT-X-MEDIA-SEQUENCE:"))) {
ptr += strlen("#EXT-X-MEDIA-SEQUENCE:");
hls->seg_begin = atoi(ptr);
if (hls->seg_begin < 0)
M_LOGW("media sequence invalid !\n");
else
M_LOGD("media sequence %d\n", hls->seg_begin);
} else if (!strncmp(ptr, "#EXT-X-TARGETDURATION:",
strlen("#EXT-X-TARGETDURATION:"))) {
ptr += strlen("#EXT-X-TARGETDURATION:");
duration_max = atof(ptr);
if (duration_max <= 0.001)
M_LOGW("target duration invalid !\n");
else
M_LOGD("target duration %f\n", duration_max);
} else if (!strncmp(ptr, "#EXT-X-ENDLIST",
strlen("#EXT-X-ENDLIST"))) {
M_LOGD("file end\n");
break;
}
}
if (!seg_found) {
M_LOGE("segment not found !\n");
return -1;
}
#ifdef HTTP_LIST_FILE_LOAD
os_fseek(hls->fp, pos_bak, OS_SEEK_SET);
#else
hls->pos = (char *)pos_bak;
#endif
hls->duration = (int)duration_sum;
M_LOGD("duration %d count %d seg_index %d\n",
hls->duration,
hls->seg_count, hls->seg_index);
if (strlen(hls->base) <= 0) {
memcpy(hls->base, loader->url, strlen(loader->url) + 1);
M_LOGD("seq base %s\n", hls->base);
}
if (!strncmp(hls->seg_desc, "http://", strlen("http://")) ||
!strncmp(hls->seg_desc, "https://", strlen("https://"))) {
if (strlen(hls->seg_desc) + 1 > HTTP_URL_LEN) {
M_LOGE("seg desc length overrange !\n");
return -1;
}
hls->sub = loader->url;
memset(hls->sub, 0, HTTP_URL_LEN);
memcpy(hls->sub, hls->seg_desc,
strlen(hls->seg_desc) + 1);
} else if (!strncmp(hls->seg_desc, "//", strlen("//"))) {
if (strlen(hls->seg_desc) + 1 > HTTP_URL_LEN) {
M_LOGE("seg desc length overrange !\n");
return -1;
}
if (!strncmp(loader->url, "http://", strlen("http://"))) {
hls->sub = loader->url + strlen("http:");
memset(hls->sub, 0,
HTTP_URL_LEN - (hls->sub - loader->url));
if (strlen(hls->seg_desc) + 1 >
HTTP_URL_LEN - (hls->sub - loader->url)) {
M_LOGE("seg desc length overrange !\n");
return -1;
}
memcpy(hls->sub, hls->seg_desc, strlen(hls->seg_desc) + 1);
} else if (!strncmp(loader->url, "https://", strlen("https://"))) {
hls->sub = loader->url + strlen("https:");
memset(hls->sub, 0,
HTTP_URL_LEN - (hls->sub - loader->url));
memcpy(hls->sub, hls->seg_desc, strlen(hls->seg_desc) + 1);
}
} else {
ptr = loader->url + strlen(loader->url);
for (ptr_name = ptr - 1;
ptr_name >= loader->url; ptr_name--) {
if (*ptr_name == '/') {
ptr_name++;
break;
}
}
if (strchr(hls->seg_desc, '/')) {
char *seg_prefix;
int prefix_len = 0;
ptr = hls->seg_desc + strlen(hls->seg_desc);
for (seg_prefix = ptr - 1;
seg_prefix >= hls->seg_desc; seg_prefix--) {
if (*seg_prefix == '/') {
prefix_len = seg_prefix - hls->seg_desc + 1;
break;
}
}
if (prefix_len > 0) {
if (!memcmp(ptr_name - prefix_len,
hls->seg_desc, prefix_len)) {
ptr_name -= prefix_len;
M_LOGD("prefix_len %d, ptr_name %s\n",
prefix_len, ptr_name);
}
}
}
if (HTTP_URL_LEN - (ptr_name - loader->url) <=
strlen(hls->seg_desc)) {
M_LOGE("seg desc name overrange !\n");
if (hls->fp)
os_fclose(hls->fp);
if (hls->content)
snd_free(hls->content);
snd_free(hls);
if (loader->hls)
loader->hls = NULL;
return -1;
}
hls->sub = ptr_name;
memcpy(hls->sub, hls->seg_desc,
strlen(hls->seg_desc) + 1);
}
M_LOGD("seg url %s\n", loader->url);
hls->seg_offset = snd_zalloc(
hls->seg_count * sizeof(int), AFM_EXTN);
if (!hls->seg_offset) {
M_LOGE("alloc seg offset failed !\n");
if (hls->fp)
os_fclose(hls->fp);
if (hls->content)
snd_free(hls->content);
snd_free(hls);
if (loader->hls)
loader->hls = NULL;
return -1;
}
hls->lock = os_mutex_new();
if (!loader->hls)
loader->hls = hls;
M_LOGD("parse hls success\n");
__exit:
return 0;
}
int uvoice_hls_release(http_loader_t *loader)
{
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
if (!loader->hls) {
M_LOGE("hls null !\n");
return -1;
}
if (loader->hls->fp) {
os_fclose(loader->hls->fp);
M_LOGD("hls file close\n");
}
if (loader->hls->content) {
snd_free(loader->hls->content);
M_LOGD("seq list content free\n");
}
if (loader->hls->seg_offset) {
snd_free(loader->hls->seg_offset);
M_LOGD("seq list offset free\n");
}
os_mutex_free(loader->hls->lock);
snd_free(loader->hls);
return 0;
}
|
YifuLiu/AliOS-Things
|
components/uvoice/stream/uvoice_hls.c
|
C
|
apache-2.0
| 25,457
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#ifndef __HLS_H__
#define __HLS_H__
static int hls_index_get(char *desc);
int uvoice_hls_index_update(http_loader_t *loader, int index);
int uvoice_hls_file_next(http_loader_t *loader);
int uvoice_hls_build(http_loader_t *loader);
int uvoice_hls_release(http_loader_t *loader);
#endif /* __HLS_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/stream/uvoice_hls.h
|
C
|
apache-2.0
| 373
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#ifdef __os_alios_things__
#include <sys/socket.h>
#include <netdb.h>
#elif defined(__os_linux__)
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#endif
#include "uvoice_types.h"
#include "uvoice_event.h"
#include "uvoice_player.h"
#include "uvoice_os.h"
#include "uvoice_config.h"
#include "uvoice_common.h"
#include "uvoice_format.h"
#include "uvoice_play.h"
#include "uvoice_cache.h"
#include "uvoice_http.h"
#include "uvoice_hls.h"
#include "uvoice_download.h"
#if defined(ALIGENIE_ENABLE)
#define HTTP_LOAD_DEEP_PAUSE_ENABLE 1
#else
#define HTTP_LOAD_DEEP_PAUSE_ENABLE 0
#endif
#define HTTP_CACHE_ENABLE 1
#define HTTP_CONNECT_TIMEOUT_MSEC 50000
#define UVOICE_MAX_HEADER_SIZE 1024
#define HTTP_REQUEST \
"GET %s HTTP/1.1\r\nAccept:*/*\r\n\
User-Agent: Mozilla/5.0\r\n\
Cache-Control: no-cache\r\n\
Connection: keep-alive\r\n\
Host:%s:%d\r\n\r\n"
#define HTTP_REQUEST_CONTINUE \
"GET %s HTTP/1.1\r\nAccept:*/*\r\n\
User-Agent: Mozilla/5.0\r\n\
Cache-Control: no-cache\r\n\
Connection: keep-alive\r\n\
Range: bytes=%d-\r\n\
Host:%s:%d\r\n\r\n"
#ifndef in_addr_t
typedef uint32_t in_addr_t;
#endif
static const char *ca_crt = \
{
\
"-----BEGIN CERTIFICATE-----\r\n"
"MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkG\r\n" \
"A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv\r\n" \
"b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAw\r\n" \
"MDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i\r\n" \
"YWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJHbG9iYWxT\r\n" \
"aWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDaDuaZ\r\n" \
"jc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavp\r\n" \
"xy0Sy6scTHAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp\r\n" \
"1Wrjsok6Vjk4bwY8iGlbKk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdG\r\n" \
"snUOhugZitVtbNV4FpWi6cgKOOvyJBNPc1STE4U6G7weNLWLBYy5d4ux2x8gkasJ\r\n" \
"U26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrXgzT/LCrBbBlDSgeF59N8\r\n" \
"9iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8E\r\n" \
"BTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0B\r\n" \
"AQUFAAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOz\r\n" \
"yj1hTdNGCbM+w6DjY1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE\r\n" \
"38NflNUVyRRBnMRddWQVDf9VMOyGj/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymP\r\n" \
"AbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhHhm4qxFYxldBniYUr+WymXUad\r\n" \
"DKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbME\r\n" \
"HMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\r\n" \
"-----END CERTIFICATE-----"
};
int http_loader_restart(http_loader_t *loader);
int http_loader_start(http_loader_t *loader);
int http_loader_stop(http_loader_t *loader);
static cache_config_t *g_cache_config;
static char *strncasestr(const char *str, const char *key)
{
int len;
if (!str || !key)
return NULL;
len = strlen(key);
if (len == 0)
return NULL;
while (*str) {
if (!strncasecmp(str, key, len))
return str;
++str;
}
return NULL;
}
static int http_setup(http_loader_t *loader, int sock)
{
struct timeval timeout;
int ret;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
timeout.tv_sec = 10;
#ifdef UVOICE_HLS_ENABLE
if (loader->hls && loader->hls->live_stream)
timeout.tv_sec = 5;
#endif
timeout.tv_usec = 0;
#ifdef UVOICE_MUSICPLAYER_ENABLE
timeout.tv_sec = 1;
timeout.tv_usec = 0;
#endif
ret = setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &timeout,
sizeof(timeout));
if (ret) {
M_LOGE("set send timeout failed %d!\n", ret);
return -1;
}
ret = setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timeout,
sizeof(timeout));
if (ret) {
M_LOGE("set recv timeout failed %d!\n", ret);
return -1;
}
#if 0
int buffer_size;
int opt_len = sizeof(buffer_size);
ret = getsockopt(sock, SOL_SOCKET, SO_RCVBUF, &buffer_size,
&opt_len);
if (ret) {
M_LOGE("get sockopt failed !\n");
}
M_LOGI("buffer_size %d\n", buffer_size);
buffer_size = 20 * 1024;
ret = setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &buffer_size,
sizeof(buffer_size));
if (ret) {
M_LOGE("set recv buffer size failed %d!\n", ret);
return -1;
}
#endif
return 0;
}
static int http_get_dns(char *hostname, in_addr_t *addr)
{
struct hostent *host;
struct in_addr in_addr;
char **pp = NULL;
#if defined(UVOICE_HTTP_MULTI_RETRY_TIMES)
int retries = UVOICE_HTTP_MULTI_RETRY_TIMES;
#else
int retries = 1;
#endif
if (!hostname || !addr) {
M_LOGE("args null !\n");
return -1;
}
while (1) {
host = gethostbyname(hostname);
if (host)
break;
if (--retries <= 0)
break;
#if defined(UVOICE_HTTP_MULTI_RETRY_TIMES)
os_msleep(100);
M_LOGD("try again\n");
#endif
}
if (!host) {
M_LOGE("get host %s failed !\n", hostname);
return -1;
}
pp = host->h_addr_list;
if (!(*pp)) {
M_LOGE("host addr null !\n");
return -1;
}
in_addr.s_addr = *((in_addr_t *)*pp);
pp++;
*addr = in_addr.s_addr;
return 0;
}
extern const char *iotx_ca_get(void);
static int http_connect(http_loader_t *loader)
{
struct sockaddr_in server;
in_addr_t addr;
int sock;
int ret;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
if (loader->https) {
#ifdef UVOICE_HTTPS_ENABLE
loader->sock = net_ssl_connect(loader->host_name,
loader->port, ca_crt, strlen(ca_crt) + 1);
if (!loader->sock) {
M_LOGE("ssl connect failed !\n");
loader->sock = -1;
return -1;
}
M_LOGD("https connect\n");
return 0;
#else
M_LOGE("https not support !\n");
return -1;
#endif
}
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock < 0) {
M_LOGE("create socket failed !\n");
return -1;
}
if (http_setup(loader, sock)) {
M_LOGE("set socket option failed !\n");
close(sock);
return -1;
}
if (loader->hls && loader->host_addr != INADDR_NONE) {
/* use existing dns addr */
addr = (in_addr_t)loader->host_addr;
} else {
if (http_get_dns(loader->host_name, &addr)) {
M_LOGE("get dns failed !\n");
close(sock);
return -1;
}
loader->host_addr = addr;
}
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(loader->port);
server.sin_addr.s_addr = addr;
ret = connect(sock, (struct sockaddr *)&server,
sizeof(struct sockaddr));
if (ret) {
M_LOGE("socket connect failed %d!\n", ret);
close(sock);
return -1;
}
loader->sock = sock;
return 0;
}
static int http_disconnect(http_loader_t *loader)
{
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
if (loader->https) {
#ifdef UVOICE_HTTPS_ENABLE
net_ssl_disconnect(loader->sock);
#endif
} else {
close(loader->sock);
}
loader->sock = -1;
return 0;
}
static int http_urlparse(http_loader_t *loader)
{
char *ptr = NULL;
char *begin = NULL;
char *end = NULL;
int len = 0;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
ptr = loader->redirect ? loader->redirect_url : loader->url;
if (!strncmp(ptr, "http://", strlen("http://"))) {
ptr += strlen("http://");
loader->https = 0;
loader->port = 80;
} else if (!strncmp(ptr, "https://", strlen("https://"))) {
ptr += strlen("https://");
loader->https = 1;
loader->port = 443;
} else {
M_LOGE("url invalid !\n");
return -1;
}
begin = ptr;
ptr = strchr(begin, '/');
if (!ptr) {
M_LOGE("url invaild !\n");
return -1;
}
end = ptr;
len = MIN(end - begin, HTTP_HOSTNAME_LEN - 1);
memcpy(loader->host_name, begin, len);
loader->host_name[len] = '\0';
ptr = strchr(begin, ':');
if (ptr && ptr < end) {
loader->port = atoi(ptr + 1);
if (loader->port <= 0 || loader->port >= 65535) {
M_LOGE("port invalid !\n");
return -1;
}
}
begin = end;
len = MIN(HTTP_URL_LEN - 1, strlen(begin));
memcpy(loader->uri, begin, len);
loader->uri[len] = '\0';
return 0;
}
static int http_request(http_loader_t *loader)
{
net_cache_t *nc;
char *header_buffer;
char *ptr;
int read_size;
int ret;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
nc = loader->nc;
if (!nc) {
M_LOGE("nc null !\n");
return -1;
}
if ((!nc->buffer) || (0 == nc->buffer_size)) {
M_LOGE("nc buffer null !\n");
return -1;
}
memset(nc->buffer, 0, nc->buffer_size);
if (loader->breakpoint_pos <= 0) {
snprintf(nc->buffer, nc->buffer_size,
HTTP_REQUEST, loader->uri,
loader->host_name, loader->port);
} else {
snprintf(nc->buffer, nc->buffer_size,
HTTP_REQUEST_CONTINUE, loader->uri,
loader->breakpoint_pos,
loader->host_name, loader->port);
M_LOGD("breakpoint pos %d\n", loader->breakpoint_pos);
}
if (loader->https) {
#ifdef UVOICE_HTTPS_ENABLE
ret = net_ssl_write(loader->sock, nc->buffer, strlen(nc->buffer), 5000);
#else
M_LOGE("https not support !\n");
return -1;
#endif
} else {
ret = send(loader->sock, nc->buffer,
strlen(nc->buffer), 0);
}
if (ret < 0) {
M_LOGE("send request failed %d!\n", ret);
return -1;
} else if (ret != strlen(nc->buffer)) {
M_LOGW("send %d ret %d\n", strlen(nc->buffer), ret);
}
header_buffer = nc->buffer;
read_size = MIN(UVOICE_MAX_HEADER_SIZE, nc->buffer_size) - 1; /* 1KB is enough */
memset(nc->buffer, 0, nc->buffer_size);
if (loader->https) {
#ifdef UVOICE_HTTPS_ENABLE
ret = net_ssl_read(loader->sock, header_buffer, read_size, 5000);
#else
M_LOGE("https not support !\n");
return -1;
#endif
} else {
ret = read(loader->sock, header_buffer, read_size);
}
if (ret <= 0) {
M_LOGE("read header failed %d!\n", ret);
return -1;
} else if (ret != read_size) {
read_size = ret;
}
// M_LOGD("HTTP Response:\n%s\n", header_buffer);
header_buffer[read_size] = '\0';
ptr = strchr(header_buffer, ' ');
if (!ptr || !strcasestr(header_buffer, "http")) {
M_LOGE("http response invalid !\n");
return -1;
}
loader->http_status = atoi(ptr + 1);
if (loader->breakpoint_pos <= 0) {
if (loader->http_status != HTTP_STAT_SUCCESS &&
loader->http_status != HTTP_CODE_PERM_REDIRECT &&
loader->http_status != HTTP_CODE_TEMP_REDIRECT) {
M_LOGE("http request failed %d\n",
loader->http_status);
return -1;
}
} else {
if (loader->http_status != HTTP_CODE_BREAKPOINT &&
loader->http_status != HTTP_CODE_PERM_REDIRECT &&
loader->http_status != HTTP_CODE_TEMP_REDIRECT) {
M_LOGE("http request failed %d\n",
loader->http_status);
return -1;
}
}
ptr = strncasestr(header_buffer, "Location: ");
if (ptr) {
ptr += strlen("Location: ");
char *loc_end_ptr = ptr;
while (strncmp(loc_end_ptr, "\r\n", strlen("\r\n"))) {
loc_end_ptr++;
if (loc_end_ptr - header_buffer >= read_size - 1) {
loc_end_ptr = NULL;
break;
}
}
if (loc_end_ptr) {
int copy_size = loc_end_ptr - ptr;
if (copy_size > HTTP_URL_LEN - 1) {
M_LOGE("redirect url length %d overrange !\n",
copy_size);
return -1;
}
memset(loader->redirect_url, 0, HTTP_URL_LEN);
memcpy(loader->redirect_url, ptr, copy_size);
loader->redirect_url[copy_size] = '\0';
loader->redirect = 1;
M_LOGD("redirect %s\n", loader->redirect_url);
return 1;
}
}
ptr = strncasestr(header_buffer, "Content-length: ");
if (ptr) {
ptr += strlen("Content-length: ");
if (loader->breakpoint_pos <= 0) {
loader->content_length = atoi(ptr);
if (loader->content_length <= 0) {
M_LOGE("content length %d invalid !\n",
loader->content_length);
return -1;
}
nc->content_length = loader->content_length;
nc->load_length = 0;
M_LOGD("content len %d\n", loader->content_length);
} else {
M_LOGD("remaining content len %d\n", atoi(ptr));
nc->content_length = loader->content_length;
nc->load_length = loader->breakpoint_pos;
}
}
ptr = strncasestr(header_buffer, "Content-Range: ");
if (ptr) {
ptr += strlen("Content-Range: ");
char *range_end_ptr = ptr;
while (strncmp(range_end_ptr, "\r\n", strlen("\r\n"))) {
range_end_ptr++;
if (range_end_ptr - header_buffer >= read_size) {
range_end_ptr = NULL;
break;
}
}
if (range_end_ptr) {
int range_size = range_end_ptr - ptr;
char range_info[range_size + 1];
memcpy(range_info, ptr, range_size);
range_info[range_size] = '\0';
M_LOGD("content range: %s\n", range_info);
}
}
ptr = strncasestr(header_buffer, "Transfer-Encoding");
if (ptr) {
if (strncasestr(header_buffer, "chunked")) {
loader->chunked = 1;
M_LOGD("http chunk enable\n");
}
}
ptr = strstr(header_buffer, "\r\n\r\n");
if (ptr) {
ptr += strlen("\r\n\r\n");
nc->head_data_size = read_size - (ptr - header_buffer);
if (nc->head_data_size > 0)
snd_memmove(nc->buffer, ptr, nc->head_data_size);
M_LOGD("head data size %d\n", nc->head_data_size);
} else {
M_LOGE("http header error !\n");
return -1;
}
return 0;
}
static int http_read(void *priv, uint8_t *buffer, int nbytes)
{
http_loader_t *loader = (http_loader_t *)priv;
int read_bytes = 0;
int ret;
bool last = false;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
if (loader->force_restart) {
loader->force_restart = 0;
if (loader->nc && loader->nc->offset > 0)
loader->nc->load_length -= loader->nc->offset;
if (http_loader_restart(loader)) {
M_LOGE("restart http load failed !\n");
return -1;
}
if (loader->nc && loader->nc->head_data_size > 0) {
M_LOGD("read head data %u\n",
loader->nc->head_data_size);
read_bytes += loader->nc->head_data_size;
loader->nc->head_data_size = 0;
}
}
while (read_bytes < nbytes) {
if (loader->https) {
#ifdef UVOICE_HTTPS_ENABLE
ret = net_ssl_read(loader->sock,
buffer + read_bytes, nbytes - read_bytes, 5000);
#else
M_LOGE("https not support !\n");
return -1;
#endif
} else {
#ifdef MUSICBOX_APP
ret = recv(loader->sock,
buffer + read_bytes, nbytes - read_bytes, 0);
#else
ret = read(loader->sock,
buffer + read_bytes, nbytes - read_bytes);
#endif
}
if (ret > 0) {
read_bytes += ret;
} else if (ret == 0) {
M_LOGD("read end\n");
break;
} else {
#if !defined(MUSICBOX_APP)
M_LOGE("read failed %d! read %d/%d\n",
errno, read_bytes, nbytes);
#endif
if (last)
break;
read_bytes = 0;
if (loader->nc && loader->nc->offset > 0)
loader->nc->load_length -= loader->nc->offset;
if (http_loader_restart(loader)) {
M_LOGE("restart http load failed !\n");
return -1;
}
if (loader->nc && loader->nc->head_data_size > 0) {
M_LOGD("read head data %u\n",
loader->nc->head_data_size);
read_bytes += loader->nc->head_data_size;
loader->nc->head_data_size = 0;
}
if (loader->cache_on) {
if (loader->nc->load_length + nbytes >= loader->content_length)
last = true;
} else {
if (loader->load_pos + nbytes >= loader->content_length)
last = true;
}
}
}
return read_bytes;
}
int http_cache_config(cache_config_t *config)
{
if (!g_cache_config) {
g_cache_config = snd_zalloc(sizeof(cache_config_t), AFM_MAIN);
if (!g_cache_config) {
M_LOGE("alloc cache config fail !\n");
return -1;
}
}
memcpy(g_cache_config, config, sizeof(cache_config_t));
M_LOGD("set cache config\n");
return 0;
}
static int http_source_format(void *priv, media_format_t *format)
{
media_loader_t *mloader = (media_loader_t *)priv;
http_loader_t *loader;
net_cache_t *nc;
int read_size;
media_format_t temp = MEDIA_FMT_UNKNOWN;
int ret;
if (!mloader) {
M_LOGE("mloader null !\n");
return -1;
}
loader = mloader->loader;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
nc = loader->nc;
if (!nc) {
M_LOGE("nc null !\n");
return -1;
}
if (!loader->start) {
if (http_loader_start(loader)) {
M_LOGE("start http load failed !\n");
return -1;
}
loader->start = 1;
}
if (loader->hls)
format_parse_byname(loader->url, &temp);
else if (strlen(loader->redirect_url) > strlen("http://"))
format_parse_byname(loader->redirect_url, &temp);
if (temp != MEDIA_FMT_UNKNOWN) {
*format = temp;
return 0;
}
read_size = MIN(nc->buffer_size - nc->head_data_size,
nc->content_length);
ret = http_read(loader,
nc->buffer + nc->head_data_size, read_size);
if (ret < 0) {
M_LOGE("read %d failed !\n", ret);
return -1;
} else if (ret != read_size) {
M_LOGW("read %d ret %d\n", read_size, ret);
}
nc->head_data_size += ret;
if (mp3_format_check(nc->buffer, nc->head_data_size)) {
*format = MEDIA_FMT_MP3;
M_LOGD("format MP3\n");
} else if (flac_format_check(nc->buffer, nc->head_data_size)) {
*format = MEDIA_FMT_FLAC;
M_LOGD("format FLAC\n");
} else if (wav_format_check(nc->buffer, nc->head_data_size)) {
*format = MEDIA_FMT_WAV;
M_LOGD("format WAV\n");
} else if (aac_format_check(nc->buffer, nc->head_data_size)) {
*format = MEDIA_FMT_AAC;
M_LOGD("format AAC\n");
} else if (m4a_format_check(nc->buffer, nc->head_data_size)) {
*format = MEDIA_FMT_M4A;
M_LOGD("format M4A\n");
} else if (ogg_format_check(nc->buffer, nc->head_data_size)) {
*format = MEDIA_FMT_OGG;
M_LOGD("format OGG\n");
} else if (wma_format_check(nc->buffer, nc->head_data_size)) {
*format = MEDIA_FMT_WMA;
M_LOGD("format WMA\n");
} else if (amrwb_format_check(nc->buffer, nc->head_data_size)) {
*format = MEDIA_FMT_AMRWB;
M_LOGD("format AMR-WB\n");
} else if (amr_format_check(nc->buffer, nc->head_data_size)) {
*format = MEDIA_FMT_AMR;
M_LOGD("format AMR\n");
} else {
if (loader->hls)
format_parse_byname(loader->url, format);
else if (strlen(loader->redirect_url) > strlen("http://"))
format_parse_byname(loader->redirect_url, format);
}
return 0;
}
static int http_get_cacheinfo(void *priv, cache_info_t *info)
{
media_loader_t *mloader = (media_loader_t *)priv;
http_loader_t *loader;
if (!mloader) {
M_LOGE("mloader null !\n");
return -1;
}
if (!info) {
M_LOGE("info null !\n");
return -1;
}
loader = mloader->loader;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
if (!loader->nc) {
M_LOGE("loader->nc null !\n");
return -1;
}
if (loader->nc &&
net_get_cacheinfo(loader->nc, info)) {
M_LOGE("get cache info failed !\n");
return -1;
}
info->seek_forward_limit = loader->content_length -
loader->load_pos - loader->nc->buffer_size;
info->seek_backward_limit = loader->load_pos;
return 0;
}
static int http_get_mediainfo(void *priv,
media_info_t *info, media_format_t format)
{
media_loader_t *mloader = (media_loader_t *)priv;
http_loader_t *loader;
if (!mloader) {
M_LOGE("mloader null !\n");
return -1;
}
loader = mloader->loader;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
if (loader->nc &&
net_get_mediainfo(loader->nc, info, format)) {
M_LOGE("get media info failed !\n");
return -1;
}
return 0;
}
static int http_get_filename(http_loader_t *loader)
{
char *url;
char *suffix;
char *name_begin;
char *name_end = NULL;
int name_len;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
if (!loader->nc) {
M_LOGE("nc null !\n");
return -1;
}
url = loader->url;
if (!url) {
M_LOGE("url null !\n");
return -1;
}
suffix = strstr(url, ".mp3");
if (!suffix) {
suffix = strstr(url, ".MP3");
if (suffix) {
name_end = suffix + 3;
}
} else {
name_end = suffix + 3;
}
if (!name_end) {
suffix = strstr(url, ".wav");
if (!suffix) {
suffix = strstr(url, ".WAV");
if (suffix) {
name_end = suffix + 3;
}
} else {
name_end = suffix + 3;
}
}
if (!name_end) {
suffix = strstr(url, ".m4a");
if (!suffix) {
suffix = strstr(url, ".M4A");
if (suffix) {
name_end = suffix + 3;
}
} else {
name_end = suffix + 3;
}
}
if (!name_end) {
suffix = strstr(url, ".pcm");
if (!suffix) {
suffix = strstr(url, ".PCM");
if (suffix) {
name_end = suffix + 3;
}
} else {
name_end = suffix + 3;
}
}
if (!name_end)
return -1;
for (name_begin = suffix - 1;
name_begin >= url; name_begin--) {
if (*name_begin == '.') {
M_LOGD("replace sensitive character\n");
*name_begin = '_';
}
if (*name_begin == '/') {
name_begin++;
break;
}
}
if (name_begin == url || name_begin == suffix) {
M_LOGE("find source name failed !\n");
return -1;
}
name_len = name_end - name_begin + 1;
if (name_len >= sizeof(loader->nc->filename)) {
M_LOGW("name length %d overrange\n", name_len);
name_len = sizeof(loader->nc->filename) - 1;
}
memcpy(loader->nc->filename,
name_end - name_len + 1, name_len);
loader->nc->filename[name_len] = '\0';
return 0;
}
static int http_loader_reset(void *priv)
{
media_loader_t *mloader = (media_loader_t *)priv;
http_loader_t *loader;
if (!mloader) {
M_LOGE("mloader null !\n");
return -1;
}
loader = mloader->loader;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
if (net_cache_reset(loader->nc)) {
M_LOGE("cache reset failed !\n");
return -1;
}
loader->http_status = 0;
loader->sock = -1;
loader->port = 0;
loader->start = 0;
loader->chunked = 0;
loader->load_pos = 0;
loader->breakpoint_pos = 0;
loader->redirect = 0;
loader->download = 0;
memset(loader->host_name, 0, sizeof(loader->host_name));
memset(loader->uri, 0, sizeof(loader->uri));
memset(loader->url, 0, sizeof(loader->url));
memset(loader->redirect_url, 0, sizeof(loader->redirect_url));
M_LOGD("http load reset\n");
return 0;
}
static int http_loader_event(void *priv, enum cache_event event, void *arg)
{
http_loader_t *loader = (http_loader_t *)priv;
media_loader_t *mloader;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
mloader = loader->priv;
if (!mloader) {
M_LOGE("mloader null !\n");
return -1;
}
switch (event) {
case CACHE_EV_CACHE_CPLT:
if (loader->hls) {
#ifdef UVOICE_HLS_ENABLE
if (uvoice_hls_file_next(loader)) {
M_LOGE("request next seq failed !\n");
return -1;
}
#endif
} else {
uvoice_event_post(UVOICE_EV_PLAYER,
UVOICE_CODE_PALYER_CACHE_CPLT, 0);
}
break;
case CACHE_EV_SEEK_DONE:
if (mloader->message)
mloader->message(mloader->priv,
PLAYER_MSG_SEEK_DONE, arg);
loader->load_pos += (int)arg;
break;
case CACHE_EV_READ_BLOCK:
if (mloader->message)
mloader->message(mloader->priv,
PLAYER_MSG_LOAD_BLOCK, arg);
break;
default:
break;
}
return 0;
}
int http_loader_start(http_loader_t *loader)
{
int retries;
int ret;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
__redirect:
ret = http_urlparse(loader);
if (ret) {
M_LOGE("parse url failed !\n");
return -1;
}
#if defined(UVOICE_HTTP_MULTI_RETRY_TIMES)
retries = UVOICE_HTTP_MULTI_RETRY_TIMES;
#else
retries = 1;
#endif
while (retries-- > 0) {
if (loader->nc->cache_stop || loader->read_paused)
return -1;
ret = http_connect(loader);
if (ret) {
M_LOGE("connect socket failed ! retries %d\n", retries);
if (retries - 1 <= 0) {
return -1;
}
#if defined(UVOICE_HTTP_MULTI_RETRY_TIMES)
if (loader->nc->cache_stop)
return -1;
continue;
#endif
}
break;
}
#if defined(UVOICE_HTTP_MULTI_RETRY_TIMES)
retries = UVOICE_HTTP_MULTI_RETRY_TIMES;
#else
retries = 1;
#endif
while (retries-- > 0) {
if (loader->nc->cache_stop || loader->read_paused) {
http_disconnect(loader);
return -1;
}
ret = http_request(loader);
if (ret < 0) {
M_LOGE("http request failed ! retries %d\n", retries);
if (retries - 1 <= 0) {
http_disconnect(loader);
return -1;
}
#if defined(UVOICE_HTTP_MULTI_RETRY_TIMES)
os_msleep(200);
continue;
#endif
} else if (ret == 1) {
http_disconnect(loader);
goto __redirect;
}
break;
}
M_LOGD("http load start\n");
return 0;
}
int http_loader_stop(http_loader_t *loader)
{
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
M_LOGD("http load stop\n");
return http_disconnect(loader);
}
int http_loader_restart(http_loader_t *loader)
{
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
http_loader_stop(loader);
loader->start = 0;
loader->chunked = 0;
loader->redirect = 0;
if (loader->cache_on)
loader->breakpoint_pos = loader->nc ?
loader->nc->load_length : loader->load_pos;
else
loader->breakpoint_pos = loader->load_pos;
M_LOGD("restart url %s\n", loader->url);
if (http_loader_start(loader)) {
M_LOGE("start http load failed !\n");
loader->breakpoint_pos = loader->load_pos;
return -1;
}
loader->breakpoint_pos = 0;
loader->start = 1;
return 0;
}
static int http_loader_read(void *priv, uint8_t *buffer, int nbytes)
{
media_loader_t *mloader = (media_loader_t *)priv;
http_loader_t *loader;
net_cache_t *nc;
int rd_ret;
if (!mloader) {
M_LOGE("mlaoder null !\n");
return -1;
}
loader = mloader->loader;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
nc = loader->nc;
if (!nc) {
M_LOGE("nc null !\n");
return -1;
}
if (loader->seek_offset != 0) {
http_loader_event(loader, CACHE_EV_SEEK_DONE,
(void *)loader->seek_offset);
loader->seek_offset = 0;
}
if (nc->cache_read) {
rd_ret = loader->nc->cache_read(nc, buffer, nbytes);
} else {
if (nc->head_data_size > 0) {
if (nc->head_data_size >= nbytes) {
M_LOGD("read head data %u\n", nbytes);
snd_memcpy(buffer, nc->buffer, nbytes);
nc->head_data_size -= nbytes;
snd_memmove(nc->buffer, nc->buffer + nbytes,
nc->head_data_size);
rd_ret = nbytes;
} else {
M_LOGD("read head data %u\n", nc->head_data_size);
snd_memcpy(buffer, nc->buffer, nc->head_data_size);
rd_ret = nc->head_data_size;
rd_ret += http_read(loader,
buffer + nc->head_data_size,
nbytes - nc->head_data_size);
nc->head_data_size = 0;
}
} else {
rd_ret = http_read(loader, buffer, nbytes);
}
}
if (rd_ret < 0) {
M_LOGE("read failed %d!\n", rd_ret);
return -1;
} else if (rd_ret == 0) {
M_LOGD("read end, load pos %d\n", loader->load_pos);
}
loader->load_pos += rd_ret;
return rd_ret;
}
static void http_dload_task(void *arg)
{
#ifdef UVOICE_DOWNLOAD_ENABLE
http_dload_t *dload = (http_dload_t *)arg;
http_loader_t *loader;
if (!dload) {
M_LOGE("dload null !\n");
goto __exit;
}
if (!dload->source) {
M_LOGE("source null !\n");
goto __exit;
}
if (!strncmp(dload->source, "https://", strlen("https://"))) {
M_LOGW("https source can't download\n");
goto __exit;
}
loader = snd_zalloc(sizeof(http_loader_t), AFM_EXTN);
if (!loader) {
M_LOGE("alloc http loader failed !\n");
goto __exit;
}
memcpy(loader->url, dload->source,
strlen(dload->source) + 1);
M_LOGD("source: %s\n", loader->url);
loader->nc = net_download_create();
if (!loader->nc) {
M_LOGE("create net download failed !\n");
goto __exit1;
}
loader->nc->cache_load = http_read;
loader->nc->event = http_loader_event;
loader->nc->priv = loader;
dload->nc = loader->nc;
if (strlen(dload->filename) <= 0) {
if (http_get_filename(loader)) {
M_LOGE("get filename failed !\n");
goto __exit2;
}
} else {
memcpy(loader->nc->filename,
dload->filename, strlen(dload->filename) + 1);
memset(dload->filename, 0, sizeof(dload->filename));
}
if (http_loader_start(loader)) {
M_LOGE("http start failed !\n");
goto __exit2;
}
if (net_download_work(loader->nc)) {
M_LOGE("download failed !\n");
goto __exit3;
}
http_loader_stop(loader);
net_download_release(loader->nc);
snd_free(loader);
dload->nc = NULL;
uvoice_event_post(UVOICE_EV_PLAYER,
UVOICE_CODE_PALYER_DLOAD_CPLT, 0);
os_task_exit(NULL);
return;
__exit3:
http_loader_stop(loader);
__exit2:
net_download_release(loader->nc);
__exit1:
snd_free(loader);
__exit:
loader->download = 0;
dload->nc = NULL;
M_LOGE("download failed !\n");
os_task_exit(NULL);
#endif
}
static int http_loader_action(void *priv,
player_action_t action, void *arg)
{
media_loader_t *mloader = (media_loader_t *)priv;
http_loader_t *loader;
if (!mloader) {
M_LOGE("mloader null !\n");
return -1;
}
loader = mloader->loader;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
if (action == PLAYER_START) {
if (!loader->nc) {
loader->nc = net_cache_create(HTTP_READ_BUFF_SIZE,
g_cache_config, !!loader->hls);
if (!loader->nc) {
M_LOGE("create net cache failed !\n");
return -1;
}
loader->nc->cache_load = http_read;
loader->nc->event = http_loader_event;
loader->nc->priv = loader;
}
if (!loader->start) {
#ifdef UVOICE_HLS_ENABLE
if (loader->hls) {
if (loader->hls->live_stream) {
if (uvoice_hls_build(loader)) {
M_LOGE("parse seq list failed !\n");
net_cache_release(loader->nc);
return -1;
}
loader->nc->sequence = 1;
}
}
#endif
if (http_loader_start(loader)) {
M_LOGE("start http load failed !\n");
return -1;
}
loader->start = 1;
}
if (net_cache_start(loader->nc)) {
M_LOGE("start net cache failed !\n");
http_loader_stop(loader);
loader->start = 0;
loader->chunked = 0;
loader->redirect = 0;
return -1;
}
if (mloader->message) {
media_info_t media_info;
memset(&media_info, 0, sizeof(media_info_t));
media_info.duration = 0;
#ifdef UVOICE_HLS_ENABLE
if (loader->hls)
media_info.duration = loader->hls->duration;
#endif
media_info.media_size = loader->nc->content_length;
mloader->message(mloader->priv,
PLAYER_MSG_MEDIA_INFO, &media_info);
}
} else if (action == PLAYER_STOP) {
if (loader->nc) {
if (net_cache_stop(loader->nc)) {
M_LOGE("stop net cache failed !\n");
return -1;
}
if (net_cache_reset(loader->nc)) {
M_LOGE("cache reset failed !\n");
return -1;
}
}
if (loader->start) {
http_loader_stop(loader);
loader->start = 0;
loader->chunked = 0;
loader->redirect = 0;
}
#ifdef UVOICE_HLS_ENABLE
if (loader->hls) {
if (loader->hls->live_stream) {
memset(loader->url, 0, sizeof(loader->url));
memcpy(loader->url, loader->hls->base,
strlen(loader->hls->base) + 1);
loader->breakpoint_pos = 0;
loader->hls->seg_current = 0;
loader->hls->seg_begin = 0;
loader->hls->seg_index = 0;
} else {
if (uvoice_hls_index_update(loader, 0)) {
M_LOGE("update list index failed !\n");
return -1;
}
}
}
#endif
loader->load_pos = 0;
loader->breakpoint_pos = 0;
} else if (action == PLAYER_UNBLOCK) {
if (loader->nc) {
M_LOGD("cache blocking cancel\n");
if (net_cache_pause(loader->nc)) {
M_LOGE("stop net cache failed !\n");
return -1;
}
if (loader->nc->rebuild &&
(loader->load_pos < loader->content_length ||
loader->hls)) {
if (net_cache_stop(loader->nc)) {
M_LOGE("stop net cache failed !\n");
return -1;
}
}
}
} else if (action == PLAYER_PAUSE) {
if (!loader->deep_pause) {
/* pause without net cache release */
if (!loader->seeking) {
loader->pause_time = os_current_time();
loader->read_paused = 1;
goto __exit;
}
}
if (loader->nc) {
if (net_cache_pause(loader->nc)) {
M_LOGE("stop net cache failed !\n");
return -1;
}
/* pause with net cache rebuild */
if (loader->nc->rebuild &&
(loader->load_pos < loader->content_length ||
loader->hls)) {
if (net_cache_stop(loader->nc)) {
M_LOGE("stop net cache failed !\n");
return -1;
}
net_cache_release(loader->nc);
loader->nc = NULL;
if (loader->start) {
http_loader_stop(loader);
loader->start = 0;
loader->chunked = 0;
loader->redirect = 0;
loader->breakpoint_pos = loader->load_pos;
M_LOGD("breakpoint pos %d\n", loader->breakpoint_pos);
}
#ifdef UVOICE_HLS_ENABLE
if (loader->hls) {
if (loader->hls->live_stream) {
memset(loader->url, 0, sizeof(loader->url));
memcpy(loader->url, loader->hls->base,
strlen(loader->hls->base) + 1);
loader->breakpoint_pos = 0;
M_LOGD("breakpoint pos %d\n", loader->breakpoint_pos);
loader->hls->seg_current = 0;
loader->hls->seg_begin = 0;
loader->hls->seg_index = 0;
} else {
int i;
os_mutex_lock(loader->hls->lock,
OS_WAIT_FOREVER);
for (i = loader->hls->seg_index; i >= 0; i--) {
if (loader->load_pos >
loader->hls->seg_offset[i])
break;
}
if (i < 0)
i = 0;
loader->breakpoint_pos = loader->load_pos -
loader->hls->seg_offset[i];
M_LOGD("load pos %d breakpoint pos %d index %d\n",
loader->load_pos,
loader->breakpoint_pos, i);
if (loader->hls->seg_index > i) {
loader->content_length =
loader->hls->seg_offset[i + 1] -
loader->hls->seg_offset[i];
}
os_mutex_unlock(loader->hls->lock);
if (uvoice_hls_index_update(loader, i)) {
M_LOGE("update list index failed !\n");
return -1;
}
}
}
#endif
}
} else {
if (loader->start) {
http_loader_stop(loader);
loader->start = 0;
loader->chunked = 0;
loader->redirect = 0;
loader->breakpoint_pos = loader->load_pos;
M_LOGD("breakpoint pos %d\n", loader->breakpoint_pos);
}
}
} else if (action == PLAYER_RESUME) {
if (!loader->deep_pause) {
/* net cache not released */
if (loader->read_paused)
loader->read_paused = 0;
if (!loader->seeking && loader->nc) {
if (os_current_time() - loader->pause_time >
HTTP_CONNECT_TIMEOUT_MSEC)
loader->force_restart = 1;
if (!loader->start) {
/* Some error arise during previous pause, such as restart failed */
if (loader->force_restart)
loader->force_restart = 0;
/* correct breakpoint pos because cache pool still valid */
loader->breakpoint_pos = loader->nc->load_length;
if (http_loader_start(loader)) {
M_LOGE("start http load failed !\n");
return -1;
}
loader->start = 1;
if (loader->nc->cache_cplt) {
if (net_cache_start(loader->nc)) {
M_LOGE("start net cache failed !\n");
http_loader_stop(loader);
loader->start = 0;
loader->chunked = 0;
loader->redirect = 0;
return -1;
}
}
}
goto __exit;
}
}
if (!loader->nc) {
loader->nc = net_cache_create(HTTP_READ_BUFF_SIZE,
g_cache_config, !!loader->hls);
if (!loader->nc) {
M_LOGE("create net cache failed !\n");
return -1;
}
loader->nc->cache_load = http_read;
loader->nc->event = http_loader_event;
loader->nc->priv = loader;
loader->nc->rebuild = 1;
#ifdef UVOICE_HLS_ENABLE
if (loader->hls) {
if (loader->hls->live_stream) {
if (uvoice_hls_build(loader)) {
M_LOGE("parse hls failed !\n");
net_cache_release(loader->nc);
return -1;
}
loader->nc->sequence = 1;
}
}
#endif
} else {
if (net_cache_resume(loader->nc)) {
M_LOGE("resume net cache failed !\n");
return -1;
}
#ifdef UVOICE_HLS_ENABLE
if (loader->hls) {
if (uvoice_hls_build(loader)) {
M_LOGE("parse seq list failed !\n");
net_cache_pause(loader->nc);
return -1;
}
}
#endif
}
if (!loader->start) {
if (http_loader_start(loader)) {
M_LOGE("start http load failed !\n");
return -1;
}
loader->breakpoint_pos = 0;
loader->start = 1;
}
if (loader->nc->rebuild) {
if (net_cache_start(loader->nc)) {
M_LOGE("start net cache failed !\n");
http_loader_stop(loader);
loader->start = 0;
loader->chunked = 0;
loader->redirect = 0;
return -1;
}
loader->nc->rebuild = 0;
}
} else if (action == PLAYER_SEEK_BEGIN) {
loader->seeking = 1;
} else if (action == PLAYER_SEEK_END) {
loader->seeking = 0;
} else if (action == PLAYER_SEEK) {
if (loader->hls) {
M_LOGE("sequence stream seek unsupport\n");
return -1;
}
int seek_offset = (int)arg;
cache_info_t cache_info;
M_LOGD("seek offset %d\n", seek_offset);
if (loader->nc && seek_offset > 0) {
memset(&cache_info, 0, sizeof(cache_info_t));
net_get_cacheinfo(loader->nc, &cache_info);
if (cache_info.avail_cache_size >= seek_offset)
return net_cache_seek(loader->nc, seek_offset);
}
if (loader->nc && !loader->nc->rebuild && loader->start) {
if (net_cache_stop(loader->nc)) {
M_LOGE("stop net cache failed !\n");
return -1;
}
net_cache_release(loader->nc);
loader->nc = NULL;
http_loader_stop(loader);
loader->start = 0;
loader->chunked = 0;
loader->redirect = 0;
loader->breakpoint_pos = loader->load_pos;
M_LOGD("breakpoint pos %d\n", loader->breakpoint_pos);
}
if (seek_offset > 0 &&
loader->load_pos + seek_offset <=
loader->content_length - 1024) {
loader->seek_offset = seek_offset;
loader->breakpoint_pos =
loader->load_pos + loader->seek_offset;
M_LOGD("update breakpoint pos %d\n",
loader->breakpoint_pos);
} else if (seek_offset < 0 &&
loader->load_pos + seek_offset >= 0) {
loader->seek_offset = seek_offset;
loader->breakpoint_pos =
loader->load_pos + loader->seek_offset;
M_LOGD("update breakpoint pos %d\n",
loader->breakpoint_pos);
}
} else if (action == PLAYER_COMPLETE) {
(void)net_cache_stop(loader->nc);
if (loader->start) {
http_loader_stop(loader);
loader->start = 0;
loader->host_addr = INADDR_NONE;
loader->chunked = 0;
loader->redirect = 0;
loader->load_pos = 0;
}
} else if (action == PLAYER_NEXT) {
if (loader->start) {
M_LOGE("loader not stop !\n");
return -1;
}
char *url = (char *)arg;
if (strlen(url) + 1 > HTTP_URL_LEN) {
M_LOGE("url length %zd overrange !\n", strlen(url));
return -1;
}
memset(loader->url, 0, sizeof(loader->url));
memcpy(loader->url, url, strlen(url) + 1);
loader->url[strlen(url)] = '\0';
/* net cache rebuild for different stream type */
bool sequence = !!strstr(loader->url, ".m3u8");
if (sequence != !!loader->hls) {
M_LOGD("http stream type change\n");
if (net_cache_release(loader->nc)) {
M_LOGE("release net cache failed !\n");
return -1;
}
loader->nc = net_cache_create(HTTP_READ_BUFF_SIZE,
g_cache_config, sequence);
if (!loader->nc) {
M_LOGE("create net cache failed !\n");
return -1;
}
loader->nc->cache_load = http_read;
loader->nc->event = http_loader_event;
loader->nc->priv = loader;
}
#ifdef UVOICE_HLS_ENABLE
if (uvoice_hls_build(loader)) {
M_LOGE("parse seq list failed !\n");
return -1;
}
#endif
} else if (action == PLAYER_DLOAD) {
#ifdef UVOICE_DOWNLOAD_ENABLE
if (loader->hls) {
M_LOGE("sequence stream download unsupport !\n");
return -1;
}
if (!loader->download) {
if (arg) {
char *filename = (char *)arg;
if (strlen(filename) > 0 &&
strlen(filename) < sizeof(loader->dload.filename)) {
memcpy(loader->dload.filename,
filename, strlen(filename) + 1);
} else {
M_LOGE("filename length %zd overrange !\n", strlen(filename));
return -1;
}
}
loader->dload.source = loader->url;
M_LOGD("start download task\n");
loader->download = 1;
os_task_create(&loader->download_task, "uvoice_dload_task",
http_dload_task,
&loader->dload,
2048, UVOICE_TASK_PRI_LOWEST);
} else {
M_LOGW("download already\n");
}
#endif
} else if (action == PLAYER_DLOAD_ABORT) {
#ifdef UVOICE_DOWNLOAD_ENABLE
if (loader->download) {
if (loader->dload.nc) {
if (new_download_abort(loader->dload.nc)) {
M_LOGW("abort download failed\n");
return -1;
}
loader->download = 0;
M_LOGD("abort download success\n");
}
}
#endif
}
__exit:
return 0;
}
int http_loader_create(media_loader_t *mloader, char *source)
{
http_loader_t *loader;
bool sequence = false;
enum cache_type cachetype;
if (!mloader) {
M_LOGE("mloader null !\n");
return -1;
}
if (!source) {
M_LOGE("source null !\n");
return -1;
}
if (strlen(source) + 1 > HTTP_URL_LEN) {
M_LOGE("url length %zd overrange !\n", strlen(source));
return -1;
}
loader = snd_zalloc(sizeof(http_loader_t), AFM_EXTN);
if (!loader) {
M_LOGE("alloc http loader failed !\n");
return -1;
}
loader->sock = -1;
loader->host_addr = INADDR_NONE;
loader->cache_on = HTTP_CACHE_ENABLE;
loader->deep_pause = HTTP_LOAD_DEEP_PAUSE_ENABLE;
loader->priv = mloader;
memcpy(loader->url, source, strlen(source));
loader->url[strlen(source)] = '\0';
sequence = !!strstr(loader->url, ".m3u8");
cachetype = loader->cache_on ? PLAYER_CACHE_TYPE : CACHE_NONE;
if (!g_cache_config) {
g_cache_config = snd_zalloc(sizeof(cache_config_t), AFM_MAIN);
if (!g_cache_config) {
M_LOGE("alloc cache config fail !\n");
snd_free(loader);
return -1;
}
g_cache_config->place = loader->cache_on ? PLAYER_CACHE_TYPE : CACHE_NONE;
if (g_cache_config->place == CACHE_FILE)
snprintf(g_cache_config->file_path, sizeof(g_cache_config->file_path),
"%s", PLAYER_CACHE_FILE_PATH);
else if (g_cache_config->place == CACHE_MEM)
g_cache_config->mem_size = PLAYER_CACHE_MEM_SIZE;
M_LOGD("set default cache config\n");
}
loader->nc = net_cache_create(HTTP_READ_BUFF_SIZE,
g_cache_config, sequence);
if (!loader->nc) {
M_LOGE("create net cache failed !\n");
snd_free(loader);
return -1;
}
loader->nc->cache_load = http_read;
loader->nc->event = http_loader_event;
loader->nc->priv = loader;
mloader->read = http_loader_read;
mloader->action = http_loader_action;
mloader->get_format = http_source_format;
mloader->get_mediainfo = http_get_mediainfo;
mloader->get_cacheinfo = http_get_cacheinfo;
mloader->reset = http_loader_reset;
#ifdef UVOICE_HLS_ENABLE
if (uvoice_hls_build(loader)) {
M_LOGE("parse hls m3u8 failed !\n");
net_cache_release(loader->nc);
snd_free(loader);
return -1;
}
#endif
mloader->loader = loader;
M_LOGD("http loader create\n");
return 0;
}
int http_loader_release(media_loader_t *mloader)
{
http_loader_t *loader;
if (!mloader) {
M_LOGE("mloader null !\n");
return -1;
}
loader = mloader->loader;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
#ifdef UVOICE_HLS_ENABLE
if (loader->hls)
uvoice_hls_release(loader);
#endif
if (loader->start) {
http_loader_stop(loader);
loader->start = 0;
}
if (loader->nc) {
net_cache_release(loader->nc);
loader->nc = NULL;
}
snd_free(loader);
mloader->loader = NULL;
M_LOGD("http loader release\n");
return 0;
}
|
YifuLiu/AliOS-Things
|
components/uvoice/stream/uvoice_http.c
|
C
|
apache-2.0
| 52,437
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#ifndef __HTTP_LOAD_H__
#define __HTTP_LOAD_H__
#ifdef VOICELOUDER_APP
#define HTTP_URL_LEN 1024
#else
#define HTTP_URL_LEN 512
#endif
#define HTTP_HOSTNAME_LEN HTTP_URL_LEN
#define HTTP_STAT_SUCCESS 200
#define HTTP_CODE_BREAKPOINT 206
#define HTTP_CODE_PERM_REDIRECT 301
#define HTTP_CODE_TEMP_REDIRECT 302
#define HTTP_READ_BUFF_SIZE 1024
typedef struct {
char *source;
char filename[64];
net_cache_t *nc;
} http_dload_t;
typedef struct {
char base[HTTP_URL_LEN];
os_file_t fp;
char *content;
char *pos;
char *sub;
int len;
int *seg_offset;
char seg_desc[64];
uint8_t live_stream:1;
int seg_begin;
int seg_index;
int seg_count;
int seg_current;
int duration;
os_mutex_t lock;
} hls_t;
typedef struct {
uint16_t port;
int sock;
int http_status;
uint16_t https:1;
uint16_t start:1;
uint16_t chunked:1;
uint16_t redirect:1;
uint16_t download:1;
uint16_t cache_on:1;
uint16_t seeking:1;
uint16_t deep_pause:1;
uint16_t force_restart:1;
uint16_t read_paused:1;
int content_length;
int breakpoint_pos;
int load_pos;
int seek_offset;
long long pause_time;
uint32_t host_addr;
char host_name[HTTP_HOSTNAME_LEN];
char uri[HTTP_URL_LEN];
char url[HTTP_URL_LEN];
char redirect_url[HTTP_URL_LEN];
http_dload_t dload;
net_cache_t *nc;
hls_t *hls;
os_task_t download_task;
void *priv;
} http_loader_t;
#endif /* __HTTP_LOAD_H__ */
|
YifuLiu/AliOS-Things
|
components/uvoice/stream/uvoice_http.h
|
C
|
apache-2.0
| 1,464
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "uvoice_types.h"
#include "uvoice_player.h"
#include "uvoice_recorder.h"
#include "uvoice_os.h"
#include "uvoice_common.h"
#include "uvoice_play.h"
#include "uvoice_record.h"
#include "uvoice_format.h"
struct partition_loader {
int part; /* partition id */
uint32_t part_size;
uint32_t begin;
uint32_t rd_offset;
int32_t bin_size;
long seek_offset;
os_mutex_t lock;
};
struct partition_packer {
int part; /* partition id */
uint32_t part_size;
uint32_t begin;
uint32_t wr_offset;
int bin_size;
os_mutex_t lock;
};
static int partition_get_format(void *priv, media_format_t *format)
{
media_loader_t *mloader = (media_loader_t *)priv;
struct partition_loader *loader;
uint8_t *head_buffer;
int32_t buffer_size;
int32_t rd_offset;
int ret;
if (!mloader) {
M_LOGE("mloader null !\n");
return -1;
}
loader = mloader->loader;
if (!loader) {
M_LOGE("loader null x!\n");
return -1;
}
os_mutex_lock(loader->lock, OS_WAIT_FOREVER);
buffer_size = MIN(512, loader->bin_size);
head_buffer = snd_zalloc(buffer_size, AFM_EXTN);
if (!head_buffer) {
M_LOGE("alloc buffer failed !\n");
os_mutex_unlock(loader->lock);
return -1;
}
rd_offset = loader->rd_offset;
loader->rd_offset = 0;
ret = os_partition_read(loader->part,
&loader->rd_offset, head_buffer, buffer_size);
if (ret) {
M_LOGE("read partition failed %d!\n", ret);
loader->rd_offset = rd_offset;
os_mutex_unlock(loader->lock);
return -1;
}
loader->rd_offset = rd_offset;
os_mutex_unlock(loader->lock);
if (flac_format_check(head_buffer, buffer_size)) {
*format = MEDIA_FMT_FLAC;
M_LOGD("format FLAC\n");
} else if (mp3_format_check(head_buffer, buffer_size)) {
*format = MEDIA_FMT_MP3;
M_LOGD("format MP3\n");
} else if (wav_format_check(head_buffer, buffer_size)) {
*format = MEDIA_FMT_WAV;
M_LOGD("format WAV\n");
} else if (aac_format_check(head_buffer, buffer_size)) {
*format = MEDIA_FMT_AAC;
M_LOGD("format AAC\n");
} else if (m4a_format_check(head_buffer, buffer_size)) {
*format = MEDIA_FMT_M4A;
M_LOGD("format M4A\n");
} else if (ogg_format_check(head_buffer, buffer_size)) {
*format = MEDIA_FMT_OGG;
M_LOGD("format OGG\n");
} else if (wma_format_check(head_buffer, buffer_size)) {
*format = MEDIA_FMT_WMA;
M_LOGD("format WMA\n");
} else if (amrwb_format_check(head_buffer, buffer_size)) {
*format = MEDIA_FMT_AMRWB;
M_LOGD("format AMR-WB\n");
} else if (amr_format_check(head_buffer, buffer_size)) {
*format = MEDIA_FMT_AMR;
M_LOGD("format AMR\n");
}
snd_free(head_buffer);
return 0;
}
static int partition_get_mediainfo(void *priv,
media_info_t *info, media_format_t format)
{
media_loader_t *mloader = (media_loader_t *)priv;
struct partition_loader *loader;
int ret;
if (!mloader) {
M_LOGE("mloader null !\n");
return -1;
}
loader = mloader->loader;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
os_mutex_lock(loader->lock, OS_WAIT_FOREVER);
if (format == MEDIA_FMT_MP3) {
if (loader->bin_size < 128) {
M_LOGE("binary too short !\n");
os_mutex_unlock(loader->lock);
return -1;
}
char buffer[128];
memset(buffer, 0, sizeof(buffer));
int rd_offset = loader->rd_offset;
loader->rd_offset =
loader->begin + loader->bin_size - 128;
ret = os_partition_read(loader->part, &loader->rd_offset,
buffer, 128);
if (ret) {
M_LOGE("read partition failed %d!\n", ret);
loader->rd_offset = rd_offset;
os_mutex_unlock(loader->lock);
return -1;
}
loader->rd_offset = rd_offset;
mp3_id3v1_parse(info, buffer, 128);
}
os_mutex_unlock(loader->lock);
return 0;
}
static int partition_info_parse(char *info,
unsigned int *part, unsigned int *begin, int *bin_size)
{
char *ptr;
if (!info || !part || !begin || !bin_size) {
M_LOGE("arg null !\n");
return -1;
}
ptr = strstr(info, "pt:");
if (ptr) {
ptr += strlen("pt:");
*part = atoi(ptr);
} else {
M_LOGE("part not found !\n");
return -1;
}
ptr = strstr(info, "offset:");
if (ptr) {
ptr += strlen("offset:");
*begin = atoi(ptr);
} else {
M_LOGE("offset not found !\n");
return -1;
}
ptr = strstr(info, "len:");
if (ptr) {
ptr += strlen("len:");
*bin_size = atoi(ptr);
} else {
M_LOGE("len not found !\n");
return -1;
}
return 0;
}
static int partition_loader_update(struct partition_loader *loader,
char *sink)
{
const char *part_name;
int part_size;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
if (!sink) {
M_LOGE("sink null !\n");
return -1;
}
if (partition_info_parse(sink, &loader->part,
&loader->begin, &loader->bin_size)) {
M_LOGE("parse partition info failed !\n");
return -1;
}
M_LOGD("part %d begin %u bin_size %d\n",
loader->part,
loader->begin, loader->bin_size);
part_name = os_partition_name(loader->part);
if (!part_name) {
M_LOGE("get partition name failed !\n");
return -1;
}
if (strncmp(part_name, "UVOICE MEDIA", strlen("UVOICE MEDIA"))) {
M_LOGE("partition name %s not match !\n", part_name);
return -1;
}
part_size = os_partition_size(loader->part);
if (part_size < 0) {
M_LOGE("get partition size failed !\n");
return -1;
}
if (loader->bin_size > part_size) {
M_LOGE("bin size %d overrange !\n", loader->bin_size);
return -1;
}
loader->part_size = part_size;
loader->rd_offset = loader->begin;
return 0;
}
static int partition_loader_reset(void *priv)
{
media_loader_t *mloader = (media_loader_t *)priv;
struct partition_loader *loader;
if (!mloader) {
M_LOGE("mloader null !\n");
return -1;
}
loader = mloader->loader;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
os_mutex_lock(loader->lock, OS_WAIT_FOREVER);
loader->begin = 0;
loader->rd_offset = loader->begin;
loader->part_size = 0;
loader->part = -1;
loader->seek_offset = 0;
os_mutex_unlock(loader->lock);
M_LOGD("partition load reset\n");
return 0;
}
static int partition_loader_read(void *priv,
uint8_t *buffer, int nbytes)
{
media_loader_t *mloader = (media_loader_t *)priv;
struct partition_loader *loader;
int read_size = 0;
int ret;
if (!mloader) {
M_LOGE("mloader null !\n");
return -1;
}
loader = mloader->loader;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
os_mutex_lock(loader->lock, OS_WAIT_FOREVER);
if (loader->seek_offset != 0) {
if (loader->seek_offset > 0) {
if (loader->seek_offset <=
loader->bin_size - loader->rd_offset) {
loader->rd_offset += loader->seek_offset;
if (mloader->message)
mloader->message(mloader->priv,
PLAYER_MSG_SEEK_DONE, (void *)loader->seek_offset);
}
} else {
if (abs(loader->seek_offset) <= loader->rd_offset) {
loader->rd_offset += loader->seek_offset;
if (mloader->message)
mloader->message(mloader->priv,
PLAYER_MSG_SEEK_DONE, (void *)loader->seek_offset);
}
}
loader->seek_offset = 0;
}
if (loader->rd_offset >= loader->bin_size) {
M_LOGD("read end\n");
goto __exit;
}
read_size = MIN(nbytes,
loader->bin_size - loader->rd_offset);
ret = os_partition_read(loader->part,
&loader->rd_offset, buffer, read_size);
if (ret) {
M_LOGE("read failed %d!\n", ret);
os_mutex_unlock(loader->lock);
return -1;
}
if (read_size != nbytes)
M_LOGD("read %d ret %d\n", nbytes, read_size);
__exit:
os_mutex_unlock(loader->lock);
return read_size;
}
static int partition_loader_action(void *priv,
player_action_t action, void *arg)
{
media_loader_t *mloader = (media_loader_t *)priv;
struct partition_loader *loader;
if (!mloader) {
M_LOGE("mloader null !\n");
return -1;
}
loader = mloader->loader;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
if (action == PLAYER_START) {
if (mloader->message) {
media_info_t media_info;
memset(&media_info, 0, sizeof(media_info_t));
os_mutex_lock(loader->lock, OS_WAIT_FOREVER);
media_info.media_size = loader->bin_size;
os_mutex_unlock(loader->lock);
mloader->message(mloader->priv,
PLAYER_MSG_MEDIA_INFO, &media_info);
}
} else if (action == PLAYER_STOP) {
os_mutex_lock(loader->lock, OS_WAIT_FOREVER);
loader->rd_offset = loader->begin;
loader->seek_offset = 0;
os_mutex_unlock(loader->lock);
} else if (action == PLAYER_SEEK) {
os_mutex_lock(loader->lock, OS_WAIT_FOREVER);
loader->seek_offset = (long)arg;
os_mutex_unlock(loader->lock);
} else if (action == PLAYER_COMPLETE) {
} else if (action == PLAYER_NEXT) {
os_mutex_lock(loader->lock, OS_WAIT_FOREVER);
if (partition_loader_update(loader, (char *)arg)) {
M_LOGE("update failed !\n");
os_mutex_unlock(loader->lock);
return -1;
}
os_mutex_unlock(loader->lock);
}
return 0;
}
int partition_loader_create(media_loader_t *mloader, char *source)
{
struct partition_loader *loader;
const char *part_name;
int part_size;
if (!mloader) {
M_LOGE("mloader null !\n");
return -1;
}
if (!source) {
M_LOGE("info null !\n");
return -1;
}
loader = snd_zalloc(sizeof(struct partition_loader), AFM_EXTN);
if (!loader) {
M_LOGE("alloc partition loader failed !\n");
return -1;
}
if (partition_info_parse(source, &loader->part,
&loader->begin, &loader->bin_size)) {
M_LOGE("parse partition info failed !\n");
snd_free(loader);
return -1;
}
M_LOGD("part %d begin %u bin_size %d\n",
loader->part, loader->begin, loader->bin_size);
part_name = os_partition_name(loader->part);
if (!part_name) {
M_LOGE("get partition name failed !\n");
snd_free(loader);
return -1;
}
if (strncmp(part_name, "UVOICE MEDIA", strlen("UVOICE MEDIA"))) {
M_LOGE("partition %s not media !\n", part_name);
snd_free(loader);
return -1;
}
part_size = os_partition_size(loader->part);
if (part_size < 0) {
M_LOGE("get partition size failed !\n");
snd_free(loader);
return -1;
}
if (loader->bin_size > part_size) {
M_LOGE("bin size %d overrange !\n", loader->bin_size);
snd_free(loader);
return -1;
}
loader->part_size = part_size;
loader->rd_offset = loader->begin;
loader->lock = os_mutex_new();
loader->seek_offset = 0;
mloader->read = partition_loader_read;
mloader->action = partition_loader_action;
mloader->get_format = partition_get_format;
mloader->get_mediainfo = partition_get_mediainfo;
mloader->get_cacheinfo = NULL;
mloader->reset = partition_loader_reset;
mloader->loader = loader;
M_LOGD("partition loader create\n");
return 0;
}
int partition_loader_release(media_loader_t *mloader)
{
struct partition_loader *loader;
if (!mloader) {
M_LOGE("mloader null !\n");
return -1;
}
loader = mloader->loader;
if (!loader) {
M_LOGE("loader null !\n");
return -1;
}
os_mutex_free(loader->lock);
snd_free(loader);
mloader->loader = NULL;
M_LOGD("partition loader release\n");
return 0;
}
static int partition_packer_write(void *priv,
uint8_t *buffer, int nbytes)
{
media_packer_t *mpacker = (media_packer_t *)priv;
struct partition_packer *packer;
int wr_size = 0;
int ret = 0;
if (!mpacker) {
M_LOGE("mpacker null !\n");
return -1;
}
packer = mpacker->packer;
if (!packer) {
M_LOGE("packer null !\n");
return -1;
}
os_mutex_lock(packer->lock, OS_WAIT_FOREVER);
wr_size = MIN(nbytes,
packer->part_size - packer->wr_offset);
if (wr_size <= 0) {
M_LOGE("write end, bin size %u\n",
packer->wr_offset);
goto __exit;
}
ret = os_partition_write(packer->part,
&packer->wr_offset, buffer, wr_size);
if (ret) {
M_LOGE("write failed %d!\n", ret);
os_mutex_unlock(packer->lock);
return -1;
}
mpacker->size += wr_size;
ret = wr_size;
__exit:
os_mutex_unlock(packer->lock);
return ret;
}
static int partition_packer_update(void *priv,
uint8_t *buffer, int nbytes, int pos)
{
media_packer_t *mpacker = (media_packer_t *)priv;
struct partition_packer *packer;
int wr_offset = 0;
int ret = 0;
if (!mpacker) {
M_LOGE("mpacker null !\n");
return -1;
}
packer = mpacker->packer;
if (!packer) {
M_LOGE("packer null !\n");
return -1;
}
os_mutex_lock(packer->lock, OS_WAIT_FOREVER);
if (pos + nbytes > packer->part_size) {
M_LOGE("pack size %d overrange !\n", nbytes);
os_mutex_unlock(packer->lock);
return -1;
}
wr_offset = packer->begin + pos;
ret = os_partition_erase(packer->part,
wr_offset, nbytes);
if (ret) {
M_LOGE("erase partition failed %d!\n", ret);
os_mutex_unlock(packer->lock);
return -1;
}
ret = os_partition_write(packer->part,
&wr_offset, buffer, nbytes);
if (ret) {
M_LOGE("write partition failed %d!\n", ret);
os_mutex_unlock(packer->lock);
return -1;
}
__exit:
os_mutex_unlock(packer->lock);
return ret;
}
static int partition_packer_action(void *priv,
recorder_action_t action, void *arg)
{
media_packer_t *mpacker = (media_packer_t *)priv;
struct partition_packer *packer;
if (!mpacker) {
M_LOGE("mpacker null !\n");
return -1;
}
packer = mpacker->packer;
if (!packer) {
M_LOGE("packer null !\n");
return -1;
}
return 0;
}
int partition_packer_create(media_packer_t *mpacker, char *sink)
{
struct partition_packer *packer;
const char *part_name;
int part_size;
int ret;
if (!mpacker) {
M_LOGE("mpacker null !\n");
return -1;
}
if (!sink) {
M_LOGE("sink null !\n");
return -1;
}
packer = snd_zalloc(sizeof(struct partition_packer), AFM_EXTN);
if (!packer) {
M_LOGE("alloc partition packer failed !\n");
return -1;
}
if (partition_info_parse(sink, &packer->part,
&packer->begin, &packer->bin_size)) {
M_LOGE("parse partition info failed !\n");
snd_free(packer);
return -1;
}
M_LOGD("part %d begin %u bin_size %d\n",
packer->part,
packer->begin, packer->bin_size);
part_name = os_partition_name(packer->part);
if (!part_name) {
M_LOGE("get partition name failed !\n");
snd_free(packer);
return -1;
}
if (strncmp(part_name, "UVOICE MEDIA", strlen("UVOICE MEDIA"))) {
M_LOGE("partition name %s not match !\n", part_name);
snd_free(packer);
return -1;
}
part_size = os_partition_size(packer->part);
if (part_size < 0) {
M_LOGE("get partition size failed !\n");
snd_free(packer);
return -1;
}
if (packer->bin_size > part_size) {
M_LOGE("bin size %d overrange !\n", packer->bin_size);
snd_free(packer);
return -1;
}
M_LOGD("partition partition erasing...\n");
ret = os_partition_erase(packer->part, packer->wr_offset,
part_size);
if (ret) {
M_LOGE("erase partition failed %d!\n", ret);
snd_free(packer);
return -1;
}
packer->part_size = part_size;
if (packer->part_size < packer->bin_size) {
M_LOGE("binary size %d overrange !\n", packer->bin_size);
snd_free(packer);
return -1;
}
packer->lock = os_mutex_new();
mpacker->packer = packer;
mpacker->pack = partition_packer_write;
mpacker->update = partition_packer_update;
mpacker->action = partition_packer_action;
M_LOGD("partition packer create\n");
return 0;
}
int partition_packer_release(media_packer_t *mpacker)
{
struct partition_packer *packer;
if (!mpacker) {
M_LOGE("mpacker null !\n");
return -1;
}
packer = mpacker->packer;
if (!packer) {
M_LOGE("packer null !\n");
return -1;
}
os_mutex_free(packer->lock);
snd_free(packer);
mpacker->packer = NULL;
M_LOGD("partition packer release\n");
return 0;
}
|
YifuLiu/AliOS-Things
|
components/uvoice/stream/uvoice_partition.c
|
C
|
apache-2.0
| 15,349
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include "uvoice_os.h"
#ifndef LINKKIT_SSL_ENABLE
#include "mbedtls/config.h"
#include "mbedtls/error.h"
#include "mbedtls/ssl.h"
#include "mbedtls/net.h"
#include "mbedtls/x509_crt.h"
#include "mbedtls/pk.h"
#include "mbedtls/debug.h"
#include "mbedtls/platform.h"
#define SEND_TIMEOUT_SECONDS (10)
typedef struct _TLSDataParams
{
mbedtls_ssl_context ssl; /**< mbed TLS control context. */
mbedtls_net_context fd; /**< mbed TLS network context. */
mbedtls_ssl_config conf; /**< mbed TLS configuration context. */
mbedtls_x509_crt cacertl; /**< mbed TLS CA certification. */
mbedtls_x509_crt clicert; /**< mbed TLS Client certification. */
mbedtls_pk_context pkey; /**< mbed TLS Client key. */
} TLSDataParams_t, *TLSDataParams_pt;
#define DEBUG_LEVEL 1
static unsigned int _avRandom()
{
uint64_t time_ms;
time_ms = aos_now_ms();
srandom((unsigned int)time_ms);
return (((unsigned int)rand() << 16) + rand());
}
static int _ssl_random(void *p_rng, unsigned char *output, size_t output_len)
{
uint32_t rnglen = output_len;
uint8_t rngoffset = 0;
while (rnglen > 0) {
*(output + rngoffset) = (unsigned char)_avRandom();
rngoffset++;
rnglen--;
}
return 0;
}
static void _ssl_debug(void *ctx, int level, const char *file, int line,
const char *str)
{
((void)level);
if (NULL != ctx) {
#if 0
fprintf((FILE *) ctx, "%s:%04d: %s", file, line, str);
fflush((FILE *) ctx);
#endif
M_LOGI("%s\n", str);
}
}
static int _real_confirm(int verify_result)
{
M_LOGI("certificate verification result: 0x%02x\n", verify_result);
#if defined(FORCE_SSL_VERIFY)
if ((verify_result & MBEDTLS_X509_BADCERT_EXPIRED) != 0) {
M_LOGE("! fail ! ERROR_CERTIFICATE_EXPIRED\n");
return -1;
}
if ((verify_result & MBEDTLS_X509_BADCERT_REVOKED) != 0) {
M_LOGE("! fail ! server certificate has been revoked\n");
return -1;
}
if ((verify_result & MBEDTLS_X509_BADCERT_CN_MISMATCH) != 0) {
M_LOGE("! fail ! CN mismatch\n");
return -1;
}
if ((verify_result & MBEDTLS_X509_BADCERT_NOT_TRUSTED) != 0) {
M_LOGE("! fail ! self-signed or not signed by a trusted CA\n");
return -1;
}
#endif
return 0;
}
static int _ssl_client_init(mbedtls_ssl_context *ssl,
mbedtls_net_context *tcp_fd,
mbedtls_ssl_config * conf,
mbedtls_x509_crt *crt509_ca, const char *ca_crt,
size_t ca_len, mbedtls_x509_crt *crt509_cli,
const char *cli_crt, size_t cli_len,
mbedtls_pk_context *pk_cli, const char *cli_key,
size_t key_len, const char *cli_pwd, size_t pwd_len)
{
int ret = -1;
/*
* 0. Initialize the RNG and the session data
*/
#if defined(MBEDTLS_DEBUG_C)
#if !defined(VOICELOUDER_APP)
//mbedtls_debug_set_threshold((int)DEBUG_LEVEL);
#endif
#endif
mbedtls_net_init(tcp_fd);
mbedtls_ssl_init(ssl);
mbedtls_ssl_config_init(conf);
mbedtls_x509_crt_init(crt509_ca);
/*verify_source->trusted_ca_crt==NULL
* 0. Initialize certificates
*/
M_LOGI("Loading the CA root certificate ...\n");
if (NULL != ca_crt) {
if (0 != (ret = mbedtls_x509_crt_parse(
crt509_ca, (const unsigned char *)ca_crt, ca_len))) {
M_LOGE(" failed ! x509parse_crt returned -0x%04x\n", -ret);
return ret;
}
}
M_LOGI(" ok (%d skipped)\n", ret);
/* Setup Client Cert/Key */
#if defined(MBEDTLS_X509_CRT_PARSE_C)
#if defined(MBEDTLS_CERTS_C)
mbedtls_x509_crt_init(crt509_cli);
mbedtls_pk_init(pk_cli);
#endif
if (cli_crt != NULL && cli_key != NULL) {
#if defined(MBEDTLS_CERTS_C)
M_LOGI("start prepare client cert .\n");
ret = mbedtls_x509_crt_parse(crt509_cli, (const unsigned char *)cli_crt,
cli_len);
#else
{
ret = 1;
M_LOGE("MBEDTLS_CERTS_C not defined.\n");
}
#endif
if (ret != 0) {
M_LOGE("failed ! mbedtls_x509_crt_parse returned -0x%x\n",
-ret);
return ret;
}
#if defined(MBEDTLS_CERTS_C)
M_LOGI("start mbedtls_pk_parse_key[%s]\n", cli_pwd);
ret =
mbedtls_pk_parse_key(pk_cli, (const unsigned char *)cli_key, key_len,
(const unsigned char *)cli_pwd, pwd_len);
#else
{
ret = 1;
M_LOGE("MBEDTLS_CERTS_C not defined.\n");
}
#endif
if (ret != 0) {
M_LOGE("failed ! mbedtls_pk_parse_key returned -0x%x\n",
-ret);
return ret;
}
}
#endif /* MBEDTLS_X509_CRT_PARSE_C */
return 0;
}
#if defined(_PLATFORM_IS_LINUX_)
static int net_prepare(void)
{
#if (defined(_WIN32) || defined(_WIN32_WCE)) && !defined(EFIX64) && \
!defined(EFI32)
WSADATA wsaData;
static int wsa_init_done = 0;
if (wsa_init_done == 0) {
if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0) {
return (MBEDTLS_ERR_NET_SOCKET_FAILED);
}
wsa_init_done = 1;
}
#else
#if !defined(EFIX64) && !defined(EFI32)
signal(SIGPIPE, SIG_IGN);
#endif
#endif
return (0);
}
static int mbedtls_net_connect_timeout(mbedtls_net_context *ctx,
const char *host, const char *port,
int proto, unsigned int timeout)
{
int ret;
struct addrinfo hints, *addr_list, *cur;
struct timeval sendtimeout;
if ((ret = net_prepare()) != 0) {
return (ret);
}
/* Do name resolution with both IPv6 and IPv4 */
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype =
proto == MBEDTLS_NET_PROTO_UDP ? SOCK_DGRAM : SOCK_STREAM;
hints.ai_protocol =
proto == MBEDTLS_NET_PROTO_UDP ? IPPROTO_UDP : IPPROTO_TCP;
hints.ai_socktype &= ~SOCK_NONBLOCK;
if (getaddrinfo(host, port, &hints, &addr_list) != 0) {
return (MBEDTLS_ERR_NET_UNKNOWN_HOST);
}
/* Try the sockaddrs until a connection succeeds */
ret = MBEDTLS_ERR_NET_UNKNOWN_HOST;
for (cur = addr_list; cur != NULL; cur = cur->ai_next) {
ctx->fd =
(int)socket(cur->ai_family, cur->ai_socktype, cur->ai_protocol);
if (ctx->fd < 0) {
ret = MBEDTLS_ERR_NET_SOCKET_FAILED;
continue;
}
sendtimeout.tv_sec = timeout;
sendtimeout.tv_usec = 0;
if (0 != setsockopt(ctx->fd, SOL_SOCKET, SO_SNDTIMEO, &sendtimeout,
sizeof(sendtimeout))) {
M_LOGE("setsockopt SO_SNDTIMEO error\n");
}
if (0 != setsockopt(ctx->fd, SOL_SOCKET, SO_RECVTIMEO, &sendtimeout,
sizeof(sendtimeout))) {
M_LOGE("setsockopt SO_RECVTIMEO error\n");
}
if (0 != setsockopt(ctx->fd, SOL_SOCKET, SO_SNDTIMEO, &sendtimeout,
sizeof(sendtimeout))) {
M_LOGE("setsockopt SO_SNDTIMEO error\n");
}
M_LOGI("setsockopt SO_SNDTIMEO SO_RECVTIMEO SO_SNDTIMEO timeout: %ds\n",
sendtimeout.tv_sec);
if (connect(ctx->fd, cur->ai_addr, cur->ai_addrlen) == 0) {
ret = 0;
break;
}
close(ctx->fd);
ret = MBEDTLS_ERR_NET_CONNECT_FAILED;
}
freeaddrinfo(addr_list);
return (ret);
}
#endif
/**
* @brief This function connects to the specific SSL server with TLS, and
* returns a value that indicates whether the connection is create successfully
* or not. Call #NewNetwork() to initialize network structure before calling
* this function.
* @param[in] n is the the network structure pointer.
* @param[in] addr is the Server Host name or IP address.
* @param[in] port is the Server Port.
* @param[in] ca_crt is the Server's CA certification.
* @param[in] ca_crt_len is the length of Server's CA certification.
* @param[in] client_crt is the client certification.
* @param[in] client_crt_len is the length of client certification.
* @param[in] client_key is the client key.
* @param[in] client_key_len is the length of client key.
* @param[in] client_pwd is the password of client key.
* @param[in] client_pwd_len is the length of client key's password.
* @sa #NewNetwork();
* @return If the return value is 0, the connection is created successfully. If
* the return value is -1, then calling lwIP #socket() has failed. If the return
* value is -2, then calling lwIP #connect() has failed. Any other value
* indicates that calling lwIP #getaddrinfo() has failed.
*/
static int _TLSConnectNetwork(TLSDataParams_t *pTlsData, const char *addr,
const char *port, const char *ca_crt,
size_t ca_crt_len, const char *client_crt,
size_t client_crt_len, const char *client_key,
size_t client_key_len, const char *client_pwd,
size_t client_pwd_len)
{
int ret = -1;
/*
* 0. Init
*/
if (0 != (ret = _ssl_client_init(
&(pTlsData->ssl), &(pTlsData->fd), &(pTlsData->conf),
&(pTlsData->cacertl), ca_crt, ca_crt_len, &(pTlsData->clicert),
client_crt, client_crt_len, &(pTlsData->pkey), client_key,
client_key_len, client_pwd, client_pwd_len))) {
M_LOGE(" failed ! ssl_client_init returned -0x%04x\n", -ret);
return ret;
}
/*
* 1. Start the connection
*/
M_LOGI("Connecting to /%s/%s...\n", addr, port);
#if defined(_PLATFORM_IS_LINUX_)
if (0 != (ret = mbedtls_net_connect_timeout(&(pTlsData->fd), addr, port,
MBEDTLS_NET_PROTO_TCP,
SEND_TIMEOUT_SECONDS))) {
M_LOGE(" failed ! net_connect returned -0x%04x\n", -ret);
return ret;
}
#else
if (0 != (ret = mbedtls_net_connect(&(pTlsData->fd), addr, port,
MBEDTLS_NET_PROTO_TCP))) {
M_LOGE(" failed ! net_connect returned -0x%04x\n", -ret);
return ret;
}
#endif
M_LOGI(" ok\n");
/*
* 2. Setup stuff
*/
M_LOGI(" . Setting up the SSL/TLS structure...\n");
if ((ret = mbedtls_ssl_config_defaults(
&(pTlsData->conf), MBEDTLS_SSL_IS_CLIENT,
MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
M_LOGE(" failed! mbedtls_ssl_config_defaults returned %d\n", ret);
return ret;
}
mbedtls_ssl_conf_max_version(&pTlsData->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
MBEDTLS_SSL_MINOR_VERSION_3);
mbedtls_ssl_conf_min_version(&pTlsData->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
MBEDTLS_SSL_MINOR_VERSION_3);
M_LOGI(" ok\n");
/* OPTIONAL is not optimal for security, but makes interop easier in this
* simplified example */
if (ca_crt != NULL) {
#if defined(FORCE_SSL_VERIFY)
mbedtls_ssl_conf_authmode(&(pTlsData->conf),
MBEDTLS_SSL_VERIFY_REQUIRED);
#else
mbedtls_ssl_conf_authmode(&(pTlsData->conf),
MBEDTLS_SSL_VERIFY_OPTIONAL);
#endif
} else {
mbedtls_ssl_conf_authmode(&(pTlsData->conf), MBEDTLS_SSL_VERIFY_NONE);
}
#if defined(MBEDTLS_X509_CRT_PARSE_C)
mbedtls_ssl_conf_ca_chain(&(pTlsData->conf), &(pTlsData->cacertl), NULL);
if ((ret = mbedtls_ssl_conf_own_cert(
&(pTlsData->conf), &(pTlsData->clicert), &(pTlsData->pkey))) != 0) {
M_LOGE(" failed\n ! mbedtls_ssl_conf_own_cert returned %d\n",
ret);
return ret;
}
#endif
mbedtls_ssl_conf_rng(&(pTlsData->conf), _ssl_random, NULL);
mbedtls_ssl_conf_dbg(&(pTlsData->conf), _ssl_debug, NULL);
/* mbedtls_ssl_conf_dbg( &(pTlsData->conf), _ssl_debug, stdout ); */
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
if ((ret = mbedtls_ssl_conf_max_frag_len( &(pTlsData->conf), MBEDTLS_SSL_MAX_FRAG_LEN_NONE)) != 0) {
M_LOGE(" failed\n ! mbedtls_ssl_conf_max_frag_len returned %d\n\n", ret);
return ret;
}
#endif
if ((ret = mbedtls_ssl_setup(&(pTlsData->ssl), &(pTlsData->conf))) != 0) {
M_LOGE("failed! mbedtls_ssl_setup returned %d\n", ret);
return ret;
}
mbedtls_ssl_set_hostname(&(pTlsData->ssl), addr);
mbedtls_ssl_set_bio(&(pTlsData->ssl), &(pTlsData->fd), mbedtls_net_send,
mbedtls_net_recv, mbedtls_net_recv_timeout);
/*
* 4. Handshake
*/
M_LOGI("Performing the SSL/TLS handshake...\n");
while ((ret = mbedtls_ssl_handshake(&(pTlsData->ssl))) != 0) {
if ((ret != MBEDTLS_ERR_SSL_WANT_READ) &&
(ret != MBEDTLS_ERR_SSL_WANT_WRITE)) {
M_LOGE("failed ! mbedtls_ssl_handshake returned -0x%04x\n",
-ret);
return ret;
}
}
M_LOGI(" ok\n");
/*
* 5. Verify the server certificate
*/
M_LOGI(" . Verifying peer X.509 certificate..\n");
if (0 != (ret = _real_confirm(
mbedtls_ssl_get_verify_result(&(pTlsData->ssl))))) {
M_LOGE(" failed ! verify result not confirmed.\n");
return ret;
}
/* n->my_socket = (int)((n->tlsdataparams.fd).fd); */
/* WRITE_IOT_DEBUG_LOG("my_socket=%d", n->my_socket); */
return 0;
}
static int _network_ssl_read(TLSDataParams_t *pTlsData, char *buffer, int len,
int timeout_ms)
{
uint32_t readLen = 0;
static int net_status = 0;
int ret = -1;
// char err_str[33] = {0};
mbedtls_ssl_conf_read_timeout(&(pTlsData->conf), timeout_ms);
while (readLen < len) {
ret = mbedtls_ssl_read(&(pTlsData->ssl),
(unsigned char *)(buffer + readLen),
(len - readLen));
if (ret > 0) {
readLen += ret;
net_status = 0;
} else if (ret == 0) {
/* if ret is 0 and net_status is -2, indicate the connection is
* closed during last call */
return (net_status == -2) ? net_status : readLen;
} else {
if (MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY == ret) {
// mbedtls_strerror(ret, err_str, sizeof(err_str));
M_LOGE("ssl recv error: code = %d\n", ret);
net_status = -2; /* connection is closed */
break;
} else if ((MBEDTLS_ERR_SSL_TIMEOUT == ret) ||
(MBEDTLS_ERR_SSL_CONN_EOF == ret) ||
(MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED == ret) ||
(MBEDTLS_ERR_SSL_WANT_READ == ret) ||
(MBEDTLS_ERR_SSL_NON_FATAL == ret)) {
/* read already complete */
/* if call mbedtls_ssl_read again, it will return 0 (means EOF)
*/
return readLen;
}
else {
// mbedtls_strerror(ret, err_str, sizeof(err_str));
#ifdef CSP_LINUXHOST
if (MBEDTLS_ERR_SSL_WANT_READ == ret && errno == EINTR) {
continue;
}
#endif
M_LOGE("ssl recv error: code = %d\n", ret);
net_status = -1;
return -1; /* Connection error */
}
}
}
return (readLen > 0) ? readLen : net_status;
}
static int _network_ssl_write(TLSDataParams_t *pTlsData, const char *buffer,
int len, int timeout_ms)
{
uint32_t writtenLen = 0;
int ret = -1;
while (writtenLen < len) {
ret = mbedtls_ssl_write(&(pTlsData->ssl),
(unsigned char *)(buffer + writtenLen),
(len - writtenLen));
if (ret > 0) {
writtenLen += ret;
continue;
} else if (ret == 0) {
M_LOGE("ssl write timeout\n");
return 0;
} else {
// mbedtls_strerror(ret, err_str, sizeof(err_str));
M_LOGE("ssl write fail, code=%d\n", ret);
return -1; /* Connnection error */
}
}
return writtenLen;
}
static void _network_ssl_disconnect(TLSDataParams_t *pTlsData)
{
mbedtls_ssl_close_notify(&(pTlsData->ssl));
mbedtls_net_free(&(pTlsData->fd));
#if defined(MBEDTLS_X509_CRT_PARSE_C)
mbedtls_x509_crt_free(&(pTlsData->cacertl));
if ((pTlsData->pkey).pk_info != NULL) {
M_LOGI("need release client crt&key\n");
#if defined(MBEDTLS_CERTS_C)
mbedtls_x509_crt_free(&(pTlsData->clicert));
mbedtls_pk_free(&(pTlsData->pkey));
#endif
}
#endif
mbedtls_ssl_free(&(pTlsData->ssl));
mbedtls_ssl_config_free(&(pTlsData->conf));
M_LOGI("ssl_disconnect\n");
}
#endif /* LINKKIT_SSL_ENABLE */
int32_t net_ssl_read(uintptr_t handle, char *buf, int len, int timeout_ms)
{
#ifdef LINKKIT_SSL_ENABLE
return HAL_SSL_Read(handle, buf, len, timeout_ms);
#else
return _network_ssl_read((TLSDataParams_t *)handle, buf, len, timeout_ms);
#endif
}
int32_t net_ssl_write(uintptr_t handle, const char *buf, int len,
int timeout_ms)
{
#ifdef LINKKIT_SSL_ENABLE
return HAL_SSL_Write(handle, buf, len, timeout_ms);
#else
return _network_ssl_write((TLSDataParams_t *)handle, buf, len, timeout_ms);
#endif
}
int32_t net_ssl_disconnect(uintptr_t handle)
{
#ifdef LINKKIT_SSL_ENABLE
return HAL_SSL_Destroy(handle);
#else
if ((uintptr_t)NULL == handle) {
M_LOGE("handle is NULL\n");
return 0;
}
_network_ssl_disconnect((TLSDataParams_t *)handle);
snd_free((void *)handle);
return 0;
#endif
}
uintptr_t net_ssl_connect(const char *host, uint16_t port, const char *ca_crt,
size_t ca_crt_len)
{
#ifdef LINKKIT_SSL_ENABLE
return HAL_SSL_Establish(host, port, ca_crt, ca_crt_len);
#else
char port_str[6];
TLSDataParams_pt pTlsData;
pTlsData = snd_zalloc(sizeof(TLSDataParams_t), AFM_MAIN);
if (NULL == pTlsData) {
return (uintptr_t)NULL;
}
memset(pTlsData, 0x0, sizeof(TLSDataParams_t));
sprintf(port_str, "%u", port);
if (0 != _TLSConnectNetwork(pTlsData, host, port_str, ca_crt, ca_crt_len,
NULL, 0, NULL, 0, NULL, 0)) {
M_LOGE("tls connect failed !\n");
_network_ssl_disconnect(pTlsData);
snd_free(pTlsData);
return (uintptr_t)NULL;
}
return (uintptr_t)pTlsData;
#endif
}
|
YifuLiu/AliOS-Things
|
components/uvoice/stream/uvoice_ssl.c
|
C
|
apache-2.0
| 19,098
|
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "uvoice_init.h"
#include "uvoice_event.h"
extern void uvoice_play_test(int argc, char **argv);
extern void uvoice_record_test(int argc, char **argv);
extern void test_tts_handle(int argc, char **argv);
static void handle_input(char *buffer)
{
char *ptr = buffer;
char *begin;
char *end;
char *temp;
int len;
int argc = 0;
int i;
char *argv[10];
if (!ptr)
return -1;
memset(argv, 0, sizeof(argv));
end = ptr + strlen(ptr) - 1;
while (*end == ' ' || *end == '\n') {
*end = '\0';
end--;
}
while (*ptr == ' ')
ptr++;
while (1) {
begin = ptr;
ptr = strchr(ptr, ' ');
if (!ptr) {
ptr = begin;
if (strlen(ptr) <= 0)
break;
if (strlen(ptr) > 0)
ptr += strlen(ptr);
}
end = ptr;
len = end - begin;
if (len <= 0)
break;
temp = malloc(len + 1);
if (!temp) {
printf("%s: alloc argv buffer failed !\n", __func__);
break;
}
memcpy(temp, begin, len);
temp[len] = '\0';
//printf("%s: argv[%d] %s\n", __func__, argc, temp);
argv[argc++] = temp;
while (*ptr == ' ')
ptr++;
}
if (argc <= 0)
return;
if (!strcmp(argv[0], "play"))
uvoice_play_test(argc, argv);
else if (!strcmp(argv[0], "record"))
uvoice_record_test(argc, argv);
else if (!strcmp(argv[0], "tts"))
test_tts_handle(argc, argv);
for (i = 0; i < argc; i++) {
if (argv[i]) {
//printf("%s: free argv[%d]\n", __func__, i);
free(argv[i]);
}
}
}
static void player_state_cb(uvoice_event_t *event, void *data)
{
//printf("%s: type %u code %u value %d\n", __func__, event->type, event->code, event->value);
}
int main(int argc, char **argv)
{
char buffer[2048];
uvoice_init();
uvoice_event_register(UVOICE_EV_PLAYER,
player_state_cb, NULL);
printf("\r>>> ");
memset(buffer, 0, sizeof(buffer));
while (fgets(buffer, sizeof(buffer), stdin)) {
if (!strncmp(buffer, "exit", strlen("exit")))
break;
handle_input(buffer);
printf("\r>>> ");
memset(buffer, 0, sizeof(buffer));
}
return 0;
}
|
YifuLiu/AliOS-Things
|
components/uvoice/test/test_main.c
|
C
|
apache-2.0
| 2,075
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "uvoice_types.h"
#include "uvoice_event.h"
#include "uvoice_player.h"
#include "uvoice_recorder.h"
#include "uvoice_os.h"
static os_task_t play_task;
static uvoice_player_t *uvocplayer;
static char text_source[256];
static int source_sample_rate;
static int source_channels;
static int get_format_from_name(char *name, media_format_t *format)
{
if (!name || !format) {
M_LOGE("arg null !\n");
return -1;
}
if (strstr(name, ".mp3") || strstr(name, ".MP3"))
*format = MEDIA_FMT_MP3;
else if (strstr(name, ".wav") || strstr(name, ".WAV"))
*format = MEDIA_FMT_WAV;
else if (strstr(name, ".aac") || strstr(name, ".AAC"))
*format = MEDIA_FMT_AAC;
else if (strstr(name, ".m4a") || strstr(name, ".M4A"))
*format = MEDIA_FMT_M4A;
else if (strstr(name, ".pcm") || strstr(name, ".PCM"))
*format = MEDIA_FMT_PCM;
else if (strstr(name, ".spx") || strstr(name, ".SPX"))
*format = MEDIA_FMT_SPX;
else if (strstr(name, ".ogg") || strstr(name, ".OGG"))
*format = MEDIA_FMT_OGG;
else if (strstr(name, ".amrwb") || strstr(name, ".AMRWB"))
*format = MEDIA_FMT_AMRWB;
else if (strstr(name, ".amr") || strstr(name, ".AMR"))
*format = MEDIA_FMT_AMR;
else if (strstr(name, ".opus") || strstr(name, ".OPUS"))
*format = MEDIA_FMT_OPS;
else if (strstr(name, ".flac") || strstr(name, ".FLAC"))
*format = MEDIA_FMT_FLAC;
return 0;
}
static void uvoice_st_event_cb(uvoice_event_t *event, void *data)
{
if (event->type != UVOICE_EV_ST)
return;
if (event->code == UVOICE_CODE_VAD_START)
printf("vad ---->begin\n");
else if (event->code == UVOICE_CODE_VAD_END)
printf("vad ---->end\n");
}
/* usage: play sine 16000 16 1 1000 */
static int play_sine_wave(int rate, int bits, int channels, int freq_hz)
{
#define PI 3.14159265
#define CYCLES_PER_PERIOD 8
if (freq_hz == 0) {
return -1;
}
unsigned int samples_per_cycle = rate / freq_hz;
unsigned int samples_per_period = samples_per_cycle * CYCLES_PER_PERIOD;
unsigned int sample_size = (bits >> 3) * channels;
if (bits != 8 && bits != 16 && bits != 24) {
M_LOGE("bits %d invalid !\n", bits);
return -1;
}
if (channels != 1 && channels != 2) {
M_LOGE("channels %d invalid !\n", channels);
return -1;
}
char *samples_data = snd_zalloc(sample_size * samples_per_cycle, AFM_MAIN);
if (!samples_data) {
M_LOGE("alloc samples_data failed !\n");
return -1;
}
char *period_buffer = snd_zalloc(sample_size * samples_per_period, AFM_MAIN);
if (!period_buffer) {
M_LOGE("alloc period_buffer failed !\n");
snd_free(samples_data);
return -1;
}
unsigned int msec_per_period = (samples_per_period * 1000) / rate;
unsigned int play_msec = 0;
unsigned int sample_val;
unsigned int sample_idx;
unsigned int cycle_idx;
double sin_float;
double triangle_float;
double triangle_step = (double)pow(2, bits) / samples_per_cycle;
M_LOGI("sample_size %d samper_per_cycly %d msec_per_period %d\n",
sample_size, samples_per_cycle, msec_per_period);
triangle_float = -(pow(2, bits) / 2 - 1);
for (sample_idx = 0; sample_idx < samples_per_cycle; sample_idx++) {
sin_float = sin(sample_idx * PI / 180.0);
if (sin_float >= 0)
triangle_float += triangle_step;
else
triangle_float -= triangle_step;
sin_float *= (pow(2, bits) / 2 - 1);
if (bits == 16) {
sample_val = 0;
sample_val += (short)triangle_float;
sample_val = sample_val << 16;
sample_val += (short)sin_float;
samples_data[sample_idx] = sample_val;
} else if (bits == 24) {
samples_data[sample_idx * 2] = ((int)triangle_float) << 8;
samples_data[sample_idx * 2 + 1] = ((int)sin_float) << 8;
} else {
samples_data[sample_idx * 2] = (int)triangle_float;
samples_data[sample_idx * 2 + 1] = (int)sin_float;
}
}
for (cycle_idx = 0; cycle_idx < CYCLES_PER_PERIOD; cycle_idx++) {
memcpy(period_buffer + cycle_idx * (sample_size * samples_per_cycle),
samples_data,
samples_per_cycle * sample_size);
}
M_LOGI("start\n");
player_state_t player_state = -1;
bool player_paused = false;
uvocplayer->get_state(&player_state);
if (player_state == PLAYER_STAT_RUNNING ||
player_state == PLAYER_STAT_COMPLETE) {
uvocplayer->set_fade(40, 60);
uvocplayer->pause();
player_paused = true;
}
uvocplayer->set_stream(MEDIA_FMT_PCM, 0, 0);
uvocplayer->set_pcminfo(rate, channels, bits, samples_per_period);
while (play_msec <= 5000) {
uvocplayer->put_stream(period_buffer, sample_size * samples_per_period);
play_msec += msec_per_period;
}
uvocplayer->clr_stream(1);
if (player_paused) {
uvocplayer->set_fade(40, 60);
uvocplayer->resume();
player_paused = false;
}
snd_free(period_buffer);
snd_free(samples_data);
M_LOGI("exit\n");
return 0;
}
static void play_music(void *arg)
{
media_format_t format = MEDIA_FMT_UNKNOWN;
get_format_from_name(text_source, &format);
if (uvocplayer->set_source(text_source)) {
M_LOGE("set source failed !\n");
os_task_exit(NULL);
return;
}
if (format == MEDIA_FMT_OPS || format == MEDIA_FMT_SPX)
uvocplayer->set_pcminfo(source_sample_rate, source_channels, 16, 1280);
if (uvocplayer->start()) {
M_LOGE("start failed !\n");
uvocplayer->clr_source();
}
os_task_exit(NULL);
}
static void play_loopback(void *arg)
{
#ifdef UVOICE_RECORDER_ENABLE
#define LOOPBACK_TEST_DURATION_SEC 20
unsigned char *read_buffer;
int read_samples = 640;
int channels = 2;
int rate = 32000;
int bits = 16;
int buffer_size;
int i = 0;
int count = (LOOPBACK_TEST_DURATION_SEC * 1000) / (read_samples / (rate / 1000));
buffer_size = read_samples * channels * (bits >> 3);
read_buffer = malloc(buffer_size);
if (!read_buffer) {
M_LOGE("alloc read buffer failed !\n");
os_task_exit(NULL);
return;
}
uvoice_recorder_t *mrecorder = uvoice_recorder_create();
if (!mrecorder) {
M_LOGE("create uvoice recorder failed !\n");
free(read_buffer);
os_task_exit(NULL);
return;
}
if (mrecorder->set_sink(MEDIA_FMT_PCM, rate, channels, bits, read_samples, 0, NULL)) {
M_LOGE("set record sink failed !\n");
uvoice_recorder_release(mrecorder);
free(read_buffer);
os_task_exit(NULL);
return;
}
uvocplayer->set_stream(MEDIA_FMT_PCM, 0, 0);
uvocplayer->set_pcminfo(rate, channels, bits, read_samples);
while (++i < count) {
mrecorder->get_stream(read_buffer, buffer_size);
uvocplayer->put_stream(read_buffer, buffer_size);
}
uvocplayer->clr_stream(0);
mrecorder->clr_sink();
uvoice_recorder_release(mrecorder);
free(read_buffer);
#endif
os_task_exit(NULL);
}
static void play_list_scan(void *arg)
{
#if (UVOICE_MLIST_ENABLE == 1)
mlist_source_scan();
#endif
os_task_exit(NULL);
}
static void play_list_del(void *arg)
{
#if (UVOICE_MLIST_ENABLE == 1)
mlist_source_del((int)arg);
#endif
os_task_exit(NULL);
}
static void play_list_set(void *arg)
{
#if (UVOICE_MLIST_ENABLE == 1)
mlist_index_set((int)arg);
#endif
os_task_exit(NULL);
}
static void play_equalizer_config(char *fc, char *width, char *gain)
{
#ifdef UVOICE_EQ_ENABLE
extern char equalizer_opt_fc[16];
extern char equalizer_opt_width[16];
extern char equalizer_opt_gain[16];
snprintf(equalizer_opt_fc, 16, "%s", fc);
snprintf(equalizer_opt_width, 16, "%s", width);
snprintf(equalizer_opt_gain, 16, "%s", gain);
#endif
}
static void play_number(char *num)
{
#ifdef UVOICE_COMB_ENABLE
comb_init();
comb_alipay_number(atof(num));
#endif
}
static void play_music_stream(void *arg)
{
media_format_t format = MEDIA_FMT_UNKNOWN;
FILE *fp;
int buffer_size = 2048;
char *buffer;
int ret;
get_format_from_name(text_source, &format);
fp = fopen(text_source, "rb");
if (!fp) {
M_LOGE("open %s failed !\n", text_source);
os_task_exit(NULL);
return;
}
buffer = malloc(buffer_size);
if (!buffer) {
M_LOGE("alloc buffer failed !\n");
fclose(fp);
os_task_exit(NULL);
return;
}
ret = fread(buffer, 1, buffer_size, fp);
if (ret <= 0) {
M_LOGE("read failed %d!\n", ret);
fclose(fp);
free(buffer);
os_task_exit(NULL);
return;
} else if (ret != buffer_size) {
M_LOGI("read %d ret %d\n", buffer_size, ret);
}
if (uvocplayer->set_stream(format, 0, 8192)) {
fclose(fp);
free(buffer);
os_task_exit(NULL);
return;
}
if (format == MEDIA_FMT_OPS || format == MEDIA_FMT_SPX)
uvocplayer->set_pcminfo(source_sample_rate, source_channels, 16, 320);
while (ret > 0) {
if (uvocplayer->put_stream(buffer, ret))
break;
ret = fread(buffer, 1, buffer_size, fp);
if (ret < 0) {
M_LOGE("read failed %d!\n", ret);
uvocplayer->clr_stream(1);
fclose(fp);
free(buffer);
os_task_exit(NULL);
return;
} else if (ret == 0) {
M_LOGI("read end\n");
break;
} else if (ret != buffer_size) {
M_LOGI("read %d ret %d\n", buffer_size, ret);
}
}
uvocplayer->clr_stream(0);
fclose(fp);
free(buffer);
os_task_exit(NULL);
}
void uvoice_play_test(int argc, char **argv)
{
if (!uvocplayer) {
uvocplayer = uvoice_player_create();
if (!uvocplayer) {
M_LOGE("create media player failed !\n");
return;
}
uvocplayer->eq_enable(0);
uvoice_event_register(UVOICE_EV_ST, uvoice_st_event_cb, NULL);
}
if (argc < 2 || strcmp(argv[0], "play"))
return;
if (!strcmp(argv[1], "stop")) {
uvocplayer->set_fade(40, 40);
uvocplayer->stop_async();
} else if (!strcmp(argv[1], "stopsync")) {
uvocplayer->set_fade(40, 40);
uvocplayer->stop();
} else if (!strcmp(argv[1], "source")) {
if (argc < 3)
return;
uvocplayer->set_source(argv[2]);
} else if (!strcmp(argv[1], "start")) {
uvocplayer->start();
} else if (!strcmp(argv[1], "clear")) {
uvocplayer->clr_source();
} else if (!strcmp(argv[1], "pause")) {
uvocplayer->set_fade(40, 40);
uvocplayer->pause_async();
} else if (!strcmp(argv[1], "pausesync")) {
uvocplayer->set_fade(40, 40);
uvocplayer->pause();
} else if (!strcmp(argv[1], "resume")) {
uvocplayer->set_fade(40, 40);
uvocplayer->resume();
} else if (!strcmp(argv[1], "complete")) {
uvocplayer->complete();
} else if (!strcmp(argv[1], "playback")) {
if (argc < 3)
return;
uvocplayer->playback(argv[2]);
} else if (!strcmp(argv[1], "dump")) {
uvocplayer->state_dump();
} else if (!strcmp(argv[1], "num")) {
if (argc < 3)
return;
play_number(argv[2]);
} else if (!strcmp(argv[1], "pcmdump")) {
uvocplayer->pcmdump_enable(atoi(argv[2]));
} else if (!strcmp(argv[1], "fade")) {
if (argc < 4)
return;
uvocplayer->set_fade(atoi(argv[2]), atoi(argv[3]));
} else if (!strcmp(argv[1], "sine")) {
if (argc < 6)
return;
play_sine_wave(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]), atoi(argv[5]));
} else if (!strcmp(argv[1], "progress")) {
int position = 0;
int duration = 0;
uvocplayer->get_position(&position);
uvocplayer->get_duration(&duration);
printf("progress: %d/%d\n", position, duration);
} else if (!strcmp(argv[1], "seek")) {
if (argc < 3)
return;
uvocplayer->seek(atoi(argv[2]));
} else if (!strcmp(argv[1], "format")) {
if (argc < 3)
return;
uvocplayer->set_format(atoi(argv[2]));
} else if (!strcmp(argv[1], "standby")) {
if (argc < 3)
return;
uvocplayer->set_standby(atoi(argv[2]));
} else if (!strcmp(argv[1], "state")) {
player_state_t state = -1;
uvocplayer->get_state(&state);
printf("state %d\n", state);
} else if (!strcmp(argv[1], "loopback")) {
os_task_create(&play_task,
"loopback task", play_loopback,
NULL, 8192, 0);
} else if (!strcmp(argv[1], "eq")) {
if (argc >= 5) {
#ifdef UVOICE_EQ_ENABLE
play_equalizer_config(argv[2], argv[3], argv[4]);
#endif
return;
}
uvocplayer->eq_enable(atoi(argv[2]));
} else if (!strcmp(argv[1], "list")) {
#if (UVOICE_MLIST_ENABLE == 1)
if (argc == 2) {
mlist_source_show();
return;
}
if (argc == 4 && !strcmp(argv[2], "index") && !strcmp(argv[3], "get")) {
int index = 0;
if (mlist_index_get(&index)) {
M_LOGE("get index failed !\n");
return;
}
M_LOGI("current source index %d\n", index);
return;
}
if (argc == 5 && !strcmp(argv[2], "index") && !strcmp(argv[3], "set")) {
os_task_create(&play_task,
"list set task", play_list_set,
atoi(argv[4]), 4096, 0);
return;
}
if (argc == 3 && !strcmp(argv[2], "scan")) {
os_task_create(&play_task,
"player scan task", play_list_scan,
NULL, 4096, 0);
return;
}
if (argc == 3) {
int index = atoi(argv[2]);
char file_path[128];
memset(file_path, 0, sizeof(file_path));
if (mlist_source_get(index, file_path, sizeof(file_path))) {
M_LOGE("search list failed !\n");
return;
}
uvocplayer->set_source(file_path);
uvocplayer->start();
return;
}
if (argc == 4 && !strcmp(argv[2], "del")) {
os_task_create(&play_task,
"player del task", play_list_del,
atoi(argv[3]), 4096, 0);
return;
}
#endif
} else if (!strcmp(argv[1], "cacheinfo")) {
int cache_len = 0;
uvocplayer->get_cacheinfo(&cache_len);
printf("avail cache len %d\n", cache_len);
} else if (!strcmp(argv[1], "download")) {
if (argc >= 3) {
if (!strcmp(argv[2], "abort"))
uvocplayer->download_abort();
else
uvocplayer->download(argv[2]);
} else {
uvocplayer->download(NULL);
}
} else if (!strcmp(argv[1], "stream")) {
if (argc < 3)
return;
if (!strcmp(argv[2], "stop")) {
uvocplayer->clr_stream(1);
return;
}
memset(text_source, 0, sizeof(text_source));
snprintf(text_source, sizeof(text_source), "%s", argv[2]);
media_format_t format = MEDIA_FMT_UNKNOWN;
get_format_from_name(text_source, &format);
if (format == MEDIA_FMT_OPS || format == MEDIA_FMT_SPX) {
if (argc < 5) {
M_LOGE("args too less for this format\n");
return;
}
source_sample_rate = atoi(argv[3]);
source_channels = atoi(argv[4]);
}
os_task_create(&play_task,
"stream play task", play_music_stream,
NULL, 4096, 0);
} else if (!strcmp(argv[1], "volume")) {
if (argc >= 3) {
uvocplayer->set_volume(atoi(argv[2]));
} else {
int volume = 0;
uvocplayer->get_volume(&volume);
printf("volume %d\n", volume);
}
} else {
memset(text_source, 0, sizeof(text_source));
snprintf(text_source, sizeof(text_source), "%s", argv[1]);
media_format_t format = MEDIA_FMT_UNKNOWN;
get_format_from_name(text_source, &format);
if (format == MEDIA_FMT_OPS || format == MEDIA_FMT_SPX) {
if (argc < 4) {
M_LOGE("args too less for this format\n");
return;
}
source_sample_rate = atoi(argv[2]);
source_channels = atoi(argv[3]);
}
os_task_create(&play_task,
"play music task", play_music,
NULL, 8192, 0);
}
}
|
YifuLiu/AliOS-Things
|
components/uvoice/test/test_player.c
|
C
|
apache-2.0
| 17,168
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "uvoice_types.h"
#include "uvoice_recorder.h"
#include "uvoice_os.h"
#define APP_LOGI(fmt, ...) printf("%s: "fmt, __func__, ##__VA_ARGS__)
#define APP_LOGE(fmt, ...) printf("%s: "fmt, __func__, ##__VA_ARGS__)
static uvoice_recorder_t *uvocrecorder;
static os_task_t record_task;
static int rec_rate;
static int rec_channels;
static int rec_bits;
static int rec_frames;
static int rec_bitrate;
static char rec_sink[64];
static int get_format_from_name(char *name, media_format_t *format)
{
if (!name || !format) {
APP_LOGE("arg null !\n");
return -1;
}
if (strstr(name, ".mp3") || strstr(name, ".MP3"))
*format = MEDIA_FMT_MP3;
else if (strstr(name, ".wav") || strstr(name, ".WAV"))
*format = MEDIA_FMT_WAV;
else if (strstr(name, ".aac") || strstr(name, ".AAC"))
*format = MEDIA_FMT_AAC;
else if (strstr(name, ".m4a") || strstr(name, ".M4A"))
*format = MEDIA_FMT_M4A;
else if (strstr(name, ".pcm") || strstr(name, ".PCM"))
*format = MEDIA_FMT_PCM;
else if (strstr(name, ".spx") || strstr(name, ".SPX"))
*format = MEDIA_FMT_SPX;
else if (strstr(name, ".ogg") || strstr(name, ".OGG"))
*format = MEDIA_FMT_OGG;
else if (strstr(name, ".amrwb") || strstr(name, ".AMRWB"))
*format = MEDIA_FMT_AMRWB;
else if (strstr(name, ".amr") || strstr(name, ".AMR"))
*format = MEDIA_FMT_AMR;
else if (strstr(name, ".opus") || strstr(name, ".OPUS"))
*format = MEDIA_FMT_OPS;
else if (strstr(name, ".flac") || strstr(name, ".FLAC"))
*format = MEDIA_FMT_FLAC;
return 0;
}
static void record_to_file(void)
{
uvocrecorder->set_sink(MEDIA_FMT_UNKNOWN, rec_rate, rec_channels,
rec_bits, rec_frames, rec_bitrate, rec_sink);
uvocrecorder->start();
os_task_exit(NULL);
}
void uvoice_record_test(int argc, char **argv)
{
if (!uvocrecorder) {
uvocrecorder = uvoice_recorder_create();
if (!uvocrecorder) {
APP_LOGE("create media recorder failed !\n");
return;
}
}
if (argc < 2 || strcmp(argv[0], "record"))
return;
if (!strcmp(argv[1], "stop")) {
uvocrecorder->stop();
} else if (!strcmp(argv[1], "start")) {
uvocrecorder->start();
} else if (!strcmp(argv[1], "clear")) {
uvocrecorder->clr_sink();
} else if (!strcmp(argv[1], "progress")) {
int position = 0;
uvocrecorder->get_position(&position);
printf("progress: %d\n", position);
} else if (!strcmp(argv[1], "state")) {
recorder_state_t state = -1;
uvocrecorder->get_state(&state);
printf("state %d\n", state);
} else if (!strcmp(argv[1], "ns")) {
if (argc < 3)
return;
if (!strcmp(argv[2], "enable"))
uvocrecorder->ns_enable(1);
else if (!strcmp(argv[2], "disable"))
uvocrecorder->ns_enable(0);
} else if (!strcmp(argv[1], "ec")) {
if (argc < 3)
return;
if (!strcmp(argv[2], "enable"))
uvocrecorder->ec_enable(1);
else if (!strcmp(argv[2], "disable"))
uvocrecorder->ec_enable(0);
} else if (!strcmp(argv[1], "agc")) {
if (argc < 3)
return;
if (!strcmp(argv[2], "enable"))
uvocrecorder->agc_enable(1);
else if (!strcmp(argv[2], "disable"))
uvocrecorder->agc_enable(0);
} else if (!strcmp(argv[1], "vad")) {
if (argc < 3)
return;
if (!strcmp(argv[2], "enable"))
uvocrecorder->vad_enable(1);
else if (!strcmp(argv[2], "disable"))
uvocrecorder->vad_enable(0);
} else {
if (argc < 7)
return;
rec_rate = atoi(argv[1]);
rec_channels = atoi(argv[2]);
rec_bits = atoi(argv[3]);
rec_frames = atoi(argv[4]);
rec_bitrate = atoi(argv[5]);
memset(rec_sink, 0, sizeof(rec_sink));
snprintf(rec_sink, sizeof(rec_sink), "%s", argv[6]);
os_task_create(&record_task,
"reord test task",
record_to_file, NULL, 4096, 0);
}
}
|
YifuLiu/AliOS-Things
|
components/uvoice/test/test_recorder.c
|
C
|
apache-2.0
| 4,333
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#ifdef AOS_NETMGR
#include "netmgr.h"
#endif
#include "uvoice_swid.h"
#define SOUND_SSID_FLOW_DISCONNECTED 0
#define SOUND_SSID_FLOW_MONITOR 1
#define SOUND_SSID_FLOW_CONNECTING 2
#define SOUND_SSID_FLOW_CONNECTED 3
static int sound_ssid_flow = SOUND_SSID_FLOW_DISCONNECTED;
static long long ssid_conn_time;
static bool uvoice_swid_initialized = false;
static int lisen_freq_result(char *result)
{
char *ssid;
char *passwd;
//printf("%s: %s\n", __func__, result);
if (sound_ssid_flow != SOUND_SSID_FLOW_MONITOR) {
if (sound_ssid_flow == SOUND_SSID_FLOW_CONNECTING) {
if (aos_now_ms() - ssid_conn_time > 10000)
sound_ssid_flow = SOUND_SSID_FLOW_MONITOR;
else
return 0;
} else {
return 0;
}
}
ssid = result;
passwd = strchr(result, '\n');
if (!passwd) {
printf("%s: no enter char\n", __func__);
return -1;
}
//sound_ssid_flow = SOUND_SSID_FLOW_CONNECTING;
//ssid_conn_time = aos_now_ms();
*passwd = '\0';
passwd++;
printf("ssid: %s, passwd: %s\n", ssid, passwd);
return 0;
netmgr_ap_config_t config;
memcpy(config.ssid, ssid, strlen(ssid) + 1);
memcpy(config.pwd, passwd, strlen(passwd) + 1);
netmgr_set_ap_config(&config);
printf("connect to '%s'\n", config.ssid);
netmgr_start(false);
return 0;
}
static void lisen_freq_start(void)
{
sound_ssid_flow = SOUND_SSID_FLOW_MONITOR;
uvoice_swid_start(lisen_freq_result);
}
static void lisen_freq_stop(void)
{
if (sound_ssid_flow == SOUND_SSID_FLOW_CONNECTING)
sound_ssid_flow = SOUND_SSID_FLOW_CONNECTED;
uvoice_swid_stop();
}
void test_swid_handle(int argc, char **argv)
{
if (!uvoice_swid_initialized) {
uvoice_swid_init();
uvoice_swid_initialized = true;
}
if (argc >= 2) {
if (!strcmp(argv[1], "off")) {
lisen_freq_stop();
} else {
lisen_freq_start();
}
return;
}
lisen_freq_start();
}
|
YifuLiu/AliOS-Things
|
components/uvoice/test/test_swid.c
|
C
|
apache-2.0
| 1,981
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "uvoice_types.h"
#include "uvoice_tts.h"
#include "../internal/uvoice_os.h"
#define APP_LOGI(fmt, ...) printf("%s: "fmt, __func__, ##__VA_ARGS__)
#define APP_LOGE(fmt, ...) printf("%s: "fmt, __func__, ##__VA_ARGS__)
static os_task_t voicelouder_task;
static char tts_text[128];
static char tts_filename[128];
static bool tts_configred = false;
static int alicloud_tts_config(void)
{
tts_config_t tts_config;
uvoice_tts_t *tts;
int ret;
/** 请开发者根据个人在智能语音交互平台的账号信息,更新下面的app_key和token
* https://nls-portal.console.aliyun.com/overview
**/
tts_config.app_key = "NULL";
tts_config.token = "NULL";
tts_config.format = MEDIA_FMT_MP3;
tts_config.sample_rate = 16000;
tts_config.voice = "siqi";
tts_config.volume = 80;
tts_config.speech_rate = 0;
tts_config.pitch_rate = 0;
tts_config.text_encode_type = TTS_ENCODE_UTF8;
if(0 == strcmp(tts_config.app_key, "NULL")) {
printf("aliyun tts need app key and token !!!\r\n");
printf("help document: https://help.aliyun.com/document_detail/72153.html\n");
return -1;
}
tts = uvoice_tts_create();
if (!tts) {
APP_LOGE("create tts failed !\n");
return -1;
}
if (tts->tts_init(TTS_AICLOUD_ALIYUN, &tts_config)) {
APP_LOGE("config tts failed !\n");
uvoice_tts_release(tts);
return -1;
}
APP_LOGI("config tts success\n");
return 0;
}
static int alicoud_tts_event(tts_event_e event, char *info)
{
return 0;
}
static int alicloud_tts_recv_data(uint8_t *buffer, int nbytes, int index)
{
FILE *fp;
if (index == 0) {
fp = fopen(tts_filename, "w");
if (!fp) {
printf("%s: open %s failed !\n", __func__, tts_filename);
return -1;
}
} else {
fp = fopen(tts_filename, "a+");
if (!fp) {
printf("%s: open %s failed !\n", __func__, tts_filename);
return -1;
}
}
printf("write data %d size %d to file %s\n",
index, nbytes, tts_filename);
fwrite(buffer, nbytes, 1, fp);
fclose(fp);
return 0;
}
static void alicloud_tts_download_task(void *arg)
{
tts_recv_callback_t recv_cb;
uvoice_tts_t *tts;
int ret = 0;
if (!tts_configred) {
ret = alicloud_tts_config();
if(ret != 0) {
printf("tts download %s fail\n", tts_filename);
return;
}
tts_configred = true;
}
tts = uvoice_tts_create();
if (!tts) {
APP_LOGE("create tts failed !\n");
return;
}
recv_cb.event = alicoud_tts_event;
recv_cb.recv_data = alicloud_tts_recv_data;
ret = tts->tts_request(tts_text, TTS_RECV_DATA, &recv_cb);//uvoice_tts_aliyun_request()
if (ret != 0) {
printf("tts failed\n");
return;
}
printf("tts download %s success\n", tts_filename);
}
int alicloud_tts_download(char *text, char *filename)
{
if (!text || !filename) {
APP_LOGE("args null !\n");
return -1;
}
memset(tts_text, 0, sizeof(tts_text));
snprintf(tts_text, sizeof(tts_text), "%s", text);
memset(tts_filename, 0, sizeof(tts_filename));
snprintf(tts_filename, sizeof(tts_filename), "%s", filename);
os_task_create(&voicelouder_task, "tts_download_task",
alicloud_tts_download_task,
NULL, 8192*2, UVOICE_TASK_PRI_NORMAL);
return 0;
}
void test_tts_handle(int argc, char **argv)
{
if (argc < 3)
return;
alicloud_tts_download(argv[1], argv[2]);
}
|
YifuLiu/AliOS-Things
|
components/uvoice/test/test_tts.c
|
C
|
apache-2.0
| 3,676
|
# -*- coding: utf-8 -*-
import os
import sys
import math
import wave
import struct
import numpy as np
max_volume = 0.85
max_short = 32767
min_short = -32768
sample_rate = 16000
min_freq = 1700
max_freq = 1700 + 96 * 50 + 100
freq_inc = 50
time_inc = 0.1
def gen_voice_freq(freq, times):
unit_sample = int(sample_rate*times)
theta_inc = 2 * math.pi * freq / sample_rate
df = sample_rate / (unit_sample - 1)
theta = 0
buffer = []
for frame in range(unit_sample):
tmp = math.pow(frame - unit_sample/2, 2) / math.pow(unit_sample/2, 2)
vol = max_volume * math.sqrt(1 - tmp)
fv_float = vol * math.cos(theta)
fv_float_16 = int(max_short * fv_float)
if fv_float_16 > max_short:
fv_float_16 = max_short
if fv_float_16 < min_short:
fv_float_16 = min_short
buffer.append(fv_float_16)
theta += theta_inc
if theta > 2.0 * math.pi:
theta -= 2.0 * math.pi
print('freq: %d' %freq)
Y = np.fft.fft(buffer)*2/unit_sample
absY = [np.abs(x) for x in Y]
#print(absY)
print(int(np.argmax(absY)*df))
return buffer
'''
i = 0
while i < len(absY):
if absY[i] > 0.01:
print("freq: %d, Y: %5.2f + %5.2f j, A:%3.2f, phi: %6.1f" % (i, Y[i].real, Y[i].imag, absY[i], math.atan2(Y[i].imag, Y[i].real)*180/math.pi))
i+=1
'''
def gen_voice(text, wav_file):
wave_data = []
wave_data += gen_voice_freq(min_freq - 50, 0.128)
for c in text:
if c == '\n' :
freq = max_freq
print('max freq : %d' % freq)
else :
freq = min_freq + (ord(c) - 33)*freq_inc
wave_data += gen_voice_freq(freq, 0.128)
freq = min_freq + (ord('f') - 33)*freq_inc
wave_data += gen_voice_freq(freq, 0.128)
freq = min_freq + (ord('c') - 33)*freq_inc
wave_data += gen_voice_freq(freq, 0.128)
wave_data += gen_voice_freq(min_freq - 50, 0.128)
f = wave.open(wav_file,"wb")
f.setnchannels(1)
f.setsampwidth(2)
f.setframerate(sample_rate)
for data in wave_data:
f.writeframes(struct.pack('h', int(data)))
f.close()
def main(args):
gen_voice("h3c_router01\n123456", "test.wav")
#gen_voice_freq(5650, 0.1)
if __name__ == '__main__':
main(sys.argv[1:])
|
YifuLiu/AliOS-Things
|
components/uvoice/tools/gen_voice.py
|
Python
|
apache-2.0
| 2,331
|
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "uvoice_os.h"
int uvoice_event_init(void);
int audio_device_init(void);
int uvoice_init(void)
{
if (uvoice_event_init()) {
M_LOGE("init uvoice event failed !\n");
return -1;
}
if (audio_device_init()) {
M_LOGE("init audio device failed !\n");
return -1;
}
M_LOGR("uvoice release v%d.%d @%s, %s\n",
UVOICE_RELEASE_VERSION_MAIN,
UVOICE_RELEASE_VERSION_SUB, __TIME__, __DATE__);
return 0;
}
int uvoice_free(void)
{
return 0;
}
|
YifuLiu/AliOS-Things
|
components/uvoice/uvoice.c
|
C
|
apache-2.0
| 607
|
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include "vfs_types.h"
#include "vfs_api.h"
#if AOS_COMP_CLI
#include "aos/cli.h"
#endif
static int32_t driver_vfs_open(vfs_file_t *fp, const char *path, int32_t flags)
{
printf("%s\n", __func__);
return 0;
}
static int32_t driver_vfs_close(vfs_file_t *fp)
{
printf("%s\n", __func__);
return 0;
}
static int32_t driver_vfs_read(vfs_file_t *fp, char *buf, uint32_t len)
{
printf("%s\n", __func__);
return 0;
}
static int32_t driver_vfs_write(vfs_file_t *fp, const char *buf, uint32_t len)
{
printf("%s\n", __func__);
return 0;
}
static int32_t driver_vfs_ioctl(vfs_file_t *fp, int32_t cmd, uint32_t arg)
{
printf("%s\n", __func__);
return 0;
}
static uint32_t driver_vfs_lseek(vfs_file_t *fp, int64_t off, int32_t whence)
{
printf("%s\n", __func__);
return 0;
}
vfs_file_ops_t driver_ops = {
.open = &driver_vfs_open,
.close = &driver_vfs_close,
.read = &driver_vfs_read,
.write = &driver_vfs_write,
.ioctl = &driver_vfs_ioctl,
.lseek = &driver_vfs_lseek,
};
static void driver_vfs_example(void)
{
char *mount_path = "/dev";
int ret = 0;
char *buf[10];
uint32_t len = 0;
int fd = 0;
int32_t cmd = 0;
uint32_t arg = 0;
int64_t off = 0;
int32_t whence = 0;
printf("driver vfs example start\r\n");
ret = vfs_register_driver(mount_path, &driver_ops, NULL);
if (ret < 0) {
printf("vfs_register_driver failed!\n");
return;
}
fd = vfs_open(mount_path, O_WRONLY);
if (fd < 0) {
printf("vfs_open failed!\n");
vfs_unregister_driver(mount_path);
return;
}
vfs_read(fd, buf, len);
vfs_write(fd, buf, len);
vfs_ioctl(fd, cmd, arg);
vfs_lseek(fd, off, whence);
vfs_close(fd);
vfs_unregister_driver(mount_path);
printf("driver vfs example end\r\n");
}
static int32_t fs_vfs_open(vfs_file_t *fp, const char *path, int32_t flags)
{
printf("%s\n", __func__);
return 0;
}
static int32_t fs_vfs_close(vfs_file_t *fp)
{
printf("%s\n", __func__);
return 0;
}
static int32_t fs_vfs_read(vfs_file_t *fp, char *buf, uint32_t len)
{
printf("%s\n", __func__);
return 0;
}
static int32_t fs_vfs_write(vfs_file_t *fp, const char *buf, uint32_t len)
{
printf("%s\n", __func__);
return 0;
}
vfs_filesystem_ops_t fs_ops = {
.open = &fs_vfs_open,
.close = &fs_vfs_close,
.read = &fs_vfs_read,
.write = &fs_vfs_write,
};
static void fs_vfs_example(void)
{
char *mount_path = "/fs";
int ret = 0;
char *buf[10];
uint32_t len = 0;
int fd = 0;
printf("fs vfs example start\r\n");
ret = vfs_register_fs(mount_path, &fs_ops, NULL);
if (ret < 0) {
printf("vfs_register_fs failed!\n");
return;
}
fd = vfs_open(mount_path, O_WRONLY | O_CREAT | O_TRUNC);
if (fd < 0) {
printf("vfs_open failed!\n");
vfs_unregister_fs(mount_path);
return;
}
vfs_read(fd, buf, len);
vfs_write(fd, buf, len);
vfs_close(fd);
vfs_unregister_fs(mount_path);
printf("fs vfs example end\r\n");
}
static void vfs_comp_example(int argc, char **argv)
{
driver_vfs_example();
fs_vfs_example();
printf("vfs example test success!\r\n");
}
#if AOS_COMP_CLI
/* reg args: fun, cmd, description*/
ALIOS_CLI_CMD_REGISTER(vfs_comp_example, vfs_example, vfs component base example)
#endif
|
YifuLiu/AliOS-Things
|
components/vfs/example/vfs_example.c
|
C
|
apache-2.0
| 3,633
|
/**
* @file vfs.h
* @copyright Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#ifndef AOS_VFS_H
#define AOS_VFS_H
#include <stddef.h>
#include <stdint.h>
#include <unistd.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifdef __cplusplus
extern "C" {
#endif
/** @addtogroup aos_vfs VFS
* VFS AOS API.
*
* @{
*/
/**
* @brief aos_utimbuf structure describes the filesystem inode's
* last access time and last modification time.
*/
struct aos_utimbuf {
time_t actime; /**< time of last access */
time_t modtime; /**< time of last modification */
};
struct aos_statfs {
long f_type; /**< fs type */
long f_bsize; /**< optimized transport block size */
long f_blocks; /**< total blocks */
long f_bfree; /**< available blocks */
long f_bavail; /**< number of blocks that non-super users can acquire */
long f_files; /**< total number of file nodes */
long f_ffree; /**< available file nodes */
long f_fsid; /**< fs id */
long f_namelen; /**< max file name length */
};
struct aos_stat {
uint16_t st_mode; /**< mode of file */
uint32_t st_size; /**< bytes of file */
time_t st_actime; /**< time of last access */
time_t st_modtime; /**< time of last modification */
};
typedef struct {
int32_t d_ino; /**< file number */
uint8_t d_type; /**< type of file */
char d_name[]; /**< file name */
} aos_dirent_t;
typedef struct {
int32_t dd_vfs_fd; /**< file index in vfs */
int32_t dd_rsv; /**< Reserved */
} aos_dir_t;
typedef const struct file_ops file_ops_t;
typedef const struct fs_ops fs_ops_t;
union inode_ops_t {
const file_ops_t *i_ops; /**< char driver operations */
const fs_ops_t *i_fops; /**< FS operations */
};
typedef struct {
union inode_ops_t ops; /**< inode operations */
void *i_arg; /**< per inode private data */
char *i_name; /**< name of inode */
int i_flags; /**< flags for inode */
uint8_t type; /**< type for inode */
uint8_t refs; /**< refs for inode */
} inode_t;
typedef struct {
inode_t *node; /**< node for file */
void *f_arg; /**< f_arg for file */
size_t offset; /**< offset for file */
} file_t;
typedef void (*poll_notify_t)(void *pollfd, void *arg);
/**
* @brief file_ops structure defines the file operation handles
*/
struct file_ops {
int (*open)(inode_t *node, file_t *fp);
int (*close)(file_t *fp);
ssize_t (*read)(file_t *fp, void *buf, size_t nbytes);
ssize_t (*write)(file_t *fp, const void *buf, size_t nbytes);
int (*ioctl)(file_t *fp, int cmd, unsigned long arg);
int (*poll)(file_t *fp, int flag, poll_notify_t notify, void *fd, void *arg);
uint32_t (*lseek)(file_t *fp, int64_t off, int32_t whence);
int (*stat)(file_t *fp, const char *path, struct aos_stat *st);
void* (*mmap)(file_t *fp, size_t len);
int (*access)(file_t *fp, const char *path, int amode);
};
/**
* @brief fs_ops structures defines the filesystem operation handles
*/
struct fs_ops {
int (*open)(file_t *fp, const char *path, int flags);
int (*close)(file_t *fp);
ssize_t (*read)(file_t *fp, char *buf, size_t len);
ssize_t (*write)(file_t *fp, const char *buf, size_t len);
off_t (*lseek)(file_t *fp, off_t off, int whence);
int (*sync)(file_t *fp);
int (*stat)(file_t *fp, const char *path, struct aos_stat *st);
int (*fstat)(file_t *fp, struct aos_stat *st);
int (*link)(file_t *fp, const char *path1, const char *path2);
int (*unlink)(file_t *fp, const char *path);
int (*remove)(file_t *fp, const char *path);
int (*rename)(file_t *fp, const char *oldpath, const char *newpath);
aos_dir_t *(*opendir)(file_t *fp, const char *path);
aos_dirent_t *(*readdir)(file_t *fp, aos_dir_t *dir);
int (*closedir)(file_t *fp, aos_dir_t *dir);
int (*mkdir)(file_t *fp, const char *path);
int (*rmdir)(file_t *fp, const char *path);
void (*rewinddir)(file_t *fp, aos_dir_t *dir);
long (*telldir)(file_t *fp, aos_dir_t *dir);
void (*seekdir)(file_t *fp, aos_dir_t *dir, long loc);
int (*ioctl)(file_t *fp, int cmd, unsigned long arg);
int (*statfs)(file_t *fp, const char *path, struct aos_statfs *suf);
int (*access)(file_t *fp, const char *path, int amode);
long (*pathconf)(file_t *fp, const char *path, int name);
long (*fpathconf)(file_t *fp, int name);
int (*utime)(file_t *fp, const char *path, const struct aos_utimbuf *times);
};
/**
* @brief aos_vfs_init() initializes vfs system.
*
* @param[in] NULL
*
* @return On success, return new file descriptor.
* On error, negative error code is returned to indicate the cause
* of the error.
*/
int aos_vfs_init(void);
/**
* @brief aos_open() opens the file or device by its @path.
*
* @param[in] path the path of the file or device to open.
* @param[in] flags the mode of open operation.
*
* @return On success, return new file descriptor.
* On error, negative error code is returned to indicate the cause
* of the error.
*/
int aos_open(const char *path, int flags);
/**
* @brief aos_close() closes the file or device associated with file
* descriptor @fd.
*
* @param[in] fd the file descriptor of the file or device.
*
* @return On success, return 0.
* On error, negative error code is returned to indicate the cause
* of the error.
*/
int aos_close(int fd);
/**
* @brief aos_read() attempts to read up to @nbytes bytes from file
* descriptor @fd into the buffer starting at @buf.
*
* @param[in] fd the file descriptor of the file or device.
* @param[out] buf the buffer to read bytes into.
* @param[in] nbytes the number of bytes to read.
*
* @return On success, the number of bytes is returned (0 indicates end
* of file) and the file position is advanced by this number.
* On error, negative error code is returned to indicate the cause
* of the error.
*/
ssize_t aos_read(int fd, void *buf, size_t nbytes);
/**
* @brief aos_write() writes up to @nbytes bytes from the buffer starting
* at @buf to the file referred to by the file descriptor @fd.
*
* @param[in] fd the file descriptor of the file or device.
* @param[in] buf the buffer to write bytes from.
* @param[in] nbytes the number of bytes to write.
*
* @return On success, the number of bytes written is returned, adn the file
* position is advanced by this number..
* On error, negative error code is returned to indicate the cause
* of the error.
*/
ssize_t aos_write(int fd, const void *buf, size_t nbytes);
/**
* @brief aos_ioctl() manipulates the underlying device parameters of special
* files. In particular, many operating characteristics of character
* special filse may be controlled with aos_iotcl() requests. The argumnet
* @fd must be an open file descriptor.
*
* @param[in] fd the file descriptior of the file or device.
* @param[in] cmd A device-dependent request code.
* @param[in] arg Argument to the request code, which is interpreted according
* to the request code.
*
* @return Usually, on success 0 is returned. Some requests use the return
* value as an output parameter and return a nonnegative value on success.
* On error, neagtive error code is returned to indicate the cause
* of the error.
*/
int aos_ioctl(int fd, int cmd, unsigned long arg);
/**
* @brief aos_do_pollfd() is a wildcard API for executing the particular poll events
*
* @param[in] fd The file descriptor of the file or device
* @param[in] flag The flag of the polling
* @param[in] notify The polling notify callback
* @param[in] fds A pointer to the array of pollfd
* @param[in] arg The arguments of the polling
*
* @return On success, return 0.
* On error, negative error code is returned to indicate the cause
* of the error.
*/
int aos_do_pollfd(int fd, int flag, poll_notify_t notify, void *fds, void *arg);
/**
* @brief aos_lseek() repositions the file offset of the open file
* description associated with the file descriptor @fd to the
* argument @offset according to the directive @whence as follows:
*
* SEEK_SET: The file offset is set to @offset bytes.
* SEEK_CUR: The file offset is set to its current location
* plus @offset bytes.
* SEEK_END: The file offset is set to the size of the file
* plus @offset bytes.
*
* @param[in] fd The file descriptor of the file.
* @param[in] offset The offset relative to @whence directive.
* @param[in] whence The start position where to seek.
*
* @return On success, return the resulting offset location as measured
* in bytes from the beginning of the file.
* On error, neagtive error code is returned to indicate the cause
* of the error.
*/
off_t aos_lseek(int fd, off_t offset, int whence);
/**
* @brief truncate a file to a specified size
*
* @param[in] fd the file descriptor of the file
* @param[in] size the new size of the file
* @return 0 on success, negative error on failure
*
*/
int aos_ftruncate(int fd, off_t size);
/**
* @brief truncate a file to a specified size
*
* @param[in] path the file path of the file
* @param[in] size the new size of the file
*
* @return 0 on success, negative error on failure
*
*/
int aos_truncate(const char *path, off_t size);
/**
* @brief aos_sync causes the pending modifications of the specified file to
* be written to the underlying filesystems.
*
* @param[in] fd the file descriptor of the file.
*
* @return On success return 0.
* On error, negative error code is returned to indicate the cause
* of the error.
*/
int aos_sync(int fd);
/**
* @brief aos_allsync causes all pending modifications to filesystem metadata
* and cached file data to be written to the underlying filesystems.
*
* @return none
*/
void aos_allsync(void);
/**
* @brief aos_stat() return information about a file pointed to by @path
* in the buffer pointed to by @st.
*
* @param[in] path The path of the file to be quried.
* @param[out] st The buffer to receive information.
*
* @return On success, return 0.
* On error, negative error code is returned to indicate the cause
* of the error.
*/
int aos_stat(const char *path, struct aos_stat *st);
/**
* @brief aos_fstat() return information about a file specified by the file
* descriptor @fd in the buffer pointed to by @st.
*
* @note aos_fstat() is identical to aos_stat(), except that the file about
* which information is to be retrieved is specified by the file
* descriptor @fd.
*
* @param[in] fd The file descriptor of the file to be quired.
* @param[out] st The buffer to receive information.
*
* @return On success, return 0.
* On error, negative error code is returned to indicate the cause
* of the error.
*/
int aos_fstat(int fd, struct aos_stat *st);
/**
* @brief aos_link() creates a new link @newpath to an existing file @oldpath.
*
* @note If @newpath exists, it will not be ovrewritten.
*
* @param[in] oldpath The old path
* @param[in] newpath The new path to be created
*
* @return On success, return 0.
* On error, negative error code is returned to indicate the cause
* of the error.
*/
int aos_link(const char *oldpath, const char *newpath);
/**
* @brief aos_unlink() deletes a name from the filesystem.
*
* @param[in] path The path of the file to be deleted.
*
* @return On success, return 0.
* On error, negative error code is returned to indicate the cause
* of the error.
*/
int aos_unlink(const char *path);
/**
* @brief aos_remove() deletes a name from the filesystem.
*
* @param[in] path The path of the file to be deleted.
*
* @return On success, return 0.
* On error, negative error code is returned to indicate the cause
* of the error.
*/
int aos_remove(const char *path);
/**
* @brief aos_rename() renames a file, moving it between directories
* if required.
*
* @param[in] oldpath The old path of the file to rename.
* @param[in] newpath The new path to rename the file to.
*
* @return On success, return 0.
* On error, negative error code is returned to indicate the cause
* of the error.
*/
int aos_rename(const char *oldpath, const char *newpath);
/**
* @brief aos_opendir() opens a directory stream corresponding to the
* directory @path, and returns a pointer to the directory stream.
* The stream is positioned at the first entry in the directory.
*
* @param[in] path the path of the directory to open.
*
* @return On success, return a point of directory stream.
* On error, NULL is returned.
*/
aos_dir_t *aos_opendir(const char *path);
/**
* @brief aos_closedir() closes the directory stream associated with
* @dir. A successful call to aos_closedir() also closes the
* underlying file descriptor associated with @dir. The directory
* stream descriptor @dir is not available after this call.
*
* @param[in] dir The directory stream descriptor to be closed.
*
* @return On success, return 0.
* On error, negative error code is returned to indicate the cause
* of the error.
*/
int aos_closedir(aos_dir_t *dir);
/**
* @brief aos_readdir() returns a pointer to an @aos_dirent_t representing
* the next directory entry in the directory stream pointed to by
* @dir. It returns Null on reaching the end of the directory stream
* or if an error occurred.
*
* @param[in] dir The directory stream descriptor to read.
*
* @return On success, aos_readdir() returns a pointer to an @aos_dirent_t
* structure. If the end of the directory stream is reached, NULL is
* returned.
* On error, NULL is returned.
*/
aos_dirent_t *aos_readdir(aos_dir_t *dir);
/**
* @brief aos_mkdir() attempts to create a directory named @path
*
* @param[in] path The name of directory to be created.
*
* @return On success, return 0.
* On error, negative error code is returned to indicate the cause
* of the error.
*/
int aos_mkdir(const char *path);
/**
* @brief aos_rmdir() deletes a directory, which must be emtpy.
*
* @param[in] path The directory to be deleted.
*
* @return On success, return 0.
* On error, negative error code is returned to indicate the cause
* of the error.
*/
int aos_rmdir(const char *path);
/**
* @brief aos_rewinddir() resets the position of the directory stream @dir
* to the beginning of the directory.
*
* @param[in] dir The directory stream descriptor pointer.
*
* @return none.
*/
void aos_rewinddir(aos_dir_t *dir);
/**
* @brief aos_telldir() returns the current location associated with the
* directory stream @dir.
*
* @param[in] dir The directory stream descriptor pointer.
*
* @return On success, aos_telldir() returns the current location in the
* directory stream.
* On error, negative error code is returned to indicate the cause
* of the error.
*/
long aos_telldir(aos_dir_t *dir);
/**
* @brief aos_seekdir() sets the location in the directory stram from
* which the next aos_readdir() call will start. The @loc argument
* should be a value returnned by a previous call to aos_telldir().
*
* @param[in] dir The directory stream descriptor pointer.
* @param[in] loc The location in the directory stream from which the next
* aos_readdir() call will start.
*
* @return none.
*/
void aos_seekdir(aos_dir_t *dir, long loc);
/**
* @brief aos_statfs() gets information about a mounted filesystem.
*
* @param[in] path The path name of any file within the mounted filessytem.
* @param[out] buf Buffer points to an aos_statfs structure to receive
* filesystem information.
*
* @return On success, return 0.
* On error, negative error code is returned to indicate the cause
* of the error.
*/
int aos_statfs(const char *path, struct aos_statfs *buf);
/**
* @brief aos_access() checks whether the calling process can access the
* file @path.
*
* @param[in] path The path of the file.
* @param[in] mode Specifies the accessibility check(s) to be performed, and
* is either the value of F_OK, or a mask consisting of the
* bitwise OR of one or more of R_OK, W_OK, and X_OK. F_OK
* tests for the existence of the file. R_OK, W_OK and X_OK
* tests whether the file exists and grants read, write, and
* execute permissions, repectively.
*
* @return On success (all requested permissions granted, or mode is F_OK and
* the file exists), 0 is returned.
* On error (at least one bit in mode asked for a permission that is
* denied, or mode is F_OK and the file does not exist, or some other
* error occurred), negative error code is returned to indicate the
* cause of the error.
*/
int aos_access(const char *path, int amode);
/**
* @brief aos_chdir() changes the current working directory of the calling
* process to the directory specified in @path.
*
* @param[in] path The path to change to.
*
* @return On success return 0.
* On error, negative error code is returned to indicate the cause
* of the error.
*/
int aos_chdir(const char *path);
/**
* @brief aos_getcwd() return a null-terminated string containing an absolute
* pathname that is the current working directory of the calling process.
* The pathname is returned as the function result and via the argument
* @buf, if present.
* aos_getcwd() function copies an absolute pathname of the current
* working directory to the array pointed by @buf, which is of length @size.
*
* If the length of the absolute pathname of the current working directory,
* including the terminating null byte, exceeds @size bytes, NULL is returned.
*
* @param[out] buf The buffer to receive the current working directory pathname.
* @param[in] size The size of buffer.
*
* @return On success, aos_getcwd() returns a pointer to a string containing
* the pathname of the current working directory.
* On error, NULL is returned.
*/
char *aos_getcwd(char *buf, size_t size);
/**
* @brief aos_pathconf() gets a value for configuration option @name for the
* filename @path.
*
* @param[in] path The path name to quire
* @param[in] name The configuration option
*
* @return On error, negative error code is returned to indicate the cause
* of the error.
* On success, if @name corresponds to an option, a positive value is
* returned if the option is supported.
*/
long aos_pathconf(const char *path, int name);
/**
* @brief aos_fpathconf() gets a value for the cofiguration option @name for
* the open file descriptor @fd.
*
* @param[in] fd The open file descriptor to quire
* @param[in] name The configuration option
*
* @return On success, if @name corresponds to an option, a positive value is
* returned if the option is supported.
* On error, negative error code is returned to indicate the cause
* of the error.
*/
long aos_fpathconf(int fd, int name);
/**
* @brief aos_utime() changes teh access and modification times of the inode
* specified by @path to the actime and modtime fields of the @times
* respectively.
* If @times is NULL, then the access and modification times of the file
* are set to the current time.
*
* @param[in] path Path name of the inode to operate.
* @param[in] times Buffer pointer to structure aos_utimbuf whose actime
* and modtime fields will be set to the inode @path.
*
* @return 0 on success, negative error code on failure
*/
int aos_utime(const char *path, const struct aos_utimbuf *times);
/**
* @brief aos_vfs_fd_offset_get() gets VFS fd offset
*
* @return VFS fd offset
*/
int aos_vfs_fd_offset_get(void);
/**
* @brief aos_fcntl() change the nature of the opened file
*
* @param[in] fd The open file descriptor to quire
* @param[in] cmd The configuration command.
* @param[in] val The configuration value.
*
* @return On success return 0.
* On error, negative error code is returned to indicate the cause
* of the error.
*/
int aos_fcntl(int fd, int cmd, int val);
/**
* @brief Bind driver to the file or device
*
* @param[in] path The path of the file or device
* @param[in] ops The driver operations to bind
* @param[in] arg The arguments of the driver operations
*
* @return On success return 0.
* On error, negative error code is returned to indicate the cause
* of the error.
*/
int aos_register_driver(const char *path, file_ops_t *ops, void *arg);
/**
* @brief Unbind driver from the file or device
*
* @param[in] path The path of the file or device
*
* @return On success return 0.
* On error, negative error code is returned to indicate the cause
* of the error.
*/
int aos_unregister_driver(const char *path);
/**
* @brief aos_register_fs() mounts filesystem to the path
*
* @param[in] path The mount point path
* @param[in] ops The filesystem operations
* @param[in] arg The arguments of the filesystem operations
*
* @return On success return 0.
* On error, negative error code is returned to indicate the cause
* of the error.
*/
int aos_register_fs(const char *path, fs_ops_t* ops, void *arg);
/**
* @brief aos_unregister_fs() unmounts the filesystem
*
* @param[in] path The mount point path
*
* @return On success return 0.
* On error, negative error code is returned to indicate the cause
* of the error.
*/
int aos_unregister_fs(const char *path);
/* adapter tmp */
//typedef struct aos_stat stat;
/** @} */
#ifdef __cplusplus
}
#endif
#endif /* AOS_VFS_H */
|
YifuLiu/AliOS-Things
|
components/vfs/include/aos/vfs.h
|
C
|
apache-2.0
| 22,780
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef VFS_ADAPT_H
#define VFS_ADAPT_H
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Create OS lock
*
* @return the pointer of the lock
*
*/
void *vfs_lock_create(void);
/**
* @brief Free OS lock
*
* @param[in] lock pointer to the os lock
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_lock_free(void *lock);
/**
* @brief Lock the os lock
*
* @param[in] lock pointer to the os lock
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_lock(void *lock);
/**
* @brief Unlock the os lock
*
* @param[in] lock pointer to the os lock
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_unlock(void *lock);
/**
* @brief wrapper of MM allocation
*
* @param[in] size size of the mem to alloc
*
* @return NULL is error, other is memory address
*
*/
void *vfs_malloc(uint32_t size);
/**
* @brief wrapper of MM free
*
* @param[in] ptr address point of the mem
*
*/
void vfs_free(void *ptr);
#ifdef __cplusplus
}
#endif
#endif /* VFS_ADAPT_H */
|
YifuLiu/AliOS-Things
|
components/vfs/include/vfs_adapt.h
|
C
|
apache-2.0
| 1,107
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef VFS_API_H
#define VFS_API_H
#define VFS_OK 0
#define VFS_ERR_NOMEM -10000
#define VFS_ERR_INVAL -10001
#define VFS_ERR_NOENT -10002
#define VFS_ERR_NAMETOOLONG -10003
#define VFS_ERR_NOSYS -10004
#define VFS_ERR_ENFILE -10005
#define VFS_ERR_NODEV -10006
#define VFS_ERR_LOCK -10007
#define VFS_ERR_BUSY -10008
#define VFS_ERR_GENERAL -10009
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Initialize the vfs module
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_init(void);
/**
* @brief Open the file or device by path
*
* @param[in] path the path of the file or device to open
* @param[in] flags the mode of the open operation
*
* @return the new file descriptor, negative error on failure
*
*/
int32_t vfs_open(const char *path, int32_t flags);
/**
* @brief Close the file or device by file descriptor
*
* @param[in] fd the file descriptor of the file ot device
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_close(int32_t fd);
/**
* @brief Read the contents of a file or device into a buffer
*
* @param[in] fd the file descriptor of the file or device
* @param[out] buf the buffer to read into
* @param[in] nbytes the number of bytes to read
*
* @return the number of bytes read, 0 at end of file, negative error on failure
*
*/
int32_t vfs_read(int32_t fd, void *buf, uint32_t nbytes);
/**
* @brief Write the contents of a buffer to file or device
*
* @param[in] fd the file descriptor of the file or device
* @param[in] buf the buffer to write from
* @param[in] nbytes the number of bytes to write
*
* @return the number of bytes written, negative error on failure
*
*/
int32_t vfs_write(int32_t fd, const void *buf, uint32_t nbytes);
/**
* @brief This is a wildcard API for sending specific commands
*
* @param[in] fd the file descriptor of the file or device
* @param[in] cmd a specific command
* @param[in] arg argument to the command, interpreted according to the cmd
*
* @return any return from the command
*
*/
int32_t vfs_ioctl(int32_t fd, int32_t cmd, uint32_t arg);
/**
* @brief This is a wildcard API for executing the particular poll by fd
*
* @param[in] fd the file descriptor of the file or device
* @param[in] flag the flag of the polling
* @param[in] notify the polling notify callback
* @param[in] fds a pointer to the array of pollfd
* @param[in] arg the arguments of the polling
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_do_pollfd(int32_t fd, int32_t flag, vfs_poll_notify_t notify,
void *fds, void *arg);
/**
* @brief Move the file position to a given offset from a given location
*
* @param[in] fd the file descriptor of the file
* @param[in] offset the offset from whence to move to
* @param[in] whence the start of where to seek
* SEEK_SET to start from beginning of the file
* SEEK_CUR to start from current position in file
* SEEK_END to start from end of file
*
* @return the new offset of the file
*
*/
uint32_t vfs_lseek(int32_t fd, int64_t offset, int32_t whence);
/**
* @brief truncate a file to a specified size
*
* @param[in] path the file path of the file
* @param[in] size the new size of the file
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_truncate(const char *path, int64_t size);
/**
* @brief truncate a file to a specified size
*
* @param[in] fd the file descriptor of the file
* @param[in] size the new size of the file
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_ftruncate(int32_t fd, int64_t size);
/**
* @brief Flush any buffers associated with the file
*
* @param[in] fd the file descriptor of the file
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_sync(int32_t fd);
/**
* @brief Flush all information in memory that updates file systems to be
* be written to the file systems
*
* @return none
*
*/
void vfs_allsync(void);
/**
* Store information about the file in a vfs_stat structure
*
* @param[in] path the path of the file to find information about
* @param[out] st the vfs_stat buffer to write to
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_stat(const char *path, vfs_stat_t *st);
/**
* Store information about the file in a vfs_stat structure
*
* @param[in] fd the file descriptor of the file
* @param[out] st the vfs_stat buffer to write to
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_fstat(int fd, vfs_stat_t *st);
#ifdef AOS_PROCESS_SUPPORT
/**
* Map memory to process address space to share memory between
* kernel and process.
*
* @note Currently only support input arg @len to tell kernel the
* size of shared memory.
*
* @return shared memory virtual address on success, NULL on failure
*/
void *vfs_mmap(void *start, size_t len, int prot, int flags, int fd, off_t offset);
/**
* @brief unmap shared memory area
*
* @param[in] start The address of the shared memory area
* @param[in] len The size of the shared memory area
*
* @return 0 on success, negative error on failure
*/
int vfs_munmap(void *start, size_t len);
#endif
/**
* @brief link path2 to path1
*
* @param[in] path1 the path to be linked
* @param[in] path2 the path to link
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_link(const char *oldpath, const char *newpath);
/**
* @brief Remove a file from the filesystem
*
* @param[in] path the path of the file to remove
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_unlink(const char *path);
/**
* @brief Remove a file from the filesystem
*
* @param[in] path the path of the file to remove
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_remove(const char *path);
/**
* @brief Rename a file in the filesystem
*
* @param[in] oldpath the path of the file to rename
* @param[in] newpath the path to rename it to
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_rename(const char *oldpath, const char *newpath);
/**
* @brief Open a directory on the filesystem
*
* @param[in] path the path of the directory to open
*
* @return a pointer of directory stream on success, NULL on failure
*
*/
vfs_dir_t *vfs_opendir(const char *path);
/**
* @brief Close a directory
*
* @param[in] dir the pointer of the directory to close
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_closedir(vfs_dir_t *dir);
/**
* @brief Read the next directory entry
*
* @param[in] dir the pointer of the directory to read
*
* @return a pointer to a vfs_dirent structure
*
*/
vfs_dirent_t *vfs_readdir(vfs_dir_t *dir);
/**
* @brief Create the directory, if ther do not already exist
*
* @param[in] path the path of the directory to create
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_mkdir(const char *path);
/**
* @brief Remove a directory
*
* @param[in] path the path of the directory to remove
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_rmdir(const char *path);
/**
* @brief Reset the position of a directory stream to the beginning of a directory
*
* @param[in] dir the pointer of the directory to rewind
*
* @return none
*
*/
void vfs_rewinddir(vfs_dir_t *dir);
/**
* @brief Obtain the current location associated with the directory
*
* @param[in] dir the pointer of the directory to tell
*
* @return the current location of the directory, negative error on failure
*
*/
int32_t vfs_telldir(vfs_dir_t *dir);
/**
* @brief Move the directory position to a given location
*
* @param[in] dir the pointer of the directory to seek
* @param[in] loc the location of the directory
*
* @return none
*/
void vfs_seekdir(vfs_dir_t *dir, int32_t loc);
/**
* @brief Store information about the filesystem in a vfs_statfs structure
*
* @param[in] path the path of the filesystem to find information about
* @param[out] buf the vfs_statfs buffer to write to
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_statfs(const char *path, vfs_statfs_t *buf);
/**
* @brief Get access information
*
* @param[in] path the path of the file to access
* @param[in] amode the access information to get
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_access(const char *path, int32_t amode);
/**
* @brief Manipulate file descriptor
* @param[in] fd the file descriptor of the file
* @param[in] cmd A controller specific command
* @param[val] val Argument to the command
*
* @return 0 on success, negative error on failure
*
*/
int vfs_fcntl(int fd, int cmd, int val);
/**
* set the pathname of the current working directory
*
* @param path The path to set.
*
* @return 0 on success, negative error code on failure.
*
*/
int vfs_chdir(const char *path);
/**
* get the pathname of the current working directory.
*
* @param buf The buffer to save the current working directory.
* @param size The size of buf.
*
* @return NULL if error occured, buf if succeed.
*
*/
char *vfs_getcwd(char *buf, size_t size);
/**
* @brief Get path conf
*
* @param[in] path the path conf to get from
* @param[in] name the kind of path conf to get
*
* @return value of path info
*/
int32_t vfs_pathconf(const char *path, int name);
/**
* @brief Get path info
*
* @param[in] name the path info to get
*
* @return value of path info
*/
int32_t vfs_fpathconf(int fd, int name);
/**
* @brief Set the access and modification times
*
* @param[in] path the path conf to get from
* @param[in] times the buffer to store time info
*
* @return 0 on success, negative error code on failure
*/
int vfs_utime(const char *path, const vfs_utimbuf_t *times);
/**
* @brief Get file descriptor offset
*
* @return the vfs file descriptor offset
*
*/
int32_t vfs_fd_offset_get(void);
/**
* @brief Bind driver to the file or device
*
* @param[in] path the path of the file or device
* @param[in] ops the driver operations to bind
* @param[in] arg the arguments of the driver operations
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_register_driver(const char *path, vfs_file_ops_t *ops, void *arg);
/**
* @brief Unbind driver from the file or device
*
* @param[in] path the path of the file or device
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_unregister_driver(const char *path);
/**
* @brief Mount filesystem to the path
*
* @param[in] path the mount point path
* @param[in] ops the filesystem operations
* @param[in] arg the arguments of the filesystem operations
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_register_fs(const char *path, vfs_filesystem_ops_t* ops, void *arg);
/**
* @brief Unmount the filesystem
*
* @param[in] path the mount point path
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_unregister_fs(const char *path);
/**
* @brief open vfs file dump
*
*/
void vfs_dump_open();
/**
* @brief vfs list
*
* @param[in] t vfs list type:fs or device
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_list(vfs_list_type_t t);
/**
* @brief get fs node name for current path.
*
* @param[in] path current dir path.
* @param[out] names fs node names which mounted under current path.
* @param[out] size names count.
* @return 0 on success, negative error on failure.
*/
int32_t vfs_get_node_name(const char *path, char names[][64], uint32_t* size);
/**
* @brief set detach state of the node.
*
* @param[in] name the name of the node.
* @return 0 on success, negative error on failure.
*/
int32_t vfs_inode_detach_by_name(const char *name);
/**
* @brief the node is busy or not
*
* @param[in] name the name of the node.
* @return 0 on success, negative error on failure.
*/
int32_t vfs_inode_busy_by_name(const char *name);
/**
* @brief copy the file descriptor
*
* @param[in] oldfd the file descriptor to copy.
* @return 0 on success, negative error on failure.
*/
int vfs_dup(int oldfd);
/**
* @brief copy the file descriptor to new file decriptor
*
* @param[in] oldfd the file descriptor to copy.
* @param[in] newfd the new file decriptor.
* @return 0 on success, negative error on failure.
*/
int vfs_dup2(int oldfd, int newfd);
#ifdef __cplusplus
}
#endif
#endif /* VFS_API_H */
|
YifuLiu/AliOS-Things
|
components/vfs/include/vfs_api.h
|
C
|
apache-2.0
| 12,725
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef VFS_CONF_H
#define VFS_CONF_H
#ifndef VFS_CONFIG_DEVICE_NODES
#define VFS_DEVICE_NODES 25
#else
#define VFS_DEVICE_NODES VFS_CONFIG_DEVICE_NODES
#endif
#ifndef VFS_CONFIG_FD_OFFSET
#define VFS_FD_OFFSET 48
#else
#define VFS_FD_OFFSET VFS_CONFIG_FD_OFFSET
#endif
#ifndef VFS_CONFIG_PATH_MAX
#define VFS_PATH_MAX 256
#else
#define VFS_PATH_MAX VFS_CONFIG_PATH_MAX
#endif
#ifndef VFS_CONFIG_MAX_FILE_NUM
#define VFS_MAX_FILE_NUM (VFS_DEVICE_NODES * 2)
#else
#define VFS_MAX_FILE_NUM VFS_CONFIG_MAX_FILE_NUM
#endif
#ifndef VFS_CONFIG_STAT_INCLUDE_SIZE
#define VFS_STAT_INCLUDE_SIZE 1
#else
#define VFS_STAT_INCLUDE_SIZE VFS_CONFIG_STAT_INCLUDE_SIZE
#endif
#ifndef VFS_CONFIG_CURRENT_DIRECTORY_ENABLE
#define CURRENT_WORKING_DIRECTORY_ENABLE 0
#else
#define CURRENT_WORKING_DIRECTORY_ENABLE VFS_CONFIG_CURRENT_DIRECTORY_ENABLE
#endif
#endif /* VFS_CONF_H */
|
YifuLiu/AliOS-Things
|
components/vfs/include/vfs_conf.h
|
C
|
apache-2.0
| 934
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef VFS_FILE_H
#define VFS_FILE_H
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Get the file descriptor by file structure
*
* @param[in] file pointer the file structure
*
* @return the file descriptor
*
*/
int32_t vfs_fd_get(vfs_file_t *file);
/**
* @brief Get the file structure by file descriptor
*
* @param[in] fd the file descriptor
*
* @return the pointer of the file structure
*
*/
vfs_file_t *vfs_file_get(int32_t fd);
/**
* @brief Create a new file structure
*
* @param[in] node pointer to the inode
*
* @return the pointer of the file structure
*
*/
vfs_file_t *vfs_file_new(vfs_inode_t *node);
/**
* @brief Delete the file structure
*
* @param[in] file pointer to the file structure
*
* @return none
*/
void vfs_file_del(vfs_file_t *file);
/**
* @brief Mark fd as opened
*
* @param[in] fd the file descriptor
*
* @return On success return 0
* if the fd is invalid return -1
* if the fd has already been marked return 1
*/
int32_t vfs_fd_mark_open(int32_t fd);
/**
* @brief mark fd as closed
*
* @param[in] fd the file descriptor
*
* @return On success return 0
* if the fd is invalid return -1
* if the fd has already been marked return 1
*/
int32_t vfs_fd_mark_close(int32_t fd);
/**
* @brief query wether the fd is opened
*
* @param[in] fd the file descriptor
*
* @return if the fd is opened, return 1
* else return 0
*/
int32_t vfs_fd_is_open(int32_t fd);
/* adapter tmp */
#define get_fd vfs_fd_get
#define get_file vfs_file_get
#define new_file vfs_file_new
#define del_file vfs_file_del
#ifdef __cplusplus
}
#endif
#endif /* VFS_FILE_H */
|
YifuLiu/AliOS-Things
|
components/vfs/include/vfs_file.h
|
C
|
apache-2.0
| 1,731
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef VFS_INODE_H
#define VFS_INODE_H
#ifdef __cplusplus
extern "C" {
#endif
#include "vfs_types.h"
enum {
VFS_TYPE_NOT_INIT,
VFS_TYPE_CHAR_DEV,
VFS_TYPE_BLOCK_DEV,
VFS_TYPE_FS_DEV
};
#define INODE_IS_TYPE(node, t) ((node)->type == (t))
#define INODE_IS_CHAR(node) INODE_IS_TYPE(node, VFS_TYPE_CHAR_DEV)
#define INODE_IS_BLOCK(node) INODE_IS_TYPE(node, VFS_TYPE_BLOCK_DEV)
#define INODE_IS_FS(node) INODE_IS_TYPE(node, VFS_TYPE_FS_DEV)
#define INODE_GET_TYPE(node) ((node)->type)
#define INODE_SET_TYPE(node, t) do { (node)->type = (t); } while(0)
#define INODE_SET_CHAR(node) INODE_SET_TYPE(node, VFS_TYPE_CHAR_DEV)
#define INODE_SET_BLOCK(node) INODE_SET_TYPE(node, VFS_TYPE_BLOCK_DEV)
#define INODE_SET_FS(node) INODE_SET_TYPE(node, VFS_TYPE_FS_DEV)
/**
* @brief Initialize inode
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_inode_init(void);
/**
* @brief Alloc a free inode
*
* @return the index of inode, VFS_ERR_NOMEM on failure
*
*/
int32_t vfs_inode_alloc(void);
/**
* @brief Delete a inode
*
* @param[in] node pointer to the inode to delete
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_inode_del(vfs_inode_t *node);
/**
* @brief Open the inode by path
*
* @param[in] path the path of the inode reference
*
* @return the pointer of the inode, NULL on failure or not found
*
*/
vfs_inode_t *vfs_inode_open(const char *path);
/**
* @brief Get the inode pointer by fd
*
* @param[in] fd the file descriptor
* @param[out] p_node the pointer of the inode pointer
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_inode_ptr_get(int32_t fd, vfs_inode_t **p_node);
/**
* @brief Get the available inode count
*
* @return the count of the available inodes
*
*/
int32_t vfs_inode_avail_count(void);
/**
* @brief Add the inode refence count
*
* @param[in] node the pointer of the inode
*
* @return none
*
*/
void vfs_inode_ref(vfs_inode_t *node);
/**
* @brief Dec the inode refence count
*
* @param[in] node the pointer of the inode
*
* @return none
*
*/
void vfs_inode_unref(vfs_inode_t *node);
/**
* @brief Check whether the inode is busy or not
*
* @param[in] node the pointer of the inode
*
* @return 1 on busy, 0 on free
*
*/
int32_t vfs_inode_busy(vfs_inode_t *node);
/**
* @brief Reserve an inode
*
* @param[in] path the path of the inode reference
* @param[in] p_node pointer to the inode pointer
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_inode_reserve(const char *path, vfs_inode_t **p_node);
/**
* @brief Release an inode
*
* @param[in] path the path of the inode reference
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_inode_release(const char *path);
/**
* @brief list all inode with the type
*
* @param[in] type the type of inode
*
* @return 0 on success, negative error on failure
*
*/
int32_t vfs_inode_list(vfs_list_type_t type);
/**
* @brief get FS nodes name
*
* @param[in] path the parent path of inodes
*
* @param[out] names FS nodes name as request
*
* @param[out] size names count
*
* @return 0 on success, negative error on failure
*
*/
int vfs_inode_get_names(const char *path, char names[][64], uint32_t* size);
/**
* @brief only used by FS node to mark deatched state, so it can
* umount itself after it ceases to be busy.
*/
int32_t vfs_inode_detach(vfs_inode_t *node);
#define inode_init vfs_inode_init
#define inode_alloc vfs_inode_alloc
#define inode_del vfs_inode_del
#define inode_open vfs_inode_open
#define inode_ptr_get vfs_inode_ptr_get
#define inode_avail_count vfs_inode_avail_count
#ifdef __cplusplus
}
#endif
#endif /* VFS_INODE_H */
|
YifuLiu/AliOS-Things
|
components/vfs/include/vfs_inode.h
|
C
|
apache-2.0
| 3,810
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef VFS_TYPES_H
#define VFS_TYPES_H
#include <stdint.h>
#include <time.h>
typedef struct {
time_t actime; /* time of last access */
time_t modtime; /* time of last modification */
} vfs_utimbuf_t;
typedef struct {
uint16_t st_mode; /* mode of file */
uint32_t st_size; /* bytes of file */
time_t st_actime; /* time of last access */
time_t st_modtime; /* time of last modification */
} vfs_stat_t;
typedef struct {
int32_t d_ino; /* file number */
uint8_t d_type; /* type of file */
char d_name[]; /* file name */
} vfs_dirent_t;
typedef struct {
int32_t dd_vfs_fd;
int32_t dd_rsv;
} vfs_dir_t;
typedef struct {
int32_t f_type; /* fs type */
int32_t f_bsize; /* optimized transport block size */
int32_t f_blocks; /* total blocks */
int32_t f_bfree; /* available blocks */
int32_t f_bavail; /* number of blocks that non-super users can acquire */
int32_t f_files; /* total number of file nodes */
int32_t f_ffree; /* available file nodes */
int32_t f_fsid; /* fs id */
int32_t f_namelen; /* max file name length */
} vfs_statfs_t;
typedef void (*vfs_poll_notify_t)(void *fds, void *arg);
typedef struct vfs_file_ops vfs_file_ops_t;
typedef struct vfs_filesystem_ops vfs_filesystem_ops_t;
union vfs_inode_ops_t {
const vfs_file_ops_t *i_ops;
const vfs_filesystem_ops_t *i_fops;
};
typedef enum {
VFS_INODE_VALID, /* node is available*/
VFS_INODE_INVALID, /* Node is ready to be deleted, unavailable*/
VFS_INODE_DETACHED, /* Node is ready to be deleted, and Wait for the operation to complete */
VFS_INODE_MAX
} vfs_inode_status_t;
typedef struct {
union vfs_inode_ops_t ops; /* inode operations */
void *i_arg; /* per inode private data */
char *i_name; /* name of inode */
int32_t i_flags; /* flags for inode */
uint8_t type; /* type for inode */
uint8_t refs; /* refs for inode */
void *lock; /* lock for inode operations */
vfs_inode_status_t status; /* valid or invalid status for this inode */
} vfs_inode_t;
typedef struct {
vfs_inode_t *node; /* node for file or device */
void *f_arg; /* arguments for file or device */
uint32_t offset; /* offset of the file */
#ifdef CONFIG_VFS_LSOPEN
char filename[VFS_CONFIG_PATH_MAX];
#endif
int32_t redirect_fd; /* the target FD that it's redirected to, optionally used. */
} vfs_file_t;
typedef enum {
VFS_LIST_TYPE_FS,
VFS_LIST_TYPE_DEVICE
} vfs_list_type_t;
struct vfs_file_ops {
int32_t (*open) (vfs_inode_t *node, vfs_file_t *fp);
int32_t (*close) (vfs_file_t *fp);
int32_t (*read) (vfs_file_t *fp, void *buf, uint32_t nbytes);
int32_t (*write) (vfs_file_t *fp, const void *buf, uint32_t nbytes);
int32_t (*ioctl) (vfs_file_t *fp, int32_t cmd, uint32_t arg);
int32_t (*poll) (vfs_file_t *fp, int32_t flag, vfs_poll_notify_t notify, void *fds, void *arg);
uint32_t (*lseek) (vfs_file_t *fp, int64_t off, int32_t whence);
#ifdef AOS_PROCESS_SUPPORT
void* (*mmap)(vfs_file_t *fp, void *addr, size_t length, int prot, int flags,
int fd, off_t offset);
#endif
};
struct vfs_filesystem_ops {
int32_t (*open) (vfs_file_t *fp, const char *path, int32_t flags);
int32_t (*close) (vfs_file_t *fp);
int32_t (*read) (vfs_file_t *fp, char *buf, uint32_t len);
int32_t (*write) (vfs_file_t *fp, const char *buf, uint32_t len);
uint32_t (*lseek) (vfs_file_t *fp, int64_t off, int32_t whence);
int32_t (*sync) (vfs_file_t *fp);
int32_t (*stat) (vfs_file_t *fp, const char *path, vfs_stat_t *st);
int32_t (*fstat) (vfs_file_t *fp, vfs_stat_t *st);
int32_t (*link) (vfs_file_t *fp, const char *path1, const char *path2);
int32_t (*unlink) (vfs_file_t *fp, const char *path);
int32_t (*remove) (vfs_file_t *fp, const char *path);
int32_t (*rename) (vfs_file_t *fp, const char *oldpath, const char *newpath);
vfs_dir_t *(*opendir) (vfs_file_t *fp, const char *path);
vfs_dirent_t *(*readdir) (vfs_file_t *fp, vfs_dir_t *dir);
int32_t (*closedir) (vfs_file_t *fp, vfs_dir_t *dir);
int32_t (*mkdir) (vfs_file_t *fp, const char *path);
int32_t (*rmdir) (vfs_file_t *fp, const char *path);
void (*rewinddir) (vfs_file_t *fp, vfs_dir_t *dir);
int32_t (*telldir) (vfs_file_t *fp, vfs_dir_t *dir);
void (*seekdir) (vfs_file_t *fp, vfs_dir_t *dir, int32_t loc);
int32_t (*ioctl) (vfs_file_t *fp, int32_t cmd, uint32_t arg);
int32_t (*statfs) (vfs_file_t *fp, const char *path, vfs_statfs_t *suf);
int32_t (*access) (vfs_file_t *fp, const char *path, int32_t amode);
int32_t (*pathconf) (vfs_file_t *fp, const char *path, int name);
int32_t (*fpathconf) (vfs_file_t *fp, int name);
int32_t (*utime) (vfs_file_t *fp, const char *path, const vfs_utimbuf_t *times);
int32_t (*truncate) (vfs_file_t *fp, int64_t length);
};
#if VFS_CONFIG_DEBUG > 0
#define VFS_ERROR printf
#else
#define VFS_ERROR(x, ...) do { } while (0)
#endif
#endif /* VFS_TYPES_H */
|
YifuLiu/AliOS-Things
|
components/vfs/include/vfs_types.h
|
C
|
apache-2.0
| 5,438
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <aos/errno.h>
#include "vfs_types.h"
#include "vfs_api.h"
#include "vfs_conf.h"
#include "vfs_inode.h"
#include "vfs_file.h"
#include "vfs_adapt.h"
#ifdef IO_NEED_TRAP
#include "vfs_trap.h"
#endif
static uint8_t g_vfs_init = 0;
static void *g_vfs_lock_ptr = NULL;
static void *g_stdio_lock_ptr = NULL;
static int32_t stdio_redirect_fd[3] = {-1, -1, -1}; // 0: stdin, 1: stdout, 2: stderr
int32_t vfs_inode_list(vfs_list_type_t type);
int vfs_inode_get_names(const char *path, char names[][64], uint32_t* size);
#if (CURRENT_WORKING_DIRECTORY_ENABLE > 0)
char g_current_working_directory[VFS_PATH_MAX];
#endif
extern int uring_fifo_push_s(const void* buf, const uint16_t len);
static int32_t write_stdout(const void *buf, uint32_t nbytes)
{
uring_fifo_push_s(buf, nbytes);
return nbytes;
}
static int is_stdio_fd(int32_t fd)
{
return fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO? 1 : 0;
}
static int32_t find_stdio_redirect_fd(int32_t fd)
{
int32_t rfd = -1;
if (vfs_lock(g_stdio_lock_ptr) != VFS_OK) {
return -1;
}
if (fd == STDIN_FILENO) {
rfd = stdio_redirect_fd[0];
} else if (fd == STDOUT_FILENO) {
rfd = stdio_redirect_fd[1];
} else if (fd == STDERR_FILENO) {
rfd = stdio_redirect_fd[2];
}
vfs_unlock(g_stdio_lock_ptr);
return rfd;
}
static int32_t set_stdio_redirect_fd(int32_t sfd, int32_t rfd)
{
int ret = 0, real_rfd = rfd - VFS_FD_OFFSET;
if (vfs_lock(g_stdio_lock_ptr) != VFS_OK) {
return -1;
}
if (real_rfd < 0 || real_rfd >= VFS_MAX_FILE_NUM || !vfs_fd_is_open(rfd)) {
vfs_unlock(g_vfs_lock_ptr);
return -1;
}
if (sfd == STDIN_FILENO) {
stdio_redirect_fd[0] = rfd;
} else if (sfd == STDOUT_FILENO) {
stdio_redirect_fd[1] = rfd;
} else if (sfd == STDERR_FILENO) {
stdio_redirect_fd[2] = rfd;
} else {
ret = -1;
}
vfs_unlock(g_stdio_lock_ptr);
return ret;
}
static int clear_stdio_redirect_fd(int fd)
{
int ret = 0;
if (vfs_lock(g_stdio_lock_ptr) != VFS_OK) {
return -1;
}
if (fd == STDIN_FILENO) {
stdio_redirect_fd[0] = -1;
} else if (fd == STDOUT_FILENO) {
stdio_redirect_fd[1] = -1;
} else if (fd == STDERR_FILENO) {
stdio_redirect_fd[2] = -1;
} else {
ret = -1;
}
vfs_unlock(g_stdio_lock_ptr);
return ret;
}
static int32_t vfs_close_without_glock(int32_t fd)
{
int32_t ret = VFS_OK;
vfs_file_t *f;
vfs_inode_t *node;
f = vfs_file_get(fd);
if (f == NULL) return VFS_ERR_NOENT;
node = f->node;
assert(node != (vfs_inode_t *)(-1));
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
goto end;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->close) != NULL) {
ret = (node->ops.i_fops->close)(f);
}
} else {
if ((node->ops.i_ops->close) != NULL) {
ret = (node->ops.i_ops->close)(f);
}
}
vfs_unlock(node->lock);
end:
vfs_fd_mark_close(fd);
vfs_file_del(f);
return ret;
}
static int32_t set_normal_redirect_fd(int32_t oldfd, int32_t newfd)
{
int ret = -1, realold = oldfd - VFS_FD_OFFSET;
vfs_file_t *f;
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return -1;
}
if (realold < 0 || realold >= VFS_MAX_FILE_NUM || !vfs_fd_is_open(oldfd)) {
vfs_unlock(g_vfs_lock_ptr);
return -1;
}
if (vfs_fd_is_open(newfd)) {
if (vfs_close_without_glock(newfd) != VFS_OK) {
goto end;
}
}
f = vfs_file_get2(newfd);
if (!f) goto end;
f->redirect_fd = oldfd;
/* -1 as *node, just for NULL check, do NOT really use it! */
f->node = (vfs_inode_t *)(-1);
vfs_fd_mark_open(newfd);
ret = newfd;
end:
vfs_unlock(g_vfs_lock_ptr);
return ret;
}
static int clear_normal_redirect_fd(int32_t fd)
{
int ret = -1;
vfs_file_t *f;
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
if (!vfs_fd_is_open(fd)) {
goto end;
}
f = vfs_file_get2(fd);
if (!f) goto end;
f->redirect_fd = -1;
/* -1 as *node, just for NULL check, do NOT really use it! */
f->node = NULL;
vfs_fd_mark_close(fd);
vfs_file_del(f);
ret = 0;
end:
vfs_unlock(g_vfs_lock_ptr);
return ret;
}
int32_t vfs_init(void)
{
if (g_vfs_init == 1) {
return VFS_OK;
}
g_vfs_lock_ptr = vfs_lock_create();
if (g_vfs_lock_ptr == NULL) {
return VFS_ERR_NOMEM;
}
g_stdio_lock_ptr = vfs_lock_create();
if (g_stdio_lock_ptr == NULL) {
vfs_lock_free(g_vfs_lock_ptr);
return VFS_ERR_NOMEM;
}
vfs_inode_init();
#if (CURRENT_WORKING_DIRECTORY_ENABLE > 0)
/* init current working directory */
memset(g_current_working_directory, 0, sizeof(g_current_working_directory));
#ifdef VFS_CONFIG_ROOTFS
strncpy(g_current_working_directory, "/", sizeof(g_current_working_directory) - 1);
#else
strncpy(g_current_working_directory, "/default", sizeof(g_current_working_directory) - 1);
#endif
#endif
g_vfs_init = 1;
return VFS_OK;
}
int32_t vfs_open(const char *path, int32_t flags)
{
int32_t len = 0;
int32_t ret = VFS_OK;
vfs_file_t *f;
vfs_inode_t *node;
if (path == NULL) {
return VFS_ERR_INVAL;
}
len = strlen(path);
if (len > VFS_PATH_MAX) {
return VFS_ERR_NAMETOOLONG;
}
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
node = vfs_inode_open(path);
if (node == NULL) {
vfs_unlock(g_vfs_lock_ptr);
#ifdef IO_NEED_TRAP
return trap_open(path, flags);
#else
return VFS_ERR_NOENT;
#endif
}
f = vfs_file_new(node);
vfs_unlock(g_vfs_lock_ptr);
if (f == NULL) {
return VFS_ERR_ENFILE;
}
#ifdef CONFIG_VFS_LSOPEN
strncpy(f->filename, path, sizeof(f->filename) - 1);
#endif
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
ret = VFS_ERR_LOCK;
goto end;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now, %d!\n\r", __func__, node, node->status);
ret = VFS_ERR_NOENT;
goto end;
}
node->i_flags = flags;
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->open) != NULL) {
ret = (node->ops.i_fops->open)(f, path, flags);
}
} else {
if ((node->ops.i_ops->open) != NULL) {
ret = (node->ops.i_ops->open)(node, f);
}
}
vfs_unlock(node->lock);
end:
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
if (ret != VFS_OK) {
vfs_file_del(f);
} else {
ret = vfs_fd_get(f);
vfs_fd_mark_open(ret);
}
vfs_unlock(g_vfs_lock_ptr);
return ret;
}
int32_t vfs_close(int32_t fd)
{
int32_t ret = VFS_OK;
vfs_file_t *f;
vfs_inode_t *node;
/* handle special case forstdio */
if (is_stdio_fd(fd)) {
return clear_stdio_redirect_fd(fd) == 0 ? VFS_OK : VFS_ERR_GENERAL;
}
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
/* check if redirect or not first */
f = vfs_file_get2(fd);
if (f == NULL) {
vfs_unlock(g_vfs_lock_ptr);
return VFS_ERR_NOENT;
} else {
if (f->redirect_fd >= 0) {
vfs_unlock(g_vfs_lock_ptr);
return clear_normal_redirect_fd(fd) == 0 ? VFS_OK : VFS_ERR_GENERAL;
}
}
f = vfs_file_get(fd);
vfs_unlock(g_vfs_lock_ptr);
if (f == NULL) {
#ifdef IO_NEED_TRAP
return trap_close(fd);
#else
return VFS_ERR_NOENT;
#endif
}
node = f->node;
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
goto end;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->close) != NULL) {
ret = (node->ops.i_fops->close)(f);
}
} else {
if ((node->ops.i_ops->close) != NULL) {
ret = (node->ops.i_ops->close)(f);
}
}
vfs_unlock(node->lock);
end:
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
vfs_fd_mark_close(fd);
vfs_file_del(f);
vfs_unlock(g_vfs_lock_ptr);
return ret;
}
int32_t vfs_read(int32_t fd, void *buf, uint32_t nbytes)
{
int32_t nread = -1;
vfs_file_t *f;
vfs_inode_t *node;
f = vfs_file_get(fd);
if (f == NULL) {
#ifdef IO_NEED_TRAP
return trap_read(fd, buf, nbytes);
#else
return VFS_ERR_NOENT;
#endif
}
node = f->node;
if(node == NULL) {
return VFS_ERR_NOENT;
}
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
goto ret;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->read) != NULL) {
nread = (node->ops.i_fops->read)(f, buf, nbytes);
}
} else {
if ((node->ops.i_ops->read) != NULL) {
nread = (node->ops.i_ops->read)(f, buf, nbytes);
}
}
ret:
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
return nread;
}
int32_t vfs_write(int32_t fd, const void *buf, uint32_t nbytes)
{
int32_t nwrite = -1, rfd = -1;
vfs_file_t *f;
vfs_inode_t *node;
/* handle special case for stdout and stderr */
if ((fd == STDOUT_FILENO) || (fd == STDERR_FILENO)) {
if ((rfd = find_stdio_redirect_fd(fd)) >= 0) {
fd = rfd;
} else {
return write_stdout(buf, nbytes);
}
}
f = vfs_file_get(fd);
if (f == NULL) {
#ifdef IO_NEED_TRAP
return trap_write(fd, buf, nbytes);
#else
return VFS_ERR_NOENT;
#endif
}
node = f->node;
if(node == NULL) {
return VFS_ERR_NOENT;
}
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
goto ret;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops) != NULL) {
if ((node->ops.i_fops->write) != NULL) {
nwrite = (node->ops.i_fops->write)(f, buf, nbytes);
}
}
} else {
if ((node->ops.i_ops) != NULL) {
if ((node->ops.i_ops->write) != NULL) {
nwrite = (node->ops.i_ops->write)(f, buf, nbytes);
}
}
}
ret:
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
return nwrite;
}
int32_t vfs_ioctl(int32_t fd, int32_t cmd, uint32_t arg)
{
int32_t ret = VFS_ERR_NOSYS;
vfs_file_t *f;
vfs_inode_t *node;
if (fd < 0) {
return VFS_ERR_INVAL;
}
f = vfs_file_get(fd);
if (f == NULL) {
return VFS_ERR_NOENT;
}
node = f->node;
if(node == NULL) {
return VFS_ERR_NOENT;
}
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
goto ret;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->ioctl) != NULL) {
ret = (node->ops.i_fops->ioctl)(f, cmd, arg);
}
} else {
if ((node->ops.i_ops->ioctl) != NULL) {
ret = (node->ops.i_ops->ioctl)(f, cmd, arg);
}
}
ret:
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
return ret;
}
int32_t vfs_do_pollfd(int32_t fd, int32_t flag, vfs_poll_notify_t notify,
void *fds, void *arg)
{
int32_t ret = VFS_ERR_NOSYS;
vfs_file_t *f;
vfs_inode_t *node;
#if 0
#ifdef WITH_LWIP
if ((fd >= FD_AOS_SOCKET_OFFSET) &&
(fd <= (FD_AOS_EVENT_OFFSET + FD_AOS_NUM_EVENTS - 1))) {
return lwip_poll(fd, flag, notify, fds, arg);
}
if ((fd >= FD_UDS_SOCKET_OFFSET) &&
(fd < FD_UDS_SOCKET_OFFSET + FD_UDS_SOCKET_NUM)) {
return uds_poll(fd, flag, notify, fds, arg);
}
#endif
#endif
f = vfs_file_get(fd);
if (f == NULL) {
return VFS_ERR_NOENT;
}
node = f->node;
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
return VFS_ERR_NOENT;
}
if (!INODE_IS_FS(node)) {
if ((node->ops.i_ops->poll) != NULL) {
ret = (node->ops.i_ops->poll)(f, flag, notify, fds, arg);
}
}
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
return ret;
}
uint32_t vfs_lseek(int32_t fd, int64_t offset, int32_t whence)
{
int32_t ret = VFS_ERR_NOSYS;
vfs_file_t *f;
vfs_inode_t *node;
f = vfs_file_get(fd);
if (f == NULL) {
return VFS_ERR_NOENT;
}
node = f->node;
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
return VFS_ERR_NOENT;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->lseek) != NULL) {
ret = (node->ops.i_fops->lseek)(f, offset, whence);
}
} else {
if ((node->ops.i_ops->lseek) != NULL) {
ret = (node->ops.i_ops->lseek)(f, offset, whence);
}
}
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
return ret;
}
static int32_t vfs_truncate_inode(vfs_inode_t *node, vfs_file_t *f, int64_t size)
{
int32_t ret = VFS_ERR_NOSYS;
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
return VFS_ERR_NOENT;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->truncate) != NULL) {
ret = (node->ops.i_fops->truncate)(f, size);
}
}
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
return ret;
}
int32_t vfs_truncate(const char *path, int64_t size)
{
int32_t ret = VFS_ERR_NOSYS;
vfs_file_t *f;
vfs_inode_t *node;
// TODO: support truncate later.
return VFS_ERR_NOSYS;
if ((path == NULL) || (path[0] == '\0') || (size < 0)) {
return VFS_ERR_INVAL;
}
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
node = vfs_inode_open(path);
if (node == NULL) {
vfs_unlock(g_vfs_lock_ptr);
return VFS_ERR_NODEV;
}
f = vfs_file_new(node);
vfs_unlock(g_vfs_lock_ptr);
if (f == NULL) {
return VFS_ERR_NOENT;
}
ret = vfs_truncate_inode(node, f, size);
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
vfs_file_del(f);
vfs_unlock(g_vfs_lock_ptr);
return ret;
}
int32_t vfs_ftruncate(int32_t fd, int64_t size)
{
vfs_file_t *f = NULL;
if ((fd < 0) || (size < 0)) {
return VFS_ERR_INVAL;
}
f = vfs_file_get(fd);
if ((f == NULL) || (f->node == NULL)) {
return VFS_ERR_NOENT;
}
return vfs_truncate_inode(f->node, f, size);
}
int32_t vfs_sync(int32_t fd)
{
int32_t ret = VFS_ERR_NOSYS;
vfs_file_t *f;
vfs_inode_t *node;
f = vfs_file_get(fd);
if (f == NULL) {
return VFS_ERR_NOENT;
}
node = f->node;
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
return VFS_ERR_NOENT;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->sync) != NULL) {
ret = (node->ops.i_fops->sync)(f);
}
}
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
return ret;
}
void vfs_allsync(void)
{
int i;
int32_t fd;
/**
* prevent other threads from closing
* the file while syncing it
*/
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return;
}
for (i = 0; i < VFS_MAX_FILE_NUM; i++) {
fd = VFS_FD_OFFSET + i;
if (vfs_fd_is_open(fd)) {
vfs_sync(fd);
}
}
vfs_unlock(g_vfs_lock_ptr);
}
int32_t vfs_stat(const char *path, vfs_stat_t *st)
{
int32_t ret = VFS_ERR_NOSYS;
vfs_file_t *f;
vfs_inode_t *node;
if (path == NULL) {
return VFS_ERR_INVAL;
}
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
node = vfs_inode_open(path);
if (node == NULL) {
vfs_unlock(g_vfs_lock_ptr);
return VFS_ERR_NODEV;
}
f = vfs_file_new(node);
vfs_unlock(g_vfs_lock_ptr);
if (f == NULL) {
return VFS_ERR_NOENT;
}
#ifdef CONFIG_VFS_LSOPEN
strncpy(f->filename, path, sizeof(f->filename) - 1);
#endif
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
ret = VFS_ERR_LOCK;
goto end;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
ret = VFS_ERR_NOENT;
goto end;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->stat) != NULL) {
ret = (node->ops.i_fops->stat)(f, path, st);
}
}
#if 0
else if (INODE_IS_CHAR(node) || INODE_IS_BLOCK(node)) {
if ((node->ops.i_ops->stat) != NULL) {
ret = (node->ops.i_ops->stat)(f, path, st);
} else {
ret = VFS_OK;
if (INODE_IS_CHAR(node)) {
st->st_mode &= ~S_IFMT;
st->st_mode |= S_IFCHR;
}
}
}
#endif
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
ret = VFS_ERR_LOCK;
goto end;
}
end:
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
vfs_file_del(f);
vfs_unlock(g_vfs_lock_ptr);
return ret;
}
int32_t vfs_fstat(int fd, vfs_stat_t *st)
{
int32_t ret = VFS_ERR_NOSYS;
vfs_file_t *f;
vfs_inode_t *node;
f = vfs_file_get(fd);
if (f == NULL) {
return VFS_ERR_NOENT;
}
node = f->node;
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
return VFS_ERR_NOENT;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->fstat) != NULL) {
ret = (node->ops.i_fops->fstat)(f, st);
}
}
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
return ret;
}
#ifdef AOS_PROCESS_SUPPORT
void *vfs_mmap(void *start, size_t len, int prot, int flags, int fd, off_t offset)
{
void *ret = (void *)VFS_ERR_NOSYS;
vfs_file_t *f;
vfs_inode_t *node;
f = vfs_file_get(fd);
if (f == NULL) {
return NULL;
}
node = f->node;
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
return NULL;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
return NULL;
}
if (INODE_IS_CHAR(node) || INODE_IS_BLOCK(node)) {
if ((node->ops.i_ops->mmap) != NULL) {
ret = (node->ops.i_ops->mmap)(f, start, len, prot, flags, fd, offset);
}
}
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
return NULL;
}
return ret;
}
#endif
int32_t vfs_link(const char *oldpath, const char *newpath)
{
int32_t ret = VFS_ERR_NOSYS;
vfs_file_t *f;
vfs_inode_t *node;
if ((oldpath == NULL)||(newpath == NULL)) {
return VFS_ERR_INVAL;
}
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
node = vfs_inode_open(oldpath);
if (node == NULL) {
vfs_unlock(g_vfs_lock_ptr);
return VFS_ERR_NODEV;
}
f = vfs_file_new(node);
vfs_unlock(g_vfs_lock_ptr);
if (f == NULL) {
return VFS_ERR_NOENT;
}
#ifdef CONFIG_VFS_LSOPEN
strncpy(f->filename, oldpath, sizeof(f->filename) - 1);
#endif
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
ret = VFS_ERR_LOCK;
goto end;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
ret = VFS_ERR_NOENT;
goto end;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->link) != NULL) {
ret = (node->ops.i_fops->link)(f, oldpath, newpath);
}
}
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
ret = VFS_ERR_LOCK;
goto end;
}
end:
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
vfs_file_del(f);
vfs_unlock(g_vfs_lock_ptr);
return ret;
}
int32_t vfs_unlink(const char *path)
{
int32_t ret = VFS_ERR_NOSYS;
vfs_file_t *f;
vfs_inode_t *node;
if (path == NULL) {
return VFS_ERR_INVAL;
}
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
node = vfs_inode_open(path);
if (node == NULL) {
vfs_unlock(g_vfs_lock_ptr);
return VFS_ERR_NODEV;
}
f = vfs_file_new(node);
vfs_unlock(g_vfs_lock_ptr);
if (f == NULL) {
return VFS_ERR_NOENT;
}
#ifdef CONFIG_VFS_LSOPEN
strncpy(f->filename, path, sizeof(f->filename) - 1);
#endif
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
ret = VFS_ERR_LOCK;
goto end;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
ret = VFS_ERR_NOENT;
goto end;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->unlink) != NULL) {
ret = (node->ops.i_fops->unlink)(f, path);
}
}
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
ret = VFS_ERR_LOCK;
goto end;
}
end:
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
vfs_file_del(f);
vfs_unlock(g_vfs_lock_ptr);
return ret;
}
int32_t vfs_remove(const char *path)
{
int32_t ret = VFS_ERR_NOSYS;
vfs_file_t *f;
vfs_inode_t *node;
if (path == NULL) {
return VFS_ERR_INVAL;
}
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
node = vfs_inode_open(path);
if (node == NULL) {
vfs_unlock(g_vfs_lock_ptr);
return VFS_ERR_NODEV;
}
f = vfs_file_new(node);
vfs_unlock(g_vfs_lock_ptr);
if (f == NULL) {
return VFS_ERR_NOENT;
}
#ifdef CONFIG_VFS_LSOPEN
strncpy(f->filename, path, sizeof(f->filename) - 1);
#endif
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
ret = VFS_ERR_LOCK;
goto end;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
ret = VFS_ERR_NOENT;
goto end;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->remove) != NULL) {
ret = (node->ops.i_fops->remove)(f, path);
}
}
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
ret = VFS_ERR_LOCK;
goto end;
}
end:
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
vfs_file_del(f);
vfs_unlock(g_vfs_lock_ptr);
return ret;
}
int32_t vfs_rename(const char *oldpath, const char *newpath)
{
int32_t ret = VFS_ERR_NOSYS;
vfs_file_t *f;
vfs_inode_t *node;
if ((oldpath == NULL) || (newpath == NULL)) {
return VFS_ERR_INVAL;
}
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
node = vfs_inode_open(oldpath);
if (node == NULL) {
vfs_unlock(g_vfs_lock_ptr);
return VFS_ERR_NODEV;
}
f = vfs_file_new(node);
vfs_unlock(g_vfs_lock_ptr);
if (f == NULL) {
return VFS_ERR_NOENT;
}
#ifdef CONFIG_VFS_LSOPEN
strncpy(f->filename, oldpath, sizeof(f->filename) - 1);
#endif
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
ret = VFS_ERR_LOCK;
goto end;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
ret = VFS_ERR_NOENT;
goto end;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->rename) != NULL) {
ret = (node->ops.i_fops->rename)(f, oldpath, newpath);
}
}
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
ret = VFS_ERR_LOCK;
goto end;
}
end:
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
vfs_file_del(f);
vfs_unlock(g_vfs_lock_ptr);
return ret;
}
vfs_dir_t *vfs_opendir(const char *path)
{
vfs_dir_t *dp = NULL;
vfs_file_t *f;
vfs_inode_t *node;
if (path == NULL) {
return NULL;
}
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return NULL;
}
node = vfs_inode_open(path);
if (node == NULL) {
vfs_unlock(g_vfs_lock_ptr);
return NULL;
}
f = vfs_file_new(node);
vfs_unlock(g_vfs_lock_ptr);
if (f == NULL) {
return NULL;
}
#ifdef CONFIG_VFS_LSOPEN
strncpy(f->filename, path, sizeof(f->filename) - 1);
#endif
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
goto end;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
goto end;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->opendir) != NULL) {
dp = (node->ops.i_fops->opendir)(f, path);
}
}
if (vfs_unlock(node->lock) != VFS_OK) {
if (dp && (node->ops.i_fops->closedir) != NULL) {
(node->ops.i_fops->closedir)(f, dp);
}
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
dp = NULL;
goto end;
}
end:
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return NULL;
}
if (dp == NULL) {
vfs_file_del(f);
vfs_unlock(g_vfs_lock_ptr);
return NULL;
}
dp->dd_vfs_fd = vfs_fd_get(f);
vfs_fd_mark_open(dp->dd_vfs_fd);
vfs_unlock(g_vfs_lock_ptr);
return dp;
}
int32_t vfs_closedir(vfs_dir_t *dir)
{
int32_t ret = VFS_ERR_NOSYS;
vfs_file_t *f;
vfs_inode_t *node;
if (dir == NULL) {
return VFS_ERR_INVAL;
}
f = vfs_file_get(dir->dd_vfs_fd);
if (f == NULL) {
return VFS_ERR_NOENT;
}
node = f->node;
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
return VFS_ERR_NOENT;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->closedir) != NULL) {
ret = (node->ops.i_fops->closedir)(f, dir);
}
}
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
vfs_file_del(f);
vfs_unlock(g_vfs_lock_ptr);
return ret;
}
vfs_dirent_t *vfs_readdir(vfs_dir_t *dir)
{
vfs_dirent_t *dirent = NULL;
vfs_file_t *f;
vfs_inode_t *node;
if (dir == NULL) {
return NULL;
}
f = vfs_file_get(dir->dd_vfs_fd);
if (f == NULL) {
return NULL;
}
node = f->node;
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
return NULL;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
return NULL;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->readdir) != NULL) {
dirent = (node->ops.i_fops->readdir)(f, dir);
}
}
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
return NULL;
}
return dirent;
}
int32_t vfs_mkdir(const char *path)
{
int32_t ret = VFS_ERR_NOSYS;
vfs_file_t *f;
vfs_inode_t *node;
if (path == NULL) {
return VFS_ERR_INVAL;
}
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
node = vfs_inode_open(path);
if (node == NULL) {
vfs_unlock(g_vfs_lock_ptr);
return VFS_ERR_NODEV;
}
f = vfs_file_new(node);
vfs_unlock(g_vfs_lock_ptr);
if (f == NULL) {
return VFS_ERR_NOENT;
}
#ifdef CONFIG_VFS_LSOPEN
strncpy(f->filename, path, sizeof(f->filename) - 1);
#endif
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
ret = VFS_ERR_LOCK;
goto end;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
ret = VFS_ERR_NOENT;
goto end;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->mkdir) != NULL) {
ret = (node->ops.i_fops->mkdir)(f, path);
}
}
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
ret = VFS_ERR_LOCK;
goto end;
}
end:
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
vfs_file_del(f);
vfs_unlock(g_vfs_lock_ptr);
return ret;
}
int32_t vfs_rmdir(const char *path)
{
int32_t ret = VFS_ERR_NOSYS;
vfs_file_t *f;
vfs_inode_t *node;
if (path == NULL) {
return VFS_ERR_INVAL;
}
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
node = vfs_inode_open(path);
if (node == NULL) {
vfs_unlock(g_vfs_lock_ptr);
return VFS_ERR_NODEV;
}
f = vfs_file_new(node);
vfs_unlock(g_vfs_lock_ptr);
if (f == NULL) {
return VFS_ERR_NOENT;
}
#ifdef CONFIG_VFS_LSOPEN
strncpy(f->filename, path, sizeof(f->filename) - 1);
#endif
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
ret = VFS_ERR_LOCK;
goto end;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
ret = VFS_ERR_NOENT;
goto end;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->rmdir) != NULL) {
ret = (node->ops.i_fops->rmdir)(f, path);
}
}
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
ret = VFS_ERR_LOCK;
goto end;
}
end:
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
vfs_file_del(f);
vfs_unlock(g_vfs_lock_ptr);
return ret;
}
void vfs_rewinddir(vfs_dir_t *dir)
{
vfs_file_t *f;
vfs_inode_t *node;
if (dir == NULL) {
return;
}
f = vfs_file_get(dir->dd_vfs_fd);
if (f == NULL) {
return;
}
node = f->node;
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
return;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
return;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->rewinddir) != NULL) {
(node->ops.i_fops->rewinddir)(f, dir);
}
}
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
}
return;
}
int32_t vfs_telldir(vfs_dir_t *dir)
{
vfs_file_t *f;
vfs_inode_t *node;
int32_t ret = 0;
if (dir == NULL) {
return VFS_ERR_INVAL;
}
f = vfs_file_get(dir->dd_vfs_fd);
if (f == NULL) {
return VFS_ERR_NOENT;
}
node = f->node;
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
return VFS_ERR_NOENT;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->telldir) != NULL) {
ret = (node->ops.i_fops->telldir)(f, dir);
}
}
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
return ret;
}
void vfs_seekdir(vfs_dir_t *dir, int32_t loc)
{
vfs_file_t *f;
vfs_inode_t *node;
if (dir == NULL) {
return;
}
f = vfs_file_get(dir->dd_vfs_fd);
if (f == NULL) {
return;
}
node = f->node;
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
return;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
return;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->seekdir) != NULL) {
(node->ops.i_fops->seekdir)(f, dir, loc);
}
}
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
}
return;
}
int32_t vfs_statfs(const char *path, vfs_statfs_t *buf)
{
int32_t ret = VFS_ERR_NOSYS;
vfs_file_t *f;
vfs_inode_t *node;
if (path == NULL) {
return VFS_ERR_INVAL;
}
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
node = vfs_inode_open(path);
if (node == NULL) {
vfs_unlock(g_vfs_lock_ptr);
return VFS_ERR_NODEV;
}
f = vfs_file_new(node);
vfs_unlock(g_vfs_lock_ptr);
if (f == NULL) {
return VFS_ERR_NOENT;
}
#ifdef CONFIG_VFS_LSOPEN
strncpy(f->filename, path, sizeof(f->filename) - 1);
#endif
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
ret = VFS_ERR_LOCK;
goto end;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
ret = VFS_ERR_NOENT;
goto end;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->statfs) != NULL) {
ret = (node->ops.i_fops->statfs)(f, path, buf);
}
}
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
ret = VFS_ERR_LOCK;
goto end;
}
end:
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
vfs_file_del(f);
vfs_unlock(g_vfs_lock_ptr);
return ret;
}
int32_t vfs_access(const char *path, int32_t amode)
{
int32_t ret = VFS_ERR_NOSYS;
vfs_file_t *f;
vfs_inode_t *node;
if (path == NULL) {
return VFS_ERR_INVAL;
}
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
node = vfs_inode_open(path);
if (node == NULL) {
vfs_unlock(g_vfs_lock_ptr);
return VFS_ERR_NODEV;
}
f = vfs_file_new(node);
vfs_unlock(g_vfs_lock_ptr);
if (f == NULL) {
return VFS_ERR_NOENT;
}
#ifdef CONFIG_VFS_LSOPEN
strncpy(f->filename, path, sizeof(f->filename) - 1);
#endif
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
ret = VFS_ERR_LOCK;
goto end;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
ret = VFS_ERR_NOENT;
goto end;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->access) != NULL) {
ret = (node->ops.i_fops->access)(f, path, amode);
}
} else {
ret = VFS_OK; // always OK for devices
}
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
ret = VFS_ERR_LOCK;
goto end;
}
end:
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
vfs_file_del(f);
vfs_unlock(g_vfs_lock_ptr);
return ret;
}
int vfs_chdir(const char *path)
{
#if (CURRENT_WORKING_DIRECTORY_ENABLE > 0)
if ((path == NULL) || (strlen(path) > VFS_PATH_MAX)){
return VFS_ERR_NAMETOOLONG;
}
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
memset(g_current_working_directory, 0, sizeof(g_current_working_directory));
strncpy(g_current_working_directory, path, strlen(path) + 1);
vfs_unlock(g_vfs_lock_ptr);
return VFS_OK;
#else
return VFS_ERR_INVAL;
#endif
}
char *vfs_getcwd(char *buf, size_t size)
{
#if (CURRENT_WORKING_DIRECTORY_ENABLE > 0)
if ((buf == NULL) || (size < strlen(g_current_working_directory))) {
return NULL;
}
strncpy(buf, g_current_working_directory, strlen(g_current_working_directory) + 1);
return buf;
#else
return NULL;
#endif
}
int32_t vfs_pathconf(const char *path, int name)
{
int32_t ret = VFS_ERR_NOSYS;
vfs_file_t *f;
vfs_inode_t *node;
if (path == NULL) {
return VFS_ERR_INVAL;
}
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
node = vfs_inode_open(path);
if (node == NULL) {
vfs_unlock(g_vfs_lock_ptr);
return VFS_ERR_NODEV;
}
f = vfs_file_new(node);
vfs_unlock(g_vfs_lock_ptr);
if (f == NULL) {
return VFS_ERR_NOENT;
}
#ifdef CONFIG_VFS_LSOPEN
strncpy(f->filename, path, sizeof(f->filename) - 1);
#endif
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
ret = VFS_ERR_LOCK;
goto end;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
ret = VFS_ERR_NOENT;
goto end;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->pathconf) != NULL) {
ret = (node->ops.i_fops->pathconf)(f, path, name);
}
}
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
ret = VFS_ERR_LOCK;
goto end;
}
end:
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
vfs_file_del(f);
vfs_unlock(g_vfs_lock_ptr);
return ret;
}
int32_t vfs_fpathconf(int fd, int name)
{
int32_t ret = VFS_ERR_NOSYS;
vfs_file_t *file;
vfs_inode_t *node;
file = vfs_file_get(fd);
if (file == NULL) {
return VFS_ERR_NOENT;
}
node = file->node;
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
return VFS_ERR_NOENT;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->fpathconf) != NULL) {
ret = (node->ops.i_fops->fpathconf)(file, name);
}
}
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
return ret;
}
int vfs_utime(const char *path, const vfs_utimbuf_t *times)
{
int32_t ret = VFS_ERR_NOSYS;
vfs_file_t *f;
vfs_inode_t *node;
if (path == NULL) {
return VFS_ERR_INVAL;
}
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
node = vfs_inode_open(path);
if (node == NULL) {
vfs_unlock(g_vfs_lock_ptr);
return VFS_ERR_NODEV;
}
f = vfs_file_new(node);
vfs_unlock(g_vfs_lock_ptr);
if (f == NULL) {
return VFS_ERR_NOENT;
}
#ifdef CONFIG_VFS_LSOPEN
strncpy(f->filename, path, sizeof(f->filename) - 1);
#endif
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
ret = VFS_ERR_LOCK;
goto end;
}
if (node->status != VFS_INODE_VALID) {
vfs_unlock(node->lock);
VFS_ERROR("%s node %p is invalid now!\n\r", __func__, node);
ret = VFS_ERR_NOENT;
goto end;
}
if (INODE_IS_FS(node)) {
if ((node->ops.i_fops->utime) != NULL) {
ret = (node->ops.i_fops->utime)(f, path, times);
}
}
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
ret = VFS_ERR_LOCK;
goto end;
}
end:
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
vfs_file_del(f);
vfs_unlock(g_vfs_lock_ptr);
return ret;
}
int32_t vfs_fd_offset_get(void)
{
return VFS_FD_OFFSET;
}
int vfs_fcntl(int fd, int cmd, int val)
{
if (fd < 0) {
return -EINVAL;
}
if (fd < vfs_fd_offset_get()) {
#ifdef IO_NEED_TRAP
return trap_fcntl(fd, cmd, val);
#else
return -ENOENT;
#endif
}
return 0;
}
int32_t vfs_register_driver(const char *path, vfs_file_ops_t *ops, void *arg)
{
int32_t ret = VFS_ERR_NOSYS;
vfs_inode_t *node = NULL;
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
node = vfs_inode_open(path);
if(NULL != node)
{
VFS_ERROR("%s failed to register, the path has exist %s, %d!\n\r", __func__, path, node->status);
vfs_unlock(g_vfs_lock_ptr);
return VFS_ERR_INVAL;
}
ret = vfs_inode_reserve(path, &node);
if (ret == VFS_OK) {
INODE_SET_CHAR(node);
node->ops.i_ops = ops;
node->i_arg = arg;
}
if (vfs_unlock(g_vfs_lock_ptr) != VFS_OK) {
if (node->i_name != NULL) {
vfs_free(node->i_name);
}
memset(node, 0, sizeof(vfs_inode_t));
return VFS_ERR_LOCK;
}
return ret;
}
int32_t vfs_unregister_driver(const char *path)
{
int32_t ret;
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
ret = vfs_inode_release(path);
if (vfs_unlock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
return ret;
}
int32_t vfs_register_fs(const char *path, vfs_filesystem_ops_t* ops, void *arg)
{
int32_t ret;
vfs_inode_t *node = NULL;
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
node = vfs_inode_open(path);
if(NULL != node)
{
VFS_ERROR("%s failed to register, the path has exist %s, %d!\n\r", __func__, path, node->status);
vfs_unlock(g_vfs_lock_ptr);
return VFS_ERR_INVAL;
}
ret = vfs_inode_reserve(path, &node);
if (ret == VFS_OK) {
INODE_SET_FS(node);
node->ops.i_fops = ops;
node->i_arg = arg;
}
if (vfs_unlock(g_vfs_lock_ptr) != VFS_OK) {
if (node->i_name != NULL) {
vfs_free(node->i_name);
}
memset(node, 0, sizeof(vfs_inode_t));
return VFS_ERR_LOCK;
}
return ret;
}
int32_t vfs_unregister_fs(const char *path)
{
int32_t ret;
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
ret = vfs_inode_release(path);
if (vfs_unlock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
return ret;
}
#ifdef CONFIG_VFS_LSOPEN
void vfs_dump_open()
{
vfs_lock(g_vfs_lock_ptr);
vfs_file_open_dump();
vfs_unlock(g_vfs_lock_ptr);
}
#endif
int32_t vfs_list(vfs_list_type_t t)
{
return vfs_inode_list(t);
}
int32_t vfs_get_node_name(const char *path, char names[][64], uint32_t* size)
{
return vfs_inode_get_names(path, names, size);
}
int vfs_dup(int oldfd)
{
int ret = VFS_ERR_GENERAL, realold = oldfd - VFS_FD_OFFSET;;
vfs_file_t *f;
if (vfs_lock(g_vfs_lock_ptr) != VFS_OK) {
return VFS_ERR_LOCK;
}
if (realold < 0 || realold >= VFS_MAX_FILE_NUM || !vfs_fd_is_open(oldfd)) {
vfs_unlock(g_vfs_lock_ptr);
return VFS_ERR_GENERAL;
}
/* -1 as *node, just for NULL check, do NOT really use it! */
f = vfs_file_new((vfs_inode_t *)(-1));
if (f) {
ret = vfs_fd_get(f);
vfs_fd_mark_open(ret);
f->redirect_fd = oldfd;
} else {
ret = VFS_ERR_GENERAL;
}
vfs_unlock(g_vfs_lock_ptr);
return ret;
}
int vfs_dup2(int oldfd, int newfd)
{
if (is_stdio_fd(newfd)) {
return set_stdio_redirect_fd(newfd, oldfd) == 0 ? VFS_OK : VFS_ERR_GENERAL;
} else {
return set_normal_redirect_fd(oldfd, newfd) >= 0 ? newfd : VFS_ERR_GENERAL;
}
}
|
YifuLiu/AliOS-Things
|
components/vfs/vfs.c
|
C
|
apache-2.0
| 48,682
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#include <stdint.h>
#include "k_api.h"
#include "vfs_adapt.h"
void *vfs_lock_create(void)
{
int32_t ret;
kmutex_t *m;
m = krhino_mm_alloc(sizeof(kmutex_t));
if (m == NULL) {
return NULL;
}
ret = krhino_mutex_create(m, "VFS");
if (ret != RHINO_SUCCESS) {
krhino_mm_free(m);
return NULL;
}
return (void *)m;
}
int32_t vfs_lock_free(void *lock)
{
int32_t ret;
kmutex_t *m = (kmutex_t *)lock;
if (m == NULL) {
return -1;
}
ret = krhino_mutex_del(m);
if (ret != RHINO_SUCCESS) {
return ret;
}
krhino_mm_free(m);
return ret;
}
int32_t vfs_lock(void *lock)
{
int ret = krhino_mutex_lock((kmutex_t *)lock, RHINO_WAIT_FOREVER);
if (ret == RHINO_MUTEX_OWNER_NESTED) {
ret = RHINO_SUCCESS;
}
return ret;
}
int32_t vfs_unlock(void *lock)
{
int ret = krhino_mutex_unlock((kmutex_t *)lock);
if (ret == RHINO_MUTEX_OWNER_NESTED) {
ret = RHINO_SUCCESS;
}
return ret;
}
void *vfs_malloc(uint32_t size)
{
return krhino_mm_alloc(size);
}
void vfs_free(void *ptr)
{
krhino_mm_free(ptr);
}
|
YifuLiu/AliOS-Things
|
components/vfs/vfs_adapt.c
|
C
|
apache-2.0
| 1,225
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#include <string.h>
#include "aos/vfs.h"
#include "aos/errno.h"
#include "vfs_types.h"
#include "vfs_api.h"
static int _vfs_to_aos_res(int res)
{
switch (res) {
case VFS_OK:
return 0;
case VFS_ERR_NOMEM:
return -ENOMEM;
case VFS_ERR_INVAL:
return -EINVAL;
case VFS_ERR_NOENT:
return -ENOENT;
case VFS_ERR_NAMETOOLONG:
return -ENAMETOOLONG;
case VFS_ERR_NOSYS:
return -ENOSYS;
case VFS_ERR_ENFILE:
return -ENFILE;
case VFS_ERR_NODEV:
return -ENODEV;
case VFS_ERR_LOCK:
return -EIO;
case VFS_ERR_BUSY:
return -EBUSY;
default:
return res;
}
}
int aos_vfs_init(void)
{
return _vfs_to_aos_res(vfs_init());
}
int aos_open(const char *path, int flags)
{
return _vfs_to_aos_res(vfs_open(path, flags));
}
int aos_close(int fd)
{
return _vfs_to_aos_res(vfs_close(fd));
}
ssize_t aos_read(int fd, void *buf, size_t nbytes)
{
return _vfs_to_aos_res(vfs_read(fd, buf, nbytes));
}
ssize_t aos_write(int fd, const void *buf, size_t nbytes)
{
return _vfs_to_aos_res(vfs_write(fd, buf, nbytes));
}
int aos_ioctl(int fd, int cmd, unsigned long arg)
{
return _vfs_to_aos_res(vfs_ioctl(fd, cmd, arg));
}
int aos_do_pollfd(int fd, int flag, poll_notify_t notify, void *fds, void *arg)
{
return _vfs_to_aos_res(vfs_do_pollfd(fd, flag, (vfs_poll_notify_t)notify, fds, arg));
}
off_t aos_lseek(int fd, off_t offset, int whence)
{
return _vfs_to_aos_res(vfs_lseek(fd, offset, whence));
}
int aos_ftruncate(int fd, off_t size)
{
return _vfs_to_aos_res(vfs_ftruncate(fd, size));
}
int aos_truncate(const char *path, off_t size)
{
return _vfs_to_aos_res(vfs_truncate(path, size));
}
int aos_sync(int fd)
{
return _vfs_to_aos_res(vfs_sync(fd));
}
void aos_allsync(void)
{
vfs_allsync();
}
int aos_stat(const char *path, struct aos_stat *st)
{
return _vfs_to_aos_res(vfs_stat(path, (vfs_stat_t *)st));
}
int aos_fstat(int fd, struct aos_stat *st)
{
return _vfs_to_aos_res(vfs_fstat(fd, (vfs_stat_t *)st));
}
int aos_link(const char *oldpath, const char *newpath)
{
return _vfs_to_aos_res(vfs_link(oldpath, newpath));
}
int aos_unlink(const char *path)
{
return _vfs_to_aos_res(vfs_unlink(path));
}
int aos_remove(const char *path)
{
return _vfs_to_aos_res(vfs_remove(path));
}
int aos_rename(const char *oldpath, const char *newpath)
{
return _vfs_to_aos_res(vfs_rename(oldpath, newpath));
}
aos_dir_t *aos_opendir(const char *path)
{
return (aos_dir_t *)vfs_opendir(path);
}
int aos_closedir(aos_dir_t *dir)
{
return _vfs_to_aos_res(vfs_closedir((vfs_dir_t *)dir));
}
aos_dirent_t *aos_readdir(aos_dir_t *dir)
{
return (aos_dirent_t *)vfs_readdir((vfs_dir_t *)dir);
}
int aos_mkdir(const char *path)
{
return _vfs_to_aos_res(vfs_mkdir(path));
}
int aos_rmdir(const char *path)
{
return _vfs_to_aos_res(vfs_rmdir(path));
}
void aos_rewinddir(aos_dir_t *dir)
{
vfs_rewinddir((vfs_dir_t *)dir);
}
long aos_telldir(aos_dir_t *dir)
{
return _vfs_to_aos_res(vfs_telldir((vfs_dir_t *)dir));
}
void aos_seekdir(aos_dir_t *dir, long loc)
{
vfs_seekdir((vfs_dir_t *)dir, loc);
}
int aos_statfs(const char *path, struct aos_statfs *buf)
{
return _vfs_to_aos_res(vfs_statfs(path, (vfs_statfs_t *)buf));
}
int aos_access(const char *path, int amode)
{
return _vfs_to_aos_res(vfs_access(path, amode));
}
int aos_chdir(const char *path)
{
return _vfs_to_aos_res(vfs_chdir(path));
}
char *aos_getcwd(char *buf, size_t size)
{
return vfs_getcwd(buf, size);
}
int aos_vfs_fd_offset_get(void)
{
return vfs_fd_offset_get();
}
int aos_fcntl(int fd, int cmd, int val)
{
return vfs_fcntl(fd, cmd, val);
}
long aos_pathconf(const char *path, int name)
{
return _vfs_to_aos_res(vfs_pathconf(path, name));
}
long aos_fpathconf(int fh, int name)
{
return _vfs_to_aos_res(vfs_fpathconf(fh, name));
}
int aos_utime(const char *path, const struct aos_utimbuf *times)
{
return _vfs_to_aos_res(vfs_utime(path, (vfs_utimbuf_t *)times));
}
int aos_register_driver(const char *path, file_ops_t *ops, void *arg)
{
return _vfs_to_aos_res(vfs_register_driver(path, (vfs_file_ops_t *)ops, arg));
}
int aos_unregister_driver(const char *path)
{
return _vfs_to_aos_res(vfs_unregister_driver(path));
}
int aos_register_fs(const char *path, fs_ops_t* ops, void *arg)
{
return _vfs_to_aos_res(vfs_register_fs(path, (vfs_filesystem_ops_t *)ops, arg));
}
int aos_unregister_fs(const char *path)
{
return _vfs_to_aos_res(vfs_unregister_fs(path));
}
|
YifuLiu/AliOS-Things
|
components/vfs/vfs_aos.c
|
C
|
apache-2.0
| 4,764
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
#include "vfs_types.h"
#include "vfs_conf.h"
#include "vfs_file.h"
static vfs_file_t g_files[VFS_MAX_FILE_NUM];
static uint32_t g_opened_fd_bitmap[(VFS_MAX_FILE_NUM + 31) / 32];
extern void vfs_inode_ref(vfs_inode_t *node);
extern void vfs_inode_unref(vfs_inode_t *node);
int32_t vfs_fd_get(vfs_file_t *file)
{
return (file - g_files) + VFS_FD_OFFSET;
}
static vfs_file_t *vfs_file_get_helper(int32_t fd, int explore)
{
int32_t rfd, real_fd, real_rfd;
vfs_file_t *f;
real_fd = fd - VFS_FD_OFFSET;
if ((real_fd < 0) || (real_fd >= VFS_MAX_FILE_NUM) || (!vfs_fd_is_open(fd)))
{
return NULL;
}
f = &g_files[real_fd];
if (!explore)
{
return f;
}
/* fd redirect logic */
rfd = f->redirect_fd;
real_rfd = rfd - VFS_FD_OFFSET;
while (real_rfd >= 0) {
if (real_rfd >= VFS_MAX_FILE_NUM || !vfs_fd_is_open(rfd))
{
return NULL;
}
else
{
f = &g_files[real_rfd];
rfd = f->redirect_fd;
real_rfd = rfd - VFS_FD_OFFSET;
}
}
return f->node ? f : NULL;
}
vfs_file_t *vfs_file_get(int32_t fd)
{
return vfs_file_get_helper(fd, 1);
}
vfs_file_t *vfs_file_get2(int32_t fd)
{
return vfs_file_get_helper(fd, 0);
}
vfs_file_t *vfs_file_new(vfs_inode_t *node)
{
int32_t idx;
vfs_file_t *f;
for (idx = 0; idx < VFS_MAX_FILE_NUM; idx++) {
f = &g_files[idx];
if (f->node == NULL) {
goto got_file;
}
}
printf("[vfs_warn]: Failed to open file, too many files open now in system!\r\n");
return NULL;
got_file:
f->redirect_fd = -1;
f->node = node;
f->f_arg = NULL;
f->offset = 0;
/* do NOT really use node if it is for redirect fd (i.e. -1 as node) */
if (node && node != (vfs_inode_t *)(-1))
{
vfs_inode_ref(node);
}
return f;
}
void vfs_file_del(vfs_file_t *file)
{
if (!file)
return;
/* do NOT really use node if it is for redirect fd (i.e. -1 as node) */
if (file->node && file->node != (vfs_inode_t *)(-1)) {
vfs_inode_unref(file->node);
}
file->node = NULL;
file->redirect_fd = -1;
}
int32_t vfs_fd_mark_open(int32_t fd)
{
int word, bit;
fd -= VFS_FD_OFFSET;
/* invalid fd */
if (fd < 0) {
return -1;
}
word = fd / 32;
bit = fd % 32;
if (g_opened_fd_bitmap[word] & (1 << bit))
{
/* fd has been opened */
return 1;
}
else
{
g_opened_fd_bitmap[word] |= (1 << bit);
}
return 0;
}
int32_t vfs_fd_mark_close(int32_t fd)
{
int word, bit;
fd -= VFS_FD_OFFSET;
/* invalid fd */
if (fd < 0) {
return -1;
}
word = fd / 32;
bit = fd % 32;
if (g_opened_fd_bitmap[word] & (1 << bit))
{
g_opened_fd_bitmap[word] &= ~(1 << bit);
}
else
{
/* fd has been close */
return 1;
}
return 0;
}
int32_t vfs_fd_is_open(int32_t fd)
{
int word, bit;
fd -= VFS_FD_OFFSET;
/* invalid fd */
if (fd < 0) {
return -1;
}
word = fd / 32;
bit = fd % 32;
return g_opened_fd_bitmap[word] & (1 << bit);
}
|
YifuLiu/AliOS-Things
|
components/vfs/vfs_file.c
|
C
|
apache-2.0
| 3,356
|
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <stdio.h>
#include "vfs_types.h"
#include "vfs_api.h"
#include "vfs_conf.h"
#include "vfs_inode.h"
#include "vfs_adapt.h"
static vfs_inode_t g_vfs_nodes[VFS_DEVICE_NODES];
#ifdef VFS_CONFIG_ROOTFS
static vfs_inode_t *g_rootfs_node;
#endif
static int32_t vfs_inode_set_name(const char *path, vfs_inode_t **p_node)
{
int32_t len;
void *mem;
len = strlen(path);
mem = (void *)vfs_malloc(len + 1);
if (mem == NULL) {
return VFS_ERR_NOMEM;
}
memcpy(mem, (const void *)path, len);
(*p_node)->i_name = (char *)mem;
(*p_node)->i_name[len] = '\0';
return VFS_OK;
}
int32_t vfs_inode_init(void)
{
memset(g_vfs_nodes, 0, sizeof(vfs_inode_t) * VFS_DEVICE_NODES);
return VFS_OK;
}
int32_t vfs_inode_alloc(void)
{
int32_t idx;
for (idx = 0; idx < VFS_DEVICE_NODES; idx++) {
if (g_vfs_nodes[idx].type == VFS_TYPE_NOT_INIT) {
return idx;
}
}
return VFS_ERR_NOMEM;
}
static void close_all_files_on_node(vfs_inode_t *node)
{
int idx;
vfs_file_t *f;
for (idx = 0; idx < VFS_MAX_FILE_NUM; idx++) {
f = vfs_file_get(idx);
if (f && f->node == node) {
if (INODE_IS_FS(node)) {
if (node->ops.i_fops->close) {
node->ops.i_fops->close(f);
}
} else {
if (node->ops.i_ops->close) {
node->ops.i_ops->close(f);
}
}
}
}
}
int32_t vfs_inode_del(vfs_inode_t *node)
{
#if 0
if (node->refs > 0) {
return VFS_ERR_BUSY;
}
if (node->refs == 0) {
if (node->i_name != NULL) {
vfs_free(node->i_name);
}
node->i_name = NULL;
node->i_arg = NULL;
node->i_flags = 0;
node->type = VFS_TYPE_NOT_INIT;
}
return VFS_OK;
#else
if (vfs_lock(node->lock) != VFS_OK)
{
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
if (node->refs > 0)
{
node->status = VFS_INODE_INVALID;
// ensure to close all files at this point since
// ops will become unavailable soon!!
close_all_files_on_node(node);
if (vfs_unlock(node->lock) != VFS_OK)
{
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
}
else
{
if (node->i_name != NULL)
{
vfs_free(node->i_name);
}
node->i_name = NULL;
node->i_arg = NULL;
node->i_flags = 0;
node->type = VFS_TYPE_NOT_INIT;
if (vfs_lock_free(node->lock) != VFS_OK)
{
VFS_ERROR("%s failed to free lock for node %p\n\r", __func__, node);
return VFS_ERR_LOCK;
}
}
return VFS_OK;
#endif
}
vfs_inode_t *vfs_inode_open(const char *path)
{
int32_t idx;
vfs_inode_t *node;
#ifdef VFS_CONFIG_ROOTFS
bool fs_match = false;
#endif
for (idx = 0; idx < VFS_DEVICE_NODES; idx++) {
node = &g_vfs_nodes[idx];
if (node->i_name == NULL) {
continue;
}
if (INODE_IS_TYPE(node, VFS_TYPE_FS_DEV)) {
if ((strncmp(node->i_name, path, strlen(node->i_name)) == 0) && (strncmp("/dev", path, strlen("/dev")) != 0)) {
#ifdef VFS_CONFIG_ROOTFS
fs_match = true;
#endif
if (*(path + strlen(node->i_name)) == '/') {
return node;
}
}
}
if (strcmp(node->i_name, path) == 0) {
return node;
}
}
#ifdef VFS_CONFIG_ROOTFS
if (fs_match) {
return g_rootfs_node;
}
#endif
return NULL;
}
int32_t vfs_inode_ptr_get(int32_t fd, vfs_inode_t **p_node)
{
if (fd < 0 || fd >= VFS_DEVICE_NODES) {
return VFS_ERR_INVAL;
}
*p_node = &g_vfs_nodes[fd];
return VFS_OK;
}
int32_t vfs_inode_avail_count(void)
{
int32_t idx, count = 0;
for (idx = 0; idx < VFS_DEVICE_NODES; idx++){
if (g_vfs_nodes[count].type == VFS_TYPE_NOT_INIT) {
count++;
}
}
return count;
}
void vfs_inode_ref(vfs_inode_t *node)
{
if (!node)
{
return;
}
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
return;
}
node->refs++;
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
return;
}
}
void vfs_inode_unref(vfs_inode_t *node)
{
bool delete = false, detach = false;;
if (!node) return;
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
return;
}
if (node->refs > 0) {
node->refs--;
}
if (node->refs == 0) {
if (node->status == VFS_INODE_INVALID) {
delete = true;
} else if (node->status == VFS_INODE_DETACHED) {
detach = true;
}
}
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
return;
}
if (delete) {
vfs_inode_del(node);
} else if (detach) {
// umount(node->i_name);
}
}
int32_t vfs_inode_busy(vfs_inode_t *node)
{
int32_t ret;
if (!node) return VFS_ERR_INVAL;
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
ret = node->refs > 0 ? 1 : 0;
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
return ret;
}
int32_t vfs_inode_busy_by_name(const char *name)
{
for (int i = 0; i < VFS_DEVICE_NODES; i++) {
if (strcmp(g_vfs_nodes[i].i_name, name) == 0) {
return vfs_inode_busy(&(g_vfs_nodes[i]));
}
}
return 0;
}
int32_t vfs_inode_detach(vfs_inode_t *node)
{
if (vfs_lock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to lock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
node->status = VFS_INODE_DETACHED;
if (vfs_unlock(node->lock) != VFS_OK) {
VFS_ERROR("%s failed to unlock inode %p!\n\r", __func__, node);
return VFS_ERR_LOCK;
}
return VFS_OK;
}
/* only used by FS inode to umount itself after it ceases to be busy */
int32_t vfs_inode_detach_by_name(const char *name)
{
int32_t ret = -1;
for (int i = 0; i < VFS_DEVICE_NODES; i++) {
if ((g_vfs_nodes[i].type == VFS_TYPE_FS_DEV) && (strcmp(g_vfs_nodes[i].i_name, name) == 0)) {
ret = vfs_inode_detach(&(g_vfs_nodes[i]));
}
}
return ret;
}
int32_t vfs_inode_reserve(const char *path, vfs_inode_t **p_node)
{
int32_t ret;
vfs_inode_t *node = NULL;
if ((path == NULL) || (p_node == NULL)) {
return VFS_ERR_INVAL;
}
*p_node = NULL;
/* Handle paths that are interpreted as the root directory */
#ifdef _WIN32
if ((path[0] == '\0') || (path[1] != ':')) {
#else
if ((path[0] == '\0') || (path[0] != '/')) {
#endif
return VFS_ERR_INVAL;
}
ret = vfs_inode_alloc();
if (ret == VFS_ERR_NOMEM) {
return ret;
}
vfs_inode_ptr_get(ret, &node);
if (node == NULL) {
return VFS_ERR_NOMEM;
}
node->lock = vfs_lock_create();
if (node->lock == NULL) {
VFS_ERROR("%s faile to create lock for inode %p\r\n", __func__, node);
return VFS_ERR_LOCK;
}
ret = vfs_inode_set_name(path, &node);
if (ret != VFS_OK) {
return ret;
}
node->status = VFS_INODE_VALID;
*p_node = node;
#ifdef VFS_CONFIG_ROOTFS
/* for rootfs use */
if (strcmp(path, "/") == 0) g_rootfs_node = node;
#endif
return VFS_OK;
}
int32_t vfs_inode_release(const char *path)
{
int32_t ret;
vfs_inode_t *node;
if (path == NULL) {
return VFS_ERR_INVAL;
}
node = vfs_inode_open(path);
if (node == NULL) {
return VFS_ERR_NODEV;
}
ret = vfs_inode_del(node);
return ret;
}
int32_t vfs_inode_list(vfs_list_type_t type)
{
int32_t idx;
for (idx = 0; idx < VFS_DEVICE_NODES; idx++) {
if (VFS_LIST_TYPE_FS == type) {
if (g_vfs_nodes[idx].type == VFS_TYPE_FS_DEV) {
printf("%s\r\n", g_vfs_nodes[idx].i_name);
}
} else if (VFS_LIST_TYPE_DEVICE == type) {
if (g_vfs_nodes[idx].type == VFS_TYPE_CHAR_DEV ||
g_vfs_nodes[idx].type == VFS_TYPE_BLOCK_DEV) {
printf("%s\r\n", g_vfs_nodes[idx].i_name);
}
}
}
return VFS_OK;
}
uint32_t vfs_get_match_dev_node(const char *name, char *match_name)
{
int32_t idx;
uint32_t match_count = 0;
int32_t match_idx = 0;
for (idx = 0; idx < VFS_DEVICE_NODES; idx++) {
if (g_vfs_nodes[idx].type == VFS_TYPE_CHAR_DEV ||
g_vfs_nodes[idx].type == VFS_TYPE_BLOCK_DEV) {
if (name == NULL) {
printf("%s ", g_vfs_nodes[idx].i_name + strlen("/dev/"));
} else if (!strncmp(name, g_vfs_nodes[idx].i_name + strlen("/dev/"), strlen(name))) {
match_count++;
if (1 == match_count) {
match_idx = idx;
} else if (match_count == 2) {
printf("%s %s",
g_vfs_nodes[match_idx].i_name + strlen("/dev/"),
g_vfs_nodes[idx].i_name + strlen("/dev/"));
} else {
printf(" %s", g_vfs_nodes[idx].i_name + strlen("/dev/"));
}
}
}
}
if (1 == match_count) {
strncpy(match_name,
g_vfs_nodes[match_idx].i_name + strlen("/dev/"),
strlen(g_vfs_nodes[match_idx].i_name + strlen("/dev/")));
}
return match_count;
}
int vfs_inode_get_names(const char *path, char names[][64], uint32_t* size)
{
uint32_t idx;
uint32_t index = 0;
uint32_t len = 0;
if (path == NULL)
return VFS_ERR_INVAL;
for (idx = 0; idx < VFS_DEVICE_NODES; idx++) {
if (g_vfs_nodes[idx].type == VFS_TYPE_FS_DEV &&
strncmp(path, g_vfs_nodes[idx].i_name, strlen(path)) == 0) {
memset(names[index], 0, 64);
len = strlen(g_vfs_nodes[idx].i_name) + 1;
if (len > 64) {
strncpy(names[index], g_vfs_nodes[idx].i_name, 63);
names[index][63] = '\0';
index++;
} else {
strncpy(names[index++], g_vfs_nodes[idx].i_name, len);
}
}
}
*size = index;
return VFS_OK;
}
|
YifuLiu/AliOS-Things
|
components/vfs/vfs_inode.c
|
C
|
apache-2.0
| 10,991
|
/*
* Copyright (c) 2014 - 2016 Kulykov Oleh <info@resident.name>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <stdlib.h>
#include <string.h>
#include <aos/kernel.h>
#include <librws.h>
#if AOS_COMP_CLI
#include <aos/cli.h>
#endif
#define WEBSOCKET_CONNECTED (0x01)
#define WEBSOCKET_DISCONNECTED (0x02)
#define WEBSOCKET_DATA_NOT_RECVED (0x04)
#define WEBSOCKET_SSL_TEST 0
#define WEBSOCKET_BIN_DATA_TEST 0
#if WEBSOCKET_SSL_TEST
const char *ECHO_WEBSOCKET_CER = {
"-----BEGIN CERTIFICATE-----\r\n"
"MIIEkjCCA3qgAwIBAgIQCgFBQgAAAVOFc2oLheynCDANBgkqhkiG9w0BAQsFADA/\r\n"
"MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT\r\n"
"DkRTVCBSb290IENBIFgzMB4XDTE2MDMxNzE2NDA0NloXDTIxMDMxNzE2NDA0Nlow\r\n"
"SjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUxldCdzIEVuY3J5cHQxIzAhBgNVBAMT\r\n"
"GkxldCdzIEVuY3J5cHQgQXV0aG9yaXR5IFgzMIIBIjANBgkqhkiG9w0BAQEFAAOC\r\n"
"AQ8AMIIBCgKCAQEAnNMM8FrlLke3cl03g7NoYzDq1zUmGSXhvb418XCSL7e4S0EF\r\n"
"q6meNQhY7LEqxGiHC6PjdeTm86dicbp5gWAf15Gan/PQeGdxyGkOlZHP/uaZ6WA8\r\n"
"SMx+yk13EiSdRxta67nsHjcAHJyse6cF6s5K671B5TaYucv9bTyWaN8jKkKQDIZ0\r\n"
"Z8h/pZq4UmEUEz9l6YKHy9v6Dlb2honzhT+Xhq+w3Brvaw2VFn3EK6BlspkENnWA\r\n"
"a6xK8xuQSXgvopZPKiAlKQTGdMDQMc2PMTiVFrqoM7hD8bEfwzB/onkxEz0tNvjj\r\n"
"/PIzark5McWvxI0NHWQWM6r6hCm21AvA2H3DkwIDAQABo4IBfTCCAXkwEgYDVR0T\r\n"
"AQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAYYwfwYIKwYBBQUHAQEEczBxMDIG\r\n"
"CCsGAQUFBzABhiZodHRwOi8vaXNyZy50cnVzdGlkLm9jc3AuaWRlbnRydXN0LmNv\r\n"
"bTA7BggrBgEFBQcwAoYvaHR0cDovL2FwcHMuaWRlbnRydXN0LmNvbS9yb290cy9k\r\n"
"c3Ryb290Y2F4My5wN2MwHwYDVR0jBBgwFoAUxKexpHsscfrb4UuQdf/EFWCFiRAw\r\n"
"VAYDVR0gBE0wSzAIBgZngQwBAgEwPwYLKwYBBAGC3xMBAQEwMDAuBggrBgEFBQcC\r\n"
"ARYiaHR0cDovL2Nwcy5yb290LXgxLmxldHNlbmNyeXB0Lm9yZzA8BgNVHR8ENTAz\r\n"
"MDGgL6AthitodHRwOi8vY3JsLmlkZW50cnVzdC5jb20vRFNUUk9PVENBWDNDUkwu\r\n"
"Y3JsMB0GA1UdDgQWBBSoSmpjBH3duubRObemRWXv86jsoTANBgkqhkiG9w0BAQsF\r\n"
"AAOCAQEA3TPXEfNjWDjdGBX7CVW+dla5cEilaUcne8IkCJLxWh9KEik3JHRRHGJo\r\n"
"uM2VcGfl96S8TihRzZvoroed6ti6WqEBmtzw3Wodatg+VyOeph4EYpr/1wXKtx8/\r\n"
"wApIvJSwtmVi4MFU5aMqrSDE6ea73Mj2tcMyo5jMd6jmeWUHK8so/joWUoHOUgwu\r\n"
"X4Po1QYz+3dszkDqMp4fklxBwXRsW10KXzPMTZ+sOPAveyxindmjkW8lGy+QsRlG\r\n"
"PfZ+G6Z6h7mjem0Y+iWlkYcV4PIWL1iwBi8saCbGS5jN2p8M+X+Q7UNKEkROb3N6\r\n"
"KOqkqm57TH2H3eDJAkSnh6/DNFu0Qg==\r\n"
"-----END CERTIFICATE-----\r\n"
};
#endif
static rws_socket _socket = NULL;
static int state_flags = 0;
static void on_socket_received_text(rws_socket socket, const char *text, const unsigned int length, bool is_finish)
{
char *buff = NULL;
if (!socket || !text || !length) {
DBG("%s: Invalid parameter(s).", __FUNCTION__);
return;
}
buff = (char *)aos_malloc(length + 1);
if (!buff) {
DBG("%s: Not enough memory. len:%d", __FUNCTION__, length + 1);
return;
}
state_flags &= (~WEBSOCKET_DATA_NOT_RECVED);
memcpy(buff, text, length);
buff[length] = 0;
DBG("%s: Socket text: %s", __FUNCTION__, buff);
aos_free(buff);
buff = NULL;
}
static void on_socket_received_bin(rws_socket socket, const void * data, const unsigned int length, bool is_finish)
{
char *buff = NULL;
if (!socket || !data || !length) {
DBG("%s: Invalid parameter(s).", __FUNCTION__);
return;
}
buff = (char *)aos_malloc(length + 1);
if (!buff) {
DBG("%s: Not enough memory. len:%d", __FUNCTION__, length + 1);
return;
}
state_flags &= ~WEBSOCKET_DATA_NOT_RECVED;
memcpy(buff, data, length);
buff[length] = 0;
DBG("%s: Socket bin: \n%s", __FUNCTION__, buff);
aos_free(buff);
buff = NULL;
}
static void on_socket_received_pong(rws_socket socket)
{
if (!socket) {
DBG("%s: Invalid parameter(s).", __FUNCTION__);
return;
}
DBG("received pong!!!!!!!!!!!");
}
static void on_socket_connected(rws_socket socket)
{
const char * test_send_text =
"{\"version\":\"1.0\",\"supportedConnectionTypes\":[\"websocket\"],\"minimumVersion\":\"1.0\",\"channel\":\"/meta/handshake\"}";
DBG("%s: Socket connected", __FUNCTION__);
state_flags |= WEBSOCKET_CONNECTED;
state_flags &= ~WEBSOCKET_DISCONNECTED;
rws_socket_send_text(socket, test_send_text);
}
static void on_socket_disconnected(rws_socket socket)
{
rws_error error = rws_socket_get_error(socket);
if (error) {
DBG("%s: Socket disconnect with code, error: %i, %s",
__FUNCTION__,
rws_error_get_code(error),
rws_error_get_description(error));
}
state_flags &= ~WEBSOCKET_CONNECTED;
state_flags |= WEBSOCKET_DISCONNECTED;
_socket = NULL;
}
int websoc_cli_test_int(const char *scheme, const char *host,
const char *path, const int port,
const char *cert)
{
int sleep_count = 0;
int ret = 0;
if (!scheme || !host || !path) {
DBG("%s: Invalid parameter(s).", __FUNCTION__);
return -1;
}
if (_socket) {
DBG("%s: Socket is not closed.", __FUNCTION__);
return -2;
}
_socket = rws_socket_create(); // create and store socket handle
state_flags = 0;
state_flags |= WEBSOCKET_DATA_NOT_RECVED;
rws_socket_set_scheme(_socket, scheme);
rws_socket_set_host(_socket, host);
rws_socket_set_path(_socket, path);
rws_socket_set_port(_socket, port);
#ifdef WEBSOCKET_SSL_ENABLE
if (cert) {
rws_socket_set_server_cert(_socket, cert, strlen(cert) + 1);
}
#endif
rws_socket_set_on_disconnected(_socket, &on_socket_disconnected);
rws_socket_set_on_connected(_socket, &on_socket_connected);
rws_socket_set_on_received_text(_socket, &on_socket_received_text);
rws_socket_set_on_received_bin(_socket, &on_socket_received_bin);
rws_socket_set_on_received_pong(_socket, &on_socket_received_pong);
rws_socket_connect(_socket);
/* Connecting */
while ((!(state_flags & WEBSOCKET_CONNECTED)) &&
(!(state_flags & WEBSOCKET_DISCONNECTED))) {
rws_thread_sleep(1000);
DBG("Wait for websocket connection\n");
sleep_count++;
if (30 == sleep_count) {
if (!(state_flags & WEBSOCKET_CONNECTED)) {
ERR("Connect timeout\n");
ret = -1;
}
break;
}
}
/* Receiving data */
sleep_count = 0;
if (state_flags & WEBSOCKET_CONNECTED) {
while ((state_flags & WEBSOCKET_DATA_NOT_RECVED) && _socket &&
(rws_true == rws_socket_is_connected(_socket))) {
rws_thread_sleep(1000);
sleep_count++;
if (20 == sleep_count) {
if (state_flags & WEBSOCKET_DATA_NOT_RECVED) {
ERR("recv timeout\n");
ret = -1;
}
break;
}
}
}
#if WEBSOCKET_BIN_DATA_TEST
static const char *text_arr[] = {
"-----BEGIN CERTIFICATE-----"
"MIIFZjCCA06gAwIBAgIQCgFCgAAAAUUjz0Z8AAAAAjANBgkqhkiG9w0BAQsFADBN"
"MQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0MSowKAYDVQQDEyFJZGVu"
"VHJ1c3QgUHVibGljIFNlY3RvciBSb290IENBIDEwHhcNMTQwMTE2MTc1MzMyWhcN"
"MzQwMTE2MTc1MzMyWjBNMQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0"
"MSowKAYDVQQDEyFJZGVuVHJ1c3QgUHVibGljIFNlY3RvciBSb290IENBIDEwggIi"
"MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC2IpT8pEiv6EdrCvsnduTyP4o7"
"ekosMSqMjbCpwzFrqHd2hCa2rIFCDQjrVVi7evi8ZX3yoG2LqEfpYnYeEe4IFNGy"
"RBb06tD6Hi9e28tzQa68ALBKK0CyrOE7S8ItneShm+waOh7wCLPQ5CQ1B5+ctMlS"
"bdsHyo+1W/CD80/HLaXIrcuVIKQxKFdYWuSNG5qrng0M8gozOSI5Cpcu81N3uURF"
"/YTLNiCBWS2ab21ISGHKTN9T0a9SvESfqy9rg3LvdYDaBjMbXcjaY8ZNzaxmMc3R"
"3j6HEDbhuaR672BQssvKplbgN6+rNBM5Jeg5ZuSYeqoSmJxZZoY+rfGwyj4GD3vw"
"EUs3oERte8uojHH01bWRNszwFcYr3lEXsZdMUD2xlVl8BX0tIdUAvwFnol57plzy"
"9yLxkA2T26pEUWbMfXYD62qoKjgZl3YNa4ph+bz27nb9cCvdKTz4Ch5bQhyLVi9V"
"GxyhLrXHFub4qjySjmm2AcG1hp2JDws4lFTo6tyePSW8Uybt1as5qsVATFSrsrTZ"
"2fjXctscvG29ZV/viDUqZi/u9rNl8DONfJhBaUYPQxxp+pu10GFqzcpL2UyQRqsV"
"WaFHVCkugyhfHMKiq3IXAAaOReyL4jM9f9oZRORicsPfIsbyVtTdX5Vy7W1f90gD"
"W/3FKqD2cyOEEBsB5wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/"
"BAUwAwEB/zAdBgNVHQ4EFgQU43HgntinQtnbcZFrlJPrw6PRFKMwDQYJKoZIhvcN"
"AQELBQADggIBAEf63QqwEZE4rU1d9+UOl1QZgkiHVIyqZJnYWv6IAcVYpZmxI1Qj"
"t2odIFflAWJBF9MJ23XLblSQdf4an4EKwt3X9wnQW3IV5B4Jaj0z8yGa5hV+rVHV"
"DRDtfULAj+7AmgjVQdZcDiFpboBhDhXAuM/FSRJSzL46zNQuOAXeNf0fb7iAaJg9"
"TaDKQGXSc3z1i9kKlT/YPyNtGtEqJBnZhbMX73huqVjRI9PHE+1yJX9dsXNw0H8G"
"lwmEKYBhHfpe/3OsoOOJuBxxFcbeMX8S3OFtm6/n6J91eEyrRjuazr8FGF1NFTwW"
"mhlQBJqymm9li1JfPFgEKCXAZmExfrngdbkaqIHWchezxQMxNRF4eKLg6TCMf4Df"
"WN88uieW4oA0beOY02QnrEh+KHdcxiVhJfiFDGX6xDIvpZgF5PgLZxYWxoK4Mhn5"
"+bl53B/N66+rDt0b20XkeucC4pVd/GnwU2lhlXV5C15V5jgclKlZM57IcXR5f1GJ"
"tshquDDIajjDbp7hNxbqBWJMWxJH7ae0s1hWx0nzfxJoCTFx8G34Tkf71oXuxVhA"
"GaQdp/lLQzfcaFpPz+vCZHTetBXZ9FRUGi8c15dxVJCO2SCdUyt/q4/i6jC8UDfv"
"8Ue1fXwsBOxonbRJRBD0ckscZOf85muQ3Wl9af0AVqW3rLatt8o+Ae+c"
"-----END CERTIFICATE-----",
"AABBsdfasdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdfasdfasdfasdfasdfasdfadfasdfasdfasdfasdfasdf",
"09840523490582034850-2385023845023845023840523orjoewjrt0932u4ojt[iq3w04tu32094503u4t32u4059",
";';,,'s'd,fdg;sm;lsdf;g,s;d ;s,g ;,df;gl s;dg, ;sd,;gf,sd; g,",
"46s4f64s6df4a6sd4f64sdgf654segf654df66dsfg4e4rt65w4t6w4et64ewr6g4sd64fg65ds4fg",
"sdfasdg4sag64a6g45sd4 64365 46 4d6f4asd64 f6as4 f6as74f987s6543654165JJKK",
NULL
};
rws_socket_send_bin_start(_socket, "start", strlen("start"));
int i = 0;
while(text_arr[i] != NULL) {
rws_socket_send_bin_continue(_socket, text_arr[i], strlen(text_arr[i]));
// aos_msleep(100);
i++;
}
rws_socket_send_bin_finish(_socket, "finish", strlen("finish"));
#endif
if (_socket) {
rws_socket_disconnect_and_release(_socket);
}
_socket = NULL;
return ret;
}
void websoc_cli_test_entry(void *arg)
{
int ret = 0, ssl_ret = 0;
#if WEBSOCKET_SSL_TEST
char *cert = (char *)ECHO_WEBSOCKET_CER;
printf("Test client wss.");
ssl_ret = websoc_cli_test_int("wss", "echo.websocket.org", "/", 443, cert);
#else
printf("Test client ws.");
// ret = websoc_cli_test_int("ws", "echo.websocket.org", "/", 80, NULL);
ret = websoc_cli_test_int("ws", "121.40.165.18", "/", 8800, NULL);
#endif
if (0 == ret && 0 == ssl_ret) {
printf("example websocket test success!");
} else {
printf("example websocket test failed! ret:%d, ssl_ret:%d", ret, ssl_ret);
}
}
void websocket_comp_example(int argc, char **argv)
{
aos_task_new("ws-test", websoc_cli_test_entry, NULL, 10 * 1024);
}
#if AOS_COMP_CLI
/* reg args: fun, cmd, description*/
ALIOS_CLI_CMD_REGISTER(websocket_comp_example, websocket_example, websocket component base example)
#endif
|
YifuLiu/AliOS-Things
|
components/websocket/example/websocket_example.c
|
C
|
apache-2.0
| 12,143
|
/*
* Copyright (c) 2014 - 2019 Oleh Kulykov <info@resident.name>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef __LIBRWS_H__
#define __LIBRWS_H__ 1
#include <stdio.h>
#include <stdbool.h>
#ifndef _AMLOGIC_
#include "ulog/ulog.h"
#else
#include <printf.h>
#endif
#define RWS_VERSION_MAJOR 1
#define RWS_VERSION_MINOR 2
#define RWS_VERSION_PATCH 4
#define WEBSOC_TAG "websoc"
#if defined(WEBSOCKET_DEBUG)
#define DBG(format, arg...) LOGD(WEBSOC_TAG, format, ##arg)
#define WRN(format,arg...) LOGW(WEBSOC_TAG, format, ##arg)
#define ERR(format,arg...) LOGE(WEBSOC_TAG, format, ##arg)
#else
#define DBG(format,arg...) LOGD(WEBSOC_TAG, format, ##arg)
#define WRN(format,arg...) LOGW(WEBSOC_TAG, format, ##arg)
#define ERR(format,arg...) LOGE(WEBSOC_TAG, format, ##arg)
#endif
// check windows
#if defined(WIN32) || defined(_WIN32) || defined(WIN32_LEAN_AND_MEAN) || defined(_WIN64) || defined(WIN64)
#define RWS_OS_WINDOWS 1
#endif
// extern
#if defined(__cplusplus) || defined(_cplusplus)
#define RWS_EXTERN extern "C"
#else
#define RWS_EXTERN extern
#endif
// attribute
#if defined(__GNUC__)
#if (__GNUC__ >= 4)
#if defined(__cplusplus) || defined(_cplusplus)
#define RWS_ATTRIB __attribute__((visibility("default")))
#else
#define RWS_ATTRIB __attribute__((visibility("default")))
#endif
#endif
#endif
// check attrib and define empty if not defined
#if !defined(RWS_ATTRIB)
#define RWS_ATTRIB
#endif
// dll api
#if defined(RWS_OS_WINDOWS)
#if defined(RWS_BUILD)
#define RWS_DYLIB_API __declspec(dllexport)
#else
#define RWS_DYLIB_API __declspec(dllimport)
#endif
#endif
// check dll api and define empty if not defined
#if !defined(RWS_DYLIB_API)
#define RWS_DYLIB_API
#endif
// combined lib api
#define RWS_API(return_type) RWS_EXTERN RWS_ATTRIB RWS_DYLIB_API return_type
// types
/**
@brief Boolean type as unsigned byte type.
*/
typedef unsigned char rws_bool;
#define rws_true 1
#define rws_false 0
#define RWS_WAIT_FOREVER 0xffffffffu
/**
@brief Type of all public objects.
*/
typedef void* rws_handle;
/**
@brief Socket handle.
*/
typedef struct rws_socket_struct * rws_socket;
/**
@brief Error object handle.
*/
typedef struct rws_error_struct * rws_error;
/**
@brief Mutex object handle.
*/
typedef rws_handle rws_mutex;
/**
@brief Mutex object handle.
*/
typedef rws_handle rws_sem;
/**
@brief Thread object handle.
*/
typedef struct rws_thread_struct * rws_thread;
/**
@brief Callback type of thread function.
@param user_object User object provided during thread creation.
*/
typedef void (*rws_thread_funct)(void * user_object);
/**
@brief Callback type of socket object.
@param socket Socket object.
*/
typedef void (*rws_on_socket)(rws_socket socket);
/**
@brief Callback type on socket receive text frame.
@param socket Socket object.
@param text Pointer to reseived text.
@param length Received text lenght without null terminated char.
*/
typedef void (*rws_on_socket_recvd_text)(rws_socket socket, const char * text, const unsigned int length, bool is_finished);
/**
@brief Callback type on socket receive binary frame.
@param socket Socket object.
@param data Received binary data.
@param length Received binary data lenght.
*/
typedef void (*rws_on_socket_recvd_bin)(rws_socket socket, const void * data, const unsigned int length, bool is_finished);
/**
@brief Callback type on socket receive pong.
@param socket Socket object.
*/
typedef void (*rws_on_socket_recvd_pong)(rws_socket socket);
/**
@brief Callback type on socket send ping.
@param socket Socket object.
*/
typedef void (*rws_on_socket_send_ping)(rws_socket socket);
// socket
/**
@brief Create new socket.
@return Socket handler or NULL on error.
*/
RWS_API(rws_socket) rws_socket_create(void);
/**
@brief Set socket connect URL.
@param socket Socket object.
@param scheme Connect URL scheme, "http" or "ws"
@param scheme Connect URL host, "echo.websocket.org"
@param scheme Connect URL port.
@param scheme Connect URL path started with '/' character, "/" - for empty, "/path"
@code
rws_socket_set_url(socket, "http", "echo.websocket.org", 80, "/");
rws_socket_set_url(socket, "ws", "echo.websocket.org", 80, "/");
@endcode
*/
RWS_API(void) rws_socket_set_url(rws_socket socket,
const char * scheme,
const char * host,
const int port,
const char * path);
/**
@brief Set socket connect URL scheme string.
@param socket Socket object.
@param scheme Connect URL scheme, "http" or "ws"
@code
rws_socket_set_scheme(socket, "http");
rws_socket_set_scheme(socket, "ws");
@endcode
*/
RWS_API(void) rws_socket_set_scheme(rws_socket socket, const char * scheme);
/**
@brief Get socket connect URL scheme string.
@param socket Socket object.
@return Connect URL cheme or null.
*/
RWS_API(const char *) rws_socket_get_scheme(rws_socket socket);
/**
@brief Set socket connect URL scheme string.
@param socket Socket object.
@param scheme Connect URL host, "echo.websocket.org"
@code
rws_socket_set_host(socket, "echo.websocket.org");
@endcode
*/
RWS_API(void) rws_socket_set_host(rws_socket socket, const char * host);
/**
@brief Get socket connect URL host string.
@param socket Socket object.
@return Connect URL host or null.
*/
RWS_API(const char *) rws_socket_get_host(rws_socket socket);
/**
@brief Set socket connect URL port.
@param socket Socket object.
@param scheme Connect URL port.
@code
rws_socket_set_port(socket, 80);
@endcode
*/
RWS_API(void) rws_socket_set_port(rws_socket socket, const int port);
/**
@brief Get socket connect URL port.
@param socket Socket object.
@return Connect URL port or 0.
*/
RWS_API(int) rws_socket_get_port(rws_socket socket);
/**
@brief Set socket connect URL path string.
@param socket Socket object.
@param scheme Connect URL path started with '/' character, "/" - for empty, "/path"
@code
rws_socket_set_path(socket, "/"); // empty path
rws_socket_set_path(socket, "/path"); // some path
@endcode
*/
RWS_API(void) rws_socket_set_path(rws_socket socket, const char * path);
/**
@brief Get socket connect URL path string.
@param socket Socket object.
@return Connect URL path or null.
*/
RWS_API(const char *) rws_socket_get_path(rws_socket socket);
/**
@brief Set socket connect Sec-WebSocket-Protocol field.
@param socket Socket object.
@param Sec-WebSocket-Protocol.
@code
rws_socket_set_protocol(socket, "echo-protocol")
rws_socket_set_protocol(socket, "chat, superchat")
@endcode
*/
RWS_API(void) rws_socket_set_protocol(rws_socket socket, const char * protocol);
#ifdef WEBSOCKET_SSL_ENABLE
/**
@brief Set server certificate for ssl connection.
@param socket Socket object.
@param server_cert Server certificate.
@param server_cert_len The length of the server certificate caculated by sizeof
*/
RWS_API(void) rws_socket_set_server_cert(rws_socket socket, const char *server_cert, int server_cert_len);
#endif
/**
@brief Get socket last error object handle.
@param socket Socket object.
@return Last error object handle or null if no error.
*/
RWS_API(rws_error) rws_socket_get_error(rws_socket socket);
/**
@brief Start connection.
@detailed This method can generate error object.
@param socket Socket object.
@return rws_true - all params exists and connection started, otherwice rws_false.
*/
RWS_API(rws_bool) rws_socket_connect(rws_socket socket);
/**
@brief Disconnect socket.
@detailed Cleanup prev. send messages and start disconnection sequence.
SHOULD forget about this socket handle and don't use it anymore.
@warning Don't use this socket object handler after this command.
@param socket Socket object.
*/
RWS_API(void) rws_socket_disconnect_and_release(rws_socket socket);
/**
@brief Check is socket has connection to host and handshake(sucessfully done).
@detailed Thread safe getter.
@param socket Socket object.
@return trw_true - connected to host and handshacked, otherwice rws_false.
*/
RWS_API(rws_bool) rws_socket_is_connected(rws_socket socket);
/**
@brief Send text to connect socket.
@detailed Thread safe method.
@param socket Socket object.
@param text Text string for sending.
@return rws_true - socket and text exists and placed to send queue, otherwice rws_false.
*/
RWS_API(rws_bool) rws_socket_send_text(rws_socket socket, const char * text);
/**
@brief Set socket user defined object pointer for identificating socket object.
@param socket Socket object.
@param user_object Void pointer to user object.
*/
RWS_API(void) rws_socket_set_user_object(rws_socket socket, void * user_object);
/**
@brief Get socket user defined object.
@param socket Socket object.
@return User defined object pointer or null.
*/
RWS_API(void *) rws_socket_get_user_object(rws_socket socket);
RWS_API(void) rws_socket_set_on_connected(rws_socket socket, rws_on_socket callback);
RWS_API(void) rws_socket_set_on_disconnected(rws_socket socket, rws_on_socket callback);
RWS_API(void) rws_socket_set_on_received_text(rws_socket socket, rws_on_socket_recvd_text callback);
RWS_API(void) rws_socket_set_on_received_bin(rws_socket socket, rws_on_socket_recvd_bin callback);
/**
@brief Get socket user defined object.
@param socket Socket object.
*/
RWS_API(void) rws_socket_set_on_received_pong(rws_socket socket, rws_on_socket_recvd_pong callback);
/**
@brief Get socket user defined object.
@param socket Socket object.
*/
RWS_API(void) rws_socket_set_on_send_ping(rws_socket socket, rws_on_socket_send_ping callback);
/**
@brief Send bin header to connect socket.
@detailed Thread safe method.
@param socket Socket object.
@param bin header string for sending.
@param len length of header, 8 bytes.
@return rws_true - socket and bin header exists and placed to send queue, otherwice rws_false
*/
RWS_API(rws_bool) rws_socket_send_bin_start(rws_socket socket, const char *bin, size_t len);
/**
@brief Send bin content to connect socket.
@detailed Thread safe method.
@param socket Socket object.
@param binary content for sending.
@param len length of binary content.
@return rws_true - socket and bin content exists and placed to send queue, otherwice rws_false.
*/
RWS_API(rws_bool) rws_socket_send_bin_continue(rws_socket socket, const char *bin, size_t len);
/**
@brief Send final bin to connect socket.
@detailed Thread safe method.
@param socket Socket object.
@param final bin string for sending.
@param len length of final, 6 bytes.
@return rws_true - socket and final bin exists and placed to send queue, otherwice rws_false
*/
RWS_API(rws_bool) rws_socket_send_bin_finish(rws_socket socket, const char * bin, size_t len);
/**
@brief Send ping async to connect socket.
@detailed Thread safe method.
@param socket Socket object.
@return rws_true - send ping success, otherwice rws_false
*/
RWS_API(rws_bool) rws_socket_send_ping(rws_socket socket);
// error
typedef enum _rws_error_code {
rws_error_code_none = 0,
rws_error_code_missed_parameter,
rws_error_code_send_handshake,
rws_error_code_parse_handshake,
rws_error_code_read_write_socket,
rws_error_code_connect_to_host,
/**
@brief Connection was closed by endpoint.
Reasons: an endpoint shutting down, an endpoint having received a frame too large, or an
endpoint having received a frame that does not conform to the format expected by the endpoint.
*/
rws_error_code_connection_closed,
} rws_error_code;
/**
@return 0 - if error is empty or no error, otherwice error code.
*/
RWS_API(int) rws_error_get_code(rws_error error);
/**
@return 0 - if error is empty or no error, otherwice HTTP error.
*/
RWS_API(int) rws_error_get_http_error(rws_error error);
/**
@brief Get description of the error object.
*/
RWS_API(const char *) rws_error_get_description(rws_error error);
// mutex
/**
@brief Creates recursive mutex object.
*/
RWS_API(rws_mutex) rws_mutex_create_recursive(void);
/**
@brief Lock mutex object.
*/
RWS_API(void) rws_mutex_lock(rws_mutex mutex);
/**
@brief Unlock mutex object.
*/
RWS_API(void) rws_mutex_unlock(rws_mutex mutex);
/**
@brief Unlock mutex object.
*/
RWS_API(void) rws_mutex_delete(rws_mutex mutex);
// semphore
/**
@brief Creates semhpore object.
*/
RWS_API(rws_sem) rws_sem_create(void);
/**
@brief Release a semhpore
*/
RWS_API(void) rws_sem_signal(rws_sem sem);
/**
@brief Wait for a semhpore
*/
RWS_API(int) rws_sem_wait(rws_sem sem, unsigned int timeout);
/**
@brief Free semhpore object.
*/
RWS_API(void) rws_sem_delete(rws_sem sem);
// thread
/**
@brief Create thread object that start immidiatelly.
*/
RWS_API(rws_thread) rws_thread_create(rws_thread_funct thread_function, void * user_object);
/**
@brief Pause current thread for a number of milliseconds.
*/
RWS_API(void) rws_thread_sleep(const unsigned int millisec);
#endif
|
YifuLiu/AliOS-Things
|
components/websocket/include/librws.h
|
C
|
apache-2.0
| 13,934
|
/*
* Copyright (c) 2014 - 2019 Oleh Kulykov <info@resident.name>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef __RWS_COMMON_H__
#define __RWS_COMMON_H__ 1
#include <stdio.h>
/* check os */
/* gcc -dM -E - < /dev/null */
/* check windows */
#if !defined(RWS_OS_WINDOWS)
#if defined(WIN32) || defined(_WIN32) || defined(WIN32_LEAN_AND_MEAN) || defined(_WIN64) || defined(WIN64)
#define RWS_OS_WINDOWS 1
#endif
#endif
/* end check windows */
/* check Apple */
#if !defined(RWS_OS_APPLE)
#if defined(__APPLE__) || defined(__MACH__)
#define RWS_OS_APPLE 1
#endif
#endif
/* check Unix */
#if !defined(RWS_OS_UNIX)
#if defined(__unix) || defined(unix) || defined(__unix__)
#define RWS_OS_UNIX 1
#endif
#endif
/* check Linux */
#if !defined(RWS_OS_LINUX)
#if defined(__linux__) || defined(__linux)
#define RWS_OS_LINUX 1
#endif
#endif
/* check Android */
#if !defined(RWS_OS_ANDROID)
#if defined(__ANDROID__) || defined(ANDROID)
#define RWS_OS_ANDROID 1
#endif
#endif
#endif
|
YifuLiu/AliOS-Things
|
components/websocket/include/rws_common.h
|
C
|
apache-2.0
| 2,052
|
/*
* Copyright (c) 2014 - 2019 Oleh Kulykov <info@resident.name>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef __RWS_ERROR_H__
#define __RWS_ERROR_H__ 1
#include "rws_string.h"
struct rws_error_struct {
int code;
int http_error;
char * description;
};
rws_error rws_error_create(void);
rws_error rws_error_new_code_descr(const int code, const char * description);
void rws_error_delete(rws_error error);
void rws_error_delete_clean(rws_error * error);
#endif
|
YifuLiu/AliOS-Things
|
components/websocket/include/rws_error.h
|
C
|
apache-2.0
| 1,554
|
/*
* Copyright (c) 2014 - 2019 Oleh Kulykov <info@resident.name>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef __RWS_FRAME_H__
#define __RWS_FRAME_H__ 1
#include "librws.h"
#include "rws_common.h"
typedef enum _rws_opcode {
rws_opcode_continuation = 0x0, // %x0 denotes a continuation frame
rws_opcode_text_frame = 0x1, // %x1 denotes a text frame
rws_opcode_binary_frame = 0x2, // %x2 denotes a binary frame
rws_opcode_connection_close = 0x8, // %x8 denotes a connection close
rws_opcode_ping = 0x9, // %x9 denotes a ping
rws_opcode_pong = 0xA // %xA denotes a pong
} rws_opcode;
typedef enum _rws_binary {
rws_binary_start,
rws_binary_continue,
rws_binary_finish
} rws_binary;
typedef struct _rws_frame_struct {
void * data;
size_t data_size;
rws_opcode opcode;
unsigned char mask[4];
rws_bool is_masked;
rws_bool is_finished;
unsigned char header_size;
} _rws_frame;
size_t rws_check_recv_frame_size(const void * data, const size_t data_size);
_rws_frame * rws_frame_create_with_recv_data(const void * data, const size_t data_size);
// data - should be null, and setted by newly created. 'data' & 'data_size' can be null
void rws_frame_fill_with_send_data(_rws_frame * f, const void * data, const size_t data_size, rws_bool is_finish);
void litews_frame_fill_with_send_bin_data(_rws_frame * f, const void * data, const size_t data_size, rws_binary bin_type);
// combine datas of 2 frames. combined is 'to'
void rws_frame_combine_datas(_rws_frame * to, _rws_frame * from);
_rws_frame * rws_frame_create(void);
void rws_frame_delete(_rws_frame * f);
void rws_frame_delete_clean(_rws_frame ** f);
#endif
|
YifuLiu/AliOS-Things
|
components/websocket/include/rws_frame.h
|
C
|
apache-2.0
| 2,709
|
/*
* Copyright (c) 2014 - 2019 Oleh Kulykov <info@resident.name>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef __RWS_LIST_H__
#define __RWS_LIST_H__ 1
#include <stdio.h>
typedef union _rws_node_value_union {
void * object;
char * string;
int int_value;
unsigned int uint_value;
} _rws_node_value;
typedef struct _rws_node_struct {
_rws_node_value value;
struct _rws_node_struct * next;
} _rws_node, _rws_list;
_rws_list * rws_list_create(void);
void rws_list_delete(_rws_list * list);
void rws_list_delete_clean(_rws_list ** list);
void rws_list_append(_rws_list * list, _rws_node_value value);
#endif
|
YifuLiu/AliOS-Things
|
components/websocket/include/rws_list.h
|
C
|
apache-2.0
| 1,693
|
/*
* Copyright (c) 2014 - 2019 Oleh Kulykov <info@resident.name>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef __RWS_MEMORY_H__
#define __RWS_MEMORY_H__ 1
#include <stdio.h>
#include <stdlib.h>
#include "rws_common.h"
// size > 0 => malloc
void * rws_malloc(const size_t size);
// size > 0 => malloc
void * rws_malloc_zero(const size_t size);
void rws_free(void * mem);
void rws_free_clean(void ** mem);
#endif
|
YifuLiu/AliOS-Things
|
components/websocket/include/rws_memory.h
|
C
|
apache-2.0
| 1,493
|
/*
* Copyright (C) 2019-2020 Alibaba Group Holding Limited
*/
#ifndef __NETWORK_H__
#define __NETWORK_H__
#include <sys/socket.h>
#include <arpa/inet.h>
#include <lwip/netdb.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct network {
int fd;
struct sockaddr_in address;
int (*net_connect)(struct network *n, char *addr, int port, int net_type);
int (*net_read)(struct network *, unsigned char *, int, int);
int (*net_write)(struct network *, unsigned char *, int, int);
void (*net_disconncet)(struct network *n);
} network_t;
void rws_net_init(network_t *n);
#ifdef __cplusplus
}
#endif
#endif
|
YifuLiu/AliOS-Things
|
components/websocket/include/rws_network.h
|
C
|
apache-2.0
| 632
|
/*
* Copyright (c) 2014 - 2019 Oleh Kulykov <info@resident.name>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef __RWS_SOCKET_H__
#define __RWS_SOCKET_H__ 1
#include "rws_common.h"
#if defined(RWS_OS_WINDOWS)
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <sys/socket.h>
#include <netdb.h>
#include <sys/types.h>
#include <unistd.h>
#endif
#include <assert.h>
#include <errno.h>
#include "rws_error.h"
#include "rws_thread.h"
#include "rws_frame.h"
#include "rws_list.h"
#ifdef WEBSOCKET_SSL_ENABLE
#include "mbedtls/net.h"
#include "mbedtls/ssl.h"
#include "mbedtls/certs.h"
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/debug.h"
#endif
typedef int rws_socket_t;
#define RWS_INVALID_SOCKET -1
#define RWS_SOCK_CLOSE(sock) close(sock)
static const char * k_rws_socket_min_http_ver = "1.1";
static const char * k_rws_socket_sec_websocket_accept = "sec-websocket-accept";
static const char * k_rws_socket_sec_websocket_accept_alt = "Sec-WebSocket-Accept";
#ifdef WEBSOCKET_SSL_ENABLE
typedef struct _rws_ssl_struct
{
mbedtls_ssl_context ssl_ctx; /* mbedtls ssl context */
mbedtls_net_context net_ctx; /* Fill in socket id */
mbedtls_ssl_config ssl_conf; /* SSL configuration */
// mbedtls_entropy_context entropy;
// mbedtls_ctr_drbg_context ctr_drbg;
mbedtls_x509_crt_profile profile;
mbedtls_x509_crt cacert;
mbedtls_x509_crt clicert;
mbedtls_pk_context pkey;
} _rws_ssl;
#endif
struct rws_socket_struct {
int port;
rws_socket_t socket;
char * scheme;
char * host;
char * path;
char * sec_ws_protocol;// "Sec-WebSocket-Protocol" field
char * sec_ws_accept; // "Sec-WebSocket-Accept" field from handshake
rws_thread work_thread;
int command;
unsigned int next_message_id;
rws_bool is_connected; // sock connected + handshake done
void * user_object;
rws_on_socket on_connected;
rws_on_socket on_disconnected;
rws_on_socket_recvd_text on_recvd_text;
rws_on_socket_recvd_bin on_recvd_bin;
rws_on_socket_recvd_pong on_recvd_pong;
rws_on_socket_send_ping on_send_ping;
void * received;
size_t received_size; // size of 'received' memory
size_t received_len; // length of actualy readed message
_rws_list * send_frames;
_rws_list * recvd_frames;
rws_error error;
rws_mutex work_mutex;
rws_mutex send_mutex;
rws_sem exit_sem;
#ifdef WEBSOCKET_SSL_ENABLE
const char *server_cert; /**< Server certification. */
const char *client_cert; /**< Client certification. */
const char *client_pk; /**< Client private key. */
int server_cert_len; /**< Server certification lenght, server_cert buffer size. */
int client_cert_len; /**< Client certification lenght, client_cert buffer size. */
int client_pk_len; /**< Client private key lenght, client_pk buffer size. */
_rws_ssl *ssl; /**< Ssl content. */
#endif
char *recv_buffer;
int recv_buffer_size;
};
rws_bool rws_socket_process_handshake_responce(rws_socket s);
// receive raw data from socket
rws_bool rws_socket_recv(rws_socket s);
// send raw data to socket
rws_bool rws_socket_send(rws_socket s, const void * data, const size_t data_size);
_rws_frame * rws_socket_last_unfin_recvd_frame_by_opcode(rws_socket s, const rws_opcode opcode);
void rws_socket_process_bin_or_text_frame(rws_socket s, _rws_frame * frame);
void rws_socket_process_ping_frame(rws_socket s, _rws_frame * frame);
void rws_socket_process_pong_frame(rws_socket s, _rws_frame * frame);
void rws_socket_process_conn_close_frame(rws_socket s, _rws_frame * frame);
void rws_socket_process_received_frame(rws_socket s, _rws_frame * frame);
void rws_socket_idle_recv(rws_socket s);
void rws_socket_idle_send(rws_socket s);
void rws_socket_wait_handshake_responce(rws_socket s);
unsigned int rws_socket_get_next_message_id(rws_socket s);
rws_bool rws_socket_send_ping_priv(rws_socket s);
void rws_socket_send_disconnect(rws_socket s);
void rws_socket_send_handshake(rws_socket s);
struct addrinfo * rws_socket_connect_getaddr_info(rws_socket s);
void rws_socket_connect_to_host(rws_socket s);
rws_bool rws_socket_create_start_work_thread(rws_socket s);
void rws_socket_close(rws_socket s);
void rws_socket_resize_received(rws_socket s, const size_t size);
void rws_socket_append_recvd_frames(rws_socket s, _rws_frame * frame);
void rws_socket_append_send_frames(rws_socket s, _rws_frame * frame);
rws_bool rws_socket_send_text_priv(rws_socket s, const char * text);
rws_bool rws_socket_send_bin_priv(rws_socket s, const char *bin, size_t len, rws_binary bin_type);
rws_bool rws_socket_send_bin_continue_priv(rws_socket s, const char *bin, size_t len);
rws_bool rws_socket_send_bin_finish_priv(rws_socket s, const char *bin, size_t len);
void rws_socket_inform_recvd_frames(rws_socket s);
void rws_socket_set_option(rws_socket_t s, int option, int value);
void rws_socket_delete_all_frames_in_list(_rws_list * list_with_frames);
void rws_socket_check_write_error(rws_socket s, int error_num);
void rws_socket_delete(rws_socket s);
#ifdef WEBSOCKET_SSL_ENABLE
int rws_ssl_conn(rws_socket s);
int rws_ssl_close(rws_socket s);
#endif
#define COMMAND_IDLE -1
#define COMMAND_NONE 0
#define COMMAND_CONNECT_TO_HOST 1
#define COMMAND_SEND_HANDSHAKE 2
#define COMMAND_WAIT_HANDSHAKE_RESPONCE 3
#define COMMAND_INFORM_CONNECTED 4
#define COMMAND_INFORM_DISCONNECTED 5
#define COMMAND_DISCONNECT 6
#define COMMAND_END 9999
#endif
|
YifuLiu/AliOS-Things
|
components/websocket/include/rws_socket.h
|
C
|
apache-2.0
| 6,597
|
/*
* Copyright (c) 2014 - 2019 Oleh Kulykov <info@resident.name>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef __RWS_STRING_H__
#define __RWS_STRING_H__ 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "rws_common.h"
#if defined(_MSC_VER)
#define rws_sprintf(s,l,f,...) sprintf_s(s,l,f,__VA_ARGS__)
#define rws_sscanf(s,f,...) sscanf_s(s,f,__VA_ARGS__)
#define rws_strerror(e) strerror(e)
#else
#define rws_sprintf(s,l,f,...) sprintf(s,f,__VA_ARGS__)
#define rws_sscanf(s,f,...) sscanf(s,f,__VA_ARGS__)
#define rws_strerror(e) strerror(e)
#endif
char * rws_string_copy(const char * str);
char * rws_string_copy_len(const char * str, const size_t len);
void rws_string_delete(char * str);
void rws_string_delete_clean(char ** str);
#endif
|
YifuLiu/AliOS-Things
|
components/websocket/include/rws_string.h
|
C
|
apache-2.0
| 1,842
|
/*
* Copyright (c) 2014 - 2019 Oleh Kulykov <info@resident.name>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef __RWS_THREAD_H__
#define __RWS_THREAD_H__ 1
#include <stdio.h>
#endif
|
YifuLiu/AliOS-Things
|
components/websocket/include/rws_thread.h
|
C
|
apache-2.0
| 1,261
|
/*
* Copyright (c) 2014 - 2019 Oleh Kulykov <info@resident.name>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "librws.h"
|
YifuLiu/AliOS-Things
|
components/websocket/src/librws.c
|
C
|
apache-2.0
| 1,201
|
/*
* Copyright (c) 2014 - 2019 Oleh Kulykov <info@resident.name>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "rws_common.h"
|
YifuLiu/AliOS-Things
|
components/websocket/src/rws_common.c
|
C
|
apache-2.0
| 1,205
|
/*
* Copyright (c) 2014 - 2019 Oleh Kulykov <info@resident.name>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "librws.h"
#include "rws_error.h"
#include "rws_string.h"
#include "rws_memory.h"
// private
rws_error rws_error_create(void) {
return (rws_error)rws_malloc_zero(sizeof(struct rws_error_struct));
}
rws_error rws_error_new_code_descr(const int code, const char * description) {
rws_error e = (rws_error)rws_malloc_zero(sizeof(struct rws_error_struct));
e->code = code;
e->description = rws_string_copy(description);
return e;
}
void rws_error_delete(rws_error error) {
if (error) {
rws_string_delete(error->description);
rws_free(error);
}
}
void rws_error_delete_clean(rws_error * error) {
if (error) {
rws_error_delete(*error);
*error = NULL;
}
}
// public
int rws_error_get_code(rws_error error) {
return error ? error->code : 0;
}
int rws_error_get_http_error(rws_error error) {
return error ? error->http_error : 0;
}
const char * rws_error_get_description(rws_error error) {
return error ? error->description : NULL;
}
|
YifuLiu/AliOS-Things
|
components/websocket/src/rws_error.c
|
C
|
apache-2.0
| 2,141
|
/*
* Copyright (c) 2014 - 2019 Oleh Kulykov <info@resident.name>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "rws_frame.h"
#include "rws_memory.h"
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <time.h>
_rws_frame * rws_frame_create_with_recv_data(const void * data, const size_t data_size) {
if (data && data_size >= 2) {
const unsigned char * udata = (const unsigned char *)data;
const rws_opcode opcode = (rws_opcode)(udata[0] & 0x0f);
const unsigned int is_finshd = (udata[0] >> 7) & 0x01;
const unsigned int is_masked = (udata[1] >> 7) & 0x01;
const unsigned int payload = udata[1] & 0x7f;
unsigned int header_size = is_masked ? 6 : 2;
unsigned int expected_size = 0, mask_pos = 0;
size_t index = 0;
_rws_frame * frame = NULL;
const unsigned char * actual_udata = NULL;
unsigned char * unmasked = NULL;
switch (payload) {
case 126: header_size += 2; break;
case 127: header_size += 8; break;
default: break;
}
if (data_size < header_size) {
return NULL;
}
switch (payload) {
case 126:
expected_size |= ((unsigned int)udata[2]) << 8;
expected_size |= (unsigned int)udata[3];
mask_pos = 4;
break;
case 127:
expected_size |= ((unsigned int)udata[6]) << 24;
expected_size |= ((unsigned int)udata[7]) << 16;
expected_size |= ((unsigned int)udata[8]) << 8;
expected_size |= (unsigned int)udata[9];
mask_pos = 10;
break;
default:
if (payload <= 125) {
mask_pos = 2;
expected_size = payload;
}
break;
}
frame = rws_frame_create();
frame->opcode = opcode;
if (is_finshd) frame->is_finished = rws_true;
frame->header_size = (unsigned char)header_size;
if (is_masked) {
frame->is_masked = rws_true;
memcpy(frame->mask, &udata[mask_pos], 4);
}
if (opcode == rws_opcode_connection_close || opcode == rws_opcode_pong) {
return frame;
}
if (!is_finshd) {
frame->is_finished = rws_false;
}
if (expected_size > 0) {
frame->data = rws_malloc(expected_size);
frame->data_size = expected_size;
actual_udata = udata + header_size;
if (is_masked) {
unmasked = (unsigned char *)frame->data;
for (index = 0; index < expected_size; index++) {
*unmasked = *actual_udata ^ frame->mask[index & 0x3];
unmasked++; actual_udata++;
}
} else {
memcpy(frame->data, actual_udata, expected_size);
}
}
return frame;
}
return NULL;
}
void rws_frame_create_header(_rws_frame * f, unsigned char * header, const size_t data_size) {
const unsigned int size = (unsigned int)data_size;
unsigned char fin = 0x80;
if (f->is_finished == rws_false) fin = 0x00;
*header++ = fin | f->opcode;
if (size < 126) {
*header++ = (size & 0xff) | (f->is_masked ? 0x80 : 0);
f->header_size = 2;
} else if (size < 65536) {
*header++ = 126 | (f->is_masked ? 0x80 : 0);
*header++ = (size >> 8) & 0xff;
*header++ = size & 0xff;
f->header_size = 4;
} else {
*header++ = 127 | (f->is_masked ? 0x80 : 0);
*(unsigned int *)header = 0;
header += 4;
*header++ = (size >> 24) & 0xff;
*header++ = (size >> 16) & 0xff;
*header++ = (size >> 8) & 0xff;
*header++ = size & 0xff;
f->header_size = 10;
}
if (f->is_masked) {
memcpy(header, f->mask, 4);
f->header_size += 4;
}
}
void litews_frame_create_bin_header(_rws_frame * f, unsigned char * header, const size_t data_size, rws_binary bin_type)
{
const unsigned int size = (unsigned int)data_size;
if(bin_type == rws_binary_start)
{
*header++ = 0x00 | f->opcode;
}
else if(bin_type == rws_binary_continue)
{
*header++ = 0x00 | f->opcode;
}
else
{
*header++ = 0x80 | f->opcode;
}
if (size < 126)
{
*header++ = (size & 0xff) | (f->is_masked ? 0x80 : 0);
f->header_size = 2;
}
else if (size < 65536)
{
*header++ = 126 | (f->is_masked ? 0x80 : 0);
*header++ = (size >> 8) & 0xff;
*header++ = size & 0xff;
f->header_size = 4;
}
else
{
*header++ = 127 | (f->is_masked ? 0x80 : 0);
*(unsigned int *)header = 0;
header += 4;
*header++ = (size >> 24) & 0xff;
*header++ = (size >> 16) & 0xff;
*header++ = (size >> 8) & 0xff;
*header++ = size & 0xff;
f->header_size = 10;
}
if (f->is_masked)
{
memcpy(header, f->mask, 4);
f->header_size += 4;
}
}
void rws_frame_fill_with_send_data(_rws_frame * f, const void * data, const size_t data_size, rws_bool is_finish) {
unsigned char header[16];
unsigned char * frame = NULL;
unsigned char mask[4];
size_t index = 0;
f->is_finished = is_finish;
rws_frame_create_header(f, header, data_size);
f->data_size = data_size + f->header_size;
f->data = rws_malloc(f->data_size);
if (f->data == NULL) {
DBG("rws_malloc fail\n");
return;
}
frame = (unsigned char *)f->data;
memcpy(frame, header, f->header_size);
if (data) { // have data to send
frame += f->header_size;
memcpy(frame, data, data_size);
if (f->is_masked) {
memcpy(mask, &f->mask, 4);
for (index = 0; index < data_size; index++) {
*frame = *frame ^ mask[index & 0x3];
frame++;
}
}
}
//f->is_finished = rws_true;
}
void litews_frame_fill_with_send_bin_data(_rws_frame * f, const void * data, const size_t data_size, rws_binary bin_type)
{
unsigned char header[16];
unsigned char * frame = NULL;
unsigned char mask[4];
size_t index = 0;
litews_frame_create_bin_header(f, header, data_size, bin_type);
//check bin header data
// -----------------------------------------------
// F | | | | | | | |
// I | 0 | 0 | 0 | OPCODE |
// N | | | | | | | |
f->data_size = data_size + f->header_size;
f->data = rws_malloc(f->data_size);
if (f->data == NULL) {
DBG("rws_malloc fail\n");
return;
}
frame = (unsigned char *)f->data;
memcpy(frame, header, f->header_size);
if (data)
{ // have data to send
frame += f->header_size;
memcpy(frame, data, data_size);
if (f->is_masked)
{
memcpy(mask, &f->mask, 4);
for (index = 0; index < data_size; index++)
{
*frame = *frame ^ mask[index & 0x3];
frame++;
}
}
}
if(bin_type == rws_binary_finish)
{
f->is_finished = rws_true;
}
else
{
f->is_finished = rws_false;
}
}
void rws_frame_combine_datas(_rws_frame * to, _rws_frame * from) {
unsigned char * comb_data = (unsigned char *)rws_malloc(to->data_size + from->data_size);
if (comb_data) {
if (to->data && to->data_size) {
memcpy(comb_data, to->data, to->data_size);
}
comb_data += to->data_size;
if (from->data && from->data_size) {
memcpy(comb_data, from->data, from->data_size);
}
}
rws_free(to->data);
to->data = comb_data;
to->data_size += from->data_size;
}
_rws_frame * rws_frame_create(void) {
_rws_frame * f = (_rws_frame *)rws_malloc_zero(sizeof(_rws_frame));
union {
unsigned int ui;
unsigned char b[4];
} mask_union;
assert(sizeof(unsigned int) == 4);
// mask_union.ui = 2018915346;
mask_union.ui = (rand() / (RAND_MAX / 2) + 1) * rand();
memcpy(f->mask, mask_union.b, 4);
return f;
}
void rws_frame_delete(_rws_frame * f) {
if (f) {
rws_free(f->data);
rws_free(f);
}
}
void rws_frame_delete_clean(_rws_frame ** f) {
if (f) {
rws_frame_delete(*f);
*f = NULL;
}
}
size_t rws_check_recv_frame_size(const void * data, const size_t data_size) {
if (data && data_size >= 2) {
const unsigned char * udata = (const unsigned char *)data;
// const unsigned int is_finshd = (udata[0] >> 7) & 0x01;
const unsigned int is_masked = (udata[1] >> 7) & 0x01;
const unsigned int payload = udata[1] & 0x7f;
unsigned int header_size = is_masked ? 6 : 2;
unsigned int expected_size = 0;
switch (payload) {
case 126: header_size += 2; break;
case 127: header_size += 8; break;
default: break;
}
if (data_size < header_size) {
return 0;
}
switch (payload) {
case 126:
expected_size |= ((unsigned int)udata[2]) << 8;
expected_size |= (unsigned int)udata[3];
break;
case 127:
expected_size |= ((unsigned int)udata[6]) << 24;
expected_size |= ((unsigned int)udata[7]) << 16;
expected_size |= ((unsigned int)udata[8]) << 8;
expected_size |= (unsigned int)udata[9];
break;
default:
if (payload <= 125) {
expected_size = payload;
}
break;
}
const unsigned int nPackSize = expected_size + header_size;
return (nPackSize <= data_size) ? nPackSize : 0;
}
return 0;
}
|
YifuLiu/AliOS-Things
|
components/websocket/src/rws_frame.c
|
C
|
apache-2.0
| 9,513
|
/*
* Copyright (c) 2014 - 2019 Oleh Kulykov <info@resident.name>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "rws_list.h"
#include "rws_memory.h"
_rws_list * rws_list_create(void) {
return (_rws_list *)rws_malloc_zero(sizeof(_rws_list));
}
void rws_list_delete(_rws_list * list) {
_rws_list * cur = list;
while (cur) {
_rws_list * prev = cur;
cur = cur->next;
rws_free(prev);
}
}
void rws_list_delete_clean(_rws_list ** list) {
if (list) {
rws_list_delete(*list);
*list = NULL;
}
}
void rws_list_append(_rws_list * list, _rws_node_value value) {
if (list) {
_rws_list * cur = list;
while (cur->next) {
cur = cur->next;
}
cur->next = (_rws_node *)rws_malloc_zero(sizeof(_rws_node));
cur->next->value = value;
}
}
|
YifuLiu/AliOS-Things
|
components/websocket/src/rws_list.c
|
C
|
apache-2.0
| 1,826
|
/*
* Copyright (c) 2014 - 2019 Oleh Kulykov <info@resident.name>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "rws_memory.h"
#include <string.h>
#include <stdlib.h>
#include <assert.h>
void * rws_malloc(const size_t size) {
if (size > 0) {
void * mem = malloc(size);
assert(mem);
return mem;
}
return NULL;
}
void * rws_malloc_zero(const size_t size) {
void * mem = rws_malloc(size);
if (mem) {
memset(mem, 0, size);
}
return mem;
}
void rws_free(void * mem) {
if (mem) {
free(mem);
}
}
void rws_free_clean(void ** mem) {
if (mem) {
rws_free(*mem);
*mem = NULL;
}
}
|
YifuLiu/AliOS-Things
|
components/websocket/src/rws_memory.c
|
C
|
apache-2.0
| 1,672
|
/*
* Copyright (c) 2014 - 2019 Oleh Kulykov <info@resident.name>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "librws.h"
#include "rws_socket.h"
#include "rws_memory.h"
#include "rws_string.h"
#define READ_TIMEOUT_MS 5000
#define WRITE_TIMEOUT_MS 5000
#define RWS_CONNECT_RETRY_DELAY 200
#define RWS_CONNECT_ATTEMPS 2
#define WSAEWOULDBLOCK EAGAIN
#define WSAEINPROGRESS EINPROGRESS
#ifndef MAX_THRESH_VAL
#define MAX_THRESH_VAL 204800 /* common TTS play size */
#endif
unsigned int rws_socket_get_next_message_id(rws_socket s) {
const unsigned int mess_id = ++s->next_message_id;
if (mess_id > 9999999) {
s->next_message_id = 0;
}
return mess_id;
}
rws_bool rws_socket_send_ping_priv(rws_socket s) {
char buff[16];
size_t len = 0;
_rws_frame * frame = rws_frame_create();
if (frame == NULL)
return rws_false;
len = rws_sprintf(buff, 16, "%u", rws_socket_get_next_message_id(s));
frame->is_masked = rws_true;
frame->opcode = rws_opcode_ping;
rws_frame_fill_with_send_data(frame, buff, len, rws_true);
rws_socket_append_send_frames(s, frame);
return rws_true;
}
void rws_socket_inform_recvd_frames(rws_socket s) {
rws_bool is_all_finished = rws_true;
_rws_frame * frame = NULL;
_rws_node * cur = s->recvd_frames;
while (cur) {
frame = (_rws_frame *)cur->value.object;
if (frame) {
//if (frame->is_finished) {
switch (frame->opcode) {
case rws_opcode_continuation:
// continue send finish
if (s->on_recvd_bin) {
s->on_recvd_bin(s, frame->data, (unsigned int)frame->data_size, frame->is_finished);
}
break;
case rws_opcode_text_frame:
if (s->on_recvd_text) {
s->on_recvd_text(s, (const char *)frame->data, (unsigned int)frame->data_size, frame->is_finished);
}
break;
case rws_opcode_binary_frame:
if (s->on_recvd_bin) {
s->on_recvd_bin(s, frame->data, (unsigned int)frame->data_size, frame->is_finished);
}
break;
case rws_opcode_pong:
if (s->on_recvd_pong) {
s->on_recvd_pong(s);
}
break;
default: break;
}
rws_frame_delete(frame);
cur->value.object = NULL;
/*} else {
is_all_finished = rws_false;
}*/
}
cur = cur->next;
}
if (is_all_finished) {
rws_list_delete_clean(&s->recvd_frames);
}
}
void rws_socket_read_handshake_responce_value(const char * str, char ** value) {
const char * s = NULL;
size_t len = 0;
while (*str == ':' || *str == ' ') {
str++;
}
s = str;
while (*s != '\r' && *s != '\n') {
s++;
len++;
}
if (len > 0) {
*value = rws_string_copy_len(str, len);
}
}
rws_bool rws_socket_process_handshake_responce(rws_socket s) {
const char * str = (const char *)s->received;
const char * sub = NULL;
const char * accept_str = NULL;
float http_ver = -1;
int http_code = -1;
rws_error_delete_clean(&s->error);
sub = strstr(str, "HTTP/");
if (!sub) {
return rws_false;
}
//sub += 5;
sub += 9;
// ATTENTION: some platform may not support float
//if (rws_sscanf(sub, "%f %i", &http_ver, &http_code) != 2) {
if (rws_sscanf(sub, "%i", &http_code) != 1) {
http_ver = -1;
http_code = -1;
}
sub = strstr(str, k_rws_socket_sec_websocket_accept); // "Sec-WebSocket-Accept"
if (sub) {
accept_str = k_rws_socket_sec_websocket_accept;
} else {
sub = strstr(str, k_rws_socket_sec_websocket_accept_alt);
if (sub) {
accept_str = k_rws_socket_sec_websocket_accept_alt;
}
}
if (sub) {
sub += strlen(accept_str);
rws_socket_read_handshake_responce_value(sub, &s->sec_ws_accept);
}
if (http_code != 101 || !s->sec_ws_accept) {
s->error = rws_error_new_code_descr(rws_error_code_parse_handshake,
(http_code != 101) ? "HTPP code not found or non 101" : "Accept key not found");
return rws_false;
}
return rws_true;
}
// need close socket on error
rws_bool rws_socket_send(rws_socket s, const void * data, const size_t data_size) {
int sended = -1, error_number = -1;
uint32_t writtenLen = 0;
rws_error_delete_clean(&s->error);
while (writtenLen < data_size) {
#ifdef WEBSOCKET_SSL_ENABLE
if (s->scheme && strcmp(s->scheme, "wss") == 0) {
if (s->ssl)
sended = mbedtls_ssl_write(&(s->ssl->ssl_ctx), (const unsigned char *)(data + writtenLen), (int)(data_size - writtenLen));
else {
ERR("%s %d ssl invlalid ctx", __func__, __LINE__);
sended = -1;
break;
}
}
else
#endif
sended = (int)send(s->socket, (data + writtenLen), (int)(data_size - writtenLen), 0);
if (sended > 0) {
writtenLen += sended;
} else {
error_number = errno;
break;
}
}
if (sended > 0) {
if (sended < data_size) {
WRN("%s %d sended %d but want %d", __func__, __LINE__, sended, data_size);
}
return rws_true;
}
rws_socket_check_write_error(s, error_number);
if (s->error) {
ERR("rws_socket_send return %d\n", error_number);
rws_socket_close(s);
}
return rws_false;
}
rws_bool rws_socket_recv(rws_socket s) {
int is_reading = 1, error_number = -1, len = -1;
char * received = NULL;
size_t total_len = 0;
char *buffer = NULL;
int buffer_size = 0;
int ssl_status = 0;
buffer = s->recv_buffer;
buffer_size = s->recv_buffer_size;
if (NULL == buffer || buffer_size <= 0) {
return false;
}
memset(buffer, 0, buffer_size);
rws_error_delete_clean(&s->error);
while (is_reading) {
#ifdef WEBSOCKET_SSL_ENABLE
if(s->scheme && strcmp(s->scheme, "wss") == 0) {
if (s->ssl) {
len = mbedtls_ssl_read(&(s->ssl->ssl_ctx), (unsigned char *)buffer, buffer_size);
} else {
ERR("%s %d ssl invlalid ctx", __func__, __LINE__);
return false;
}
}
else
#endif
len = (int)recv(s->socket, buffer, buffer_size, 0);
error_number = errno;
if (len > 0) {
total_len += len;
if (s->received_size - s->received_len < len) {
#ifdef _AMLOGIC_
if (s->received_size + len > MAX_THRESH_VAL) {
WRN("Message len exceed MAX_THRESH_VAL, drop it!");
s->received_len = 0;
continue;
}
#endif
rws_socket_resize_received(s, s->received_size + len);
}
received = (char *)s->received;
if (s->received_len) {
received += s->received_len;
}
memcpy(received, buffer, len);
s->received_len += len;
} else if (len == 0) {
is_reading = 0;
} else {
is_reading = 0;
#ifdef WEBSOCKET_SSL_ENABLE
if(s->scheme && strcmp(s->scheme, "wss") == 0) {
if (MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY == len) {
ERR("peer close -0x%04x", -len);
// net_status = -2; /* connection is closed */
} else if ((MBEDTLS_ERR_SSL_TIMEOUT == len)
|| (MBEDTLS_ERR_SSL_CONN_EOF == len)
|| (MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED == len)
|| (MBEDTLS_ERR_SSL_NON_FATAL == len)) {
/* read already complete */
/* if call mbedtls_ssl_read again, it will return 0 (means EOF) */
ssl_status = 1;
} else {
/* Connection error */
ERR("recv -0x%04x", -len);
}
}
#endif
}
}
//if (error_number < 0) return rws_true;
if (error_number != WSAEWOULDBLOCK && error_number != WSAEINPROGRESS
&& ssl_status != 1) {
ERR("in close websocket %d\n", error_number);
s->error = rws_error_new_code_descr(rws_error_code_read_write_socket, "Failed read/write socket");
rws_socket_close(s);
return rws_false;
}
return rws_true;
}
_rws_frame * rws_socket_last_unfin_recvd_frame_by_opcode(rws_socket s, const rws_opcode opcode) {
_rws_frame * last = NULL;
_rws_frame * frame = NULL;
_rws_node * cur = s->recvd_frames;
while (cur) {
frame = (_rws_frame *)cur->value.object;
if (frame) {
// [FIN=0,opcode !=0 ],[FIN=0,opcode ==0 ],....[FIN=1,opcode ==0 ]
if (!frame->is_finished /*&& frame->opcode == opcode*/) {
last = frame;
}
}
cur = cur->next;
}
return last;
}
void rws_socket_process_bin_or_text_frame(rws_socket s, _rws_frame * frame) {
_rws_frame * last_unfin = rws_socket_last_unfin_recvd_frame_by_opcode(s, frame->opcode);
if (last_unfin) {
rws_frame_combine_datas(last_unfin, frame);
last_unfin->is_finished = frame->is_finished;
rws_frame_delete(frame);
} else if (frame->data && frame->data_size) {
rws_socket_append_recvd_frames(s, frame);
} else if (frame->data_size == 0 && frame->is_finished) {
rws_socket_append_recvd_frames(s, frame);
} else {
rws_frame_delete(frame);
}
}
void rws_socket_process_pong_frame(rws_socket s, _rws_frame * frame) {
rws_socket_append_recvd_frames(s, frame);
}
void rws_socket_process_ping_frame(rws_socket s, _rws_frame * frame) {
_rws_frame * pong_frame = rws_frame_create();
pong_frame->opcode = rws_opcode_pong;
pong_frame->is_masked = rws_true;
rws_frame_fill_with_send_data(pong_frame, frame->data, frame->data_size, rws_true);
rws_frame_delete(frame);
rws_socket_append_send_frames(s, pong_frame);
}
void rws_socket_process_conn_close_frame(rws_socket s, _rws_frame * frame) {
s->command = COMMAND_INFORM_DISCONNECTED;
s->error = rws_error_new_code_descr(rws_error_code_connection_closed, "Connection was closed by endpoint");
//rws_socket_close(s);
rws_frame_delete(frame);
}
void rws_socket_process_received_frame(rws_socket s, _rws_frame * frame) {
DBG("%s: frame->opcode:%d", __FUNCTION__, frame->opcode);
switch (frame->opcode) {
case rws_opcode_ping: rws_socket_process_ping_frame(s, frame); break;
case rws_opcode_pong:
DBG("%s: rws_opcode_pong\n", __FUNCTION__);
if (s->on_recvd_pong) s->on_recvd_pong(s);
rws_frame_delete(frame);
break;
case rws_opcode_text_frame:
case rws_opcode_binary_frame:
case rws_opcode_continuation:
rws_socket_process_bin_or_text_frame(s, frame);
break;
case rws_opcode_connection_close: rws_socket_process_conn_close_frame(s, frame); break;
default:
// unprocessed => delete
rws_frame_delete(frame);
break;
}
}
void rws_socket_idle_recv(rws_socket s) {
_rws_frame * frame = NULL;
if (!rws_socket_recv(s)) {
// sock already closed
if (s->error) {
s->command = COMMAND_INFORM_DISCONNECTED;
}
return;
}
const size_t nframe_size = rws_check_recv_frame_size(s->received, s->received_len);
if (nframe_size) {
frame = rws_frame_create_with_recv_data(s->received, nframe_size);
if (frame) {
rws_socket_process_received_frame(s, frame);
}
if (nframe_size == s->received_len) {
s->received_len = 0;
} else if (s->received_len > nframe_size) {
const size_t nLeftLen = s->received_len - nframe_size;
memmove((char*)s->received, (char*)s->received + nframe_size, nLeftLen);
s->received_len = nLeftLen;
}
}
}
void rws_socket_idle_send(rws_socket s) {
_rws_node * cur = NULL;
rws_bool sending = rws_true;
_rws_frame * frame = NULL;
rws_mutex_lock(s->send_mutex);
cur = s->send_frames;
if (cur) {
while (cur && s->is_connected && sending) {
frame = (_rws_frame *)cur->value.object;
cur->value.object = NULL;
if (frame) {
sending = rws_socket_send(s, frame->data, frame->data_size);
if (sending) {
if (rws_opcode_ping == frame->opcode &&
s->on_send_ping) {
s->on_send_ping(s);
}
}
}
rws_frame_delete(frame);
cur = cur->next;
}
rws_socket_delete_all_frames_in_list(s->send_frames);
rws_list_delete_clean(&s->send_frames);
if (s->error) {
s->command = COMMAND_INFORM_DISCONNECTED;
}
}
rws_mutex_unlock(s->send_mutex);
}
void rws_socket_wait_handshake_responce(rws_socket s) {
if (!rws_socket_recv(s)) {
// sock already closed
if (s->error) {
s->command = COMMAND_INFORM_DISCONNECTED;
}
return;
}
if (s->received_len == 0) {
return;
}
if (rws_socket_process_handshake_responce(s)) {
s->received_len = 0;
s->is_connected = rws_true;
s->command = COMMAND_INFORM_CONNECTED;
} else {
rws_socket_close(s);
s->command = COMMAND_INFORM_DISCONNECTED;
}
}
void rws_socket_send_disconnect(rws_socket s) {
char buff[16];
size_t len = 0;
_rws_frame * frame = NULL;
if (s->socket == RWS_INVALID_SOCKET)
return;
frame = rws_frame_create();
len = rws_sprintf(buff, 16, "%u", rws_socket_get_next_message_id(s));
frame->is_masked = rws_true;
frame->opcode = rws_opcode_connection_close;
rws_frame_fill_with_send_data(frame, buff, len, rws_true);
rws_socket_send(s, frame->data, frame->data_size);
rws_frame_delete(frame);
s->command = COMMAND_END;
rws_thread_sleep(RWS_CONNECT_RETRY_DELAY); // little bit wait after send message
}
void rws_socket_send_handshake(rws_socket s) {
char buff[512];
char * ptr = buff;
size_t writed = 0;
char * protocol = (s->sec_ws_protocol ? s->sec_ws_protocol : "chat, superchat");
writed = rws_sprintf(ptr, 512, "GET %s HTTP/%s\r\n", s->path, k_rws_socket_min_http_ver);
if (s->port == 80) {
writed += rws_sprintf(ptr + writed, 512 - writed, "Host: %s\r\n", s->host);
} else {
writed += rws_sprintf(ptr + writed, 512 - writed, "Host: %s:%i\r\n", s->host, s->port);
}
writed += rws_sprintf(ptr + writed, 512 - writed,
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Origin: %s://%s\r\n",
s->scheme, s->host);
writed += rws_sprintf(ptr + writed, 512 - writed,
"Sec-WebSocket-Key: %s\r\n"
"Sec-WebSocket-Protocol: %s\r\n"
"Sec-WebSocket-Version: 13\r\n"
"\r\n",
"dGhlIHNhbXBsZSBub25jZQ==", protocol);
if (rws_socket_send(s, buff, writed)) {
s->command = COMMAND_WAIT_HANDSHAKE_RESPONCE;
} else {
if (s->error) {
s->error->code = rws_error_code_send_handshake;
} else {
s->error = rws_error_new_code_descr(rws_error_code_send_handshake, "Send handshake");
}
rws_socket_close(s);
s->command = COMMAND_INFORM_DISCONNECTED;
}
}
struct addrinfo * rws_socket_connect_getaddr_info(rws_socket s) {
struct addrinfo hints;
char portstr[16];
struct addrinfo * result = NULL;
int ret = 0, retry_number = 0, last_ret = 0;
rws_error_delete_clean(&s->error);
rws_sprintf(portstr, 16, "%i", s->port);
while (++retry_number < RWS_CONNECT_ATTEMPS) {
result = NULL;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
ret = getaddrinfo(s->host, portstr, &hints, &result);
if (ret == 0 && result) {
return result;
}
WRN("websoc getaddrinfo failed! try times: %d!", retry_number);
if (ret != 0) {
last_ret = ret;
}
if (result) {
freeaddrinfo(result);
}
rws_thread_sleep(RWS_CONNECT_RETRY_DELAY);
}
// s->error = rws_error_new_code_descr(rws_error_code_connect_to_host,
// (last_ret > 0) ? gai_strerror(last_ret) : "Failed connect to host");
s->error = rws_error_new_code_descr(rws_error_code_connect_to_host,
"Failed connect to host");
s->command = COMMAND_INFORM_DISCONNECTED;
ERR("websoc connect_getaddr_info failed!");
return NULL;
}
void rws_socket_connect_to_host(rws_socket s) {
struct addrinfo * result = NULL;
struct addrinfo * p = NULL;
rws_socket_t sock = RWS_INVALID_SOCKET;
int retry_number = 0;
result = rws_socket_connect_getaddr_info(s);
if (!result) {
return;
}
while ((++retry_number < RWS_CONNECT_ATTEMPS) && (sock == RWS_INVALID_SOCKET)) {
for (p = result; p != NULL; p = p->ai_next) {
sock = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
if (sock != RWS_INVALID_SOCKET) {
rws_socket_set_option(sock, SO_ERROR, 1); // When an error occurs on a socket, set error variable so_error and notify process
rws_socket_set_option(sock, SO_KEEPALIVE, 1); // Periodically test if connection is alive
if (connect(sock, p->ai_addr, p->ai_addrlen) == 0) {
s->received_len = 0;
s->socket = sock;
fcntl(s->socket, F_SETFL, O_NONBLOCK);
break;
}
RWS_SOCK_CLOSE(sock);
sock = RWS_INVALID_SOCKET;
WRN("websoc connect failed! try times: %d!", retry_number);
}
}
if (sock == RWS_INVALID_SOCKET) {
rws_thread_sleep(RWS_CONNECT_RETRY_DELAY);
}
}
freeaddrinfo(result);
if (s->socket == RWS_INVALID_SOCKET) {
ERR("websoc rws_socket_connect_to_host failed!");
s->error = rws_error_new_code_descr(rws_error_code_connect_to_host, "Failed connect to host");
s->command = COMMAND_INFORM_DISCONNECTED;
} else {
s->command = COMMAND_SEND_HANDSHAKE;
}
}
static void rws_socket_work_th_func(void * user_object) {
rws_socket s = (rws_socket)user_object;
while (s->command < COMMAND_END) {
rws_mutex_lock(s->work_mutex);
switch (s->command) {
case COMMAND_CONNECT_TO_HOST:
{
#ifdef WEBSOCKET_SSL_ENABLE
if(s->scheme && strcmp(s->scheme, "wss") == 0) {
rws_ssl_conn(s);
DBG("after rws_ssl_conn %d\n", s->command);
break;
}
else
#endif /* WEBSOCKET_SSL_ENABLE */
{
rws_socket_connect_to_host(s); break;
}
}
case COMMAND_SEND_HANDSHAKE: rws_socket_send_handshake(s); break;
case COMMAND_WAIT_HANDSHAKE_RESPONCE: rws_socket_wait_handshake_responce(s); break;
case COMMAND_DISCONNECT: rws_socket_send_disconnect(s); break;
case COMMAND_IDLE:
if (s->is_connected) {
rws_socket_idle_send(s);
}
if (s->is_connected) {
rws_socket_idle_recv(s);
}
break;
default: break;
}
rws_mutex_unlock(s->work_mutex);
switch (s->command) {
case COMMAND_INFORM_CONNECTED:
s->command = COMMAND_IDLE;
if (s->on_connected) {
s->on_connected(s);
}
break;
case COMMAND_INFORM_DISCONNECTED: {
s->command = COMMAND_END;
rws_error last_error = rws_socket_get_error(s);
s->error = NULL;
rws_socket_send_disconnect(s);
if (s->error) {
rws_error_delete_clean(&s->error);
}
s->error = last_error;
if (s->on_disconnected) {
s->on_disconnected(s);
}
WRN("rws_socket_work_th_func COMMAND_INFORM_DISCONNECTED\n");
}
break;
case COMMAND_IDLE:
if (s->recvd_frames) {
rws_socket_inform_recvd_frames(s);
}
break;
default: break;
}
rws_thread_sleep(10);
}
rws_socket_close(s);
s->work_thread = NULL;
rws_sem_signal(s->exit_sem);
WRN("end rws_socket_work_th_func\n");
}
rws_bool rws_socket_create_start_work_thread(rws_socket s) {
rws_error_delete_clean(&s->error);
s->command = COMMAND_NONE;
s->work_thread = rws_thread_create(&rws_socket_work_th_func, s);
if (s->work_thread) {
s->command = COMMAND_CONNECT_TO_HOST;
return rws_true;
}
return rws_false;
}
void rws_socket_resize_received(rws_socket s, const size_t need_size) {
void * res = NULL;
size_t min = 0;
size_t size = MAX_THRESH_VAL;
if (need_size == s->received_size) {
return;
}
if (need_size > MAX_THRESH_VAL) {
size = need_size;
}
res = rws_malloc(size);
assert(res && (size > 0));
min = (s->received_size < size) ? s->received_size : size;
if (min > 0 && s->received) {
memcpy(res, s->received, min);
}
rws_free_clean(&s->received);
s->received = res;
s->received_size = size;
}
void rws_socket_close(rws_socket s) {
s->received_len = 0;
if (s->socket != RWS_INVALID_SOCKET) {
#ifdef WEBSOCKET_SSL_ENABLE
if(s->scheme && strcmp(s->scheme, "wss") == 0)
rws_ssl_close(s);
else
#endif /* WEBSOCKET_SSL_ENABLE */
RWS_SOCK_CLOSE(s->socket);
s->socket = RWS_INVALID_SOCKET;
}
s->is_connected = rws_false;
}
void rws_socket_append_recvd_frames(rws_socket s, _rws_frame * frame) {
_rws_node_value frame_list_var;
frame_list_var.object = frame;
if (s->recvd_frames) {
rws_list_append(s->recvd_frames, frame_list_var);
} else {
s->recvd_frames = rws_list_create();
s->recvd_frames->value = frame_list_var;
}
}
void rws_socket_append_send_frames(rws_socket s, _rws_frame * frame) {
_rws_node_value frame_list_var;
frame_list_var.object = frame;
if (s->send_frames) {
rws_list_append(s->send_frames, frame_list_var);
} else {
s->send_frames = rws_list_create();
s->send_frames->value = frame_list_var;
}
}
rws_bool rws_socket_send_text_priv(rws_socket s, const char * text) {
size_t len = text ? strlen(text) : 0;
_rws_frame * frame = NULL;
if (len <= 0) {
return rws_false;
}
frame = rws_frame_create();
frame->is_masked = rws_true;
frame->opcode = rws_opcode_text_frame;
rws_frame_fill_with_send_data(frame, text, len, rws_true);
rws_socket_append_send_frames(s, frame);
return rws_true;
}
rws_bool rws_socket_send_bin_priv(rws_socket s, const char * bin, size_t size, rws_binary bin_type)
{
_rws_frame * frame = NULL;
frame = rws_frame_create();
if (frame != NULL)
{
frame->is_masked = rws_true;
switch (bin_type)
{
case rws_binary_start:
//DBG("rws_binary_start\n");
frame->opcode = rws_opcode_binary_frame;
break;
case rws_binary_continue:
//DBG("rws_binary_continue\n");
frame->opcode = rws_opcode_continuation;
break;
case rws_binary_finish:
//DBG("rws_binary_finish\n");
frame->opcode = rws_opcode_continuation;
break;
}
litews_frame_fill_with_send_bin_data(frame, bin, size, bin_type);
rws_socket_append_send_frames(s, frame);
return rws_true;
}
else
{
/*Need to free data????*/
return rws_false;
}
}
rws_bool rws_socket_send_bin_start_priv(rws_socket s, const char *bin, size_t len) {
//CHECK_RET_WITH_RET(bin, rws_false);
_rws_frame * frame = NULL;
if (len <= 0) {
return rws_false;
}
frame = rws_frame_create();
frame->is_masked = rws_true;
frame->opcode = rws_opcode_binary_frame;
rws_frame_fill_with_send_data(frame, bin, len, rws_false);
rws_socket_append_send_frames(s, frame);
return rws_true;
}
rws_bool rws_socket_send_bin_continue_priv(rws_socket s, const char *bin, size_t len) {
//CHECK_RET_WITH_RET(bin, rws_false);
_rws_frame * frame = NULL;
if (len <= 0) {
return rws_false;
}
frame = rws_frame_create();
frame->is_masked = rws_true;
frame->opcode = rws_opcode_continuation;
rws_frame_fill_with_send_data(frame, bin, len, rws_false);
rws_socket_append_send_frames(s, frame);
return rws_true;
}
rws_bool rws_socket_send_bin_finish_priv(rws_socket s, const char *bin, size_t len) {
//CHECK_RET_WITH_RET(bin, rws_false);
_rws_frame * frame = NULL;
if (len <= 0) {
return rws_false;
}
frame = rws_frame_create();
frame->is_masked = rws_true;
frame->opcode = rws_opcode_continuation;
rws_frame_fill_with_send_data(frame, bin, len, rws_true);
rws_socket_append_send_frames(s, frame);
return rws_true;
}
void rws_socket_delete_all_frames_in_list(_rws_list * list_with_frames) {
_rws_frame * frame = NULL;
_rws_node * cur = list_with_frames;
while (cur) {
frame = (_rws_frame *)cur->value.object;
if (frame) {
rws_frame_delete(frame);
}
cur->value.object = NULL;
cur = cur->next;
}
}
void rws_socket_set_option(rws_socket_t s, int option, int value) {
setsockopt(s, SOL_SOCKET, option, (char *)&value, sizeof(int));
}
void rws_socket_check_write_error(rws_socket s, int error_num) {
int socket_code = 0, code = 0;
socklen_t socket_code_size = sizeof(socket_code);
if (s->socket != RWS_INVALID_SOCKET) {
if (getsockopt(s->socket, SOL_SOCKET, SO_ERROR, &socket_code, &socket_code_size) != 0) {
socket_code = 0;
}
}
code = (socket_code > 0) ? socket_code : error_num;
if (code <= 0) {
return;
}
switch (code) {
// send errors
case EACCES: //
// case EAGAIN: // The socket is marked nonblocking and the requested operation would block
// case EWOULDBLOCK: // The socket is marked nonblocking and the receive operation would block
case EBADF: // An invalid descriptor was specified
case ECONNRESET: // Connection reset by peer
case EDESTADDRREQ: // The socket is not connection-mode, and no peer address is set
case EFAULT: // An invalid user space address was specified for an argument
// The receive buffer pointer(s) point outside the process's address space.
case EINTR: // A signal occurred before any data was transmitted
// The receive was interrupted by delivery of a signal before any data were available
case EINVAL: // Invalid argument passed
case EISCONN: // The connection-mode socket was connected already but a recipient was specified
case EMSGSIZE: // The socket type requires that message be sent atomically, and the size of the message to be sent made this impossible
case ENOBUFS: // The output queue for a network interface was full
case ENOMEM: // No memory available
case ENOTCONN: // The socket is not connected, and no target has been given
// The socket is associated with a connection-oriented protocol and has not been connected
case ENOTSOCK: // The argument sockfd is not a socket
// The argument sockfd does not refer to a socket
case EOPNOTSUPP: // Some bit in the flags argument is inappropriate for the socket type.
case EPIPE: // The local end has been shut down on a connection oriented socket
// recv errors
case ECONNREFUSED: // A remote host refused to allow the network connection (typically because it is not running the requested service).
s->error = rws_error_new_code_descr(rws_error_code_read_write_socket, rws_strerror(code));
break;
default:
break;
}
}
#ifdef WEBSOCKET_SSL_ENABLE
#if defined(MBEDTLS_DEBUG_C)
#define DEBUG_LEVEL 1
#endif
static void _rws_tls_net_init( mbedtls_net_context *ctx )
{
ctx->fd = -1;
}
static void _rws_tls_net_free( mbedtls_net_context *ctx )
{
if( ctx->fd == -1 )
return;
shutdown( ctx->fd, 2 );
close( ctx->fd );
ctx->fd = -1;
}
static int s_send_timeout_ms = WRITE_TIMEOUT_MS;
static int _rws_tls_net_send( void *ctx, const unsigned char *buf, size_t len )
{
int ret;
int fd = ((mbedtls_net_context *) ctx)->fd;
struct timeval interval = {s_send_timeout_ms / 1000, (s_send_timeout_ms % 1000) * 1000};
if( fd < 0 )
return( MBEDTLS_ERR_NET_INVALID_CONTEXT );
if (interval.tv_sec < 0 || (interval.tv_sec == 0 && interval.tv_usec <= 100)) {
interval.tv_sec = 0;
interval.tv_usec = 10000;
}
#if 0 // FIXME: not support yet, need to fix it later
/*set send timeout to avoid send block*/
if (setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (char *)&interval,
sizeof(struct timeval))) {
return -1;
}
#endif
ret = (int) send( fd, buf, len, 0);
if( ret < 0 )
{
if( errno == EPIPE || errno == ECONNRESET )
return( MBEDTLS_ERR_NET_CONN_RESET );
if( errno == EINTR )
return( MBEDTLS_ERR_SSL_WANT_WRITE );
return( MBEDTLS_ERR_NET_SEND_FAILED );
}
return( ret );
}
static int _rws_tls_net_recv( void *ctx, unsigned char *buf, size_t len )
{
int ret;
int fd = ((mbedtls_net_context *) ctx)->fd;
if( fd < 0 )
return( MBEDTLS_ERR_NET_INVALID_CONTEXT );
ret = (int) recv( fd, buf, len, 0);
// DBG("@@ret:%d, errno:%d", ret, errno);
if( ret < 0 )
{
// if( errno == EAGAIN )
// return( MBEDTLS_ERR_SSL_WANT_READ );
if( errno == EPIPE || errno == ECONNRESET )
return( MBEDTLS_ERR_NET_CONN_RESET );
if( errno == EINTR )
return( MBEDTLS_ERR_SSL_WANT_READ );
return( MBEDTLS_ERR_NET_RECV_FAILED );
}
return( ret );
}
static int _rws_tls_net_recv_timeout( void *ctx, unsigned char *buf, size_t len,
uint32_t timeout )
{
int ret;
struct timeval tv;
fd_set read_fds;
int fd = ((mbedtls_net_context *) ctx)->fd;
if( fd < 0 )
return( MBEDTLS_ERR_NET_INVALID_CONTEXT );
FD_ZERO( &read_fds );
FD_SET( fd, &read_fds );
tv.tv_sec = timeout / 1000;
tv.tv_usec = ( timeout % 1000 ) * 1000;
/* no wait if timeout == 0 */
ret = select( fd + 1, &read_fds, NULL, NULL, &tv );
/* Zero fds ready means we timed out */
if( ret == 0 )
return( MBEDTLS_ERR_SSL_TIMEOUT );
if( ret < 0 )
{
if( errno == EINTR )
return( MBEDTLS_ERR_SSL_WANT_READ );
return( MBEDTLS_ERR_NET_RECV_FAILED );
}
/* This call will not block */
return( _rws_tls_net_recv( ctx, buf, len ) );
}
static void transport_utils_random(unsigned char *output, size_t output_len)
{
#if defined(CONFIG_TEE_CA)
csi_tee_rand_generate(output, output_len);
#else
int i;
uint32_t random;
int mod = output_len % 4;
int count = 0;
static uint32_t rnd = 0x12345;
for (i = 0; i < output_len / 4; i++) {
random = rnd * 0xFFFF777;
rnd = random;
output[count++] = (random >> 24) & 0xFF;
output[count++] = (random >> 16) & 0xFF;
output[count++] = (random >> 8) & 0xFF;
output[count++] = (random) & 0xFF;
}
random = rnd * 0xFFFF777;
rnd = random;
for (i = 0; i < mod; i++) {
output[i + count] = (random >> 8 * i) & 0xFF;
}
#endif
}
static int _rws_random(void *p_rng, unsigned char *output, size_t output_len)
{
(void)p_rng;
transport_utils_random(output, output_len);
return 0;
}
static void _rws_debug( void *ctx, int level, const char *file, int line, const char *str )
{
DBG("%s", str);
}
int rws_ssl_conn(rws_socket s)
{
int authmode = MBEDTLS_SSL_VERIFY_NONE;
// const char *pers = "https";
int value, ret = 0;
uint32_t flags;
// char port[10] = {0};
_rws_ssl *ssl;
s->ssl = rws_malloc_zero(sizeof(_rws_ssl));
if (!s->ssl) {
DBG("Memory malloc error.");
ret = -1;
goto exit;
}
ssl = s->ssl;
if (s->server_cert)
authmode = MBEDTLS_SSL_VERIFY_REQUIRED;
/*
* Initialize the RNG and the session data
*/
#if defined(MBEDTLS_DEBUG_C)
mbedtls_debug_set_threshold(DEBUG_LEVEL);
#endif
_rws_tls_net_init(&ssl->net_ctx);
// mbedtls_net_init(&ssl->net_ctx);
mbedtls_ssl_init(&ssl->ssl_ctx);
mbedtls_ssl_config_init(&ssl->ssl_conf);
mbedtls_x509_crt_init(&ssl->cacert);
mbedtls_x509_crt_init(&ssl->clicert);
mbedtls_pk_init(&ssl->pkey);
/* mbedtls_ctr_drbg_init(&ssl->ctr_drbg);
mbedtls_entropy_init(&ssl->entropy);
if ((value = mbedtls_ctr_drbg_seed(&ssl->ctr_drbg,
mbedtls_entropy_func,
&ssl->entropy,
(const unsigned char*)pers,
strlen(pers))) != 0) {
DBG("mbedtls_ctr_drbg_seed() failed, value:-0x%x.", -value);
ret = -1;
goto exit;
}
*/
/*
* Load the Client certificate
*/
if (s->client_cert && s->client_pk) {
ret = mbedtls_x509_crt_parse(&ssl->clicert, (const unsigned char *)s->client_cert, s->client_cert_len);
if (ret < 0) {
ERR("Loading cli_cert failed! mbedtls_x509_crt_parse returned -0x%x.", -ret);
ret = -1;
goto exit;
}
ret = mbedtls_pk_parse_key(&ssl->pkey, (const unsigned char *)s->client_pk, s->client_pk_len, NULL, 0);
if (ret != 0) {
ERR("failed! mbedtls_pk_parse_key returned -0x%x.", -ret);
ret = -1;
goto exit;
}
}
/*
* Load the trusted CA
*/
/* cert_len passed in is gotten from sizeof not strlen */
if (s->server_cert && ((value = mbedtls_x509_crt_parse(&ssl->cacert,
(const unsigned char *)s->server_cert,
s->server_cert_len)) < 0)) {
ERR("mbedtls_x509_crt_parse() failed, value:-0x%x.", -value);
ret = -1;
goto exit;
}
/*
* Start the connection
*/
/*
snprintf(port, sizeof(port), "%d", client->port) ;
if ((ret = mbedtls_net_connect(&ssl->net_ctx, host, port, MBEDTLS_NET_PROTO_TCP)) != 0) {
DBG("failed! mbedtls_net_connect returned %d, port:%s.", ret, port);
goto exit;
}*/
DBG("start to connect to host");
rws_socket_connect_to_host(s);
if (s->socket == RWS_INVALID_SOCKET){
ret = -1;
ERR("failed! mbedtls_net_connect returned.");
goto exit;
} else {
DBG("connect to host ok");
ssl->net_ctx.fd = s->socket;
}
/*
* Setup stuff
*/
if ((value = mbedtls_ssl_config_defaults(&ssl->ssl_conf,
MBEDTLS_SSL_IS_CLIENT,
MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
ERR("mbedtls_ssl_config_defaults() failed, value:-0x%x.", -value);
ret = -1;
goto exit;
}
mbedtls_ssl_conf_read_timeout(&ssl->ssl_conf, READ_TIMEOUT_MS);
// TODO: add customerization encryption algorithm
memcpy(&ssl->profile, ssl->ssl_conf.cert_profile, sizeof(mbedtls_x509_crt_profile));
ssl->profile.allowed_mds = ssl->profile.allowed_mds | MBEDTLS_X509_ID_FLAG(MBEDTLS_MD_MD5);
mbedtls_ssl_conf_cert_profile(&ssl->ssl_conf, &ssl->profile);
mbedtls_ssl_conf_authmode(&ssl->ssl_conf, authmode);
mbedtls_ssl_conf_ca_chain(&ssl->ssl_conf, &ssl->cacert, NULL);
if (s->client_cert && (ret = mbedtls_ssl_conf_own_cert(&ssl->ssl_conf, &ssl->clicert, &ssl->pkey)) != 0) {
ERR(" failed! mbedtls_ssl_conf_own_cert returned %d.", ret );
ret = -1;
goto exit;
}
mbedtls_ssl_conf_rng(&ssl->ssl_conf, _rws_random, NULL);
mbedtls_ssl_conf_dbg(&ssl->ssl_conf, _rws_debug, NULL);
// mbedtls_ssl_conf_rng(&ssl->ssl_conf, mbedtls_ctr_drbg_random, &ssl->ctr_drbg);
if ((value = mbedtls_ssl_setup(&ssl->ssl_ctx, &ssl->ssl_conf)) != 0) {
ERR("mbedtls_ssl_setup() failed, value:-0x%x.", -value);
ret = -1;
goto exit;
}
mbedtls_ssl_set_bio(&ssl->ssl_ctx, &ssl->net_ctx, _rws_tls_net_send, _rws_tls_net_recv, _rws_tls_net_recv_timeout);
// mbedtls_ssl_set_bio(&ssl->ssl_ctx, &ssl->net_ctx, mbedtls_net_send, mbedtls_net_recv, NULL);
//mbedtls_net_set_block(&ssl->net_ctx);
DBG("start to handshake...");
/*
* Handshake
*/
while ((ret = mbedtls_ssl_handshake(&ssl->ssl_ctx)) != 0) {
if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) {
ERR("mbedtls_ssl_handshake() failed, ret:-0x%x.", -ret);
ret = -1;
goto exit;
}
}
mbedtls_ssl_conf_read_timeout(&ssl->ssl_conf, 5);
/*
* Verify the server certificate
*/
/* In real life, we would have used MBEDTLS_SSL_VERIFY_REQUIRED so that the
* handshake would not succeed if the peer's cert is bad. Even if we used
* MBEDTLS_SSL_VERIFY_OPTIONAL, we would bail out here if ret != 0 */
if ((flags = mbedtls_ssl_get_verify_result(&ssl->ssl_ctx)) != 0) {
#if defined(MBEDTLS_DEBUG_C)
char vrfy_buf[512];
ERR("svr_cert varification failed. authmode:%d", authmode);
mbedtls_x509_crt_verify_info(vrfy_buf, sizeof(vrfy_buf), " ! ", flags);
DBG("%s", vrfy_buf);
#endif
ret = -1;
}
else {
WRN("svr_cert varification ok. authmode:%d", authmode);
}
exit:
if(ret != 0) {
DBG("ret=%d.", ret);
s->error = rws_error_new_code_descr(rws_error_code_connect_to_host, "Failed connect to host");
ERR("%s: code:%d, error:%s", __FUNCTION__, s->error->code, s->error->description);
s->command = COMMAND_INFORM_DISCONNECTED;
rws_ssl_close(s);
}
return ret;
}
int rws_ssl_close(rws_socket s)
{
_rws_ssl *ssl = s->ssl;
if (!ssl)
return -1;
s->ssl = NULL;
s->client_cert = NULL;
s->server_cert = NULL;
s->client_pk = NULL;
mbedtls_ssl_close_notify(&ssl->ssl_ctx);
_rws_tls_net_free(&ssl->net_ctx);
// mbedtls_net_free(&ssl->net_ctx);
mbedtls_x509_crt_free(&ssl->cacert);
mbedtls_x509_crt_free(&ssl->clicert);
mbedtls_pk_free(&ssl->pkey);
mbedtls_ssl_free(&ssl->ssl_ctx);
mbedtls_ssl_config_free(&ssl->ssl_conf);
// mbedtls_ctr_drbg_free(&ssl->ctr_drbg);
// mbedtls_entropy_free(&ssl->entropy);
rws_free(ssl);
return 0;
}
#endif
|
YifuLiu/AliOS-Things
|
components/websocket/src/rws_socketpriv.c
|
C
|
apache-2.0
| 37,582
|
/*
* Copyright (c) 2014 - 2019 Oleh Kulykov <info@resident.name>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "librws.h"
#include "rws_socket.h"
#include "rws_memory.h"
#include "rws_string.h"
#include <assert.h>
#include <signal.h>
// public
rws_bool rws_socket_connect(rws_socket socket) {
const char * params_error_msg = NULL;
if (!socket) {
return rws_false;
}
rws_error_delete_clean(&socket->error);
if (socket->port <= 0) {
params_error_msg = "No URL port provided";
}
if (!socket->scheme) {
params_error_msg = "No URL scheme provided";
}
if (!socket->host) {
params_error_msg = "No URL host provided";
}
if (!socket->path) {
params_error_msg = "No URL path provided";
}
if (!socket->on_disconnected) {
params_error_msg = "No on_disconnected callback provided";
}
socket->received_len = 0;
if (params_error_msg) {
socket->error = rws_error_new_code_descr(rws_error_code_missed_parameter, params_error_msg);
return rws_false;
}
return rws_socket_create_start_work_thread(socket);
}
void rws_socket_disconnect_and_release(rws_socket socket) {
if (!socket) {
return;
}
rws_mutex_lock(socket->work_mutex);
rws_socket_delete_all_frames_in_list(socket->send_frames);
rws_list_delete_clean(&socket->send_frames);
if (socket->is_connected) { // connected in loop
socket->command = COMMAND_DISCONNECT;
} else if (socket->work_thread) { // disconnected in loop
socket->command = COMMAND_END;
}
rws_mutex_unlock(socket->work_mutex);
rws_sem_wait(socket->exit_sem, RWS_WAIT_FOREVER);
rws_socket_delete(socket);
}
rws_bool rws_socket_send_bin_start(rws_socket socket, const char *bin, size_t len) {
rws_bool r = rws_false;
if (socket) {
rws_mutex_lock(socket->send_mutex);
if (socket->socket != RWS_INVALID_SOCKET && socket->is_connected)
r = rws_socket_send_bin_priv(socket, bin, len, rws_binary_start);
rws_mutex_unlock(socket->send_mutex);
}
return r;
}
rws_bool rws_socket_send_bin_continue(rws_socket socket, const char *bin, size_t len) {
rws_bool r = rws_false;
if (socket) {
rws_mutex_lock(socket->send_mutex);
if (socket->socket != RWS_INVALID_SOCKET && socket->is_connected)
r = rws_socket_send_bin_priv(socket, bin, len, rws_binary_continue);
rws_mutex_unlock(socket->send_mutex);
}
return r;
}
rws_bool rws_socket_send_bin_finish(rws_socket socket, const char *bin, size_t len) {
rws_bool r = rws_false;
if (socket) {
rws_mutex_lock(socket->send_mutex);
if (socket->socket != RWS_INVALID_SOCKET && socket->is_connected)
r = rws_socket_send_bin_priv(socket, bin, len, rws_binary_finish);
rws_mutex_unlock(socket->send_mutex);
}
return r;
}
rws_bool rws_socket_send_text(rws_socket socket, const char * text) {
rws_bool r = rws_false;
if (socket) {
rws_mutex_lock(socket->send_mutex);
if (socket->socket != RWS_INVALID_SOCKET && socket->is_connected)
r = rws_socket_send_text_priv(socket, text);
rws_mutex_unlock(socket->send_mutex);
}
return r;
}
rws_bool rws_socket_send_ping(rws_socket socket) {
rws_bool r = rws_false;
if (socket) {
rws_mutex_lock(socket->send_mutex);
if (socket->socket != RWS_INVALID_SOCKET && socket->is_connected)
r = rws_socket_send_ping_priv(socket);
rws_mutex_unlock(socket->send_mutex);
}
return r;
}
/*void rws_socket_handle_sigpipe(int signal_number) {
printf("\nlibrws handle sigpipe %i", signal_number);
(void)signal_number;
return;
}*/
#define STRING_I(s) #s
#define TO_STRING(s) STRING_I(s)
#define BUFF_SIZE 8192
void rws_socket_check_info(const char * info) {
assert(info);
(void)info;
}
rws_socket rws_socket_create(void) {
rws_socket s = (rws_socket)rws_malloc_zero(sizeof(struct rws_socket_struct));
if (!s) {
return NULL;
}
s->recv_buffer = (char *) rws_malloc(BUFF_SIZE);
if (NULL == s->recv_buffer) {
rws_free(s);
return NULL;
}
s->recv_buffer_size = BUFF_SIZE;
s->port = -1;
s->socket = RWS_INVALID_SOCKET;
s->command = COMMAND_NONE;
s->work_mutex = rws_mutex_create_recursive();
s->send_mutex = rws_mutex_create_recursive();
s->exit_sem = rws_sem_create();
static const char * info = "librws ver: " TO_STRING(RWS_VERSION_MAJOR) "." TO_STRING(RWS_VERSION_MINOR) "." TO_STRING(RWS_VERSION_PATCH) "\n";
rws_socket_check_info(info);
return s;
}
void rws_socket_delete(rws_socket s) {
rws_socket_close(s);
rws_free_clean(&s->received);
s->received_size = 0;
s->received_len = 0;
rws_socket_delete_all_frames_in_list(s->send_frames);
rws_list_delete_clean(&s->send_frames);
rws_socket_delete_all_frames_in_list(s->recvd_frames);
rws_list_delete_clean(&s->recvd_frames);
rws_string_delete_clean(&s->scheme);
rws_string_delete_clean(&s->host);
rws_string_delete_clean(&s->path);
rws_string_delete_clean(&s->sec_ws_protocol);
rws_string_delete_clean(&s->sec_ws_accept);
rws_error_delete_clean(&s->error);
rws_mutex_delete(s->work_mutex);
s->work_mutex = NULL;
rws_mutex_delete(s->send_mutex);
s->send_mutex = NULL;
rws_sem_delete(s->exit_sem);
s->exit_sem = NULL;
rws_free(s->recv_buffer);
s->recv_buffer = NULL;
s->recv_buffer_size = 0;
rws_free(s);
}
void rws_socket_set_url(rws_socket socket,
const char * scheme,
const char * host,
const int port,
const char * path) {
if (socket) {
rws_string_delete(socket->scheme);
socket->scheme = rws_string_copy(scheme);
rws_string_delete(socket->host);
socket->host = rws_string_copy(host);
rws_string_delete(socket->path);
socket->path = rws_string_copy(path);
socket->port = port;
}
}
void rws_socket_set_scheme(rws_socket socket, const char * scheme) {
if (socket) {
rws_string_delete(socket->scheme);
socket->scheme = rws_string_copy(scheme);
}
}
const char * rws_socket_get_scheme(rws_socket socket) {
return socket ? socket->scheme : NULL;
}
void rws_socket_set_host(rws_socket socket, const char * host) {
if (socket) {
rws_string_delete(socket->host);
socket->host = rws_string_copy(host);
}
}
const char * rws_socket_get_host(rws_socket socket) {
return socket ? socket->host : NULL;
}
void rws_socket_set_path(rws_socket socket, const char * path) {
if (socket) {
rws_string_delete(socket->path);
socket->path = rws_string_copy(path);
}
}
const char * rws_socket_get_path(rws_socket socket) {
return socket ? socket->path : NULL;
}
void rws_socket_set_port(rws_socket socket, const int port) {
if (socket) {
socket->port = port;
}
}
int rws_socket_get_port(rws_socket socket) {
return socket ? socket->port : -1;
}
void rws_socket_set_protocol(rws_socket socket, const char * protocol) {
if (socket) {
rws_string_delete(socket->sec_ws_protocol);
socket->sec_ws_protocol = rws_string_copy(protocol);
}
}
/*
unsigned int _rws_socket_get_receive_buffer_size(rws_socket_t socket) {
unsigned int size = 0;
#if defined(RWS_OS_WINDOWS)
int len = sizeof(unsigned int);
if (getsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char *)&size, &len) == -1) {
size = 0;
}
#else
socklen_t len = sizeof(unsigned int);
if (getsockopt(socket, SOL_SOCKET, SO_RCVBUF, &size, &len) == -1) {
size = 0;
}
#endif
return size;
}
unsigned int rws_socket_get_receive_buffer_size(rws_socket socket) {
_rws_socket * s = (_rws_socket *)socket;
if (!s) {
return 0;
}
if (s->socket == RWS_INVALID_SOCKET) {
return 0;
}
return _rws_socket_get_receive_buffer_size(s->socket);
}
*/
rws_error rws_socket_get_error(rws_socket socket) {
return socket ? socket->error : NULL;
}
void rws_socket_set_user_object(rws_socket socket, void * user_object) {
if (socket) {
socket->user_object = user_object;
}
}
void * rws_socket_get_user_object(rws_socket socket) {
return socket ? socket->user_object : NULL;
}
void rws_socket_set_on_connected(rws_socket socket, rws_on_socket callback) {
if (socket) {
socket->on_connected = callback;
}
}
void rws_socket_set_on_disconnected(rws_socket socket, rws_on_socket callback) {
if (socket) {
socket->on_disconnected = callback;
}
}
void rws_socket_set_on_received_text(rws_socket socket, rws_on_socket_recvd_text callback) {
if (socket) {
socket->on_recvd_text = callback;
}
}
void rws_socket_set_on_received_bin(rws_socket socket, rws_on_socket_recvd_bin callback) {
if (socket) {
socket->on_recvd_bin = callback;
}
}
rws_bool rws_socket_is_connected(rws_socket socket) {
rws_bool r = rws_false;
if (socket) {
rws_mutex_lock(socket->send_mutex);
r = socket->is_connected;
rws_mutex_unlock(socket->send_mutex);
}
return r;
}
void rws_socket_set_on_received_pong(rws_socket socket, rws_on_socket_recvd_pong callback) {
if (socket) {
socket->on_recvd_pong = callback;
}
}
void rws_socket_set_on_send_ping(rws_socket socket, rws_on_socket_send_ping callback) {
if (socket) {
socket->on_send_ping = callback;
}
}
#ifdef WEBSOCKET_SSL_ENABLE
void rws_socket_set_server_cert(rws_socket socket, const char *server_cert, int server_cert_len)
{
DBG("%s: server_cert[len:%d]: \n%s", __FUNCTION__, server_cert_len, server_cert);
rws_socket s = socket;
if (s) {
s->server_cert = server_cert;
s->server_cert_len = server_cert_len;
}
}
#endif
|
YifuLiu/AliOS-Things
|
components/websocket/src/rws_socketpub.c
|
C
|
apache-2.0
| 10,205
|
/*
* Copyright (c) 2014 - 2019 Oleh Kulykov <info@resident.name>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "rws_string.h"
#include "rws_memory.h"
char * rws_string_copy(const char * str) {
return str ? rws_string_copy_len(str, strlen(str)) : NULL;
}
char * rws_string_copy_len(const char * str, const size_t len) {
char * s = (str && len > 0) ? (char *)rws_malloc(len + 1) : NULL;
if (s) {
memcpy(s, str, len);
s[len] = 0;
return s;
}
return NULL;
}
void rws_string_delete(char * str) {
rws_free(str);
}
void rws_string_delete_clean(char ** str) {
if (str) {
rws_free(*str);
*str = NULL;
}
}
|
YifuLiu/AliOS-Things
|
components/websocket/src/rws_string.c
|
C
|
apache-2.0
| 1,695
|
/*
* Copyright (c) 2014 - 2019 Oleh Kulykov <info@resident.name>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "librws.h"
#include "rws_thread.h"
#include "rws_memory.h"
#include "rws_common.h"
#include <assert.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <sys/time.h>
struct rws_thread_struct {
rws_thread_funct thread_function;
void * user_object;
pthread_t thread;
};
typedef struct _rws_threads_joiner_struct {
rws_thread thread;
rws_mutex mutex;
} _rws_threads_joiner;
static _rws_threads_joiner * _threads_joiner = NULL;
static void rws_threads_joiner_clean(void) { // private
rws_thread t = _threads_joiner->thread;
void * r = NULL;
if (!t) {
return;
}
_threads_joiner->thread = NULL;
pthread_join(t->thread, &r);
assert(r == NULL);
rws_free(t);
}
static void rws_threads_joiner_add(rws_thread thread) { // public
rws_mutex_lock(_threads_joiner->mutex);
rws_threads_joiner_clean();
_threads_joiner->thread = thread;
rws_mutex_unlock(_threads_joiner->mutex);
}
static void rws_threads_joiner_create_ifneed(void) {
if (_threads_joiner) {
return;
}
_threads_joiner = (_rws_threads_joiner *)rws_malloc_zero(sizeof(_rws_threads_joiner));
_threads_joiner->mutex = rws_mutex_create_recursive();
}
static void * rws_thread_func_priv(void * some_pointer) {
rws_thread t = (rws_thread)some_pointer;
t->thread_function(t->user_object);
rws_threads_joiner_add(t);
return NULL;
}
rws_thread rws_thread_create(rws_thread_funct thread_function, void * user_object) {
rws_thread t = NULL;
int res = -1;
pthread_attr_t attr;
if (!thread_function) {
return NULL;
}
rws_threads_joiner_create_ifneed();
t = (rws_thread)rws_malloc_zero(sizeof(struct rws_thread_struct));
t->user_object = user_object;
t->thread_function = thread_function;
if (pthread_attr_init(&attr) == 0) {
pthread_attr_setstacksize(&attr, 16 * 1024);
struct sched_param sched;
#ifndef _AMLOGIC_
sched.sched_priority = 32;
#else
sched.sched_priority = 3;
#endif
pthread_attr_setschedparam(&attr, &sched);
//if (pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM) == 0) {
if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE) == 0) {
res = pthread_create(&t->thread, &attr, &rws_thread_func_priv, (void *)t);
pthread_setname_np(t->thread, "GnWebsoc");
}
//}
pthread_attr_destroy(&attr);
}
assert(res == 0);
return t;
}
void rws_thread_sleep(const unsigned int millisec) {
usleep(millisec * 1000); // 1s = 1'000'000 microsec.
}
rws_mutex rws_mutex_create_recursive(void) {
pthread_mutex_t * mutex = (pthread_mutex_t *)rws_malloc_zero(sizeof(pthread_mutex_t));
int res = -1;
pthread_mutexattr_t attr;
if (pthread_mutexattr_init(&attr) == 0) {
if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) == 0) {
res = pthread_mutex_init(mutex, &attr);
}
pthread_mutexattr_destroy(&attr);
}
assert(res == 0);
return mutex;
}
void rws_mutex_lock(rws_mutex mutex) {
if (mutex) {
pthread_mutex_lock((pthread_mutex_t *)mutex);
}
}
void rws_mutex_unlock(rws_mutex mutex) {
if (mutex) {
pthread_mutex_unlock((pthread_mutex_t *)mutex);
}
}
void rws_mutex_delete(rws_mutex mutex) {
if (mutex) {
pthread_mutex_destroy((pthread_mutex_t *)mutex);
rws_free(mutex);
}
}
rws_sem rws_sem_create(void)
{
int ret = -1;
sem_t *sem = (sem_t *) rws_malloc_zero(sizeof(sem_t));
if (sem)
ret = sem_init(sem, 0, 0);
assert(ret == 0);
return sem;
}
void rws_sem_delete(rws_sem sem)
{
if (sem) {
sem_destroy(sem);
rws_free(sem);
}
}
void rws_sem_signal(rws_sem sem)
{
if (sem) {
sem_post(sem);
}
}
int rws_sem_wait(rws_sem sem, unsigned int timeout_ms)
{
int ret = -1;
if (sem) {
if (timeout_ms == RWS_WAIT_FOREVER) {
ret = sem_wait(sem);
} else {
struct timespec abs_timeout;
struct timeval tv;
gettimeofday(&tv, NULL);
abs_timeout.tv_sec = tv.tv_sec + timeout_ms / 1000;
abs_timeout.tv_nsec = tv.tv_usec * 1000 + (timeout_ms % 1000) * 1000000;
ret = sem_timedwait(sem, &abs_timeout);
}
}
return ret;
}
|
YifuLiu/AliOS-Things
|
components/websocket/src/rws_thread.c
|
C
|
apache-2.0
| 5,215
|
/* The standard CSS for doxygen 1.9.1 */
body, table, div, p, dl {
font: 400 14px/22px Roboto,sans-serif;
}
p.reference, p.definition {
font: 400 14px/22px Roboto,sans-serif;
}
/* @group Heading Levels */
h1.groupheader {
font-size: 150%;
}
.title {
font: 400 14px/28px Roboto,sans-serif;
font-size: 150%;
font-weight: bold;
margin: 10px 2px;
}
h2.groupheader {
border-bottom: 1px solid #87ABCB;
color: #355A7B;
font-size: 150%;
font-weight: normal;
margin-top: 1.75em;
padding-top: 8px;
padding-bottom: 4px;
width: 100%;
}
h3.groupheader {
font-size: 100%;
}
h1, h2, h3, h4, h5, h6 {
-webkit-transition: text-shadow 0.5s linear;
-moz-transition: text-shadow 0.5s linear;
-ms-transition: text-shadow 0.5s linear;
-o-transition: text-shadow 0.5s linear;
transition: text-shadow 0.5s linear;
margin-right: 15px;
}
h1.glow, h2.glow, h3.glow, h4.glow, h5.glow, h6.glow {
text-shadow: 0 0 15px cyan;
}
dt {
font-weight: bold;
}
ul.multicol {
-moz-column-gap: 1em;
-webkit-column-gap: 1em;
column-gap: 1em;
-moz-column-count: 3;
-webkit-column-count: 3;
column-count: 3;
}
p.startli, p.startdd {
margin-top: 2px;
}
th p.starttd, th p.intertd, th p.endtd {
font-size: 100%;
font-weight: 700;
}
p.starttd {
margin-top: 0px;
}
p.endli {
margin-bottom: 0px;
}
p.enddd {
margin-bottom: 4px;
}
p.endtd {
margin-bottom: 2px;
}
p.interli {
}
p.interdd {
}
p.intertd {
}
/* @end */
caption {
font-weight: bold;
}
span.legend {
font-size: 70%;
text-align: center;
}
h3.version {
font-size: 90%;
text-align: center;
}
div.navtab {
border-right: 1px solid #A3BFD7;
padding-right: 15px;
text-align: right;
line-height: 110%;
}
div.navtab table {
border-spacing: 0;
}
td.navtab {
padding-right: 6px;
padding-left: 6px;
}
td.navtabHL {
background-image: url('tab_a.png');
background-repeat:repeat-x;
padding-right: 6px;
padding-left: 6px;
}
td.navtabHL a, td.navtabHL a:visited {
color: #fff;
text-shadow: 0px 1px 1px rgba(0, 0, 0, 1.0);
}
a.navtab {
font-weight: bold;
}
div.qindex{
text-align: center;
width: 100%;
line-height: 140%;
font-size: 130%;
color: #A0A0A0;
}
dt.alphachar{
font-size: 180%;
font-weight: bold;
}
.alphachar a{
color: black;
}
.alphachar a:hover, .alphachar a:visited{
text-decoration: none;
}
.classindex dl {
padding: 25px;
column-count:1
}
.classindex dd {
display:inline-block;
margin-left: 50px;
width: 90%;
line-height: 1.15em;
}
.classindex dl.odd {
background-color: #F8FAFC;
}
@media(min-width: 1120px) {
.classindex dl {
column-count:2
}
}
@media(min-width: 1320px) {
.classindex dl {
column-count:3
}
}
/* @group Link Styling */
a {
color: #3D678C;
t-weight: normal;
text-decoration: none;
}
.contents a:visited {
color: #4677A2;
}
a:hover {
text-decoration: underline;
}
.contents a.qindexHL:visited {
color: #FFFFFF;
}
a.el {
font-weight: bold;
}
a.elRef {
}
a.code, a.code:visited, a.line, a.line:visited {
color: #4677A2;
}
a.codeRef, a.codeRef:visited, a.lineRef, a.lineRef:visited {
color: #4677A2;
}
/* @end */
dl.el {
margin-left: -1cm;
}
ul {
overflow: hidden; /*Fixed: list item bullets overlap floating elements*/
}
#side-nav ul {
overflow: visible; /* reset ul rule for scroll bar in GENERATE_TREEVIEW window */
}
#main-nav ul {
overflow: visible; /* reset ul rule for the navigation bar drop down lists */
}
.fragment {
text-align: left;
direction: ltr;
overflow-x: auto; /*Fixed: fragment lines overlap floating elements*/
overflow-y: hidden;
}
pre.fragment {
border: 1px solid #C4D6E5;
background-color: #FBFCFD;
padding: 4px 6px;
margin: 4px 8px 4px 2px;
overflow: auto;
word-wrap: break-word;
font-size: 9pt;
line-height: 125%;
font-family: monospace, fixed;
font-size: 105%;
}
div.fragment {
padding: 0 0 1px 0; /*Fixed: last line underline overlap border*/
margin: 4px 8px 4px 2px;
background-color: #FBFCFD;
border: 1px solid #C4D6E5;
}
div.line {
font-family: monospace, fixed;
font-size: 13px;
min-height: 13px;
line-height: 1.0;
text-wrap: unrestricted;
white-space: -moz-pre-wrap; /* Moz */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
white-space: pre-wrap; /* CSS3 */
word-wrap: break-word; /* IE 5.5+ */
text-indent: -53px;
padding-left: 53px;
padding-bottom: 0px;
margin: 0px;
-webkit-transition-property: background-color, box-shadow;
-webkit-transition-duration: 0.5s;
-moz-transition-property: background-color, box-shadow;
-moz-transition-duration: 0.5s;
-ms-transition-property: background-color, box-shadow;
-ms-transition-duration: 0.5s;
-o-transition-property: background-color, box-shadow;
-o-transition-duration: 0.5s;
transition-property: background-color, box-shadow;
transition-duration: 0.5s;
}
div.line:after {
content:"\000A";
white-space: pre;
}
div.line.glow {
background-color: cyan;
box-shadow: 0 0 10px cyan;
}
span.lineno {
padding-right: 4px;
text-align: right;
border-right: 2px solid #0F0;
background-color: #E8E8E8;
white-space: pre;
}
span.lineno a {
background-color: #D8D8D8;
}
span.lineno a:hover {
background-color: #C8C8C8;
}
.lineno {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
div.ah, span.ah {
background-color: black;
font-weight: bold;
color: #FFFFFF;
margin-bottom: 3px;
margin-top: 3px;
padding: 0.2em;
border: solid thin #333;
border-radius: 0.5em;
-webkit-border-radius: .5em;
-moz-border-radius: .5em;
box-shadow: 2px 2px 3px #999;
-webkit-box-shadow: 2px 2px 3px #999;
-moz-box-shadow: rgba(0, 0, 0, 0.15) 2px 2px 2px;
background-image: -webkit-gradient(linear, left top, left bottom, from(#eee), to(#000),color-stop(0.3, #444));
background-image: -moz-linear-gradient(center top, #eee 0%, #444 40%, #000 110%);
}
div.classindex ul {
list-style: none;
padding-left: 0;
}
div.classindex span.ai {
display: inline-block;
}
div.groupHeader {
margin-left: 16px;
margin-top: 12px;
font-weight: bold;
}
div.groupText {
margin-left: 16px;
font-style: italic;
}
body {
background-color: white;
color: black;
margin: 0;
}
div.contents {
margin-top: 10px;
margin-left: 12px;
margin-right: 8px;
}
td.indexkey {
background-color: #EBF1F6;
font-weight: bold;
border: 1px solid #C4D6E5;
margin: 2px 0px 2px 0;
padding: 2px 10px;
white-space: nowrap;
vertical-align: top;
}
td.indexvalue {
background-color: #EBF1F6;
border: 1px solid #C4D6E5;
padding: 2px 10px;
margin: 2px 0px;
}
tr.memlist {
background-color: #EEF3F7;
}
p.formulaDsp {
text-align: center;
}
img.formulaDsp {
}
img.formulaInl, img.inline {
vertical-align: middle;
}
div.center {
text-align: center;
margin-top: 0px;
margin-bottom: 0px;
padding: 0px;
}
div.center img {
border: 0px;
}
address.footer {
text-align: right;
padding-right: 12px;
}
img.footer {
border: 0px;
vertical-align: middle;
}
/* @group Code Colorization */
span.keyword {
color: #008000
}
span.keywordtype {
color: #604020
}
span.keywordflow {
color: #e08000
}
span.comment {
color: #800000
}
span.preprocessor {
color: #806020
}
span.stringliteral {
color: #002080
}
span.charliteral {
color: #008080
}
span.vhdldigit {
color: #ff00ff
}
span.vhdlchar {
color: #000000
}
span.vhdlkeyword {
color: #700070
}
span.vhdllogic {
color: #ff0000
}
blockquote {
background-color: #F7F9FB;
border-left: 2px solid #9CBAD4;
margin: 0 24px 0 4px;
padding: 0 12px 0 16px;
}
blockquote.DocNodeRTL {
border-left: 0;
border-right: 2px solid #9CBAD4;
margin: 0 4px 0 24px;
padding: 0 16px 0 12px;
}
/* @end */
/*
.search {
color: #003399;
font-weight: bold;
}
form.search {
margin-bottom: 0px;
margin-top: 0px;
}
input.search {
font-size: 75%;
color: #000080;
font-weight: normal;
background-color: #e8eef2;
}
*/
td.tiny {
font-size: 75%;
}
.dirtab {
padding: 4px;
border-collapse: collapse;
border: 1px solid #A3BFD7;
}
th.dirtab {
background: #EBF1F6;
font-weight: bold;
}
hr {
height: 0px;
border: none;
border-top: 1px solid #4A7DAA;
}
hr.footer {
height: 1px;
}
/* @group Member Descriptions */
table.memberdecls {
border-spacing: 0px;
padding: 0px;
}
.memberdecls td, .fieldtable tr {
-webkit-transition-property: background-color, box-shadow;
-webkit-transition-duration: 0.5s;
-moz-transition-property: background-color, box-shadow;
-moz-transition-duration: 0.5s;
-ms-transition-property: background-color, box-shadow;
-ms-transition-duration: 0.5s;
-o-transition-property: background-color, box-shadow;
-o-transition-duration: 0.5s;
transition-property: background-color, box-shadow;
transition-duration: 0.5s;
}
.memberdecls td.glow, .fieldtable tr.glow {
background-color: cyan;
box-shadow: 0 0 15px cyan;
}
.mdescLeft, .mdescRight,
.memItemLeft, .memItemRight,
.memTemplItemLeft, .memTemplItemRight, .memTemplParams {
background-color: #F9FBFC;
border: none;
margin: 4px;
padding: 1px 0 0 8px;
}
.mdescLeft, .mdescRight {
padding: 0px 8px 4px 8px;
color: #555;
}
.memSeparator {
border-bottom: 1px solid #DEE8F0;
line-height: 1px;
margin: 0px;
padding: 0px;
}
.memItemLeft, .memTemplItemLeft {
white-space: nowrap;
}
.memItemRight, .memTemplItemRight {
width: 100%;
}
.memTemplParams {
color: #4677A2;
white-space: nowrap;
font-size: 80%;
}
/* @end */
/* @group Member Details */
/* Styles for detailed member documentation */
.memtitle {
padding: 8px;
border-top: 1px solid #A8C2D9;
border-left: 1px solid #A8C2D9;
border-right: 1px solid #A8C2D9;
border-top-right-radius: 4px;
border-top-left-radius: 4px;
margin-bottom: -1px;
background-image: url('nav_f.png');
background-repeat: repeat-x;
background-color: #E2EBF2;
line-height: 1.25;
font-weight: 300;
float:left;
}
.permalink
{
font-size: 65%;
display: inline-block;
vertical-align: middle;
}
.memtemplate {
font-size: 80%;
color: #4677A2;
font-weight: normal;
margin-left: 9px;
}
.memnav {
background-color: #EBF1F6;
border: 1px solid #A3BFD7;
text-align: center;
margin: 2px;
margin-right: 15px;
padding: 2px;
}
.mempage {
width: 100%;
}
.memitem {
padding: 0;
margin-bottom: 10px;
margin-right: 5px;
-webkit-transition: box-shadow 0.5s linear;
-moz-transition: box-shadow 0.5s linear;
-ms-transition: box-shadow 0.5s linear;
-o-transition: box-shadow 0.5s linear;
transition: box-shadow 0.5s linear;
display: table !important;
width: 100%;
}
.memitem.glow {
box-shadow: 0 0 15px cyan;
}
.memname {
font-weight: 400;
margin-left: 6px;
}
.memname td {
vertical-align: bottom;
}
.memproto, dl.reflist dt {
border-top: 1px solid #A8C2D9;
border-left: 1px solid #A8C2D9;
border-right: 1px solid #A8C2D9;
padding: 6px 0px 6px 0px;
color: #253E55;
font-weight: bold;
text-shadow: 0px 1px 1px rgba(255, 255, 255, 0.9);
background-color: #DFE8F1;
/* opera specific markup */
box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15);
border-top-right-radius: 4px;
/* firefox specific markup */
-moz-box-shadow: rgba(0, 0, 0, 0.15) 5px 5px 5px;
-moz-border-radius-topright: 4px;
/* webkit specific markup */
-webkit-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15);
-webkit-border-top-right-radius: 4px;
}
.overload {
font-family: "courier new",courier,monospace;
font-size: 65%;
}
.memdoc, dl.reflist dd {
border-bottom: 1px solid #A8C2D9;
border-left: 1px solid #A8C2D9;
border-right: 1px solid #A8C2D9;
padding: 6px 10px 2px 10px;
background-color: #FBFCFD;
border-top-width: 0;
background-image:url('nav_g.png');
background-repeat:repeat-x;
background-color: #FFFFFF;
/* opera specific markup */
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15);
/* firefox specific markup */
-moz-border-radius-bottomleft: 4px;
-moz-border-radius-bottomright: 4px;
-moz-box-shadow: rgba(0, 0, 0, 0.15) 5px 5px 5px;
/* webkit specific markup */
-webkit-border-bottom-left-radius: 4px;
-webkit-border-bottom-right-radius: 4px;
-webkit-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.15);
}
dl.reflist dt {
padding: 5px;
}
dl.reflist dd {
margin: 0px 0px 10px 0px;
padding: 5px;
}
.paramkey {
text-align: right;
}
.paramtype {
white-space: nowrap;
}
.paramname {
color: #602020;
white-space: nowrap;
}
.paramname em {
font-style: normal;
}
.paramname code {
line-height: 14px;
}
.params, .retval, .exception, .tparams {
margin-left: 0px;
padding-left: 0px;
}
.params .paramname, .retval .paramname, .tparams .paramname, .exception .paramname {
font-weight: bold;
vertical-align: top;
}
.params .paramtype, .tparams .paramtype {
font-style: italic;
vertical-align: top;
}
.params .paramdir, .tparams .paramdir {
font-family: "courier new",courier,monospace;
vertical-align: top;
}
table.mlabels {
border-spacing: 0px;
}
td.mlabels-left {
width: 100%;
padding: 0px;
}
td.mlabels-right {
vertical-align: bottom;
padding: 0px;
white-space: nowrap;
}
span.mlabels {
margin-left: 8px;
}
span.mlabel {
background-color: #729CC1;
border-top:1px solid #5387B4;
border-left:1px solid #5387B4;
border-right:1px solid #C4D6E5;
border-bottom:1px solid #C4D6E5;
text-shadow: none;
color: white;
margin-right: 4px;
padding: 2px 3px;
border-radius: 3px;
font-size: 7pt;
white-space: nowrap;
vertical-align: middle;
}
/* @end */
/* these are for tree view inside a (index) page */
div.directory {
margin: 10px 0px;
border-top: 1px solid #9CBAD4;
border-bottom: 1px solid #9CBAD4;
width: 100%;
}
.directory table {
border-collapse:collapse;
}
.directory td {
margin: 0px;
padding: 0px;
vertical-align: top;
}
.directory td.entry {
white-space: nowrap;
padding-right: 6px;
padding-top: 3px;
}
.directory td.entry a {
outline:none;
}
.directory td.entry a img {
border: none;
}
.directory td.desc {
width: 100%;
padding-left: 6px;
padding-right: 6px;
padding-top: 3px;
border-left: 1px solid rgba(0,0,0,0.05);
}
.directory tr.even {
padding-left: 6px;
background-color: #F7F9FB;
}
.directory img {
vertical-align: -30%;
}
.directory .levels {
white-space: nowrap;
width: 100%;
text-align: right;
font-size: 9pt;
}
.directory .levels span {
cursor: pointer;
padding-left: 2px;
padding-right: 2px;
color: #3D678C;
}
.arrow {
color: #9CBAD4;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
cursor: pointer;
font-size: 80%;
display: inline-block;
width: 16px;
height: 22px;
}
.icon {
font-family: Arial, Helvetica;
font-weight: bold;
font-size: 12px;
height: 14px;
width: 16px;
display: inline-block;
background-color: #729CC1;
color: white;
text-align: center;
border-radius: 4px;
margin-left: 2px;
margin-right: 2px;
}
.icona {
width: 24px;
height: 22px;
display: inline-block;
}
.iconfopen {
width: 24px;
height: 18px;
margin-bottom: 4px;
background-image:url('folderopen.png');
background-position: 0px -4px;
background-repeat: repeat-y;
vertical-align:top;
display: inline-block;
}
.iconfclosed {
width: 24px;
height: 18px;
margin-bottom: 4px;
background-image:url('folderclosed.png');
background-position: 0px -4px;
background-repeat: repeat-y;
vertical-align:top;
display: inline-block;
}
.icondoc {
width: 24px;
height: 18px;
margin-bottom: 4px;
background-image:url('doc.png');
background-position: 0px -4px;
background-repeat: repeat-y;
vertical-align:top;
display: inline-block;
}
table.directory {
font: 400 14px Roboto,sans-serif;
}
/* @end */
div.dynheader {
margin-top: 8px;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
address {
font-style: normal;
color: #2A4861;
}
table.doxtable caption {
caption-side: top;
}
table.doxtable {
border-collapse:collapse;
margin-top: 4px;
margin-bottom: 4px;
}
table.doxtable td, table.doxtable th {
border: 1px solid #2D4C68;
padding: 3px 7px 2px;
}
table.doxtable th {
background-color: #375E7F;
color: #FFFFFF;
font-size: 110%;
padding-bottom: 4px;
padding-top: 5px;
}
table.fieldtable {
/*width: 100%;*/
margin-bottom: 10px;
border: 1px solid #A8C2D9;
border-spacing: 0px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
-moz-box-shadow: rgba(0, 0, 0, 0.15) 2px 2px 2px;
-webkit-box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.15);
box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.15);
}
.fieldtable td, .fieldtable th {
padding: 3px 7px 2px;
}
.fieldtable td.fieldtype, .fieldtable td.fieldname {
white-space: nowrap;
border-right: 1px solid #A8C2D9;
border-bottom: 1px solid #A8C2D9;
vertical-align: top;
}
.fieldtable td.fieldname {
padding-top: 3px;
}
.fieldtable td.fielddoc {
border-bottom: 1px solid #A8C2D9;
/*width: 100%;*/
}
.fieldtable td.fielddoc p:first-child {
margin-top: 0px;
}
.fieldtable td.fielddoc p:last-child {
margin-bottom: 2px;
}
.fieldtable tr:last-child td {
border-bottom: none;
}
.fieldtable th {
background-image:url('nav_f.png');
background-repeat:repeat-x;
background-color: #E2EBF2;
font-size: 90%;
color: #253E55;
padding-bottom: 4px;
padding-top: 5px;
text-align:left;
font-weight: 400;
-moz-border-radius-topleft: 4px;
-moz-border-radius-topright: 4px;
-webkit-border-top-left-radius: 4px;
-webkit-border-top-right-radius: 4px;
border-top-left-radius: 4px;
border-top-right-radius: 4px;
border-bottom: 1px solid #A8C2D9;
}
.tabsearch {
top: 0px;
left: 10px;
height: 36px;
background-image: url('tab_b.png');
z-index: 101;
overflow: hidden;
font-size: 13px;
}
.navpath ul
{
font-size: 11px;
background-image:url('tab_b.png');
background-repeat:repeat-x;
background-position: 0 -5px;
height:30px;
line-height:30px;
color:#8AADCC;
border:solid 1px #C2D4E4;
overflow:hidden;
margin:0px;
padding:0px;
}
.navpath li
{
list-style-type:none;
float:left;
padding-left:10px;
padding-right:15px;
background-image:url('bc_s.png');
background-repeat:no-repeat;
background-position:right;
color:#365B7C;
}
.navpath li.navelem a
{
height:32px;
display:block;
text-decoration: none;
outline: none;
color: #28445D;
font-family: 'Lucida Grande',Geneva,Helvetica,Arial,sans-serif;
text-shadow: 0px 1px 1px rgba(255, 255, 255, 0.9);
text-decoration: none;
}
.navpath li.navelem a:hover
{
color:#6895BD;
}
.navpath li.footer
{
list-style-type:none;
float:right;
padding-left:10px;
padding-right:15px;
background-image:none;
background-repeat:no-repeat;
background-position:right;
color:#365B7C;
font-size: 8pt;
}
div.summary
{
float: right;
font-size: 8pt;
padding-right: 5px;
width: 50%;
text-align: right;
}
div.summary a
{
white-space: nowrap;
}
table.classindex
{
margin: 10px;
white-space: nowrap;
margin-left: 3%;
margin-right: 3%;
width: 94%;
border: 0;
border-spacing: 0;
padding: 0;
}
div.ingroups
{
font-size: 8pt;
width: 50%;
text-align: left;
}
div.ingroups a
{
white-space: nowrap;
}
div.header
{
background-image:url('nav_h.png');
background-repeat:repeat-x;
background-color: #F9FBFC;
margin: 0px;
border-bottom: 1px solid #C4D6E5;
}
div.headertitle
{
padding: 5px 5px 5px 10px;
}
.PageDocRTL-title div.headertitle {
text-align: right;
direction: rtl;
}
dl {
padding: 0 0 0 0;
}
/* dl.note, dl.warning, dl.attention, dl.pre, dl.post, dl.invariant, dl.deprecated, dl.todo, dl.test, dl.bug, dl.examples */
dl.section {
margin-left: 0px;
padding-left: 0px;
}
dl.section.DocNodeRTL {
margin-right: 0px;
padding-right: 0px;
}
dl.note {
margin-left: -7px;
padding-left: 3px;
border-left: 4px solid;
border-color: #D0C000;
}
dl.note.DocNodeRTL {
margin-left: 0;
padding-left: 0;
border-left: 0;
margin-right: -7px;
padding-right: 3px;
border-right: 4px solid;
border-color: #D0C000;
}
dl.warning, dl.attention {
margin-left: -7px;
padding-left: 3px;
border-left: 4px solid;
border-color: #FF0000;
}
dl.warning.DocNodeRTL, dl.attention.DocNodeRTL {
margin-left: 0;
padding-left: 0;
border-left: 0;
margin-right: -7px;
padding-right: 3px;
border-right: 4px solid;
border-color: #FF0000;
}
dl.pre, dl.post, dl.invariant {
margin-left: -7px;
padding-left: 3px;
border-left: 4px solid;
border-color: #00D000;
}
dl.pre.DocNodeRTL, dl.post.DocNodeRTL, dl.invariant.DocNodeRTL {
margin-left: 0;
padding-left: 0;
border-left: 0;
margin-right: -7px;
padding-right: 3px;
border-right: 4px solid;
border-color: #00D000;
}
dl.deprecated {
margin-left: -7px;
padding-left: 3px;
border-left: 4px solid;
border-color: #505050;
}
dl.deprecated.DocNodeRTL {
margin-left: 0;
padding-left: 0;
border-left: 0;
margin-right: -7px;
padding-right: 3px;
border-right: 4px solid;
border-color: #505050;
}
dl.todo {
margin-left: -7px;
padding-left: 3px;
border-left: 4px solid;
border-color: #00C0E0;
}
dl.todo.DocNodeRTL {
margin-left: 0;
padding-left: 0;
border-left: 0;
margin-right: -7px;
padding-right: 3px;
border-right: 4px solid;
border-color: #00C0E0;
}
dl.test {
margin-left: -7px;
padding-left: 3px;
border-left: 4px solid;
border-color: #3030E0;
}
dl.test.DocNodeRTL {
margin-left: 0;
padding-left: 0;
border-left: 0;
margin-right: -7px;
padding-right: 3px;
border-right: 4px solid;
border-color: #3030E0;
}
dl.bug {
margin-left: -7px;
padding-left: 3px;
border-left: 4px solid;
border-color: #C08050;
}
dl.bug.DocNodeRTL {
margin-left: 0;
padding-left: 0;
border-left: 0;
margin-right: -7px;
padding-right: 3px;
border-right: 4px solid;
border-color: #C08050;
}
dl.section dd {
margin-bottom: 6px;
}
#projectlogo
{
text-align: center;
vertical-align: bottom;
border-collapse: separate;
}
#projectlogo img
{
border: 0px none;
}
#projectalign
{
vertical-align: middle;
}
#projectname
{
font: 300% Tahoma, Arial,sans-serif;
margin: 0px;
padding: 2px 0px;
}
#projectbrief
{
font: 120% Tahoma, Arial,sans-serif;
margin: 0px;
padding: 0px;
}
#projectnumber
{
font: 50% Tahoma, Arial,sans-serif;
margin: 0px;
padding: 0px;
}
#titlearea
{
padding: 0px;
margin: 0px;
width: 100%;
border-bottom: 1px solid #5387B4;
}
.image
{
text-align: center;
}
.dotgraph
{
text-align: center;
}
.mscgraph
{
text-align: center;
}
.plantumlgraph
{
text-align: center;
}
.diagraph
{
text-align: center;
}
.caption
{
font-weight: bold;
}
div.zoom
{
border: 1px solid #90B1CE;
}
dl.citelist {
margin-bottom:50px;
}
dl.citelist dt {
color:#335675;
float:left;
font-weight:bold;
margin-right:10px;
padding:5px;
text-align:right;
width:52px;
}
dl.citelist dd {
margin:2px 0 2px 72px;
padding:5px 0;
}
div.toc {
padding: 14px 25px;
background-color: #F4F7FA;
border: 1px solid #D8E4EE;
border-radius: 7px 7px 7px 7px;
float: right;
height: auto;
margin: 0 8px 10px 10px;
width: 200px;
}
.PageDocRTL-title div.toc {
float: left !important;
text-align: right;
}
div.toc li {
background: url("bdwn.png") no-repeat scroll 0 5px transparent;
font: 10px/1.2 Verdana,DejaVu Sans,Geneva,sans-serif;
margin-top: 5px;
padding-left: 10px;
padding-top: 2px;
}
.PageDocRTL-title div.toc li {
background-position-x: right !important;
padding-left: 0 !important;
padding-right: 10px;
}
div.toc h3 {
font: bold 12px/1.2 Arial,FreeSans,sans-serif;
color: #4677A2;
border-bottom: 0 none;
margin: 0;
}
div.toc ul {
list-style: none outside none;
border: medium none;
padding: 0px;
}
div.toc li.level1 {
margin-left: 0px;
}
div.toc li.level2 {
margin-left: 15px;
}
div.toc li.level3 {
margin-left: 30px;
}
div.toc li.level4 {
margin-left: 45px;
}
span.emoji {
/* font family used at the site: https://unicode.org/emoji/charts/full-emoji-list.html
* font-family: "Noto Color Emoji", "Apple Color Emoji", "Segoe UI Emoji", Times, Symbola, Aegyptus, Code2000, Code2001, Code2002, Musica, serif, LastResort;
*/
}
.PageDocRTL-title div.toc li.level1 {
margin-left: 0 !important;
margin-right: 0;
}
.PageDocRTL-title div.toc li.level2 {
margin-left: 0 !important;
margin-right: 15px;
}
.PageDocRTL-title div.toc li.level3 {
margin-left: 0 !important;
margin-right: 30px;
}
.PageDocRTL-title div.toc li.level4 {
margin-left: 0 !important;
margin-right: 45px;
}
.inherit_header {
font-weight: bold;
color: gray;
cursor: pointer;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.inherit_header td {
padding: 6px 0px 2px 5px;
}
.inherit {
display: none;
}
tr.heading h2 {
margin-top: 12px;
margin-bottom: 4px;
}
/* tooltip related style info */
.ttc {
position: absolute;
display: none;
}
#powerTip {
cursor: default;
white-space: nowrap;
background-color: white;
border: 1px solid gray;
border-radius: 4px 4px 4px 4px;
box-shadow: 1px 1px 7px gray;
display: none;
font-size: smaller;
max-width: 80%;
opacity: 0.9;
padding: 1ex 1em 1em;
position: absolute;
z-index: 2147483647;
}
#powerTip div.ttdoc {
color: grey;
font-style: italic;
}
#powerTip div.ttname a {
font-weight: bold;
}
#powerTip div.ttname {
font-weight: bold;
}
#powerTip div.ttdeci {
color: #006318;
}
#powerTip div {
margin: 0px;
padding: 0px;
font: 12px/16px Roboto,sans-serif;
}
#powerTip:before, #powerTip:after {
content: "";
position: absolute;
margin: 0px;
}
#powerTip.n:after, #powerTip.n:before,
#powerTip.s:after, #powerTip.s:before,
#powerTip.w:after, #powerTip.w:before,
#powerTip.e:after, #powerTip.e:before,
#powerTip.ne:after, #powerTip.ne:before,
#powerTip.se:after, #powerTip.se:before,
#powerTip.nw:after, #powerTip.nw:before,
#powerTip.sw:after, #powerTip.sw:before {
border: solid transparent;
content: " ";
height: 0;
width: 0;
position: absolute;
}
#powerTip.n:after, #powerTip.s:after,
#powerTip.w:after, #powerTip.e:after,
#powerTip.nw:after, #powerTip.ne:after,
#powerTip.sw:after, #powerTip.se:after {
border-color: rgba(255, 255, 255, 0);
}
#powerTip.n:before, #powerTip.s:before,
#powerTip.w:before, #powerTip.e:before,
#powerTip.nw:before, #powerTip.ne:before,
#powerTip.sw:before, #powerTip.se:before {
border-color: rgba(128, 128, 128, 0);
}
#powerTip.n:after, #powerTip.n:before,
#powerTip.ne:after, #powerTip.ne:before,
#powerTip.nw:after, #powerTip.nw:before {
top: 100%;
}
#powerTip.n:after, #powerTip.ne:after, #powerTip.nw:after {
border-top-color: #FFFFFF;
border-width: 10px;
margin: 0px -10px;
}
#powerTip.n:before {
border-top-color: #808080;
border-width: 11px;
margin: 0px -11px;
}
#powerTip.n:after, #powerTip.n:before {
left: 50%;
}
#powerTip.nw:after, #powerTip.nw:before {
right: 14px;
}
#powerTip.ne:after, #powerTip.ne:before {
left: 14px;
}
#powerTip.s:after, #powerTip.s:before,
#powerTip.se:after, #powerTip.se:before,
#powerTip.sw:after, #powerTip.sw:before {
bottom: 100%;
}
#powerTip.s:after, #powerTip.se:after, #powerTip.sw:after {
border-bottom-color: #FFFFFF;
border-width: 10px;
margin: 0px -10px;
}
#powerTip.s:before, #powerTip.se:before, #powerTip.sw:before {
border-bottom-color: #808080;
border-width: 11px;
margin: 0px -11px;
}
#powerTip.s:after, #powerTip.s:before {
left: 50%;
}
#powerTip.sw:after, #powerTip.sw:before {
right: 14px;
}
#powerTip.se:after, #powerTip.se:before {
left: 14px;
}
#powerTip.e:after, #powerTip.e:before {
left: 100%;
}
#powerTip.e:after {
border-left-color: #FFFFFF;
border-width: 10px;
top: 50%;
margin-top: -10px;
}
#powerTip.e:before {
border-left-color: #808080;
border-width: 11px;
top: 50%;
margin-top: -11px;
}
#powerTip.w:after, #powerTip.w:before {
right: 100%;
}
#powerTip.w:after {
border-right-color: #FFFFFF;
border-width: 10px;
top: 50%;
margin-top: -10px;
}
#powerTip.w:before {
border-right-color: #808080;
border-width: 11px;
top: 50%;
margin-top: -11px;
}
@media print
{
#top { display: none; }
#side-nav { display: none; }
#nav-path { display: none; }
body { overflow:visible; }
h1, h2, h3, h4, h5, h6 { page-break-after: avoid; }
.summary { display: none; }
.memitem { page-break-inside: avoid; }
#doc-content
{
margin-left:0 !important;
height:auto !important;
width:auto !important;
overflow:inherit;
display:inline;
}
}
/* @group Markdown */
table.markdownTable {
border-collapse:collapse;
margin-top: 4px;
margin-bottom: 4px;
}
table.markdownTable td, table.markdownTable th {
border: 1px solid #2D4C68;
padding: 3px 7px 2px;
}
table.markdownTable tr {
}
th.markdownTableHeadLeft, th.markdownTableHeadRight, th.markdownTableHeadCenter, th.markdownTableHeadNone {
background-color: #375E7F;
color: #FFFFFF;
font-size: 110%;
padding-bottom: 4px;
padding-top: 5px;
}
th.markdownTableHeadLeft, td.markdownTableBodyLeft {
text-align: left
}
th.markdownTableHeadRight, td.markdownTableBodyRight {
text-align: right
}
th.markdownTableHeadCenter, td.markdownTableBodyCenter {
text-align: center
}
.DocNodeRTL {
text-align: right;
direction: rtl;
}
.DocNodeLTR {
text-align: left;
direction: ltr;
}
table.DocNodeRTL {
width: auto;
margin-right: 0;
margin-left: auto;
}
table.DocNodeLTR {
width: auto;
margin-right: auto;
margin-left: 0;
}
tt, code, kbd, samp
{
display: inline-block;
direction:ltr;
}
/* @end */
u {
text-decoration: underline;
}
/* some custom styles for doxygen */
body {
font-family: "PingFangSC-Regular", "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 22px;
}
.ui-resizable-e {
background-image: none;
background-color: rgb(187 187 187 / 50%);
}
#nav-tree .label {
font-family: pingfang SC,helvetica neue,arial,hiragino sans gb,microsoft yahei ui,microsoft yahei,simsun,sans-serif!important;
font-size: 14px;
}
#nav-tree .label a {
font-size: 14px;
line-height: 36px;
color: #373d41;
}
#nav-tree .label a:hover {
color: #ff6a00!important;
}
#nav-tree .selected a {
color: #ff6a00!important;
}
#nav-tree .selected {
background-image: none;
text-shadow: none;
background-color: hsla(0,0%,85%,.15);
}
#nav-tree {
background-image: none;
background-color: #F7F7F7;
}
#nav-tree-contents {
margin: 16px 0 16px 16px;
}
/* some h1-6 style */
.contents h1, .contents h2, .contents h3, .contents h4, .contents h5, .contents h6 {
position: relative;
margin-top: 36px;
margin-bottom: 16px;
line-height: 1.4;
}
.contents h1 {
padding-bottom: 0;
font-size: 24px;
line-height: 24px
}
.contents h2 {
padding-bottom: 0;
font-size: 20px;
line-height: 20px
}
.contents h3 {
font-size: 16px;
line-height: 16px
}
.contents h4 {
font-size: 14px
}
.contents h5 {
font-size: 12px
}
.contents h6 {
font-size: 1em;
color: #777
}
#doc-content {
min-height: 400px;
}
div.header {
border-bottom: none;
background-image: none;
}
.arrow {
color: #9C9EA0;
font-size: 50%;
}
a {
color: #ff6a00;
font-weight: normal;
text-decoration: none;
}
.contents a:visited {
color: #ff6a00;
}
.contents a:hover {
text-decoration: underline;
}
a:hover {
color: #FF5800;
text-decoration: none;
}
/* sidebar style hack */
/*
#side-nav {
width: 100% !important;
max-width: 1180px;
margin: 0 auto;
position: relative;
}
#nav-tree {
width: 270px;
position: absolute;
}
#nav-sync {
display: none;
}
#doc-content {
width: 100% !important;
max-width: 1180px;
margin: 0 auto !important;
}
#doc-content .PageDoc {
margin-left: 275px !important;
}
*/
|
YifuLiu/AliOS-Things
|
documentation/doxygen/style/doxygen-custom.css
|
CSS
|
apache-2.0
| 34,020
|
<!-- HTML footer for doxygen 1.8.7-->
<!-- start footer part -->
<!--BEGIN GENERATE_TREEVIEW-->
<div id="haas-site-footer"></div>
<!--END GENERATE_TREEVIEW-->
</body>
</html>
|
YifuLiu/AliOS-Things
|
documentation/doxygen/style/footer.html
|
HTML
|
apache-2.0
| 175
|
<!-- HTML header for doxygen 1.8.7-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen $doxygenversion"/>
<!--BEGIN PROJECT_NAME--><title>$projectname: $title</title><!--END PROJECT_NAME-->
<!--BEGIN !PROJECT_NAME--><title>$title</title><!--END !PROJECT_NAME-->
<link href="$relpath^tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="$relpath^jquery.js"></script>
<script type="text/javascript" src="$relpath^dynsections.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, viewport-fit=cover" />
<!-- <script src="https://hli.aliyuncs.com/haas-static/js/jquery-3.6.0.min.js" type="text/javascript"></script> -->
<script src="https://hli.aliyuncs.com/haas-static/js/src/siteMount.js" type="text/javascript"></script>
<script>
(function(w, d, s, q, i) {
w[q] = w[q] || [];
var f = d.getElementsByTagName(s)[0],j = d.createElement(s);
j.async = true;
j.id = 'beacon-aplus';
j.src = 'https://d.alicdn.com/alilog/mlog/aplus/' + i + '.js';
f.parentNode.insertBefore(j, f);
})(window, document, 'script', 'aplus_queue', '203486311');
function _sendPV(spma, spmb) {
console.info(`sendPV ${spma}.${spmb}`)
aplus_queue.push({
action: 'aplus.setPageSPM',
arguments: [spma, spmb]
});
aplus_queue.push({
'action': 'aplus.sendPV',
'arguments': [{
is_auto: false
}, {
}]
})
}
_sendPV('a2cti', '24227744')
</script>
$treeview
$search
$mathjax
<link href="$relpath^$stylesheet" rel="stylesheet" type="text/css" />
<!-- debug code -->
<!-- <script type="module" src="http://localhost:3000/entry-common.js"></script>
<script type="module" src="http://localhost:3000/entry-header.js"></script>
<script type="module" src="http://localhost:3000/entry-footer.js"></script>
<link href="http://localhost:8004/style/doxygen-custom.css" rel="stylesheet" type="text/css"/> -->
$extrastylesheet
</head>
<body>
<script>
const devMount = false
if (devMount) {
var headerMounted = false
var footerMounted = false
function tryMount() {
if (window._haas_site_header_mount) {
window._haas_site_header_mount(
'#haas-site-header'
)
headerMounted = true
}
if (window._haas_site_footer_mount) {
window._haas_site_footer_mount(
'#haas-site-footer'
)
footerMounted = true
}
if (!headerMounted || !footerMounted) {
setTimeout(() => {
tryMount()
}, 700)
}
}
tryMount()
} else {
// const mode = '{{CONTEXT.env.bizEnv}}' // daily\pre\prod
window._haas_site_mount(
{
mode: 'daily', // daily\pre\prod
manifestEntries: [
'entry-common-legacy.js', 'entry-header-legacy.js', 'entry-footer-legacy.js',
],
onload: function () {
window._haas_site_header_mount('#haas-site-header')
window._haas_site_footer_mount('#haas-site-footer')
}
}
)
}
</script>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="haas-site-header"></div>
<div id="topbanner"><a href="https://github.com/Tencent/rapidjson" title="RapidJSON GitHub"><i class="githublogo"></i></a></div>
$searchbox
<!--END TITLEAREA-->
<!-- end header part -->
|
YifuLiu/AliOS-Things
|
documentation/doxygen/style/header.html
|
HTML
|
apache-2.0
| 3,642
|
@echo off
rem win os version, refer to https://en.wikipedia.org/wiki/Ver_(command)
CHCP 65001
for /f "tokens=4,5,6 delims=[]. " %%G in ('ver') do (set _major=%%G& set _minor=%%H& set _build=%%I)
echo System information: [%_major%.%_minor%.%_build%]
if %_major% LSS 6 (
echo Not supported system, minimal Windows 7.
exit /B 1
)
if "%PROCESSOR_ARCHITECTURE%"=="x86" (
echo Not supported 32-bit system.
exit /B 1
)
where curl > NUL 2>&1
if errorlevel 1 (
echo Please download curl from https://curl.se/windows/, install it and add it into PATH.
exit /B 1
)
curl -o %UserProfile%\Miniconda3-latest-Windows-x86_64.exe https://repo.anaconda.com/miniconda/Miniconda3-latest-Windows-x86_64.exe
echo Installing miniconda3...
start /wait "" %UserProfile%\Miniconda3-latest-Windows-x86_64.exe /InstallationType=JustMe /AddToPath=0 /RegisterPython=0 /S /D=%UserProfile%\Miniconda3
echo open "Anaconda Prompt(Miniconda3)" to install aos-tools
pause
exit 0
|
YifuLiu/AliOS-Things
|
documentation/quickstart/install_miniconda.bat
|
Batchfile
|
apache-2.0
| 1,004
|
#!/usr/bin/env bash
if [ "$(uname)" == "Darwin" ];then
MYOS="Darwin"
elif [ "$(expr substr $(uname -s) 1 5)" == "Linux" ];then
MYOS="Linux"
elif [ "$(expr substr $(uname -s) 1 10)" == "MINGW32_NT" ];then
MYOS="Win32"
fi
if [ -z $(which curl) ];then
echo "can not find curl. please install it"
exit 1
fi
if [ $MYOS == "Darwin" ]; then
curl https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-x86_64.sh -o ~/miniconda.sh
elif [ $MYOS == "Linux" ]; then
curl https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -o ~/miniconda.sh
else
echo "not support $MYOS"
exit 1
fi
bash ~/miniconda.sh -b -f -p $HOME/miniconda3
if [[ $SHELL = *zsh ]]
then
$HOME/miniconda3/bin/conda init zsh
else
$HOME/miniconda3/bin/conda init
fi
$HOME/miniconda3/bin/conda config --set auto_activate_base false
echo "start a new terminal to install aos-tools."
exit 0
|
YifuLiu/AliOS-Things
|
documentation/quickstart/install_miniconda.sh
|
Shell
|
apache-2.0
| 917
|
import utime
import ustruct
from micropython import const
from driver import UART
# check passwoard: 4 byte 0000
cmdVerifyPasswoard = b'\xEF\x01\xFF\xFF\xFF\xFF\x01\x00\x07\x13\x00\x00\x00\x00\x00\x1B'
# 采集图片
cmdGetImage = b'\xEF\x01\xFF\xFF\xFF\xFF\x01\x00\x03\x01\x00\x05'
# 生成指纹图片对应的特征值
cmdImage2Char = b'\xEF\x01\xFF\xFF\xFF\xFF'
cmdSaveimage2Char = b'\x01\x00\x04\x02'
# 创建指纹模板
cmdCreateModel = b'\xEF\x01\xFF\xFF\xFF\xFF\x01\x00\x03\x05\x00\x09'
# 保存指纹模板
cmdStoreModel = b'\xEF\x01\xFF\xFF\xFF\xFF'
cmdSaveStoreModel = b'\x01\x00\x06\x06\x01'
#指纹匹配指令
cmdMatch = b'\xEF\x01\xFF\xFF\xFF\xFF\x01\x00\x03\x03\x00\x07'
#指纹搜索指令
cmdSearch = b'\xEF\x01\xFF\xFF\xFF\xFF\x01\x00\x08\x04\x01\x00\x00\x00\x7F\x00\x8D'
# 读取索引表
cmdReadIndexTable = b'\xEF\x01\xFF\xFF\xFF\xFF\x01\x00\x04\x1F\x00\x00\x24'
#删除指纹记录
cmdDeleteModel = b'\xEF\x01\xFF\xFF\xFF\xFF'
cmdSaveDeleteModel = b'\x01\x00\x07\x0c\x00'
# 清除数据库中的指纹信息
cmdEmptyDatabase = b'\xEF\x01\xFF\xFF\xFF\xFF\x01\x00\x03\x0D\x00\x11'
# 获取指纹图片信息
cmdGetFPImage = b'\xEF\x01\xFF\xFF\xFF\xFF\x01\x00\x03\x0a\x00\x0e'
# 获取指纹特征值信息
cmdGetFPChar = b'\xEF\x01\xFF\xFF\xFF\xFF\x01\x00\x04\x08\x00\x00\x00'
SUCCESS = const(0)
FAIL = const(-1)
NO_FINGER = const(2)
DATABASE_CAPABILITY = const(300)
CMD_RSP_TIMEOUT_MS = const(500) # 单条指令超时时间
CMD_RSP_WAIT_TIME_MS = const(10) # 目前指令的response最多44个byte,44*(1+8+2+1)/57600 ~= 9.9ms
class AS608:
def __init__(self, *args, **kargs):
self._uartDev = None
if not isinstance(args[0], UART):
raise ValueError("parameter is not an UART object")
#实例化和AS608通信所用串口
self._uartDev=args[0]
#接收指令执行结果
def getCmdResult(self):
cnt = 0
len = 12
rx = bytearray(len * b'5')
# 检查UART接收缓冲区中是否有足够的数据
l = self._uartDev.any()
while(l < len):
# print('uart.any:', l)
cnt += 1
if cnt > CMD_RSP_TIMEOUT_MS/CMD_RSP_WAIT_TIME_MS: # 等待超时时间后退出
break
utime.sleep_ms(CMD_RSP_WAIT_TIME_MS)
l = self._uartDev.any()
self._uartDev.read(rx)
return rx
def matchCmdResult(self):
cnt = 0
len = 14
rx = bytearray(len * b'5')
# 检查UART接收缓冲区中是否有足够的数据
l = self._uartDev.any()
while(l < len):
# print('uart.any:', l)
cnt += 1
if cnt > CMD_RSP_TIMEOUT_MS/CMD_RSP_WAIT_TIME_MS: # 等待超时时间后退出
break
utime.sleep_ms(CMD_RSP_WAIT_TIME_MS)
l = self._uartDev.any()
self._uartDev.read(rx)
return rx
#接收指纹图像数据
def getLongResult(self):
cnt = 0
rx = bytearray(0)
# 检查UART接收缓冲区中是否有足够的数据
while(cnt < 5):
utime.sleep_ms(30)
buf = bytearray(512)
l = self._uartDev.any()
# 检查UART中是否有数据
if l > 0:
# 从UART读取数据
l = self._uartDev.read(buf)
#print(l)
if l > 0:
# 合并UART返回结果
rx += buf[0:l]
cnt = 0
else:
cnt += 1
return rx
# 接收搜索指令结果
def searchCmdResult(self):
cnt = 0
len = 16
rx = bytearray(len * b'5')
l = self._uartDev.any()
while(l < len):
# print('uart.any:', l)
cnt += 1
if cnt > CMD_RSP_TIMEOUT_MS/CMD_RSP_WAIT_TIME_MS: # 等待超时时间后退出
break
utime.sleep_ms(CMD_RSP_WAIT_TIME_MS)
l = self._uartDev.any()
self._uartDev.read(rx)
return rx
# 接收索引表结果
def readIndexCmdResult(self):
cnt = 0
len = 44
rx = bytearray(len * b'5')
l = self._uartDev.any()
while(l < len):
# print('uart.any:', l)
cnt += 1
if cnt > CMD_RSP_TIMEOUT_MS/CMD_RSP_WAIT_TIME_MS: # 等待超时时间后退出
break
utime.sleep_ms(CMD_RSP_WAIT_TIME_MS)
l = self._uartDev.any()
self._uartDev.read(rx)
return rx
# 验证密码
def verifyPassword(self):
self._uartDev.write(cmdVerifyPasswoard)
rsp = self.getCmdResult()
# 检查命令是否执行成功
if rsp[-3] == 0:
return SUCCESS
else:
return FAIL
'''
Confirm code=00H shows OK;
Confirm Code=01H shows receiving packet error;
Confirm Code=13H shows password incorrect;
Confirm Code=21H shows Must verify password first;
'''
# 录入指纹图像
def getImage(self):
self._uartDev.write(cmdGetImage)
rsp = self.getCmdResult()
# print(rsp)
# 检查命令是否执行成功
if rsp[9] == 0:
return SUCCESS
elif rsp[9] == 2:
return NO_FINGER
else:
return FAIL
'''
Confirm Code=00H - 录入成功
Confirm Code=01H - 收包错误
Confirm Code=02H - 传感器上无手指
Confirm Code=03H - 指纹录入失败
'''
# 生成指纹对应的特征值, slot代表Buffer缓冲区ID
def image2Character(self, slot = 1):
sumImage2Char = cmdSaveimage2Char + bytearray([slot, 0, slot + 0x7])
self._uartDev.write(cmdImage2Char)
self._uartDev.write(sumImage2Char)
rsp = self.getCmdResult()
# 检查命令是否执行成功
if rsp[9] == 0:
return SUCCESS
else:
return FAIL
'''
Confirm Code=00H - 生成特征值成功
Confirm Code=01H - 收包错误
Confirm Code=06H - 指纹图像太乱,生成特征值失败
Confirm Code=07H - 特征点太少,生成特征值失败
feature;
Confirm Code=15H - 图像缓冲区内没有有效原始图,生成特征值失败
'''
# 合并特征并生成模板
def createModel(self):
self._uartDev.write(cmdCreateModel)
rsp = self.getCmdResult()
# 检查命令是否执行成功
if rsp[9] == 0:
return SUCCESS
else:
return FAIL
'''
Confirm Code=00H - 合并成功
Confirm Code=01H - 收包错误
Confirm Code=0aH - 合并失败(两枚指纹不属于同一手指)
'''
# 将模板文件存储到PageID中,默认存储缓冲区1中的模板
def storeModel(self, id):
#sumStoreModel = cmdSaveStoreModel + bytearray([id, 0, id + 0x0E])
payload = cmdSaveStoreModel + bytearray([(id >> 8) & 0xff, id & 0xff])
s = sum(payload)
sumStoreModel = cmdStoreModel + payload + bytearray([(s >> 8) & 0xff, s & 0xff])
self._uartDev.write(sumStoreModel)
rsp = self.getCmdResult()
# 检查命令是否执行成功
if rsp[9] == 0:
return SUCCESS
else:
return FAIL
'''
Confirm Code=00H - 储存成功
Confirm Code=01H - 收包错误
Confirm Code=0bH - pageID超出范围
Confirm Code=18H - 写Flash操作出错
'''
# 精确比对两枚指纹特征
def match(self):
self._uartDev.write(cmdMatch)
rsp = self.matchCmdResult()
# 检查命令是否执行成功
if rsp[9] == 0:
return SUCCESS
else:
return FAIL
'''
Confirm Code=00H - 指纹匹配
Confirm Code=01H - 收包错误
Confirm Code=08H - 指纹不匹配
'''
# 以缓冲区1或缓冲区2中的特征文件搜索整个或部分指纹库,若搜索到,返回页码
def search(self):
result = FAIL
fingerId = -1
confidence = 0
self._uartDev.write(cmdSearch)
rsp = self.searchCmdResult()
# print(rsp)
# 检查命令是否执行成功
if rsp[9] == 0:
result = SUCCESS
fingerId, confidence = ustruct.unpack(">HH", bytes(rsp[10:14]))
else:
fingerId, confidence = -1, 0
# print (result, fingerId, confidence)
return result, fingerId, confidence
'''
Confirm Code=00H - 搜索成功
Confirm Code=01H - 收包错误
Confirm Code=09H - 没有搜索到,此时fingerId和confidence均为0
'''
# 删除Flash指纹库中的一个特征文件
def deleteModel(self, id):
if id >= DATABASE_CAPABILITY or id < 0:
return FAIL
deleteModel = cmdSaveDeleteModel + bytearray([id, 0, 1, 0, id + 0x15])
self._uartDev.write(cmdDeleteModel)
self._uartDev.write(deleteModel)
rsp = self.getCmdResult()
# 检查命令是否执行成功
if rsp[9] == 0:
return SUCCESS
else:
return FAIL
'''
Confirm Code=00H - 删除模板成功
Confirm Code=01H - 收包错误
Confirm Code=10H - 删除模板失败
'''
# 删除flash数据库中的所有指纹模板
def emptyDatabase(self):
self._uartDev.write(cmdEmptyDatabase)
rsp = self.getCmdResult()
# 检查命令是否执行成功
if rsp[9] == 0:
return SUCCESS
else:
return FAIL
'''
Confirm Code=00H - 清空指纹模板成功
Confirm Code=01H - 收包错误
Confirm Code=11H - 清空指纹模板失败
'''
# 获取指纹特征值
def getFPCharacter(self, slot = 1):
# 获取指纹特征值信息
cmd = bytearray(cmdGetFPChar)
cmd[10] = slot
s = sum(cmd[6:11])
cmd[11] = (s >> 8) & 0xff
cmd[12] = s & 0xff
self._uartDev.write(cmd)
rsp = self.getLongResult()
# 检查命令是否执行成功
if rsp[9] == 0:
return SUCCESS, rsp[12:len(rsp)]
else:
return FAIL, []
'''
Confirm Code=00H - 清空指纹模板成功
Confirm Code=01H - 收包错误
Confirm Code=0dH - 指纹执行失败
'''
# 获取指纹图像
def getFPImage(self):
self._uartDev.write(cmdGetFPImage)
rsp = self.getLongResult()
# 检查命令是否执行成功
if rsp[9] == 0:
return SUCCESS, rsp[12:len(rsp)]
else:
return FAIL, []
'''
Confirm Code=00H - 清空指纹模板成功
Confirm Code=01H - 收包错误
Confirm Code=0fH - bu不能发送后续数据包
'''
def getEmptyPosition(self):
for i in range(4):
cmdReadIndexTable = b'\xEF\x01\xFF\xFF\xFF\xFF\x01\x00\x04\x1F\x00\x00\x24'
s = sum(cmdReadIndexTable[6:10]) + i
cmd = cmdReadIndexTable[0:10] + bytearray([i]) + bytearray([(s >> 8) & 0xff, s & 0xff])
self._uartDev.write(cmd)
rsp = self.readIndexCmdResult()
# print(rsp)
# 检查命令是否执行成功
if rsp[9] == 0:
index = rsp[10:41]
for j in range(len(index)):
for m in range(8):
if not (index[j] & (1 << m)):
return i * 32 + j * 8 + m
return FAIL
# 指纹录入
def fingerEnroll(self, id):
p = FAIL
if id >= DATABASE_CAPABILITY or id < 0:
return FAIL
print('wait for finger print on the pannel')
while p != NO_FINGER:
p = self.getImage()
# 开始采集指纹
while p != SUCCESS:
p = self.getImage()
print('finger detected')
# 指纹图片转化为特征值
p = self.image2Character(1)
if p != SUCCESS:
print('image to text failed, exit')
return 0
# 再录制一次
print('take off your finger, please')
#Take off your finger
p = 0
while p != NO_FINGER:
p = self.getImage()
# put on again
# Get image again
print('put on your finger again, please')
while p != SUCCESS:
p = self.getImage()
# 指纹图片转化为特征值
p = self.image2Character(2)
if p != SUCCESS:
return 0
print('creating finger model')
# 创建指纹模板
p = self.createModel()
if p != SUCCESS:
print('creating model failed')
return 0
print('store finger model')
# 存储指纹模板
p = self.storeModel(id)
if p != SUCCESS:
# fingerrecordfail
print('store finger model failed')
return FAIL
print('store finger model success')
return SUCCESS
# 指纹识别
def fingerSearch(self):
p = FAIL
print('search finger')
print('wait for finger print on the pannel')
while p != NO_FINGER:
p = self.getImage()
while p != SUCCESS:
p = self.getImage()
print('finger detected')
p = self.image2Character(1)
if p != SUCCESS:
# 指纹图片转换为特征值失败
print('image to text failed, exit')
return -1
# 在指纹库中搜索指纹
p, id, confidence = self.search()
if p == SUCCESS:
# 搜索成功
print('finger id:', id, ' confidence:', confidence)
return SUCCESS, id
else:
# 搜索失败
print('no match finger found')
return FAIL, -1
|
YifuLiu/AliOS-Things
|
haas_lib_bundles/python/docs/examples/FingerPrintLock/as608.py
|
Python
|
apache-2.0
| 14,058
|
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
@File : cloudAI.py
@Description: 云端AI
@Author : jiangyu
@version : 1.0
'''
from aliyunIoT import Device
import utime # 延时函数在utime库中
import ujson as json
class CloudAI :
def __gesture_cb(self, dict) :
'''
Reply list :
handGestureReply : 手势识别
'''
gesture = 'NA'
if dict != None:
ext = dict['ext']
ext_dict = json.loads(ext)
result = ext_dict['result']
if result == 'success':
score = ext_dict['score']
if score > 0.4 :
gesture = ext_dict['type']
print("recognize hand gesture : " + gesture)
self.__cb('handGestureReply', gesture)
def __action_cb(self, dict) :
'''
Reply list :
actionReply : 动作识别
'''
action = 'NA'
if dict != None:
ext = dict['ext']
ext_dict = json.loads(ext)
i = 0
elements_list = ext_dict['elements']
while (i < len(elements_list)) :
g_score = elements_list[i]['score']
label = elements_list[i]['label']
if g_score > 0.5:
print("recognize action: " + label)
action = label
break
i += 1
self.__cb('recognizeActionReply', action)
def __license_plate_cb(self, dict) :
plateNumber = 'NA'
if dict != None:
ext = dict['ext']
ext_dict = json.loads(ext)
result = ext_dict['result']
if result == 'success':
g_confidence = ext_dict['confidence']
if g_confidence > 0.7 :
plateNumber = ext_dict['plateNumber']
print('detect: ' + plateNumber)
self.__cb('ocrCarNoReply', plateNumber)
def __fruits_cb(self, dict) :
fruit_name = 'NA'
if dict != None:
ext = dict['ext']
ext_dict = json.loads(ext)
result = ext_dict['result']
if result == 'success':
i = 0
fruits_list = ext_dict['fruitList']
while (i < len(fruits_list)) :
g_score = fruits_list[i]['score']
fruit_name = fruits_list[i]['name']
if g_score > 0.6:
print('detect: ' + fruit_name)
i += 1
self.__cb('detectFruitsReply', fruit_name)
def __pedestrian_cb(self, dict) :
detected = False
if dict != None:
ext = dict['ext']
ext_dict = json.loads(ext)
result = ext_dict['result']
if result == 'success':
i = 0
data = ext_dict['data']
data_dict = json.loads(data)
elements_list = data_dict['elements']
while (i < len(elements_list)) :
g_score = elements_list[i]['score']
if g_score > 0.6:
print('Pedestrian Detected')
detected = True
i += 1
self.__cb('DetectPedestrianReply', detected)
def __businesscard_cb(self, dict) :
card_info = {}
if dict != None:
ext = dict['ext']
ext_dict = json.loads(ext)
result = ext_dict['result']
if result == 'success':
card_info['name'] = ext_dict['name']
print("name : " + card_info['name'])
if card_info['name'] == '' :
card_info['name'] = 'unknown'
phoneNumbers_list = ext_dict['cellPhoneNumbers']
print("phoneNumbers : ")
print(phoneNumbers_list)
if len(phoneNumbers_list) :
card_info['phoneNumbers'] = phoneNumbers_list[0]
else :
card_info['phoneNumbers'] = 'unknown'
email_list = ext_dict['emails']
print("email_list: ")
print(email_list)
if len(email_list) :
card_info['email'] = email_list[0]
else :
card_info['email'] = 'unknown'
self.__cb('recognizeBusinessCardReply', card_info)
def __rubblish_cb(self, dict) :
name = 'NA'
if dict != None:
ext = dict['ext']
extDict = json.loads(ext)
result = extDict['result']
if result == 'success':
i = 0
elements = extDict['elements']
while (i < len(elements)) :
gScore = elements[i]['categoryScore']
if gScore > 0.8:
name = elements[i]['category']
print('detect: ' + name)
break
i += 1
self.__cb('classifyingRubbishReply', name)
def __object_cb(self, dict) :
name = 'NA'
if dict != None:
ext = dict['ext']
extDict = json.loads(ext)
result = extDict['result']
if result == 'success':
i = 0
elements = extDict['elements']
while (i < len(elements)) :
gScore = elements[i]['score']
if gScore > 0.25:
name = elements[i]['type']
print('detect: ' + name)
break
i += 1
self.__cb('detectObjectReply', name)
def __vehicletype_cb(self, dict) :
name = 'NA'
detect = False
if dict != None:
ext = dict['ext']
ext_dict = json.loads(ext)
result = ext_dict['result']
if result == 'success':
i = 0
item_list = ext_dict['items']
name = 'NA'
while (i < len(item_list)) :
g_score = item_list[i]['score']
name = item_list[i]['name']
# 这里可以修改识别的可信度,目前设置返回可信度大于85%才认为识别正确
if g_score > 0.85 and name != 'others':
print('detect: ' + name)
detect = True
self.__cb('recognizeVehicleReply', name)
break
i += 1
if detect == False:
self.__cb('recognizeVehicleReply', 'NA')
def __vehiclelogo_cb(self, dict) :
num = 0
if dict != None:
ext = dict['ext']
ext_dict = json.loads(ext)
result = ext_dict['result']
if result == 'success':
item_list = ext_dict['elements']
num = len(item_list)
if num > 0:
print('detect: ' + str(num) + ' vehicle')
detected = True
if detected == False:
print('do not detect!')
self.__cb('recognizeLogoReply', num)
def __cb_lk_service(self, data):
self.g_lk_service = True
print('download <----' + str(data))
if data != None :
params = data['params']
params_dict = json.loads(params)
command = params_dict['commandName']
if command == 'handGestureReply' :
self.__gesture_cb(params_dict)
elif command == 'recognizeActionReply' :
self.__action_cb(params_dict)
elif command == 'ocrCarNoReply' :
self.__license_plate_cb(params_dict)
elif command == 'DetectPedestrianReply' :
self.__pedestrian_cb(params_dict)
elif command == 'detectFruitsReply' :
self.__fruits_cb(params_dict)
elif command == 'recognizeBusinessCardReply' :
self.__businesscard_cb(params_dict)
elif command == 'classifyingRubbishReply' :
self.__rubblish_cb(params_dict)
elif command == 'detectObjectReply' :
self.__object_cb(params_dict)
elif command == 'recognizeVehicleReply' :
self.__vehicletype_cb(params_dict)
elif command == 'recognizeLogoReply' :
self.__vehiclelogo_cb(params_dict)
else :
print('unknown command reply')
def __cb_lk_connect(self, data):
print('link platform connected')
self.g_lk_connect = True
def __connect_iot(self) :
self.device = Device()
self.device.on(Device.ON_CONNECT, self.__cb_lk_connect)
self.device.on(Device.ON_SERVICE, self.__cb_lk_service)
self.device.connect(self.__dev_info)
while True:
if self.g_lk_connect:
break
def __init__(self, dev_info, callback) :
self.__dev_info = dev_info
self.__cb = callback
self.g_lk_connect = False
self.g_lk_service = False
self.__connect_iot()
def getDevice(self) :
return self.device
def __upload_request(self, command, frame, enlarge = 1) :
# 上传图片到LP
fileName = 'test.jpg'
start = utime.ticks_ms()
fileid = self.device.uploadContent(fileName, frame, None)
if fileid != None:
ext = { 'filePosition':'lp', 'fileName': fileName, 'fileId': fileid, 'enlarge':enlarge}
ext_str = json.dumps(ext)
all_params = {'id': 1, 'version': '1.0', 'params': { 'eventType': 'haas.faas', 'eventName': command, 'argInt': 1, 'ext': ext_str }}
all_params_str = json.dumps(all_params)
#print(all_params_str)
upload_file = {
'topic': '/sys/' + self.__dev_info['productKey'] + '/' + self.__dev_info['deviceName'] + '/thing/event/hli_event/post',
'qos': 1,
'payload': all_params_str
}
# 上传完成通知HaaS聚合平台
print('upload--->' + str(upload_file))
self.g_lk_service = False
self.device.publish(upload_file)
i = 0
while (self.g_lk_service == False and i < 200) :
utime.sleep_ms(10)
i = i + 1
continue
else:
print('filedid is none, upload content fail')
time_diff = utime.ticks_diff(utime.ticks_ms(), start)
print('recognize time : %d' % time_diff)
def recognizeGesture(self, frame) :
self.__upload_request('handGesture', frame)
def recognizeAction(self, frame) :
self.__upload_request('recognizeAction', frame, 2)
def recognizeLicensePlate(self, frame) :
self.__upload_request('ocrCarNo', frame)
def detectPedestrian(self, frame) :
self.__upload_request('detectPedestrian', frame)
def detectFruits(self, frame) :
self.__upload_request('detectFruits', frame)
def recognizeBussinessCard(self, frame) :
self.__upload_request('recognizeBusinessCard', frame)
def recognizeVehicleType(self, frame) :
self.__upload_request('recognizeVehicle', frame)
def detectVehicleCongestion(self, frame) :
self.__upload_request('vehicleCongestionDetect', frame)
def classifyRubbish(self, frame) :
self.__upload_request('classifyingRubbish', frame)
def detectObject(self, frame) :
self.__upload_request('detectObject', frame)
|
YifuLiu/AliOS-Things
|
haas_lib_bundles/python/docs/examples/action_recognization/m5stack/code/cloudAI.py
|
Python
|
apache-2.0
| 11,672
|
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
@File : main.py
@Description: 人体动作行为识别案例
@Author : jinouxiang
@version : 2.0
'''
import display # 显示库
import uai # AI识别库
import network # 网络库
import ucamera # 摄像头库
import utime # 延时函数在utime库中
import _thread # 线程库
import sntp # 网络时间同步库
from cloudAI import *
# Wi-Fi SSID和Password设置
SSID='Your-AP-SSID'
PWD='Your-AP-Password'
# HaaS设备三元组
productKey = "Your-ProductKey"
deviceName = "Your-devicename"
deviceSecret = "Your-deviceSecret"
detected = False
action = ''
key_info = {
'region' : 'cn-shanghai' ,
'productKey': productKey ,
'deviceName': deviceName ,
'deviceSecret': deviceSecret ,
'keepaliveSec': 60
}
action_dic = {
'举手' : 'lift hand',
'吃喝': 'eat and drink',
'吸烟': 'smoking',
'打电话': 'phone call',
'玩手机': 'play cell-phone',
'趴桌睡觉' : 'sleep',
'跌倒': 'fall down',
'洗手': 'wash hand',
'拍照': 'take picture'
}
def connect_wifi(ssid, pwd):
# 引用全局变量
global disp
# 初始化网络
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, pwd)
while True:
print('Wi-Fi is connecting...')
# 显示网络连接中
disp.text(20, 30, 'Wi-Fi is connecting...', disp.RED)
# 网络连接成功后,更新显示字符
if (wlan.isconnected() == True):
print('Wi-Fi is connected')
disp.textClear(20, 30, 'Wi-Fi is connecting...')
disp.text(20, 30, 'Wi-Fi is connected', disp.RED)
ip = wlan.ifconfig()[0]
print('IP: %s' %ip)
disp.text(20, 50, ip, disp.RED)
# NTP时间更新,如果更新不成功,将不能进行识别
print('NTP start')
disp.text(20, 70, 'NTP start...', disp.RED)
sntp.setTime()
print('NTP done')
disp.textClear(20, 70, 'NTP start...')
disp.text(20, 70, 'NTP done', disp.RED)
break
utime.sleep_ms(500)
utime.sleep(2)
def action_cb(commandReply, result) :
global detected, action
action = 'NA'
detected = False
if commandReply == 'recognizeActionReply' :
if result != 'NA' :
action = action_dic[result]
print('detect action: ' + action)
detected = True
else :
print('unknown command reply')
# 识别线程函数
def recognizeThread():
global frame
while True:
if frame != None:
engine.recognizeAction(frame)
#engine.recognizeGesture(frame)
utime.sleep_ms(6000)
else:
utime.sleep_ms(1000)
# 显示线程函数
def displayThread():
# 引用全局变量
global disp, frame, detected, action
# 定义清屏局部变量
clearFlag = False
# 定义显示文本局部变量
textShowFlag = False
while True:
# 采集摄像头画面
# print('start to capture')
frame = ucamera.capture()
# print('end to capture')
if frame != None:
if detected == True:
# 清除屏幕内容
disp.clear()
# 设置文字字体
disp.font(disp.FONT_DejaVu40)
# 显示识别结果
disp.text(10, 50, 'detect: ' + action, disp.RED)
#disp.text(10, 50, 'detect pedestrain', disp.RED)
utime.sleep_ms(1000)
textShowFlag = False
else:
# 显示图像
# print('start to display')
disp.image(0, 20, frame, 0)
utime.sleep_ms(100)
if textShowFlag == False:
# 设置显示字体
disp.font(disp.FONT_DejaVu18)
# 显示文字
disp.text(2, 0, 'Recognizing...', disp.WHITE)
textShowFlag = True
def main():
# 全局变量
global disp, frame, detected, action, engine
# 创建lcd display对象
disp = display.TFT()
frame = None
detected = False
# 连接网络
connect_wifi(SSID, PWD)
engine = CloudAI(key_info, action_cb)
# 初始化摄像头
ucamera.init('uart', 33, 32)
ucamera.setProp(ucamera.SET_FRAME_SIZE, ucamera.SIZE_320X240)
try:
# 启动显示线程
_thread.start_new_thread(displayThread, ())
# 设置比对线程stack
_thread.stack_size(20 * 1024)
# 启动比对线程
_thread.start_new_thread(recognizeThread, ())
except:
print("Error: unable to start thread")
while True:
utime.sleep_ms(1000)
if __name__ == '__main__':
main()
|
YifuLiu/AliOS-Things
|
haas_lib_bundles/python/docs/examples/action_recognization/m5stack/code/main.py
|
Python
|
apache-2.0
| 4,896
|