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
#include <iostream> #include "alibabacloud/core/AlibabaCloud.h" #include "alibabacloud/ocr/OcrClient.h" #include "alibabacloud/core/CommonClient.h" #include "model/common.h" extern "C" { using namespace std; using namespace AlibabaCloud; using namespace AlibabaCloud::Ocr; int recognizeIdentityCardFaceSide(char *url, AIModelCBFunc cb) { InitializeSdk(); string key = getAccessKey(); string secret = getAccessSecret(); ClientConfiguration configuration; configuration.setRegionId(CLOUD_AI_REGION_ID); configuration.setEndpoint(CLOUD_AI_OCR_ENDPOINT); OcrClient client(key, secret, configuration); Model::RecognizeIdentityCardRequest request; string imageURL; OcrResultStruct result; string address, birthDate, gender, nationality, iDNumber; int ret = 0, i; imageURL = url; request.setScheme("http"); request.setMethod(HttpRequest::Method::Post); request.setImageURL(imageURL); request.setSide("face"); auto outcome = client.recognizeIdentityCard(request); cout << endl << "ocr describeInstances returned:" << endl; cout << "error code: " << outcome.error().errorCode() << endl; cout << "requestId: " << outcome.result().requestId() << endl << endl; cout << "Address: " << outcome.result().getData().frontResult.address << endl; cout << "BirthDate: " << outcome.result().getData().frontResult.birthDate << endl; cout << "gender: " << outcome.result().getData().frontResult.gender << endl; cout << "nationality: " << outcome.result().getData().frontResult.nationality << endl; cout << "iDNumber: " << outcome.result().getData().frontResult.iDNumber << endl; cout << "faceRectangle.x: " << outcome.result().getData().frontResult.faceRectangle.center.x << endl; cout << "faceRectangle.y: " << outcome.result().getData().frontResult.faceRectangle.center.y << endl; cout << "faceRectangle.width: " << outcome.result().getData().frontResult.faceRectangle.size.width << endl; cout << "faceRectangle.height: " << outcome.result().getData().frontResult.faceRectangle.size.height << endl; cout << "faceRectangle.angle: " << outcome.result().getData().frontResult.faceRectangle.angle << endl; result.identity.face.location.x = outcome.result().getData().frontResult.faceRectangle.center.x; result.identity.face.location.y = outcome.result().getData().frontResult.faceRectangle.center.y; result.identity.face.location.w = outcome.result().getData().frontResult.faceRectangle.size.width; result.identity.face.location.h = outcome.result().getData().frontResult.faceRectangle.size.height; for (i = 0; i < 4; i++) { cout << i << "cardAreas.x: " << outcome.result().getData().frontResult.cardAreas[i].x << endl; cout << i << "cardAreas.y: " << outcome.result().getData().frontResult.cardAreas[i].y << endl; cout << i << "faceRectVertices.x: " << outcome.result().getData().frontResult.faceRectVertices[i].x << endl; cout << i << "faceRectVertices.y: " << outcome.result().getData().frontResult.faceRectVertices[i].y << endl; result.identity.face.cardX[i] = outcome.result().getData().frontResult.cardAreas[i].x; result.identity.face.cardY[i] = outcome.result().getData().frontResult.cardAreas[i].y; result.identity.face.faceX[i] = outcome.result().getData().frontResult.faceRectVertices[i].x; result.identity.face.faceY[i] = outcome.result().getData().frontResult.faceRectVertices[i].y; } address = outcome.result().getData().frontResult.address; birthDate = outcome.result().getData().frontResult.birthDate; gender = outcome.result().getData().frontResult.gender; nationality = outcome.result().getData().frontResult.nationality; iDNumber = outcome.result().getData().frontResult.iDNumber; result.identity.face.address = (char *)address.c_str(); result.identity.face.birthDate = (char *)birthDate.c_str(); result.identity.face.gender = (char *)gender.c_str(); result.identity.face.nationality = (char *)nationality.c_str(); result.identity.face.iDNumber = (char *)iDNumber.c_str(); if (cb) { ret = cb((void *)&result); } ShutdownSdk(); return ret; } int recognizeIdentityCardBackSide(char *url, AIModelCBFunc cb) { InitializeSdk(); string key = getAccessKey(); string secret = getAccessSecret(); ClientConfiguration configuration; configuration.setRegionId(CLOUD_AI_REGION_ID); configuration.setEndpoint(CLOUD_AI_OCR_ENDPOINT); OcrClient client(key, secret, configuration); Model::RecognizeIdentityCardRequest request; OcrResultStruct result; string startDate, issue, endDate; string imageURL; int ret = 0; imageURL = url; request.setScheme("http"); request.setMethod(HttpRequest::Method::Post); request.setImageURL(imageURL); request.setSide("back"); auto outcome = client.recognizeIdentityCard(request); cout << endl << "ocr describeInstances returned:" << endl; cout << "error code: " << outcome.error().errorCode() << endl; cout << "requestId: " << outcome.result().requestId() << endl << endl; cout << "startDate: " << outcome.result().getData().backResult.startDate << endl; cout << "issue: " << outcome.result().getData().backResult.issue << endl; cout << "endDate: " << outcome.result().getData().backResult.endDate << endl; startDate = outcome.result().getData().backResult.startDate; issue = outcome.result().getData().backResult.issue; endDate = outcome.result().getData().backResult.endDate; result.identity.back.startDate = (char *)startDate.c_str(); result.identity.back.issue = (char *)issue.c_str(); result.identity.back.endDate = (char *)endDate.c_str(); if (cb) { ret = cb((void *)&result); } ShutdownSdk(); return ret; } int recognizeBankCard(char *url, AIModelCBFunc cb) { InitializeSdk(); string key = getAccessKey(); string secret = getAccessSecret(); ClientConfiguration configuration; configuration.setRegionId(CLOUD_AI_REGION_ID); configuration.setEndpoint(CLOUD_AI_OCR_ENDPOINT); OcrClient client(key, secret, configuration); Model::RecognizeBankCardRequest request; OcrResultStruct result; string bankName, cardNumber, validDate; string imageURL; int ret = 0; imageURL = url; request.setScheme("http"); request.setMethod(HttpRequest::Method::Post); request.setImageURL(imageURL); auto outcome = client.recognizeBankCard(request); cout << endl << "ocr describeInstances returned:" << endl; cout << "error code: " << outcome.error().errorCode() << endl; cout << "requestId: " << outcome.result().requestId() << endl << endl; cout << "bankName: " << outcome.result().getData().bankName << endl; cout << "cardNumber: " << outcome.result().getData().cardNumber << endl; cout << "validDate: " << outcome.result().getData().validDate << endl; bankName = outcome.result().getData().bankName; cardNumber = outcome.result().getData().cardNumber; validDate = outcome.result().getData().validDate; result.bank.bankName = (char *)bankName.c_str(); result.bank.cardNumber = (char *)cardNumber.c_str(); result.bank.validDate = (char *)validDate.c_str(); if (cb) { ret = cb((void *)&result); } ShutdownSdk(); return ret; } int recognizeCharacter(char *url, AIModelCBFunc cb) { InitializeSdk(); string key = getAccessKey(); string secret = getAccessSecret(); ClientConfiguration configuration; configuration.setRegionId(CLOUD_AI_REGION_ID); configuration.setEndpoint(CLOUD_AI_OCR_ENDPOINT); OcrClient client(key, secret, configuration); Model::RecognizeCharacterRequest request; OcrResultStruct result; string text; string imageURL; int ret = 0, i; imageURL = url; request.setScheme("http"); request.setMethod(HttpRequest::Method::Post); request.setImageURL(imageURL); request.setMinHeight(10); request.setOutputProbability(true); auto outcome = client.recognizeCharacter(request); cout << endl << "ocr recognizeCharacter describeInstances returned:" << endl; cout << "error code: " << outcome.error().errorCode() << endl; cout << "requestId: " << outcome.result().requestId() << endl << endl; cout << "results size: " << outcome.result().getData().results.size() << endl; for (i = 0; i < outcome.result().getData().results.size(); i++) { cout << i << "text: " << outcome.result().getData().results[i].text << endl; cout << i << "probability: " << outcome.result().getData().results[i].probability << endl; cout << i << "text left: " << outcome.result().getData().results[i].textRectangles.left << endl; cout << i << "text angle: " << outcome.result().getData().results[i].textRectangles.angle << endl; cout << i << "text top: " << outcome.result().getData().results[i].textRectangles.top << endl; cout << i << "text height: " << outcome.result().getData().results[i].textRectangles.height << endl; cout << i << "text: width:" << outcome.result().getData().results[i].textRectangles.width << endl; text = outcome.result().getData().results[i].text; result.character.text = (char *)text.c_str(); result.character.probability = outcome.result().getData().results[i].probability; result.character.left = outcome.result().getData().results[i].textRectangles.left; result.character.angle = outcome.result().getData().results[i].textRectangles.angle; result.character.top = outcome.result().getData().results[i].textRectangles.top; result.character.height = outcome.result().getData().results[i].textRectangles.height; result.character.width = outcome.result().getData().results[i].textRectangles.width; if (cb) { ret = cb((void *)&result); } } ShutdownSdk(); return ret; } int recognizeLicensePlate(char *url, AIModelCBFunc cb) { InitializeSdk(); string key = getAccessKey(); string secret = getAccessSecret(); ClientConfiguration configuration; configuration.setRegionId(CLOUD_AI_REGION_ID); configuration.setEndpoint(CLOUD_AI_OCR_ENDPOINT); OcrClient client(key, secret, configuration); Model::RecognizeLicensePlateRequest request; OcrResultStruct result; string text; string imageURL; int ret = 0, i; imageURL = url; request.setScheme("http"); request.setMethod(HttpRequest::Method::Post); request.setImageURL(imageURL); auto outcome = client.recognizeLicensePlate(request); // cout << endl << "ocr recognizeCharacter describeInstances returned:" << endl; // cout << "error code: " << outcome.error().errorCode() << endl; // cout << "requestId: " << outcome.result().requestId() << endl << endl; for (i = 0; i < outcome.result().getData().plates.size(); i++) { // cout << "plateNumber: " << outcome.result().getData().plates[i].plateNumber << endl; // cout << "confidence: " << outcome.result().getData().plates[i].confidence << endl; // cout << "plateType: " << outcome.result().getData().plates[i].plateType << endl; // cout << "plateTypeConfidence: " << outcome.result().getData().plates[i].plateTypeConfidence << endl; // cout << "roi.x: " << outcome.result().getData().plates[i].roi.x << endl; // cout << "roi.y: " << outcome.result().getData().plates[i].roi.y << endl; // cout << "roi.w: " << outcome.result().getData().plates[i].roi.w << endl; // cout << "roi.h: " << outcome.result().getData().plates[i].roi.h << endl; result.licensePlate.plateNumber = outcome.result().getData().plates[i].plateNumber.c_str(); result.licensePlate.confidence = outcome.result().getData().plates[i].confidence; result.licensePlate.plateType = outcome.result().getData().plates[i].plateType.c_str(); result.licensePlate.plateTypeConfidence = outcome.result().getData().plates[i].plateTypeConfidence; result.licensePlate.roi.x = outcome.result().getData().plates[i].roi.x; result.licensePlate.roi.y = outcome.result().getData().plates[i].roi.y; result.licensePlate.roi.w = outcome.result().getData().plates[i].roi.w; result.licensePlate.roi.h = outcome.result().getData().plates[i].roi.h; if (cb) { ret = cb((void *)&result); } } ShutdownSdk(); return ret; } }
YifuLiu/AliOS-Things
components/ucloud_ai/src/model/ocr.cc
C++
apache-2.0
12,537
/* * Copyright (C) 2021-2023 Alibaba Group Holding Limited */ #include <stdio.h> #include <string.h> #include "ucloud_ai_common.h" #define TAG "UCLOUD_AI_CHATBOT" char *ucloud_ai_chatbot(char *instance_id, char *session_id, char *text) { if (!instance_id || !text) { return NULL; } return chatbot(instance_id, session_id, text); }
YifuLiu/AliOS-Things
components/ucloud_ai/src/ucloud_ai_chatbot.c
C
apache-2.0
356
/* * Copyright (C) 2015-2018 Alibaba Group Holding Limited */ #include <stdio.h> #include <string.h> #include "ulog/ulog.h" #include "aos/kernel.h" #include "ucloud_ai_common.h" #define TAG "UCLOUD_AI_SERVICE" #include <httpclient.h> #define HEAD_SIZE 2048 #define BODY_SZIE (1024 * 128 + 1) httpclient_t ai_client = { 0 }; httpclient_data_t ai_client_data = {0}; static ucloud_ai_model_t ai_model = UCLOUD_AI_MODEL_MAX; static char g_oss_bucket[64]; static char g_oss_endpoint[64]; void ucloud_ai_set_oss_bucket(char *bucket) { int32_t len; if (bucket) { strcpy(g_oss_bucket, bucket); len = strlen(bucket); g_oss_bucket[len] = '\0'; printf("g_oss_bucket: %s\n", g_oss_bucket); } } void ucloud_ai_set_oss_endpoint(char *endpoint) { int32_t len; if (endpoint) { strcpy(g_oss_endpoint, endpoint); len = strlen(endpoint); g_oss_endpoint[len] = '\0'; } } uint8_t *ucloud_ai_upload_file(char *path) { char *p_upload_url = NULL; char *access_key = getAccessKey(); char *access_secret = getAccessSecret(); if (strstr(path, "https") || strstr(path, "http")) { p_upload_url = strdup(path); } else { /*update capture.jpg to oss*/ char *tmp_upload_url = NULL; tmp_upload_url = oss_upload_local_file(access_key, \ (char *)access_secret, g_oss_endpoint, g_oss_bucket, path); if (!tmp_upload_url) { LOGE(TAG, "url is null\n"); return NULL; } p_upload_url = strdup(tmp_upload_url); } return p_upload_url; } void ucloud_ai_set_key_secret(char *key, char *secret) { setAccesskeyAndSecret(key, secret); } int32_t ucloud_ai_init(void) { int32_t ret; char *customer_header = "Accept: */*\r\n"; ret = httpclient_prepare(&ai_client_data, HEAD_SIZE, BODY_SZIE); if (ret != HTTP_SUCCESS) return -1; ai_client.is_http = true; httpclient_set_custom_header(&ai_client, customer_header); return ret; } int32_t ucloud_ai_uninit(void) { return httpclient_unprepare(&ai_client_data); } int32_t ucloud_ai_connect(char *url) { int32_t ret; ret = httpclient_conn(&ai_client, (const char *)url); if (HTTP_SUCCESS != ret) { LOGE(TAG, "http connect failed"); return -1; } return ret; } void ucloud_ai_disconnect(void) { httpclient_clse(&ai_client); } int32_t ucloud_ai_get_stream(char *url, char **stream) { int ret; int recv_len = 0; httpclient_reset(&ai_client_data); ret = httpclient_send(&ai_client, (const char *)url, HTTP_GET, &ai_client_data); if (HTTP_SUCCESS != ret) { LOGE(TAG, "http send request failed"); return -1; } do { ret = httpclient_recv(&ai_client, &ai_client_data); if (ret < 0) break; *stream = ai_client_data.response_buf; recv_len = ai_client_data.response_content_len; } while (ret == HTTP_EAGAIN); return recv_len; } char *ucloud_ai_get_token_id(const char *domain, const char *region_id) { return getTokenId(domain, region_id); } char *ucloud_ai_compute_md5(const char *data, size_t size) { return (char *)computeContentMD5(data, size); } char *ucloud_ai_generate_uuid() { return (char *)generateUuid(); } char *ucloud_ai_url_encode(const char *src) { return (char *)urlEncode(src); } char *ucloud_ai_url_decode(const char *src) { return (char *)urlDecode(src); }
YifuLiu/AliOS-Things
components/ucloud_ai/src/ucloud_ai_common.c
C
apache-2.0
3,489
/* * Copyright (C) 2021-2023 Alibaba Group Holding Limited */ #include <stdio.h> #include <string.h> #include <ulog/ulog.h> #include "ucloud_ai_common.h" #define TAG "UCLOUD_AI_FACEBODY" void ucloud_ai_facebody_comparing_face(char *path, char *myface, ucloud_ai_cb_t cb) { int len; char *p_upload_url = NULL; char *p_myface_url = NULL; /*update capture.jpg to oss*/ if (path) { p_upload_url = ucloud_ai_upload_file(path); if (!p_upload_url) return; } if (myface) { p_myface_url = ucloud_ai_upload_file(myface); if (!p_myface_url) return; } /*do facebody detection*/ compareFace(p_upload_url, p_myface_url, cb); if (p_upload_url) free(p_upload_url); if (p_myface_url) free(p_myface_url); } void ucloud_ai_facebody_recognize_expression(char *path, ucloud_ai_cb_t cb) { int ret; int len; char *p_upload_url; /*update capture.jpg to oss*/ p_upload_url = ucloud_ai_upload_file(path); if (!p_upload_url) return; recognizeExpression(p_upload_url, cb); free(p_upload_url); } void ucloud_ai_facebody_generate_human_anime_style(char *path, ucloud_ai_cb_t cb) { int ret; int len; char *p_upload_url; /*update capture.jpg to oss*/ p_upload_url = ucloud_ai_upload_file(path); if (!p_upload_url) return; /*do generating human anime style, and get image url*/ generateHumanAnimeStyle(p_upload_url, cb); free(p_upload_url); } void ucloud_ai_facebody_detect_pedestrian(char *path, ucloud_ai_cb_t cb) { int ret; int len; char *p_upload_url; /*update capture.jpg to oss*/ p_upload_url = ucloud_ai_upload_file(path); if (!p_upload_url) return; /*do generating human anime style, and get image url*/ detectPedestrian(p_upload_url, cb); free(p_upload_url); }
YifuLiu/AliOS-Things
components/ucloud_ai/src/ucloud_ai_facebody.c
C
apache-2.0
1,901
/* * Copyright (C) 2021-2023 Alibaba Group Holding Limited */ #include <stdio.h> #include <string.h> #include "ucloud_ai_common.h" #define TAG "UCLOUD_AI_IMAGEENHAN" /*recognizing identity card has issue to be resolved*/ void ucloud_ai_imageenhan_erase_person(char *image_path, char *user_mask_path, ucloud_ai_cb_t cb) { int ret; int len; char *p_upload_url; /*update capture.jpg to oss*/ p_upload_url = ucloud_ai_upload_file(image_path); if (!p_upload_url) return; /*do erasing person*/ erasePerson(p_upload_url, user_mask_path, cb); free(p_upload_url); } void ucloud_ai_imageenhan_extend_image_style(char *major_path, char *style_path, ucloud_ai_cb_t cb) { int ret; int len; char *p_upload_url; /*update capture.jpg to oss*/ p_upload_url = ucloud_ai_upload_file(major_path); if (!p_upload_url) return; /*do extending image style*/ extendImageStyle(p_upload_url, style_path, cb); free(p_upload_url); }
YifuLiu/AliOS-Things
components/ucloud_ai/src/ucloud_ai_imageenhan.c
C
apache-2.0
1,001
/* * Copyright (C) 2021-2023 Alibaba Group Holding Limited */ #include <stdio.h> #include <string.h> #include "ucloud_ai_common.h" #define TAG "UCLOUD_AI_IMAGERECOG" void ucloud_ai_imagerecog_classifying_rubbish(char *path, ucloud_ai_cb_t cb) { int len; char *p_upload_url; /*update capture.jpg to oss*/ p_upload_url = ucloud_ai_upload_file(path); if (!p_upload_url) return; /*do imageseg detection*/ classifyingRubbish(p_upload_url, cb); free(p_upload_url); } void ucloud_ai_imagerecog_detect_fruits(char *path, ucloud_ai_cb_t cb) { int len; char *p_upload_url; /*update capture.jpg to oss*/ p_upload_url = ucloud_ai_upload_file(path); if (!p_upload_url) return; /*do imageseg detection*/ detectFruits(p_upload_url, cb); free(p_upload_url); }
YifuLiu/AliOS-Things
components/ucloud_ai/src/ucloud_ai_imagerecog.c
C
apache-2.0
834
/* * Copyright (C) 2021-2023 Alibaba Group Holding Limited */ #include <stdio.h> #include <string.h> #include "ucloud_ai_common.h" #define TAG "UCLOUD_AI_IMAGESEG" void ucloud_ai_imageseg_segment_face(char *path, ucloud_ai_cb_t cb) { int len; char *p_upload_url; /*update capture.jpg to oss*/ p_upload_url = ucloud_ai_upload_file(path); if (!p_upload_url) return; /*do face segment*/ segmentFace(p_upload_url, cb); free(p_upload_url); } void ucloud_ai_imageseg_segment_common_image(char *path, ucloud_ai_cb_t cb) { int ret; int len; char *p_upload_url; /*update capture.jpg to oss*/ p_upload_url = ucloud_ai_upload_file(path); if (!p_upload_url) return; /*do common image segement*/ segmentCommonImage(p_upload_url, cb); free(p_upload_url); }
YifuLiu/AliOS-Things
components/ucloud_ai/src/ucloud_ai_imageseg.c
C
apache-2.0
837
/* * Copyright (C) 2021-2023 Alibaba Group Holding Limited */ #include <stdio.h> #include <string.h> #include "ulog/ulog.h" #include "ucloud_ai_common.h" #define TAG "UCLOUD_AI_OBJECTDET" void ucloud_ai_objectdet_detect_object(char *path, ucloud_ai_cb_t cb) { int ret; int len; char *p_upload_url = NULL; /*update capture.jpg to oss*/ p_upload_url = ucloud_ai_upload_file(path); if (p_upload_url) { detectObject(p_upload_url, cb); free(p_upload_url); } } void ucloud_ai_objectdet_detect_main_body(char *path, ucloud_ai_cb_t cb) { int ret; int len; char *p_upload_url = NULL; /*update capture.jpg to oss*/ p_upload_url = ucloud_ai_upload_file(path); if (p_upload_url) { detectMainBody(p_upload_url, cb); free(p_upload_url); } }
YifuLiu/AliOS-Things
components/ucloud_ai/src/ucloud_ai_objectdet.c
C
apache-2.0
825
/* * Copyright (C) 2021-2023 Alibaba Group Holding Limited */ #include <stdio.h> #include <string.h> #include "ucloud_ai_common.h" #define TAG "UCLOUD_AI_OCR" /*recognizing identity card has issue to be resolved*/ void ucloud_ai_ocr_recognize_identity_card_face_side(char *path, ucloud_ai_cb_t cb) { int ret; int len; char *p_upload_url; /*update capture.jpg to oss*/ p_upload_url = ucloud_ai_upload_file(path); if (!p_upload_url) return; recognizeIdentityCardFaceSide(p_upload_url, cb); free(p_upload_url); } void ucloud_ai_ocr_recognize_identity_card_back_side(char *path, ucloud_ai_cb_t cb) { int ret; int len; char *p_upload_url; /*update capture.jpg to oss*/ p_upload_url = ucloud_ai_upload_file(path); if (!p_upload_url) return; recognizeIdentityCardBackSide(p_upload_url, cb); free(p_upload_url); } void ucloud_ai_ocr_recognize_bank_card(char *path, ucloud_ai_cb_t cb) { int ret; int len; char *p_upload_url; /*update capture.jpg to oss*/ p_upload_url = ucloud_ai_upload_file(path); if (!p_upload_url) return; recognizeBankCard(p_upload_url, cb); free(p_upload_url); } void ucloud_ai_ocr_recognize_character(char *path, ucloud_ai_cb_t cb) { int ret; int len; char *p_upload_url; /*update capture.jpg to oss*/ p_upload_url = ucloud_ai_upload_file(path); if (!p_upload_url) return; recognizeCharacter(p_upload_url, cb); free(p_upload_url); } void ucloud_ai_ocr_recognize_license_plate(char *path, ucloud_ai_cb_t cb) { int ret; int len; char *p_upload_url; /*update capture.jpg to oss*/ p_upload_url = ucloud_ai_upload_file(path); if (!p_upload_url) return; recognizeLicensePlate(p_upload_url, cb); free(p_upload_url); }
YifuLiu/AliOS-Things
components/ucloud_ai/src/ucloud_ai_ocr.c
C
apache-2.0
1,844
/* * Copyright (C) 2015-2020 manufacturername */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <aos/kernel.h> #if AOS_COMP_CLI #include "aos/cli.h" #endif #include <ulog/ulog.h> #include "udisplay.h" #include "udisplay_cli.h" static void set_brightness(char *pbuffer, int outlen, int argc, char **argv) { int32_t brightness; brightness = atoi(argv[1]); LOGD("udisplay", "set brightness to %d\n", brightness); udisplay_set_brightness(brightness); } static void get_brightness(char *pbuffer, int outlen, int argc, char **argv) { int32_t brightness; brightness = udisplay_get_brightness(); LOGD("udisplay", "brightness is %d\n", brightness); } static void enable_backlight(char *pbuffer, int outlen, int argc, char **argv) { int ret; ret = udisplay_enable_backlight(); if (ret < 0) LOGD("udisplay", "enable backlight fail\n"); else LOGD("udisplay", "enable backlight ok\n"); } static void disable_backlight(char *pbuffer, int outlen, int argc, char **argv) { int ret; ret = udisplay_disable_backlight(); if (ret < 0) LOGD("udisplay", "disable backlight fail\n"); else LOGD("udisplay", "disable backlight ok\n"); } static char *dump_rotate_str(uint32_t id) { const char *str = NULL; switch (id) { case FB_ROTATE_UR: str = "FB_ROTATE_UR"; break; case FB_ROTATE_UD: str = "FB_ROTATE_UD"; break; case FB_ROTATE_CW: str = "FB_ROTATE_CW"; break; case FB_ROTATE_CCW: str = "FB_ROTATE_CCW"; break; } return str; } static void udisplay_comp_example(int argc, char **argv) { int32_t ret; uint32_t value = 0; uint32_t rgb_fmt; bool performance = false; long long start, end; if (argc < 2) return; start = aos_now_ms(); if (strncmp(argv[1], "pattern", 7) == 0) { rgb_fmt = strtoul(argv[2], NULL, 0); value = strtoul(argv[3], NULL, 0); if (rgb_fmt == 32) udisplay_pattern_rgb32(value, true); else if (rgb_fmt == 16) udisplay_pattern_rgb16(value, false); } else if (strncmp(argv[1], "info", 7) == 0) { udisplay_context_t *ctx = udisplay_get_context(); LOGD("udisplay", \ "[fb info] xres: %d, yres: %d, bits_per_pixel: %d, rotate: %s", \ ctx->var.xres, ctx->var.yres, \ ctx->var.bits_per_pixel, \ dump_rotate_str(ctx->var.rotate)); } else if (strncmp(argv[1], "stress_ud", 9) == 0) { // normal int i = 0; rgb_fmt = strtoul(argv[2], NULL, 0); value = strtoul(argv[3], NULL, 0); LOGD("udisplay", "stress test count=%d\n", value); if (rgb_fmt == 32) { for (i = 0; i < value; i++) udisplay_pattern_rgb32((i * 16) % 0xff, false); } else if (rgb_fmt == 16) { for (i = 0; i < value; i++) { udisplay_pattern_rgb16(0x0000ffff, false); aos_msleep(10); udisplay_pattern_rgb16((i * 16) % 0xff, false); aos_msleep(10); udisplay_pattern_rgb16(0xffff0000, false); } } performance = true; LOGD("udisplay", "stress test finish count=%d\n", i); } else if (strncmp(argv[1], "stress_cw", 9) == 0) { // rotate int i = 0; rgb_fmt = strtoul(argv[2], NULL, 0); value = strtoul(argv[3], NULL, 0); LOGD("udisplay", "stress test count=%d\n", value); if (rgb_fmt == 32) { for (i = 0; i < value; i++) udisplay_pattern_rgb32((i * 16) % 0xff, true); } else if (rgb_fmt == 16) { for (i = 0; i < value; i++) udisplay_pattern_rgb16((i * 16) % 0xff, true); } performance = true; LOGD("udisplay", \ "stress test with rotate finish count=%d\n", i); } if (performance) { end = aos_now_ms(); LOGD("udisplay", \ "[%s]time gap: %lld ms for %d counts, fps: %2.0f\r\n", \ __func__, end - start, value, \ value * 1.f / (end - start) * 1000.f); } } static void udisplay_comp_init_example(int argc, char **argv) { // init udisplay udisplay_init(); } #if AOS_COMP_CLI /* reg args: fun, cmd, description*/ // display pattern 32/16 0x0000ffff 1/0(rotate); display stress_ud/stress_cw <count>; display info ALIOS_CLI_CMD_REGISTER(udisplay_comp_init_example, udisplay_init, udisplay component base example) ALIOS_CLI_CMD_REGISTER(udisplay_comp_example, udisplay, udisplay component base example) #endif
YifuLiu/AliOS-Things
components/udisplay/example/udisplay_example.c
C
apache-2.0
4,733
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifndef UDISPLAY_API_H #define UDISPLAY_API_H #include <aos/kernel.h> #include <stdbool.h> #include <fb_define.h> #include <string.h> /* Here is Macro and struct definition*/ typedef struct _udisplay_context_t { uint8_t *framebuffer; uint32_t framebuffer_size; fb_var_screeninfo_t var; int32_t fd; uint8_t fb_id; bool swap; aos_mutex_t mutex; } udisplay_context_t; #define FB_PATH "/dev/fb0" #define UDISPLAY_STEP_DEBUG printf("[%s][%d]excute to here\n", \ __func__, __LINE__); /** @defgroup udisplay_aos_api udisplay * @{ */ /** * Init the udisplay module. * * @retrun 0 on success, otherwise will be failed. */ int32_t udisplay_init(void); /** * udisplay show rect function. * * @param[in] buf Graphic Framebuffer * @param[in] x x coordinate * @param[in] y y coordinate * @param[in] w Graphic Wide * @param[in] h Graphic High * @param[in] rotate Rotate (set true or false, The rotation angle is determined by the drivers) * * @return 0 on success, negative error on failure. */ int32_t udisplay_show_rect(uint8_t *buf, uint32_t x, \ uint32_t y, uint32_t w, uint32_t h, bool rotate); /** * udispaly get framebuffer from drivers. * * @retrun buffer on success, otherwise will return NULL. */ uint8_t *udisplay_get_framebuffer(void); /** * udispaly show (the buffer get from udisplay_get_framebuffer function). * * @retrun 0 on success, otherwise will be failed. */ int32_t udisplay_show(void); /** * udispaly set bright * before it need enable backlight * the framebuffer need get from drivers * * @param[in] brightness brightness value * * @retrun 0 on success, otherwise will be failed. */ int32_t udisplay_set_brightness(int32_t brightness); /** * udispaly get bright value * before it need enable backlight * the framebuffer need get from drivers * * @retrun bright value on success, otherwise will be failed. */ int32_t udisplay_get_brightness(void); /** * udispaly enable backlight * the framebuffer need get from drivers * * @retrun bright value on success, otherwise will be failed. */ int32_t udisplay_enable_backlight(void); /** * udispaly disable backlight * the framebuffer need get from drivers * * @retrun bright value on success, otherwise will be failed. */ int32_t udisplay_disable_backlight(void); /** * @} */ #endif
YifuLiu/AliOS-Things
components/udisplay/include/udisplay.h
C
apache-2.0
2,544
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifndef UDISPLAY_CLI_API_H #define UDISPLAY_CLI_API_H /** @defgroup udisplay_cli_aos_api udisplay_cli * @ingroup udisplay_aos_api * @{ */ /** * udispaly test API * test pattern for rgb32 * * @param[in] color color value for show * @param[in] rotate Rotate (set true or false, The rotation angle is determined by the drivers) * * @retrun 0 on success, otherwise will be failed. */ int32_t udisplay_pattern_rgb32(uint32_t color, bool rotate); /** * udispaly test API * test pattern for rgb16 * * @param[in] color color value for show * @param[in] rotate Rotate (set true or false, The rotation angle is determined by the drivers) * * @retrun 0 on success, otherwise will be failed. */ int32_t udisplay_pattern_rgb16(uint32_t color, bool rotate); /** * @} */ #endif
YifuLiu/AliOS-Things
components/udisplay/include/udisplay_cli.h
C
apache-2.0
908
/* * Copyright (C) 2015-2020 manufacturername */ #include <stdio.h> #include <stdbool.h> #include <stdint.h> #include <aos/kernel.h> #include <ulog/ulog.h> #include <fcntl.h> // #include <sys/mman.h> #include "udisplay.h" #include "udisplay_cli.h" static udisplay_context_t g_udisplay_ctx; udisplay_context_t *udisplay_get_context(void) { return &g_udisplay_ctx; } static uint8_t *get_display_buffer_addr(int32_t num) { udisplay_context_t *ctx = udisplay_get_context(); if (num == 0) return (uint8_t *)ctx->framebuffer; else if (num == 1) return (uint8_t *)(ctx->framebuffer + ctx->framebuffer_size / 2); return NULL; } static void display_draw_rect(uint32_t x1, uint32_t y1, uint32_t h, uint32_t w, uint8_t *buf) { udisplay_context_t *ctx = udisplay_get_context(); int32_t line_length = 0; uint32_t location = 0; uint32_t byte_location = 0; uint8_t bit_location = 0; uint8_t *fbaddr = NULL; fbaddr = get_display_buffer_addr(ctx->fb_id); line_length = w * ctx->var.bits_per_pixel / 8; if ((x1 > ctx->var.xres) || (y1 > ctx->var.yres) || \ ((x1 + w) > ctx->var.xres) || ((y1 + h) > ctx->var.yres)) { LOGE("udisplay", "[%s]x1, y1, h, or w is not correct : \ %d, %d, %d, %d\n", __func__, x1, y1, h, w); return; } /*32 or 24 bit per pixel*/ if (ctx->var.bits_per_pixel == 32 || ctx->var.bits_per_pixel == 24) { uint32_t * fbp32 = (uint32_t *)fbaddr; uint32_t *pbuf = buf; int32_t y; for (y = y1; y <= h + y1; y++) { location = (x1 + ctx->var.xoffset) + \ (y + ctx->var.yoffset) * line_length / 4; memcpy(&fbp32[location], (uint32_t *)pbuf, w * 4); pbuf += w; } } /*16 bit per pixel*/ else if (ctx->var.bits_per_pixel == 16) { uint16_t * fbp16 = (uint16_t *)fbaddr; uint16_t *pbuf = buf; int32_t y; for (y = y1; y <= h + y1; y++) { location = (x1 + ctx->var.xoffset) + \ (y + ctx->var.yoffset) * line_length / 2; memcpy(&fbp16[location], (uint16_t *)pbuf, w * 2); pbuf += w; } } /*8 bit per pixel*/ else if (ctx->var.bits_per_pixel == 8) { uint8_t * fbp8 = (uint8_t *)fbaddr; uint8_t *pbuf = buf; int32_t y; for (y = y1; y <= h + y1; y++) { location = (x1 + ctx->var.xoffset) + \ (y + ctx->var.yoffset) * line_length; memcpy(&fbp8[location], (uint32_t *)pbuf, w); pbuf += w; } } /*1 bit per pixel*/ else if (ctx->var.bits_per_pixel == 1) { uint8_t * fbp8 = (uint8_t *)fbaddr; uint8_t *pbuf = buf; int32_t x; int32_t y; for (y = y1; y <= y1 + h; y++) { for (x = x1; x <= x1 + w; x++) { location = (x + ctx->var.xoffset) + \ (y + ctx->var.yoffset) * ctx->var.xres; /* find the byte we need to change */ byte_location = location / 8; /* inside the byte found, find the bit we need to change */ bit_location = location % 8; fbp8[byte_location] &= ~(((uint8_t)(1)) << bit_location); fbp8[byte_location] |= ((uint8_t)(*pbuf)) << bit_location; pbuf++; } pbuf += w; } } else { /*Not supported bit per pixel*/ } } static void udisplay_draw_rgb32(uint8_t *in, uint32_t x0, uint32_t y0, uint32_t width, uint32_t height, int32_t color) { int32_t x, y; udisplay_context_t *ctx = udisplay_get_context(); const int32_t bytesPerPixel = ctx->var.bits_per_pixel / 8; const int32_t line_length = width * ctx->var.bits_per_pixel / 8; const int32_t stride = line_length / bytesPerPixel; uint32_t *dest = (uint32_t *)in; for (y = y0; y < height; ++y) { for (x = x0; x < width; ++x) dest[x] = color; dest += stride; } } static void udisplay_draw_rgb16(uint8_t *in, uint32_t x0, uint32_t y0, uint32_t width, uint32_t height, int32_t color) { int32_t x, y; udisplay_context_t *ctx = udisplay_get_context(); const int32_t bytesPerPixel = ctx->var.bits_per_pixel / 8; const int32_t line_length = width * ctx->var.bits_per_pixel / 8; const int32_t stride = line_length / bytesPerPixel; // const int32_t red = (color & 0xff0000) >> (16 + 3); // const int32_t green = (color & 0xff00) >> (8 + 2); // const int32_t blue = (color & 0xff) >> 3; // const short color16 = blue | (green << 5) | (red << (5 + 6)); short *dest = (short *) (in); for (y = y0; y < height; ++y) { for (x = x0; x < width; ++x) dest[x] = color; dest += stride; } } static int32_t udisplay_set_prefb_addr(uint8_t *buf) { int32_t ret; udisplay_context_t *ctx = udisplay_get_context(); ret = ioctl(ctx->fd, FBIOPUT_PREFB_ADDR, (unsigned long)buf); if (ret < 0) { LOGE("udisplay", "[%s]ioctl fail, ret = %d\n", __func__, ret); return -1; } return ret; } int32_t udisplay_init(void) { int32_t fd; int32_t ret; int32_t fb_size; uint8_t *fbaddr = NULL; fb_var_screeninfo_t fb_var; udisplay_context_t *ctx = udisplay_get_context(); memset(ctx, 0 , sizeof(udisplay_context_t)); if (aos_mutex_new(&ctx->mutex) != 0) { LOGE("udisplay", "[%s]create mutex error\n", __func__); return -1; } /*open framebuffer device*/ fd = open(FB_PATH, O_RDWR); if (fd < 0) { LOGE("udisplay", "[%s]open %s fail, fd : %d\n", __func__, FB_PATH, fd); return -1; } /*get framebuffer size*/ ret = ioctl(fd, FBIOGET_VSCREENINFO, (unsigned long)&fb_var); if (ret < 0) { close(fd); LOGE("udisplay", "[%s]VSCREENINFO fail, ret : %d\n", __func__, ret); return -1; } fb_size = fb_var.xres_virtual * fb_var.yres_virtual * fb_var.bits_per_pixel / 8; // need set fd first becaseof udisplay_set_prefb_addr function used ctx->fd = fd; #ifdef ENABLE_MICRO_KERNEL fbaddr = (uint8_t *)mmap(NULL, fb_size, 0, 0, fd, 0); if (!fbaddr) { close(fd); return -1; } LOGE("udisplay", "[%s]mmap addr : %p\r\n", __func__, fbaddr); ctx->framebuffer = fbaddr; ctx->framebuffer_size = fb_size; #endif ctx->swap = ((fb_var.xres_virtual * fb_var.yres_virtual) / (fb_var.xres * fb_var.yres) == 2) ? true : false; ctx->fb_id = 0; memcpy(&ctx->var, &fb_var, sizeof(fb_var_screeninfo_t)); return 0; } static int32_t wait_vsync(void) { int32_t ret; udisplay_context_t *ctx = udisplay_get_context(); ret = ioctl(ctx->fd, FBIO_WAITFORVSYNC, (unsigned long)&ctx->var); if (ret < 0) LOGE("udisplay", "[%s]ioctl fail, ret : %d\n", __func__, ret); return ret; } static int32_t udisplay_pan_display(uint8_t fb_id) { int32_t ret; udisplay_context_t *ctx = udisplay_get_context(); fb_var_screeninfo_t *var = &ctx->var; #ifdef CONFIG_UDISPLAY_TIME_MEASURE long long start, end; start = aos_now_ms(); #endif var->yoffset = (fb_id > 0) ? fb_id * var->yres : 0; ret = ioctl(ctx->fd, FBIOPAN_DISPLAY, (unsigned long)var); if (ret < 0) LOGE("udisplay", "[%s]aos_ioctl fail, ret : %d\n", __func__, ret); #ifdef CONFIG_UDISPLAY_TIME_MEASURE end = aos_now_ms(); LOGD("udisplay", "[%s]ioctl time gap: %lld ms\r\n", __func__, end - start); #endif #ifdef CONFIG_UDISPLAY_TIME_MEASURE start = aos_now_ms(); #endif /*check if enable swap buffer*/ if (ctx->swap) { wait_vsync(); ctx->fb_id = !fb_id; } #ifdef CONFIG_UDISPLAY_TIME_MEASURE end = aos_now_ms(); LOGD("udisplay", "[%s]wait vsync time gap: %lld ms\r\n", \ __func__, end - start); #endif return ret; } int32_t udisplay_show_rect(uint8_t *buf, uint32_t x, uint32_t y, uint32_t w, \ uint32_t h, bool rotate) { int32_t ret; udisplay_context_t *ctx = udisplay_get_context(); #ifdef CONFIG_UDISPLAY_TIME_MEASURE long long start, end; start = aos_now_ms(); #endif if (!buf) return -1; if (aos_mutex_lock(&ctx->mutex, AOS_WAIT_FOREVER) != 0) return -1; if (rotate) { ret = udisplay_set_prefb_addr(buf); if (ret < 0) { LOGE("udisplay", "[%s]set prefb addr fail\n", __func__); aos_mutex_unlock(&ctx->mutex); return -1; } } else { #ifdef ENABLE_MICRO_KERNEL if ((x == 0) && (y == 0)) { memcpy(get_display_buffer_addr(ctx->fb_id), buf, \ ctx->var.xres * \ ctx->var.yres * \ ctx->var.bits_per_pixel / 8); } else { display_draw_rect(x, y, w, h, buf); } #else ret = udisplay_set_prefb_addr(buf); if (ret < 0) { LOGE("udisplay", "[%s]set prefb addr fail\n", __func__); aos_mutex_unlock(&ctx->mutex); return -1; } #endif } ret = udisplay_pan_display(ctx->fb_id); #ifdef CONFIG_UDISPLAY_TIME_MEASURE end = aos_now_ms(); LOGD("udisplay", "[%s]time gap: %lld ms\r\n", __func__, end - start); #endif aos_mutex_unlock(&ctx->mutex); return ret; } int32_t udisplay_show(void) { int32_t ret; udisplay_context_t *ctx = udisplay_get_context(); if (aos_mutex_lock(&ctx->mutex, AOS_WAIT_FOREVER) != 0) return -1; ret = udisplay_pan_display(ctx->fb_id); aos_mutex_unlock(&ctx->mutex); return ret; } uint8_t *udisplay_get_framebuffer(void) { uint8_t *fb = NULL; udisplay_context_t *ctx = udisplay_get_context(); if (aos_mutex_lock(&ctx->mutex, AOS_WAIT_FOREVER) != 0) return NULL; fb = get_display_buffer_addr(ctx->fb_id); aos_mutex_unlock(&ctx->mutex); return fb; } int32_t udisplay_pattern_rgb32(uint32_t color, bool rotate) { int32_t ret; uint8_t *buf = NULL; udisplay_context_t *ctx = udisplay_get_context(); fb_var_screeninfo_t *var = &ctx->var; if (aos_mutex_lock(&ctx->mutex, AOS_WAIT_FOREVER) != 0) return -1; if (rotate) { #ifdef CONFIG_UDISPLAY_TIME_MEASURE long long start, end; start = aos_now_ms(); #endif buf = (uint8_t *)aos_malloc(var->xres * var->yres * \ var->bits_per_pixel / 8); if (!buf) { LOGE("udisplay", "[%s]no memory allocated\n", __func__); aos_mutex_unlock(&ctx->mutex); return -1; } udisplay_draw_rgb32(buf, 0, 0, var->yres, var->xres, color); ret = udisplay_set_prefb_addr(buf); if (ret < 0) { aos_free(buf); LOGE("udisplay", "[%s]set prefb addr fail\n", __func__); aos_mutex_unlock(&ctx->mutex); return -1; } aos_free(buf); #ifdef CONFIG_UDISPLAY_TIME_MEASURE end = aos_now_ms(); LOGD("udisplay", "[%s]from malloc and free time gap: %lld ms\r\n", \ __func__, end - start); #endif } else { buf = get_display_buffer_addr(ctx->fb_id); udisplay_draw_rgb32(buf, 0, 0, var->xres, var->yres, color); } ret = udisplay_pan_display(ctx->fb_id); aos_mutex_unlock(&ctx->mutex); return ret; } int32_t udisplay_pattern_rgb16(uint32_t color, bool rotate) { int32_t ret; uint8_t *buf = NULL; udisplay_context_t *ctx = udisplay_get_context(); fb_var_screeninfo_t *var = &ctx->var; if (aos_mutex_lock(&ctx->mutex, AOS_WAIT_FOREVER) != 0) { LOGE("udisplay", "[%s]aos_mutex_lock failed\n", __func__); return -1; } #ifdef ENABLE_MICRO_KERNEL buf = get_display_buffer_addr(g_udisplay_ctx.fb_id); #else buf = (uint8_t *)aos_malloc(var->xres * var->yres * var->bits_per_pixel / 8); if (!buf) { LOGE("udisplay", "[%s]no memory allocated\n", __func__); aos_mutex_unlock(&ctx->mutex); return -1; } #endif ret = udisplay_set_prefb_addr(buf); if (ret < 0) { #ifndef ENABLE_MICRO_KERNEL aos_free(buf); #endif LOGE("udisplay", "[%s]set prefb addr fail\n", __func__); aos_mutex_unlock(&ctx->mutex); return -1; } udisplay_draw_rgb16(buf, 0, 0, var->yres, var->xres, color); ret = udisplay_pan_display(ctx->fb_id); if (ret < 0) { #ifndef ENABLE_MICRO_KERNEL aos_free(buf); #endif LOGE("udisplay", "[%s]udisplay_pan_display fail\n", __func__); aos_mutex_unlock(&ctx->mutex); return -1; } #ifndef ENABLE_MICRO_KERNEL aos_free(buf); #endif aos_mutex_unlock(&ctx->mutex); LOGE("udisplay", "[%s]udisplay_pattern_rgb16 finish\n", __func__); return ret; } int32_t udisplay_set_brightness(int32_t brightness) { int32_t ret; udisplay_context_t *ctx = udisplay_get_context(); ret = ioctl(ctx->fd, FBIOPUT_BRIGHTNESS, (unsigned long)&brightness); if (ret < 0) LOGE("udisplay", "[%s]aos_ioctl fail, ret : %d\n", __func__, ret); return ret; } int32_t udisplay_get_brightness(void) { int32_t ret; int32_t brightness; udisplay_context_t *ctx = udisplay_get_context(); ret = ioctl(ctx->fd, FBIOGET_BRIGHTNESS, (unsigned long)&brightness); if (ret < 0) { LOGE("udisplay", "[%s]aos_ioctl fail, ret : %d\n", __func__, ret); return ret; } return brightness; } int32_t udisplay_enable_backlight(void) { int32_t ret; udisplay_context_t *ctx = udisplay_get_context(); ret = ioctl(ctx->fd, FBIOENABLE_BACKLIGHT, NULL); if (ret < 0) LOGE("udisplay", "[%s]aos_ioctl fail, ret : %d\n", __func__, ret); return ret; } int32_t udisplay_disable_backlight(void) { int32_t ret; udisplay_context_t *ctx = udisplay_get_context(); ret = ioctl(ctx->fd, FBIODISABLE_BACKLIGHT, NULL); if (ret < 0) LOGE("udisplay", "[%s]aos_ioctl fail, ret : %d\n", __func__, ret); return ret; }
YifuLiu/AliOS-Things
components/udisplay/src/udisplay.c
C
apache-2.0
14,417
#!/usr/bin/env python3 import os import sys import getpass import shutil comp_path = sys.path[0] print("comp_path:") print(comp_path) # original folder org_image_path = comp_path + "/example/image" org_font_path = comp_path + "/src/resources/font" # new folder data_path = comp_path + "/../../hardware/chip/haas1000/prebuild/data/data" image_path = data_path + "/ugraphics_image" font_path = data_path + "/font" # delete prebuild/data resources if os.path.exists(image_path): print ('Delete /data/ugraphics_image firstly') shutil.rmtree(image_path) if os.path.exists(font_path): print ('Delete /data/font firstly') shutil.rmtree(font_path) # copy resources shutil.copytree(org_image_path, image_path) shutil.copytree(org_font_path, font_path) # result print("run external script success")
YifuLiu/AliOS-Things
components/ugraphics/cp_resources.py
Python
apache-2.0
813
/* * Copyright (C) 2021-2023 Alibaba Group Holding Limited */ #include <stdint.h> #include <stdio.h> #include <ulog/ulog.h> #include "ugraphics.h" #if AOS_COMP_CLI #include "aos/cli.h" #endif #define TAG "ugraphics_example" #define LOG printf #define WIDTH SCREEN_W #define HEIGHT SCREEN_H static void ugraphics_comp_example(int argc, char **argv) { int ret; if (argc < 2) LOGE(TAG, "wrong parameter number\n"); if (!strncmp(argv[1], "init", 4)) { /*Initialize ugraphics window*/ ret = ugraphics_init(WIDTH, HEIGHT); if (ret < 0) { LOGE(TAG, "ugraphics init fail, ret: %d\n", ret); return; } LOG("ugraphics init ok!\n"); } else if (!strncmp(argv[1], "draw", 4)) { /*Set background color*/ ret = ugraphics_set_color(COLOR_BLACK); if (ret < 0) { LOGE(TAG, "ugraphics set color fail, ret: %d\n", ret); return; } /*Draw background rectangle*/ ret = ugraphics_fill_rect(0, 0, WIDTH, HEIGHT); if (ret < 0) { LOGE(TAG, "ugraphics fill rect fail, ret: %d\n", ret); return; } if (!strncmp(argv[2], "rect", 4)) { /*Set rect boarder color*/ ret = ugraphics_set_color(COLOR_RED); if (ret < 0) { LOGE(TAG, "ugraphics set color fail, ret: %d\n", ret); return; } /*Draw empty rectangle*/ ret = ugraphics_draw_rect(0, 0, WIDTH / 2, HEIGHT / 2); if (ret < 0) { LOGE(TAG, "ugraphics draw rect fail, ret: %d\n", ret); return; } LOG("ugraphics draw rectangle ok!\n"); } else if (!strncmp(argv[2], "line", 4)) { /*Set line color*/ ret = ugraphics_set_color(COLOR_RED); if (ret < 0) { LOGE(TAG, "ugraphics set color fail, ret: %d\n", ret); return; } /*Draw line*/ ret = ugraphics_draw_line(0, HEIGHT / 4, WIDTH, HEIGHT / 4); if (ret < 0) { LOGE(TAG, "ugraphics draw line fail, ret: %d\n", ret); return; } LOG("ugraphics draw line ok!\n"); } else if (!strncmp(argv[2], "jpg", 3)) { /*Draw image*/ ret = ugraphics_draw_image("/data/ugraphics_image/object.jpg", 0, 0); if (ret < 0) { LOGE(TAG, "ugraphics draw jpg image fail, ret: %d\n", ret); return; } LOG("ugraphics draw jpg ok!\n"); } else if (!strncmp(argv[2], "png", 3)) { /*Draw image*/ ret = ugraphics_draw_image("/data/ugraphics_image/anime.png", 0, 0); if (ret < 0) { LOGE(TAG, "ugraphics draw png image fail, ret: %d\n", ret); return; } LOG("ugraphics draw png ok!\n"); } else if (!strncmp(argv[2], "string", 6)) { /*Set string color*/ ret = ugraphics_set_color(COLOR_RED); if (ret < 0) { LOGE(TAG, "ugraphics set color fail, ret: %d\n", ret); return; } /*Load default ttf font*/ ret = ugraphics_load_font("/data/font/Alibaba-PuHuiTi-Heavy.ttf", 18); if (ret < 0) { LOGE(TAG, "ugraphics load font fail, ret: %d\n", ret); return; } /*Set font style*/ ugraphics_set_font_style(UGRAPHICS_FONT_STYLE); /*Draw string*/ ugraphics_draw_string("Welcome to AliOS Things!", WIDTH / 8, HEIGHT / 2); LOG("ugraphics draw string ok!\n"); } /*Show graphics on screen*/ ugraphics_flip(); } else if (!strncmp(argv[1], "fill", 4)) { /*Set background color*/ ret = ugraphics_set_color(COLOR_BLACK); if (ret < 0) { LOGE(TAG, "ugraphics set color fail, ret: %d\n", ret); return; } /*Draw background rectangle*/ ret = ugraphics_fill_rect(0, 0, WIDTH, HEIGHT); if (ret < 0) { LOGE(TAG, "ugraphics fill rect fail, ret: %d\n", ret); return; } if (!strncmp(argv[2], "rect", 4)) { /*Set background color*/ ret = ugraphics_set_color(COLOR_RED); if (ret < 0) { LOGE(TAG, "ugraphics set color fail, ret: %d\n", ret); return; } /*Fill full rectangle*/ ret = ugraphics_fill_rect(0, 0, WIDTH / 2, HEIGHT / 2); if (ret < 0) { LOGE(TAG, "ugraphics fill rect fail, ret: %d\n", ret); return; } LOG("ugraphics fill rectangle ok!\n"); } else { LOG("unkown command\n"); } /*Show graphics on screen*/ ugraphics_flip(); } else if (!strncmp(argv[1], "clear", 5)) { /*Clear buffer on screen*/ ret = ugraphics_clear(); if (ret < 0) { LOGE(TAG, "ugraphics clear fail, ret: %d\n", ret); return; } /*Set background color*/ ret = ugraphics_set_color(COLOR_BLACK); if (ret < 0) { LOGE(TAG, "ugraphics set color fail, ret: %d\n", ret); return; } /*Draw background rectangle*/ ret = ugraphics_fill_rect(0, 0, WIDTH, HEIGHT); if (ret < 0) { LOGE(TAG, "ugraphics fill rect fail, ret: %d\n", ret); return; } /*Show graphics on screen*/ ugraphics_flip(); LOG("ugraphics clear screen ok!\n"); } else if (!strncmp(argv[1], "quit", 4)) { /*Quit ugraphics component*/ ugraphics_quit(); LOG("ugraphics quit ok!\n"); } return; } #if AOS_COMP_CLI /* reg args: fun, cmd, description*/ ALIOS_CLI_CMD_REGISTER(ugraphics_comp_example, ugraphics, ugraphics component base example) #endif
YifuLiu/AliOS-Things
components/ugraphics/example/ugraphics_example.c
C
apache-2.0
6,064
/* * Copyright (C) 2015-2018 Alibaba Group Holding Limited */ #ifndef _TO_RGB565_H_ #define _TO_RGB565_H_ #include <stdbool.h> #include <stdint.h> /** @defgroup ugraphics_aos_api * @{ */ /** * Rotate graphic 180 degree clockwise. * * @param[in] rgb888_buf rgb888 graphics buffer. * @param[in] rgb888_size rgb888 graphics size. * @param[out] rgb565_buf rgb565 grachics buffer after convert. * @param[out] rgb565_size rgb565 grachics size after convert. * * @return 0 on success, negative error on failure. */ int rgb888torgb565(unsigned char *rgb888_buf, int rgb888_size, \ unsigned short *rgb565_buf, int rgb565_size); /** * Rotate graphic 180 degree clockwise. * * @param[in] rgb888_buf rgb565 graphics buffer. * @param[in] rgb888_size rgb565 graphics size. * @param[out] rgb565_buf rgb888 grachics buffer after convert. * @param[out] rgb565_size rgb888 grachics size after convert. * * @return 0 on success, negative error on failure. */ int rgb565torgb888(unsigned short *rgb565_buf, int rgb565_size, \ unsigned char *rgb888_buf, int rgb888_size); /** * @} */ #endif // _TO_RGB565_H_
YifuLiu/AliOS-Things
components/ugraphics/include/format/to_rgb565.h
C
apache-2.0
1,259
/* * Copyright (C) 2021-2023 Alibaba Group Holding Limited */ #ifndef _ROTATE_H_ #define _ROTATE_H_ #include <stdbool.h> #include <stdint.h> /** @defgroup ugraphics_aos_api * @{ */ /** * Rotate graphic 90 degree clockwise. * * @param[in] src graphic source buffer. * @param[in] src_w width of graphics. * @param[in] src_h height of graphics. * @param[in] channel channel number of graphics color. * * @return 0 on success, negative error on failure. */ int rotate_right90(unsigned char *src, int src_w, int src_h, int channel); /** * Rotate graphic 90 degree anticlockwise. * * @param[in] src graphic source buffer. * @param[in] src_w width of graphics. * @param[in] src_h height of graphics. * @param[in] channel channel number of graphics color. * * @return 0 on success, negative error on failure. */ int rotate_left90(unsigned char *src, int src_w, int src_h, int channel); /** * Rotate graphic 180 degree clockwise. * * @param[in] src graphic source buffer. * @param[in] src_w width of graphics. * @param[in] src_h height of graphics. * @param[in] channel channel number of graphics color. * * @return 0 on success, negative error on failure. */ int rotate_down(unsigned char *src, int src_w, int src_h, int channel); /** * @} */ #endif // _ROTATE_H_
YifuLiu/AliOS-Things
components/ugraphics/include/rotate/rotate.h
C
apache-2.0
1,432
#ifndef TETRIS_GRAPHICS #define TETRIS_GRAPHICS #include <stdint.h> #ifdef AOS_COMP_SDL2 #include <SDL.h> #include <SDL_ttf.h> #include <SDL_image.h> #endif #define RGB565 #ifdef RGB565 #define COLOR_BLACK 0x000000FF #define COLOR_RED 0xFF4D40FF #define COLOR_GREEN 0x008000FF #define COLOR_BLUE 0x0047ABFF #define COLOR_CYAN 0x00FFFFFF #define COLOR_YELLOW 0xFFFF00FF #define COLOR_PURPLE 0x9400D3FF #define COLOR_ORANGE 0xFFA000FF #define COLOR_WHITE 0xFFFFFFFF #define COLOR_SHADOW 0x808080FF #else #define COLOR_BLACK 0x000000FF #define COLOR_RED 0xFF0000FF #define COLOR_GREEN 0x00FF00FF #define COLOR_BLUE 0x0000FFFF #define COLOR_CYAN 0x00FFFFFF #define COLOR_YELLOW 0xFFFF00FF #define COLOR_PURPLE 0xA000FFFF #define COLOR_ORANGE 0xFFA000FF #define COLOR_WHITE 0xFFFFFFFF #define COLOR_SHADOW 0x606060FF #endif #define SCREEN_W 320 #define SCREEN_H 240 #ifdef AOS_COMP_SDL2 #define UGRAPHICS_FONT_STYLE TTF_STYLE_BOLD #else #define UGRAPHICS_FONT_STYLE 0 #endif /** @defgroup ugraphics_aos_api * @{ */ /** * Init the ugraphics module. * * @param[in] width width of screen. * @param[in] height height of screen. * * @return 0 on success, negative error on failure. */ int32_t ugraphics_init(int32_t width, int32_t height); /** * load ttf font file. * * @param[in] filename ttf font file name. * @param[in] size font size. * * @return 0 on success, negative error on failure. */ int32_t ugraphics_load_font(const char *filename, int32_t size); /** * load ttf font file. * * @param[in] style ttf font style. * Refer to SDL_ttf.h: TTF_STYLE_NORMAL/TTF_STYLE_BOLD... * */ void ugraphics_set_font_style(int32_t style); /** * Release graphics all resources. * */ void ugraphics_quit(void); /** * Flip graphics to lcd. * */ void ugraphics_flip(void); /** * Clear graphics on window. * */ int32_t ugraphics_clear(void); /** * Set graphics default color. * * @param[in] color grapchic color. * * @return 0 on success, negative error on failure. */ int32_t ugraphics_set_color(uint32_t color); /** * Draw empty rectangle to the window. * * @param[in] x grapchic x location on window. * @param[in] y grapchic y location on window. * @param[in] w grapchic width on window. * @param[in] h grapchic height on window. * * @return 0 on success, negative error on failure. */ int32_t ugraphics_draw_rect(int32_t x, int32_t y, int32_t w, int32_t h); /** * Fill full rectangle to the window. * * @param[in] x grapchic x location on window. * @param[in] y grapchic y location on window. * @param[in] w grapchic width on window. * @param[in] h grapchic height on window. * * @return 0 on success, negative error on failure. */ int32_t ugraphics_fill_rect(int32_t x, int32_t y, int32_t w, int32_t h); /** * Draw line on window. * * @param[in] x1 line x1 start position. * @param[in] y1 line y1 start position. * @param[in] x2 line x2 end position. * @param[in] y2 line y2 end position. * * @return 0 on success, negative error on failure. */ int32_t ugraphics_draw_line(int32_t x1, int32_t y1, int32_t x2, int32_t y2); /** * Draw string on window. * * @param[in] string string you want to draw. * @param[in] x draw string at x postion of window. * @param[in] y draw string at y position of window. * * @return 0 on success, negative error on failure. */ int32_t ugraphics_draw_string(char *string, int32_t x, int32_t y); /** * Count string width. * * @param[in] string string you want to draw. * * @return 0 on success, negative error on failure. */ int32_t ugraphics_string_width(char *string); /** * Save image graphic buffer to a image file. * @param[in] buffer image buffer. * @param[in] len image buffer length. * @param[in] path image file path in file system. * * @return 0 on success, negative error on failure. */ int32_t ugraphics_save_image(char *buffer, int32_t len, const char *path); /** * Release graphics all resources. * * @param[in] file image file location. * @param[in] x x position on window. * @param[in] y y position on window. * * @return 0 on success, negative error on failure. */ int32_t ugraphics_draw_image(const char *file, int32_t x, int32_t y); /** * @} */ #endif // TETRIS_GRAPHICS
YifuLiu/AliOS-Things
components/ugraphics/include/ugraphics.h
C
apache-2.0
4,345
/* * Copyright (C) 2015-2018 Alibaba Group Holding Limited */ #include <stdio.h> #include "to_rgb565.h" #include <stdbool.h> #define RGB565_RED 0xf800 #define RGB565_GREEN 0x07e0 #define RGB565_BLUE 0x001f /* Multiplication over 8 bit emulation */ #define mul8(a, b) (((a) * (b) + 128 + (((a) * (b) + 128) >> 8)) >> 8) /* Conversion from rgb24 to rgb565 */ #define rgb2rgb565(r, g, b) \ ((mul8(r, 31) << 11) | (mul8(g, 63) << 5) | (mul8(b, 31) << 0)) int rgb888torgb565(unsigned char *rgb888_buf, int rgb888_size, unsigned short *rgb565_buf, int rgb565_size) { int i = 0; unsigned char Red = 0; unsigned char Green = 0; unsigned char Blue = 0; int count = 0; if (rgb888_buf == NULL || rgb888_size <= 0 || rgb565_buf == NULL || \ rgb565_size <= 0 || (rgb565_size < (rgb888_size / 3) * 2)) { printf("Invail input parameter in %s\n", __func__); return -1 ; } for (i = 0; i < rgb888_size; i += 3) { Red = rgb888_buf[i] >> 3; Green = rgb888_buf[i + 1] >> 2; Blue = rgb888_buf[i + 2] >> 3; rgb565_buf[count++] = ((Red << 11) | (Green << 5) | (Blue)); } return count; } int rgb565torgb888(unsigned short *rgb565_buf, int rgb565_size, unsigned char *rgb888_buf, int rgb888_size) { int i = 0; unsigned char Red = 0; unsigned char Green = 0; unsigned char Blue = 0; int count = 0; if (rgb565_buf == NULL || rgb565_size <= 0 || rgb888_buf == NULL || rgb888_size <= 0) { printf("Invaild input parameter in %s\n", __func__); return -1; } for (i = 0; i < rgb565_size; i++) { // 获取RGB单色,并填充低位 Red = (rgb565_buf[i] & RGB565_RED) >> 8 ; Green = (rgb565_buf[i] & RGB565_GREEN) >> 3 ; Blue = (rgb565_buf[i] & RGB565_BLUE) << 3 ; // 连接 rgb888_buf[count++] = Red; rgb888_buf[count++] = Green; rgb888_buf[count++] = Blue; } return count; }
YifuLiu/AliOS-Things
components/ugraphics/src/format/to_rgb565.c
C
apache-2.0
2,008
/* * Copyright (C) 2015-2018 Alibaba Group Holding Limited */ #include <stddef.h> #include <stdint.h> #include <ulog/ulog.h> #include <stdio.h> #define USE_TURBOJPEG #define TAG "JPEG_DECODER" #ifndef USE_TURBOJPEG #include <jpeglib.h> #include <setjmp.h> static unsigned jpeg_err = 0; static void jpeg_error_exit(j_common_ptr cinfo) { LOGE(TAG, "jpeg decoder error!!\n"); jpeg_err = 1; } int tjpeg2rgb(unsigned char *jpeg_buffer, int jpeg_size, unsigned char **rgb_buffer, int *size) { int ret = 0; struct jpeg_decompress_struct jpeg_info; static struct jpeg_error_mgr jpeg_error_mgr; jpeg_create_decompress(&jpeg_info); jpeg_info.err = jpeg_std_error(&jpeg_error_mgr); jpeg_error_mgr.error_exit = jpeg_error_exit; jpeg_mem_src(&jpeg_info, jpeg_buffer, jpeg_size); if (jpeg_read_header(&jpeg_info, TRUE) == -1) { LOGE(TAG, "lv_img_decoder_open_jpeg: read header err !!\n"); return -1; } jpeg_info.out_color_space = JCS_RGB; if ((jpeg_start_decompress(&jpeg_info) == FALSE) || (jpeg_err == 1)) { LOGE(TAG, "lv_img_decoder_open_jpeg: decompress failed !!\n"); return -1; } uint32_t out_buffer_size = jpeg_info.image_width * jpeg_info.image_height * jpeg_info.num_components; LOGI(TAG, "jpeg_info.image_width: %d, jpeg_info.image_height: %d, jpeg_info.num_components: %d", jpeg_info.image_width, jpeg_info.image_height, jpeg_info.num_components); *rgb_buffer = calloc(out_buffer_size, 1); if (!*rgb_buffer) printf("rgb_buffer alloc fail\n"); *size = out_buffer_size; if (*rgb_buffer == NULL) { LOGE(TAG, "%s : no enough memory!!\n", __func__); ret = -1; goto err; } while (jpeg_info.output_scanline < jpeg_info.output_height) { JSAMPROW out_str = (JSAMPROW)(*rgb_buffer + jpeg_info.output_scanline * jpeg_info.image_width * jpeg_info.num_components); if ((jpeg_read_scanlines(&jpeg_info, &out_str, 1) != 1) || (jpeg_err == 1)) { LOGE(TAG, "[%s]: scan line failed!!\n", __func__); free((void *)*rgb_buffer); ret = -1; } } err: if (jpeg_err == 0) jpeg_finish_decompress(&jpeg_info); jpeg_destroy_decompress(&jpeg_info); return ret; } #else #include <turbojpeg.h> int tjpeg_header(unsigned char *jpeg_buffer, int jpeg_size, int *width, int *height, int *subsample, int *colorspace) { int ret = 0; tjhandle handle = NULL; handle = tjInitDecompress(); if (!handle) { LOGE(TAG, "tjInitDecompress fail, ret = %d", ret); return -1; } ret = tjDecompressHeader3(handle, jpeg_buffer, jpeg_size, width, height, subsample, colorspace); if (ret < 0) LOGE(TAG, "tjDecompressHeader3 fail, ret = %d", ret); tjDestroy(handle); return ret; } int tjpeg2rgb(unsigned char *jpeg_buffer, int jpeg_size, unsigned char **rgb_buffer, int *size) { int ret = 0; tjhandle handle = NULL; int width, height, subsample, colorspace; int flags = 0; int pixelfmt = TJPF_RGB; int pitch = 0; handle = tjInitDecompress(); if (!handle) { LOGE(TAG, "tjInitDecompress fail, ret = %d", ret); return -1; } ret = tjDecompressHeader3(handle, jpeg_buffer, jpeg_size, &width, &height, &subsample, &colorspace); if (ret < 0) { LOGE(TAG, "tjDecompressHeader3 fail, ret = %d", ret); goto finish; } LOG("width: %d, height: %d", width, height); flags |= 0; *rgb_buffer = (unsigned char *)tjAlloc(width * height * tjPixelSize[pixelfmt]); if ((*rgb_buffer) == NULL) { LOGE(TAG, "allocating uncompressed image buffer"); goto finish; } *size = width * height * tjPixelSize[pixelfmt]; pitch = tjPixelSize[pixelfmt] * width; ret = tjDecompress2(handle, jpeg_buffer, jpeg_size, *rgb_buffer, width, pitch, height, pixelfmt, flags); if (ret < 0) { LOGE(TAG, "tjDecompress2 fail, ret = %d", ret); tjFree(*rgb_buffer); } finish: tjDestroy(handle); return ret; } int trgb2jpeg(unsigned char *rgb_buffer, int width, int height, int quality, unsigned char **jpeg_buffer, unsigned long *jpeg_size) { int ret = 0; tjhandle handle = NULL; // unsigned long size=0; int flags = 0; int subsamp = TJSAMP_422; int pixelfmt = TJPF_RGB; handle = tjInitCompress(); if (!handle) { LOGE(TAG, "tjInitDecompress fail, ret = %d", ret); return -1; } // size=tjBufSize(width, height, subsamp); ret = tjCompress2(handle, rgb_buffer, width, 0, height, pixelfmt, jpeg_buffer, jpeg_size, subsamp, quality, flags); if (ret < 0) LOGE(TAG, "tjCompress2 fail, ret = %d", ret); tjDestroy(handle); return ret; } #endif
YifuLiu/AliOS-Things
components/ugraphics/src/jpegdec/jpegdec.c
C
apache-2.0
5,090
/* * Copyright (C) 2015-2018 Alibaba Group Holding Limited */ #include <stdio.h> #include "to_rgb565.h" #include <stdbool.h> // 顺时针90度 int rotate_right90(unsigned char *src, int srcW, int srcH, int channel) { unsigned char *tempSrc = NULL; int mSize = srcW * srcH * sizeof(char) * channel; int i = 0; int j = 0; int k = 0; int desW = 0; int desH = 0; desW = srcH; desH = srcW; tempSrc = (unsigned char *)malloc(sizeof(char) * srcW * srcH * channel); memcpy(tempSrc, src, mSize); for (i = 0; i < desH; i++) { for (j = 0; j < desW; j++) { for (k = 0; k < channel; k++) src[(i * desW + j) * channel + k] = tempSrc[((srcH - 1 - j) * srcW + i) * channel + k]; } } free(tempSrc); return 0; } // 逆时针90度 int rotate_left90(unsigned char *src, int srcW, int srcH, int channel) { unsigned char *tempSrc = NULL; int mSize = srcW * srcH * sizeof(char) * channel; int i = 0; int j = 0; int k = 0; int desW = 0; int desH = 0; desW = srcH; desH = srcW; tempSrc = (unsigned char *)malloc(sizeof(char) * srcW * srcH * channel); memcpy(tempSrc, src, mSize); for (i = 0; i < desH; i++) { for (j = 0; j < desW; j++) { for (k = 0; k < channel; k++) src[(i * desW + j) * channel + k] = tempSrc[(j * srcW + i) * channel + k]; } } free(tempSrc); return 0; } // 旋转180度 int rotate_down(unsigned char *src, int srcW, int srcH, int channel) { unsigned char *tempSrc = NULL; int mSize = srcW * srcH * sizeof(char) * channel; int i = 0; int j = 0; int k = 0; int desW = 0; int desH = 0; desW = srcW; desH = srcH; tempSrc = (unsigned char *)malloc(sizeof(char) * srcW * srcH * channel); memcpy(tempSrc, src, mSize); for (i = 0; i < desH; i++) { for (j = 0; j < desW; j++) { for (k = 0; k < channel; k++) src[(i * desW + j) * channel + k] = tempSrc[((srcH - 1 - i) * srcW + srcW - 1 - j) * channel + k]; } } free(tempSrc); return 0; }
YifuLiu/AliOS-Things
components/ugraphics/src/rotate/rotate.c
C
apache-2.0
2,255
#include "ugraphics.h" #include <ulog/ulog.h> #ifdef AOS_COMP_SDL2 #define MAX_TEXT 100 #define MAX_IMAGE 10 SDL_Window *window; SDL_Renderer *renderer; TTF_Font *font = NULL; struct { char *string; SDL_Texture *texture; } text[MAX_TEXT]; struct { char *file; SDL_Texture *texture; } image[MAX_IMAGE]; // Internal function prototypes static int32_t graphics_generate_text(char *string); static void graphics_wipe_text(void); static int32_t graphics_draw_texture(SDL_Texture *texture, int32_t x, int32_t y); #endif #define TAG "ugraphics" int32_t text_count = 0; int32_t image_count = 0; int32_t ugraphics_init(int32_t width, int32_t height) { #ifdef AOS_COMP_SDL2 if (SDL_Init(SDL_INIT_VIDEO) == -1) { LOGE(TAG, "SDL_Init: %s\n", SDL_GetError()); return -1; } if (IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG) == -1) { LOGE(TAG, "IMG_Init: %s\n", SDL_GetError()); return -1; } if (SDL_CreateWindowAndRenderer(width, height, 0, &window, &renderer) == -1) { LOGE(TAG, "SDL_CreateWindowAndRenderer: %s\n", SDL_GetError()); return -1; } SDL_SetWindowTitle(window, "ugraphics"); return 0; #endif } int32_t ugraphics_load_font(const char *filename, int32_t size) { #ifdef AOS_COMP_SDL2 if (font) { LOG("font has been opened\n"); return 0; } if (TTF_Init() == -1) { LOGE(TAG, "TTF_Init: %s\n", TTF_GetError()); return -1; } font = TTF_OpenFont(filename, size); if (!font) { LOGE(TAG, "TTF_OpenFont: %s\n", TTF_GetError()); return -1; } return 0; #endif } void ugraphics_set_font_style(int32_t style) { #ifdef AOS_COMP_SDL2 if (font) TTF_SetFontStyle(font, style); else LOGE(TAG, "TTF_SeetFontStyle fail\n"); #endif } // Delete all generated text forcing them to be regenerated next frame void graphics_wipe_text(void) { #ifdef AOS_COMP_SDL2 for (int32_t i = 0; i < text_count; i++) { if (text[i].string != NULL) free(text[i].string); SDL_DestroyTexture(text[i].texture); } text_count = 0; #endif } void ugraphics_quit(void) { #ifdef AOS_COMP_SDL2 if (font) { TTF_CloseFont(font); TTF_Quit(); } graphics_wipe_text(); graphics_wipe_image(); if (renderer) SDL_DestroyRenderer(renderer); if (window) SDL_DestroyWindow(window); SDL_Quit(); #endif } void ugraphics_flip(void) { #ifdef AOS_COMP_SDL2 SDL_RenderPresent(renderer); SDL_RenderClear(renderer); graphics_wipe_text(); graphics_wipe_image(); #endif } int32_t ugraphics_clear(void) { #ifdef AOS_COMP_SDL2 return SDL_RenderClear(renderer); #endif } int32_t ugraphics_set_color(uint32_t color) { #ifdef AOS_COMP_SDL2 return SDL_SetRenderDrawColor(renderer, color >> 24, color >> 16, color >> 8, color); #endif } static int32_t graphics_generate_text(char *string) { #ifdef AOS_COMP_SDL2 SDL_Color color; SDL_GetRenderDrawColor(renderer, &color.r, &color.g, &color.b, &color.a); SDL_Surface *surface = TTF_RenderUTF8_Blended(font, string, color); if (!surface) { LOGE(TAG, "TTF_RenderUTF8_Blended: %s\n", TTF_GetError()); return -1; } SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, surface); SDL_FreeSurface(surface); if (!texture) { LOGE(TAG, "SDL_CreateTextureFromSurface: %s\n", SDL_GetError()); return -1; } text[text_count].string = strdup(string); // text[text_count].string = string; text[text_count].texture = texture; text_count++; return 0; #endif } void graphics_wipe_image(void) { #ifdef AOS_COMP_SDL2 for (int32_t i = 0; i < image_count; i++) SDL_DestroyTexture(image[i].texture); image_count = 0; #endif } int32_t ugraphics_draw_rect(int32_t x, int32_t y, int32_t w, int32_t h) { #ifdef AOS_COMP_SDL2 SDL_Rect rect = { x, y, w, h }; return SDL_RenderDrawRect(renderer, &rect); #endif } int32_t ugraphics_fill_rect(int32_t x, int32_t y, int32_t w, int32_t h) { #ifdef AOS_COMP_SDL2 SDL_Rect rect = { x, y, w, h }; return SDL_RenderFillRect(renderer, &rect); #endif } int32_t ugraphics_draw_line(int32_t x1, int32_t y1, int32_t x2, int32_t y2) { #ifdef AOS_COMP_SDL2 return SDL_RenderDrawLine(renderer, x1, y1, x2, y2); #endif } #ifdef AOS_COMP_SDL2 static int32_t graphics_draw_texture(SDL_Texture *texture, int32_t x, int32_t y) { int32_t ret; SDL_Rect drect = { x, y, 0, 0 }; ret = SDL_QueryTexture(texture, NULL, NULL, &drect.w, &drect.h); if (ret < 0) return -1; printf("drect.w: %d, drect.h: %d\n", drect.w, drect.h); ret = SDL_RenderCopy(renderer, texture, NULL, &drect); if (ret < 0) return -1; return 0; } #endif int32_t ugraphics_draw_string(char *string, int32_t x, int32_t y) { int32_t ret; #ifdef AOS_COMP_SDL2 if (strcmp(string, "") == 0) return -1; for (int32_t i = 0; i < text_count; i++) { if (strcmp(string, text[i].string) != 0) continue; ret = graphics_draw_texture(text[i].texture, x, y); if (ret < 0) return -1; } /*If a texture for the string doesn't exist create it*/ ret = graphics_generate_text(string); if (ret < 0) return -1; ret = graphics_draw_texture(text[text_count - 1].texture, x, y); if (ret < 0) return -1; #endif return 0; } int32_t ugraphics_string_width(char *string) { #ifdef AOS_COMP_SDL2 if (strcmp(string, "") == 0) return 0; for (int32_t i = 0; i < text_count; i++) { if (strcmp(string, text[i].string) != 0) continue; int32_t width; SDL_QueryTexture(text[i].texture, NULL, NULL, &width, NULL); return width; } #endif return 0; } static int32_t graphics_generate_image(char *file) { #ifdef AOS_COMP_SDL2 SDL_Texture *image_texture = IMG_LoadTexture(renderer, file); if (!image_texture) { LOGE(TAG, "Couldn't load %s\n", file); return -1; } image[image_count].file = file; image[image_count].texture = image_texture; image_count++; #endif return 0; } int32_t ugraphics_draw_image(const char *file, int32_t x, int32_t y) { int32_t ret; #ifdef AOS_COMP_SDL2 SDL_Rect drect = { x, y, 0, 0 }; if (strcmp(file, "") == 0) { LOG("[%s]file is null\n"); return -1; } for (int32_t i = 0; i < image_count; i++) { if (strcmp(file, image[i].file) != 0) continue; graphics_draw_texture(image[i].texture, x, y); return 0; } ret = graphics_generate_image(file); if (ret < 0) return -1; ret = graphics_draw_texture(image[image_count - 1].texture, x, y); if (ret < 0) return -1; #endif return 0; } int32_t ugraphics_save_image(char *buffer, int32_t len, const char *path) { if (!buffer) { LOGE(TAG, "buffer is null\n"); return -1; } #ifdef AOS_COMP_SDL2 FILE *file; file = fopen(path, "wb"); if (file == NULL) { LOGE(TAG, "open file %s fail,\n", path); return -1; } if (fwrite(buffer, len, 1, file) < 1) { LOGE(TAG, "write file buf fail\n"); return -1; } fclose(file); #endif return 0; }
YifuLiu/AliOS-Things
components/ugraphics/src/ugraphics.c
C
apache-2.0
7,348
/* * Copyright (C) 2015-2021 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "aos/kernel.h" #include "ulog/ulog.h" #if AOS_COMP_CLI #include "aos/cli.h" #endif #ifdef ULOG_MOD #undef ULOG_MOD #endif /* ULOG_MOD */ #define ULOG_MOD "ULOG_DEMO" #define TEST_STR "this is ulog tester" static char show_log_list_buffer[512]; void ulog_example(int argc, char **argv) { int i = 0; aos_set_log_level(AOS_LL_DEBUG); while (1) { LOGI(ULOG_MOD, "%d-%s", i, TEST_STR); i++; if (10 == i) { #if ULOG_CONFIG_POP_FS if (0 == aos_get_ulog_list(show_log_list_buffer, sizeof(show_log_list_buffer))) { LOG("Log List %s", show_log_list_buffer); } #endif return; } aos_msleep(500); } } #if AOS_COMP_CLI /* reg args: fun, cmd, description*/ ALIOS_CLI_CMD_REGISTER(ulog_example, ulog_example, ulog component base example) #endif
YifuLiu/AliOS-Things
components/ulog/example/ulog_example.c
C
apache-2.0
971
#include "dm_export.h" #include "ulog/ulog.h" SYMBOL_EXPORT(aos_set_log_level);
YifuLiu/AliOS-Things
components/ulog/export.c
C
apache-2.0
81
/** * @file ulog/ulog.h * @copyright Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #ifndef ULOG_H #define ULOG_H #include <string.h> #include "ulog_config.h" /** @addtogroup aos_ulog ulog * Optional policy of log, which can output into default direction, virtual file * system, mqtt channel and syslog udp. * * @{ */ /** * Important!!! Switch on NDEBUG will make no log produced(except use API LOG), * it doesn't work even you try to increase log level. */ #ifdef NDEBUG #define CONFIG_LOGMACRO_SILENT #endif #if defined(CONFIG_DEBUG) && CONFIG_DEBUG #define DEBUG #endif #define ULOG_TAG __FILE__, __LINE__ #define LOG_EMERG 0 /* system is unusable */ #define LOG_ALERT 1 /* action must be taken immediately */ #define LOG_CRIT 2 /* critical conditions */ #define LOG_ERR 3 /* error conditions */ #define LOG_WARNING 4 /* warning conditions */ #define LOG_NOTICE 5 /* normal, but significant, condition */ #define LOG_INFO 6 /* informational message */ #define LOG_DEBUG 7 /* debug-level message */ #define LOG_NONE 8 /* used in stop filter, all log will pop out */ typedef enum { AOS_LL_NONE = LOG_EMERG, /* disable log */ AOS_LL_FATAL = LOG_CRIT, /* fatal log will output */ AOS_LL_ERROR = LOG_ERR, /* fatal + error log will output */ AOS_LL_WARN = LOG_WARNING, /* fatal + warn + error log will output(default level) */ AOS_LL_INFO = LOG_INFO, /* info + warn + error log will output */ AOS_LL_DEBUG = LOG_DEBUG, /* debug + info + warn + error + fatal log will output */ } aos_log_level_t; #ifdef __cplusplus extern "C" { #endif /** * Function prototype for syncronized log text, Recommed using below brief API LOGX instead of this. * * @param[in] s Serverity of Log * @param[in] mod Module name * @param[in] f Usually File name * @param[in] l Usually Line number of comment * @param[in] fmt, ... Variable Parameter, support format print to log * * @return 0 on success, negative error on failure. */ int ulog(const unsigned char s, const char *mod, const char *f, const unsigned long l, const char *fmt, ...); /** * Log at the alert level, brief using of ulog. * * @param[in] ... same as printf() usage. * * @return 0 on success, negative error on failure. */ #define LOG(...) ulog(LOG_ALERT, "AOS", ULOG_TAG, __VA_ARGS__) #ifdef CONFIG_LOGMACRO_SILENT #define LOGF(mod, ...) #define LOGE(mod, ...) #define LOGW(mod, ...) #define LOGI(mod, ...) #define LOGD(mod, ...) #else /* !CONFIG_LOGMACRO_SILENT */ /** * Log at fatal level, brief using of ulog. * * @param[in] mod string description of module. * @param[in] ... same as printf() usage. * * @return 0 on success, negative error on failure. */ #define LOGF(mod, ...) ulog(LOG_CRIT, mod, ULOG_TAG, __VA_ARGS__) /** * Log at error level, brief using of ulog. * * @param[in] mod string description of module. * @param[in] ... same as printf() usage. * * @return 0 on success, negative error on failure. */ #define LOGE(mod, ...) ulog(LOG_ERR, mod, ULOG_TAG, __VA_ARGS__) /** * Log at warning level, brief using of ulog. * * @param[in] mod string description of module. * @param[in] ... same as printf() usage. * * @return 0 on success, negative error on failure. */ #define LOGW(mod, ...) ulog(LOG_WARNING, mod, ULOG_TAG, __VA_ARGS__) /** * Log at info level, brief using of ulog. * * @param[in] mod string description of module. * @param[in] ... same as printf() usage. * * @return 0 on success, negative error on failure. */ #define LOGI(mod, ...) ulog(LOG_INFO, mod, ULOG_TAG, __VA_ARGS__) /** * Log at debug level, brief using of ulog. * * @note: This Log API take effect only the switcher 'DEBUG' is switch on. * @param[in] mod string description of module. * @param[in] ... same as printf() usage. * * @return 0 on success, negative error on failure. */ #ifdef DEBUG #define LOGD(mod, ...) ulog(LOG_DEBUG, mod, ULOG_TAG, __VA_ARGS__) #else #define LOGD(mod, ...) #endif #endif /* CONFIG_LOGMACRO_SILENT */ /** * Set the log level. * * @param[in] log_level level to be set,must be one of AOS_LL_NONE,AOS_LL_FATAL, * AOS_LL_ERROR,AOS_LL_WARN,AOS_LL_INFO or AOS_LL_DEBUG. * * @return 0 on success, negative error on failure. */ int aos_set_log_level(aos_log_level_t log_level); /** * Set the log terminal output func. * * @param[in] void (*output_func)(const char* fmt, ...) * function to output log for terminal in different platform * * @return 0 on success, negative error on failure. */ int aos_set_log_output(void (*output_func)(const char* fmt, ...)); #if ULOG_POP_CLOUD_ENABLE int aos_set_popcloud_log_level(aos_log_level_t log_level); #endif #if ULOG_POP_FS_ENABLE int ulog_fs_log_file_size(unsigned int filesize); int ulog_fs_log_file_path(char *filepath); int aos_set_popfs_log_level(aos_log_level_t log_level); #endif #if ULOG_POP_UDP_ENABLE int aos_set_popudp_log_level(aos_log_level_t log_level); #endif /** * Function prototype for log init. This is called in system level automatically, * it is not necessary calling it in application. * */ void ulog_init(void); /** * Function prototype for ulog management. * * @param[in] cmd_str command string, user fill the command string to manage ulog, format * shall as below: * "tcpip service=1" or "tcpip service=0" to notice the tcpip feature is install or not, * which have impact on the ulog pop out via udp session; * "listen ip=16777343" to nofice the syslog listener's address is 127.0.0.1; * "fspause=1" or "fspause=0" to command pause/resume into file system or not; * "ulog file up=1" to notify upload log file 1 via http. * * @return 0 on Success, -EINVAL: invalid parameter, -EPERM: ulog module not initied yet, * -EACCES: this function not work as there is no ASYNC method using. Other fail * reason may come from kernel message queue. */ int ulog_man(const char *cmd_str); /** * Function prototype for get ulog list recorded in file system. * Precondition of use this function is switch on ULOG_POP_FS_ENABLE * The result is usually like below: * {"time":" 4.500",list:[{"idx":1,"start":" 0.000","end":""}]} * context of time is system time when called, list show the start time and end time of special index. * If value of end time is empty, means this log file is logging. * * @param[in] buf buffer received the context of file list * @param[in] len length of buffer * * @return 0 sucessfully, -EINVAL param illegal, -ENOMEM not enough room to receive file * list, -EIO system error. */ int aos_get_ulog_list(char *buf, const unsigned short len); /** * Dump buffer by hex. * @param[in] tag tag * @param[in] buffer buffer * @param[in] len buffer len * @returns zero on success. On error, yoc_err is returned */ int aos_log_hexdump(const char* tag, char *buffer, int len); #ifdef __cplusplus } #endif /** @} */ #endif /* ULOG_H */
YifuLiu/AliOS-Things
components/ulog/include/ulog/ulog.h
C
apache-2.0
7,066
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #ifndef U_LOG_CONFIG_H_ #define U_LOG_CONFIG_H_ #include <stdbool.h> #include <stdint.h> #include <stdio.h> #define ULOG_TAG_SELF "ULOG" #define ULOG_POLICY_RQST '?' #define ULOG_LEVEL_RSP "{\"cloud log level\":%d}" /** * syslog management command mark * NOT RECOMMEND MODIFY THIS VALUE, READ ONLY!! */ #define ULOG_CMD_PREFIX "#@" #define ULOG_HEADER_TYPE_LEN 5 /** * syslog protocol, facility local use 0 * NOT RECOMMEND MODIFY THIS VALUE, READ ONLY!! */ #define SYSLOG_FACILITY 128 #define TAG_FILE_NAME_MAX_LEN 16 #define UNDEFINE_FILE_NAME "unknown" #define MOD_MAX_LEN 10 #define FACILITY_NORMAL_LOG 248 #define FACILITY_NORMAL_LOG_NO_POP_CLOUD 240 #define HTTP_REQ_RETRY 3 #define HTTP_RSP_RETRY 3 #define URL_PREFIX_HTTP "http://" #define URL_PREFIX_HTTPS "https://" #define RSP_BUF_SIZE 512 #define HTTP_UP_HDR_SIZE 64 /* 5 is result of cost <%03d> */ #define LOG_PREFIX_LEN 5 typedef enum { http_upload_file_operate_fail = -4, http_upload_text_empty = -3, http_upload_memory_fail = -2, http_upload_common_fail = -1, http_upload_start = 0, http_upload_finish = 1, } http_upload_fail_t; /** * sometimes found the pop log into file always fail, may result from file attribute, * or other unknown reason. If the fail operte on the same file keeps 3 times, then * destroy the log file and create new one. */ #define ULOG_FILE_FAIL_COUNT 3 /** * Specify the port of syslog watcher * NOT RECOMMEND MODIFY THIS VALUE, READ ONLY!! */ #define SYSLOG_WATCHER_DEFAULT_PORT 514 /* Specify if details mode used under sync log */ #ifndef ULOG_CONFIG_SYNC_LOG_DETAILS #define SYNC_LOG_DETAILS 0 #else #define SYNC_LOG_DETAILS ULOG_CONFIG_SYNC_LOG_DETAILS #endif #ifndef ULOG_CONFIG_SYNC_DETAIL_COLOR #define SYNC_DETAIL_COLOR 0 #else #define SYNC_DETAIL_COLOR ULOG_CONFIG_SYNC_DETAIL_COLOR #endif #ifndef ULOG_CONFIG_SYNC_ABS_PATH #define SYNC_ABS_PATH 0 #else #define SYNC_ABS_PATH ULOG_CONFIG_SYNC_ABS_PATH #endif #ifndef ULOG_CONFIG_DEFAULT_DIR_ASYNC #define LOG_DIR_ASYNC 0 #else #define LOG_DIR_ASYNC ULOG_CONFIG_DEFAULT_DIR_ASYNC #endif #ifndef ULOG_CONFIG_SYSLOG_TIME_FORMAT #define SYSLOG_TIME_FORMAT 0 #else #define SYSLOG_TIME_FORMAT ULOG_CONFIG_SYSLOG_TIME_FORMAT #endif #ifndef ULOG_CONFIG_EXTREAM_LOG_TAG #define EXTREAM_LOG_TAG 1 #else #define EXTREAM_LOG_TAG ULOG_CONFIG_EXTREAM_LOG_TAG #endif /** * the max length of every trace log to be recorded, include syslog format(if EXTREAM_LOG_TEXT * is not set), so 100 is reseanable value when syslog format support, 50 is fit for extream log mode * Log Content will be trimmed if it's too long. * SYSLOG_SIZE*SYSLOG_SIZE is the log mechanism cost heap size */ #ifndef ULOG_CONFIG_LOG_SIZE #define ULOG_SIZE 256 #else #define ULOG_SIZE ULOG_CONFIG_LOG_SIZE #endif /** * Default size of buffer queue that used to record log under aync mode. * May the trace log miss if this value was set too small. * More RAM will be costed if it set too large * So consider balance of this value and system resouce */ #ifndef ULOG_CONFIG_ASYNC_BUF_SIZE #define DEFAULT_ASYNC_BUF_SIZE 6144 #else #define DEFAULT_ASYNC_BUF_SIZE ULOG_CONFIG_ASYNC_BUF_SIZE #endif #ifndef ULOG_CONFIG_RESERVED_FS #define ULOG_RESERVED_FS 0 #else #define ULOG_RESERVED_FS ULOG_CONFIG_RESERVED_FS #endif #ifndef ULOG_CONFIG_RESERVED_FS_SIZE #define ULOG_RESERVED_FS_SIZE 64 #else #define ULOG_RESERVED_FS_SIZE ULOG_CONFIG_RESERVED_FS_SIZE #endif /** * Level Stop Filter of default direction(uart for rtos), any log level qual or lower than this (value higher than it) * will be abondoned LOG_EMERG will make none log pop out. */ #ifndef ULOG_CONFIG_STOP_FILTER_DEFAULT #define STOP_FILTER_DEFAULT LOG_WARNING #else #define STOP_FILTER_DEFAULT ULOG_CONFIG_STOP_FILTER_DEFAULT #endif /** * Level Stop Filter of udp, any log level qual or lower than this (value higher than it) * will be abondoned LOG_EMERG will make none log pop out. */ #ifndef ULOG_CONFIG_STOP_FILTER_UDP #define STOP_FILTER_UDP LOG_WARNING #else #define STOP_FILTER_UDP ULOG_CONFIG_STOP_FILTER_UDP #endif /** * switch on pop out log into file system */ #ifndef ULOG_CONFIG_POP_FS #define ULOG_POP_FS_ENABLE 0 #else #define ULOG_POP_FS_ENABLE ULOG_CONFIG_POP_FS #endif #ifndef ULOG_CONFIG_UPLOAD #define ULOG_UPLOAD_LOG_FILE 0 #else #define ULOG_UPLOAD_LOG_FILE ULOG_CONFIG_UPLOAD #endif /** * switch on pop out log via UDP */ #ifndef ULOG_CONFIG_POP_UDP #define ULOG_POP_UDP_ENABLE 0 #else #define ULOG_POP_UDP_ENABLE ULOG_CONFIG_POP_UDP #endif /** * Level Stop Filter of File system, any log level qual or lower than this (value higher than it) * will be abondoned LOG_EMERG will make none log pop out. */ #ifndef ULOG_CONFIG_STOP_FILTER_FS #define STOP_FILTER_FS LOG_WARNING #else #define STOP_FILTER_FS ULOG_CONFIG_STOP_FILTER_FS #endif /** * switch on pop out log into cloud real-time */ #ifndef AOS_COMP_UAGENT #define ULOG_POP_CLOUD_ENABLE 0 #else #define ULOG_POP_CLOUD_ENABLE 1 #endif /** * Level Stop Filter of File system, any log level qual or lower than this (value higher than it) * will be abondoned LOG_EMERG will make none log pop out. */ #ifndef ULOG_CONFIG_STOP_FILTER_CLOUD #define STOP_FILTER_CLOUD LOG_EMERG #else #define STOP_FILTER_CLOUD ULOG_CONFIG_STOP_FILTER_CLOUD #endif /** * STACK DEPTH of Log Task, will cost 3072 Byte room */ #ifndef ULOG_CONFIG_LOG_ROUTINE_TASK_STACK_DEPTH #define LOG_ROUTINE_TASK_STACK_DEPTH 3072 #else #define LOG_ROUTINE_TASK_STACK_DEPTH ULOG_CONFIG_LOG_ROUTINE_TASK_STACK_DEPTH #endif /** * Max log files support in fs, if the recording file more than this value, rolling back mechanism trigged. */ #ifndef ULOG_CONFIG_LOCAL_FILE_CNT #define LOCAL_FILE_CNT 5 #else #define LOCAL_FILE_CNT ULOG_CONFIG_LOCAL_FILE_CNT #endif /** * Max log file size locate in local file system, if the recording file larger than this value, * new files will be used to be recored. */ #ifndef ULOG_CONFIG_LOCAL_FILE_SIZE #define LOCAL_FILE_SIZE 4096 #else #define LOCAL_FILE_SIZE ULOG_CONFIG_LOCAL_FILE_SIZE #endif #if ULOG_POP_FS_ENABLE #ifdef CSP_LINUXHOST #error(modify below PATH as log file located, then disable this statement) #define ULOG_DEAULT_FS_PATH "/workspace/" #elif defined (AOS_COMP_SPIFFS) #define ULOG_DEAULT_FS_PATH "/spiffs/" #elif defined (AOS_COMP_FATFS) #ifdef CONFIG_AOS_FATFS_SUPPORT_MMC #define ULOG_DEAULT_FS_PATH "/sdcard/" #else #define ULOG_DEAULT_FS_PATH "/fatfs/" #endif /* CONFIG_AOS_FATFS_SUPPORT_MMC */ #else #define ULOG_DEAULT_FS_PATH "/data/ulog/" #endif #endif /* ULOG_POP_FS_ENABLE */ #if ULOG_POP_UDP_ENABLE #ifdef CONFIG_NO_TCPIP #error ("pop log via udp not support in no tcpip board") #endif #endif #if ULOG_POP_CLOUD_ENABLE #include "uagent_type.h" #define ULOG_SHOW (UAGENT_FUNC_USER_BASE) #define ULOG_LEVEL_CHANGE (UAGENT_FUNC_USER_BASE + 1) #define ULOG_LOG_LIST (UAGENT_FUNC_USER_BASE + 2) #define ULOG_POLICY (UAGENT_FUNC_USER_BASE + 3) #endif typedef enum { ulog_session_std = 0, /* default out direction, usually uart for rtos, termial for Linux */ #if ULOG_POP_CLOUD_ENABLE ulog_session_cloud, /* to cloud, via uagent */ #endif #if ULOG_POP_FS_ENABLE ulog_session_file, /* log on local file system */ #endif #if ULOG_POP_UDP_ENABLE ulog_session_udp, /* syslog via udp, port 514 is default for syslog watcher */ #endif ulog_session_size } ulog_session_type_t; #endif /*U_LOG_CONFIG_H_*/
YifuLiu/AliOS-Things
components/ulog/include/ulog_config.h
C
apache-2.0
7,726
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #ifndef U_LOG_API__H #define U_LOG_API__H #include <stdint.h> #include <stdbool.h> #include "ulog_config.h" #ifdef __cplusplus extern "C" { #endif extern bool aos_ulog_init; bool log_get_mutex(void); void log_release_mutex(void); void log_init_mutex(void); void on_sync_filter_level_change(const ulog_session_type_t session, const char level); void on_filter_change(const ulog_session_type_t session, const char level); uint8_t ulog_stop_filter_level(const ulog_session_type_t session); char* get_sync_stop_level(); int32_t ulog_fs_init(void); void on_filter_level_changes(const ulog_session_type_t session, const uint8_t level); bool check_pass_pop_out(const ulog_session_type_t session, const uint8_t level); void ulog_async_init(); int32_t pop_out_on_udp(const char* data, const uint16_t len); int32_t pop_out_on_fs(const char* data, const uint16_t len); void on_show_ulog_file(void); void update_net_cli(const char cmd, const char* param); void fs_control_cli(const char cmd, const char* param); void on_update_syslog_watcher_addr(const uint32_t ip_nl, const uint32_t port); void on_tcpip_service_on(const uint32_t on, const uint32_t off); void on_fs_record_pause(const uint32_t on, const uint32_t off); char* trim_file_path(const char* path); char *ulog_format_time(char *buffer, const int len); int http_start(const char *url, const unsigned short idx); void on_fs_upload(const uint32_t idx, const uint32_t start); #ifdef __cplusplus } #endif #endif /*U_LOG_API__H*/
YifuLiu/AliOS-Things
components/ulog/internal/ulog_api.h
C
apache-2.0
1,560
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #ifndef ULOG_RING_FIFO_H_ #define ULOG_RING_FIFO_H_ #include <stdint.h> #ifdef __cplusplus extern "C" { #endif typedef void (*pop_callback)(void*, void* src, const uint16_t len); extern int uring_fifo_push_s(const void* buf, const uint16_t len); extern int uring_fifo_pop_cb(pop_callback cb, void* cb_arg); extern int uring_fifo_init(void); #ifdef __cplusplus } #endif #endif /*ULOG_RING_FIFO_H_*/
YifuLiu/AliOS-Things
components/ulog/internal/ulog_ring_fifo.h
C
apache-2.0
468
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #ifndef ULOG_SESSION_FILE_H__ #define ULOG_SESSION_FILE_H__ #include <stdio.h> #include <stdbool.h> #include <stdint.h> typedef unsigned short ulog_idx_type; #define ULOG_FILE_IDX_INVALID (ulog_idx_type)0xFFFF #define ULOG_FILE_IDX_START (ulog_idx_type)1 #define ULOG_CFG_PARA_VAL_SIZE 24 #define SESSION_FS_INFO printf #define SESSION_FS_DEBUG(...) #define ULOG_FILE_FORMAT "%sulog%03d.log" #define ULOG_FILE_CFG_IDX 0 #define ULOG_CFG_LINE_MAX_SIZE 128 #define ULOG_FILE_PATH_SIZE 32 #define LOG_LINE_SEPARATOR '\n' #define LOG_LINE_END_STR "\n" #define LOG_LIST_PREFIX "{\"time\":\"%s\",list:[" #define LOG_LIST_SUFFIX "]}" #define LOG_LIST_NODE "{\"idx\":%d,\"start\":\"%s\",\"end\":\"%s\"}," typedef enum { ulog_cfg_para_start = 0, ulog_cfg_para_end, ulog_cfg_para_cnt, ulog_cfg_para_none } ulog_cfg_para_t; typedef enum { ulog_cfg_type_working = 0, ulog_cfg_type_list, ulog_cfg_type_cnt } ulog_cfg_type_t; #ifndef CSP_LINUXHOST #include "aos/vfs.h" #else /* !CSP_LINUXHOST */ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <dirent.h> #include <unistd.h> typedef DIR aos_dir_t; typedef struct dirent aos_dirent_t; #define aos_open open #define aos_close close #define aos_write write #define aos_read read #define aos_opendir opendir #define aos_readdir readdir #define aos_closedir closedir #define aos_lseek lseek #define aos_sync fsync #define aos_unlink unlink #undef ULOG_FILE_PATH_SIZE #define ULOG_FILE_PATH_SIZE 256 #endif /*CSP_LINUXHOST */ #ifdef __cplusplus extern "C" { #endif void cfg_init_mutex(void); bool cfg_get_mutex(void); void cfg_release_mutex(void); /* * get one line from specify fd. * * @param[in] fd file description. * @param[out] buf buffer to save the output character. * @param[in] buf_len buffer room size. */ int get_log_line(const int fd, char* buf, const uint16_t buf_len); /* O_APPEND */ int open_log_file(const ulog_idx_type file_idx, int flag, const off_t off); ulog_idx_type get_working_from_cfg_mm(void); int update_mm_cfg(const ulog_cfg_type_t type, const unsigned short idx, const ulog_cfg_para_t para_type, char val[ULOG_CFG_PARA_VAL_SIZE]); int cfg_mm_2_file(const int fd); int write_log_line(const int file_instanse, const char* buf, const bool keep_open); int load_cfg_2_mm(void); #ifdef __cplusplus } #endif #endif /* ULOG_SESSION_FILE_H__ */
YifuLiu/AliOS-Things
components/ulog/internal/ulog_session_file.h
C
apache-2.0
2,474
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <stdarg.h> #include <stdio.h> #include <string.h> #include "ulog/ulog.h" #include "aos/kernel.h" #include "ulog_api.h" #include "ulog_ring_fifo.h" #include "aos/errno.h" static char serverity_name[LOG_NONE] = { 'V', 'A', 'F', 'E', 'W', 'T', 'I', 'D' }; #define UNKNOWN_BUF "" void (*aos_cust_output_func)(const char *fmt, ...) = NULL; int ulog_vprintf(const char *vformat, va_list varg) { int i=0; int out_int; int *out_n; unsigned int out_hex_int; unsigned int out_unsigned_int; char out_char=0; char *out_string=NULL; char int_to_string[20]; double out_f; double out_e; double out_a; unsigned int out_o; unsigned int out_p; int k=0; char number_array[6]; int count=0; for (i = 0; vformat[i] != '\0';) { if (vformat[i] == '%') { i = i + 1; while (vformat[i] == '0'|| vformat[i] == '1'|| vformat[i] == '2'|| vformat[i] == '3' || vformat[i] == '4' || vformat[i] == '5' || vformat[i] == '6' ||vformat[i] == '7' || vformat[i] == '8' || vformat[i] == '9' || vformat[i] == '$' ||vformat[i] == '*' || vformat[i] == '.') { if (vformat[i] == '%') { break; } else { number_array[k++] = vformat[i]; i = i + 1; } } //number=findNumber(number_array); // if (vformat[i] == 'd') { out_int = va_arg(varg, int); sprintf(int_to_string, "%d", out_int); count = count + strlen(int_to_string); aos_cust_output_func("%d",out_int); i = i + 1; } else if (vformat[i] == 'i') { out_int = va_arg(varg, int); sprintf(int_to_string, "%i", out_int); count = count + strlen(int_to_string); aos_cust_output_func("%i", out_int); i = i + 1; } else if (vformat[i] == 's') { out_string = va_arg(varg, char*); count = count+strlen(out_string); aos_cust_output_func("%s", out_string); i = i + 1; } else if (vformat[i] == 'c') { out_char = va_arg(varg, int); count++; aos_cust_output_func("%c", out_char); i = i + 1; } else if (vformat[i] == 'x') { out_hex_int = va_arg(varg, int); sprintf(int_to_string, "%x", out_hex_int); count = count + strlen(int_to_string); aos_cust_output_func("%x", out_hex_int); i = i + 1; } else if (vformat[i] == 'X') { out_hex_int = va_arg(varg, int); sprintf(int_to_string, "%X", out_hex_int); count= count + strlen(int_to_string); aos_cust_output_func("%X", out_hex_int); i = i + 1; } else if (vformat[i]=='f') { out_f = va_arg(varg, double); sprintf(int_to_string, "%f", out_f); count = count + strlen(int_to_string); aos_cust_output_func("%f", out_f); i = i + 1; } else if (vformat[i] == 'u') { out_unsigned_int = va_arg(varg, int); sprintf(int_to_string, "%u", out_unsigned_int); count = count + strlen(int_to_string); aos_cust_output_func("%u", out_unsigned_int); i=i+1; } else if (vformat[i]=='h') { if (vformat[i+1] == 'n') { out_n = (int *)va_arg(varg, int*); //*out_n=count; i = i + 2; } else { count++; aos_cust_output_func("%c", vformat[i]); i = i + 1; } } else if (vformat[i]=='e') { out_e = va_arg(varg, double); sprintf(int_to_string, "%e", out_e); count = count + strlen(int_to_string); aos_cust_output_func("%e", out_e); i = i + 1; } else if (vformat[i] == 'o') { out_o = va_arg(varg, unsigned int); sprintf(int_to_string, "%o", out_o); count = count + strlen(int_to_string); aos_cust_output_func("%o", out_o); i = i + 1; } else if (vformat[i]=='p') { out_p = va_arg(varg, unsigned int); sprintf(int_to_string, "%p", (void *)out_p); count = count + strlen(int_to_string); aos_cust_output_func("%p", (void *)out_p); i = i + 1; } else if (vformat[i] == 'a') { out_a = va_arg(varg,double); sprintf(int_to_string, "%a", out_a); count = count + strlen(int_to_string); aos_cust_output_func("%a", out_a); i = i + 1; } else if (vformat[i] == 'n') { out_n=(int *)va_arg(varg,int*); //*out_n=count; //uncomment this for test1 and test2 i=i+1; } else if (vformat[i] == '%') { count++; aos_cust_output_func("%c", vformat[i]); i = i + 1; } else { count++; i++; } } else { count++; aos_cust_output_func("%c", vformat[i]); i++; } } return 0; } /* stop filter, any level <= stop_filter_level(value >= this value) will be abonded */ static uint8_t stop_filter_level[ulog_session_size] = { STOP_FILTER_DEFAULT, #if ULOG_POP_CLOUD_ENABLE STOP_FILTER_CLOUD, #endif #if ULOG_POP_FS_ENABLE STOP_FILTER_FS, #endif #if ULOG_POP_UDP_ENABLE STOP_FILTER_UDP, #endif }; static uint8_t push_stop_filter_level = LOG_EMERG; /* Prefix <248>~<255> */ /* using type char instead of int8_t which align with the prototype of string operation function */ static char ulog_buf[ULOG_SIZE + 1]; /*check whether session can pop log*/ bool check_pass_pop_out(const ulog_session_type_t session, const uint8_t level) { return (stop_filter_level[session]>level); } /*获取日志停止输出的level*/ uint8_t ulog_stop_filter_level(const ulog_session_type_t session) { return stop_filter_level[session]; } /*设置本地终端日志输出level*/ int aos_set_log_level(aos_log_level_t log_level) { int rc = -EINVAL; if(aos_ulog_init) { if (log_level <= AOS_LL_DEBUG) { on_filter_level_changes(ulog_session_std, log_level + 1); rc = 0; } } return rc; } /*设置输出到云端日志level*/ #if ULOG_POP_CLOUD_ENABLE int aos_set_popcloud_log_level(aos_log_level_t log_level) { int rc = -EINVAL; if (aos_ulog_init) { if (log_level <= AOS_LL_DEBUG) { on_filter_level_changes(ulog_session_cloud, log_level + 1); rc = 0; } } return rc; } #endif /*设置输出到本地文件系统日志level*/ #if ULOG_POP_FS_ENABLE int aos_set_popfs_log_level(aos_log_level_t log_level) { int rc = -EINVAL; if (aos_ulog_init) { if (log_level <= AOS_LL_DEBUG) { on_filter_level_changes(ulog_session_file, log_level + 1); rc = 0; } } return rc; } #endif /*设置输出到syslog 服务器到日志等级*/ #if ULOG_POP_UDP_ENABLE int aos_set_popudp_log_level(aos_log_level_t log_level) { int rc = -EINVAL; if (aos_ulog_init) { if (log_level <= AOS_LL_DEBUG) { on_filter_level_changes(ulog_session_udp, log_level + 1); rc = 0; } } return rc; } #endif int aos_log_hexdump(const char *tag, char *buffer, int len) { int i; if (aos_ulog_init == false) { return -1; } aos_cust_output_func("[%s]\n", tag); aos_cust_output_func("0x0000: "); for (i = 0; i < len; i++) { aos_cust_output_func("0x%02x ", buffer[i]); if (i % 8 == 7) { aos_cust_output_func("\n"); aos_cust_output_func("0x%04x: ", i + 1); } } aos_cust_output_func("\n"); return 0; } int aos_set_log_output(void (*output_func)(const char* fmt, ...)) { if (NULL == output_func) { return -1; } aos_cust_output_func = output_func; return 0; } char* get_sync_stop_level() { static char buf[32]; #ifdef CONFIG_LOGMACRO_SILENT return "NDEBUG mode active"; #else if (stop_filter_level[ulog_session_std] == LOG_NONE) { return "all log recorded"; } else if (stop_filter_level[ulog_session_std] == LOG_EMERG) { return "all log stop"; } else { snprintf(buf, 24, "current log level %c",serverity_name[stop_filter_level[ulog_session_std]-1]); return buf; } #endif } #if SYNC_DETAIL_COLOR /* * color def. * see http://stackoverflow.com/questions/3585846/color-text-in-terminal-applications-in-unix */ #define COL_DEF "\x1B[0m" /* white */ #define COL_RED "\x1B[31m" /* red */ #define COL_GRE "\x1B[32m" /* green */ #define COL_BLU "\x1B[34m" /* blue */ #define COL_YEL "\x1B[33m" /* yellow */ #define COL_WHE "\x1B[37m" /* white */ #define COL_CYN "\x1B[36m" #define COL_MAG "\x1B[35m" static char log_col_list[LOG_NONE][12] = { COL_DEF, COL_RED, COL_RED, COL_RED, COL_BLU, COL_GRE, COL_GRE, COL_WHE }; static char* log_col_def(const unsigned char level) { if(level<LOG_NONE) { return log_col_list[level]; } else { return log_col_list[0]; } } #else #define log_col_def(x) "" #endif #ifdef ULOG_CONFIG_ASYNC static uint8_t get_lowest_level(const ulog_session_type_t start); #endif int ulog(const unsigned char s, const char *mod, const char *f, const unsigned long l, const char *fmt, ...) { int rc = -1; if (aos_ulog_init && (s < push_stop_filter_level) ) { char log_time[24]; if (log_get_mutex()) { const char* rpt_mod = NULL; if ((mod == NULL) || (0 == strlen(mod))) { rpt_mod = UNKNOWN_BUF; } else { rpt_mod = mod; } #if ULOG_CONFIG_ASYNC uint8_t facility = FACILITY_NORMAL_LOG; if (strlen(rpt_mod) == 0 || 0 == strncmp("MQTT", rpt_mod, strlen("MQTT"))) { facility = FACILITY_NORMAL_LOG_NO_POP_CLOUD; } snprintf(ulog_buf,ULOG_HEADER_TYPE_LEN+1,"<%03d>",s+(facility&0xF8)); #if SYNC_LOG_DETAILS snprintf(&ulog_buf[ULOG_HEADER_TYPE_LEN], ULOG_SIZE-ULOG_HEADER_TYPE_LEN, "%s[%s]<%c>%s %s[%d]: ", log_col_def(s), ulog_format_time(log_time, 24), serverity_name[s], rpt_mod, trim_file_path(f), (int)l); #else /* !SYNC_LOG_DETAILS */ snprintf(&ulog_buf[ULOG_HEADER_TYPE_LEN], ULOG_SIZE-ULOG_HEADER_TYPE_LEN, "[%s]<%c>%s ", ulog_format_time(log_time, 24), serverity_name[s], rpt_mod); #endif va_list args; va_start(args, fmt); rc = vsnprintf(&ulog_buf[strlen(ulog_buf)], ULOG_SIZE-strlen(ulog_buf), fmt, args); va_end(args); rc = rc<ULOG_SIZE-1?rc:ULOG_SIZE-1; bool skip_session_std = false; #if !LOG_DIR_ASYNC if(s < stop_filter_level[ulog_session_std]) { skip_session_std = true; puts(&ulog_buf[LOG_PREFIX_LEN]); } #endif if(!skip_session_std || (s<get_lowest_level(ulog_session_std))) { uring_fifo_push_s(ulog_buf, strlen(ulog_buf)+1); } #else /* !ULOG_CONFIG_ASYNC */ #if SYNC_LOG_DETAILS aos_cust_output_func("%s[%s]<%c>%s %s[%d]: ", log_col_def(s), ulog_format_time(log_time, 24), serverity_name[s], rpt_mod, trim_file_path(f), (int)l); #else /* !SYNC_LOG_DETAILS */ rc = snprintf(ulog_buf, ULOG_SIZE, "[%s]<%c>%s ", ulog_format_time(log_time, 24), serverity_name[s], rpt_mod); #endif /* SYNC_LOG_DETAILS */ va_list args; va_start(args, fmt); rc = vsnprintf(&ulog_buf[strlen(ulog_buf)], ULOG_SIZE-strlen(ulog_buf), fmt, args); va_end(args); fflush(stdout); aos_cust_output_func(ulog_buf); #endif /* if def ULOG_CONFIG_ASYNC */ log_release_mutex(); } } return rc; } /*用于loglevel 命令行处理*/ void on_sync_filter_level_change(const ulog_session_type_t session, const char level) { if ('N' == level) { on_filter_level_changes(session, LOG_EMERG); } else { int8_t i = 0; for (; i < LOG_NONE; i++) { if (serverity_name[i] == level) { on_filter_level_changes(session, i+1); break; } } } } void on_filter_level_changes(const ulog_session_type_t session, const uint8_t level) { bool next_handle = true; uint8_t i = 0; if (session == ulog_session_size) {/* only happen on init, get the initial push level */ push_stop_filter_level = LOG_EMERG; } else if (session < ulog_session_size && level <= LOG_NONE) { stop_filter_level[session] = level; /* suppose we use update session sf(stop filter) as push filter, this value will be updated below */ push_stop_filter_level = stop_filter_level[session]; } else { next_handle = false; } if (next_handle) { /*遍历所有终端的 filter level , push pop filter 选择最低的一个,保证每一条日志都能吐出来*/ for (; i < ulog_session_size; i++) { if (push_stop_filter_level < stop_filter_level[i]) { push_stop_filter_level = stop_filter_level[i]; } } } } #ifdef ULOG_CONFIG_ASYNC static uint8_t get_lowest_level(const ulog_session_type_t start) { uint8_t i = start+1; uint8_t lowest_level = LOG_EMERG; for(; i<ulog_session_size; i++) { if(lowest_level<stop_filter_level[i]) { lowest_level = stop_filter_level[i]; } } return lowest_level; } #endif void on_filter_change(const ulog_session_type_t session, const char level) { if(session<ulog_session_size && level<=LOG_NONE) { on_filter_level_changes(session, level); } }
YifuLiu/AliOS-Things
components/ulog/src/ulog.c
C
apache-2.0
14,652
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <string.h> #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <time.h> #include "ulog/ulog.h" #include "ulog_api.h" #include "ulog_ring_fifo.h" #include "aos/kernel.h" #include "k_config.h" #if ULOG_POP_CLOUD_ENABLE #include "uagent.h" #endif #define SUB_FUNC_MAX_NUM 2 static aos_task_t ulog_routine; typedef void(*on_ulog_man_service)(const uint32_t, const uint32_t); typedef struct { char *func_mark; char *sub_func_mark[SUB_FUNC_MAX_NUM]; on_ulog_man_service handler; } ulog_man_handler_service_t; static void ulog_man_handler(const char* raw_str); const ulog_man_handler_service_t ulog_man_handler_service[] = { #if ULOG_POP_UDP_ENABLE { "listen", {"ip","port"}, on_update_syslog_watcher_addr }, { "tcpip", {"on","off" }, on_tcpip_service_on }, #endif #if ULOG_POP_FS_ENABLE { "fspause", {"on","off"}, on_fs_record_pause }, #if ULOG_UPLOAD_LOG_FILE { "up", {"idx","none"}, on_fs_upload }, #endif #endif }; static void ulog_handler(void* para, void* log_text, const uint16_t log_len) { if ((log_text != NULL) && log_len > 0) { char *str = (char*)log_text; char *text_info = NULL; if ((str[0] == '<') && ((text_info = strchr(str, '>')) != NULL)) { /* pri = facility*8+level */ const uint32_t pri = strtoul(&str[1], NULL, 10); const uint8_t severity = (pri & 0x7); #if LOG_DIR_ASYNC if (check_pass_pop_out(ulog_session_std, severity)) { if (log_get_mutex()) { puts(&((char*)log_text)[LOG_PREFIX_LEN]); log_release_mutex(); } } #endif #if ULOG_POP_UDP_ENABLE if (check_pass_pop_out(ulog_session_udp, severity)) { (void)pop_out_on_udp(&((char *)log_text)[LOG_PREFIX_LEN], log_len); } #endif #if ULOG_POP_FS_ENABLE if (check_pass_pop_out(ulog_session_file, severity)) { (void)pop_out_on_fs(&((char *)log_text)[LOG_PREFIX_LEN], log_len); } #endif #if ULOG_POP_CLOUD_ENABLE if ((FACILITY_NORMAL_LOG_NO_POP_CLOUD != (pri & 0xF8)) && check_pass_pop_out(ulog_session_cloud, severity)) { (void)uagent_send(UAGENT_MOD_ULOG, ULOG_SHOW, strlen(text_info + 1), text_info + 1, 0); } #endif } else if (0 == strncmp(str, ULOG_CMD_PREFIX, strlen(ULOG_CMD_PREFIX))) { /* syslog management */ ulog_man_handler(&str[strlen(ULOG_CMD_PREFIX)]); } else { /* unkown format */ puts(log_text); } } } static void log_routine(void* para) { while (1) { /* PRI HEADER MSG */ /* <130>Oct 9 22:33:20.111 soc kernel.c[111]: The audit daemon is exiting. */ uring_fifo_pop_cb(ulog_handler, NULL); } } void ulog_async_init() { /* start log on fs feature if both vfs && spiffs support */ #if ULOG_POP_FS_ENABLE ulog_fs_init(); #endif uring_fifo_init(); if (0 == aos_task_new_ext(&ulog_routine, "ulog", log_routine, NULL, LOG_ROUTINE_TASK_STACK_DEPTH, RHINO_CONFIG_USER_PRI_MAX)) { } } void ulog_man_handler(const char* raw_str) { const int8_t man_handler_service_size = sizeof(ulog_man_handler_service) / sizeof(ulog_man_handler_service_t); int8_t i = 0; uint8_t j = 0; int func_len = 0; int subfunc_len = 0; unsigned short data_len = 0; uint32_t param[SUB_FUNC_MAX_NUM] = { -1, -1 }; char *p = NULL; char *val_str = NULL; if (raw_str == NULL) { return ; } data_len = strlen(raw_str); for (; i < man_handler_service_size; i++) { func_len = strlen(ulog_man_handler_service[i].func_mark); if (0 == strncmp(ulog_man_handler_service[i].func_mark, raw_str, func_len)) { /* printf("%s %d find ulog func mark %s \r\n", __FILE__, __LINE__, ulog_man_handler_service[i].func_mark); */ p = &raw_str[func_len]; if (p[0] == ' ') { for (; j < SUB_FUNC_MAX_NUM; j++) { subfunc_len = strlen(ulog_man_handler_service[i].sub_func_mark[j]); if (strncmp(&p[1], ulog_man_handler_service[i].sub_func_mark[j], subfunc_len) == 0) { /* printf("%s %d find ulog sub func mark %s \r\n", __FILE__, __LINE__, ulog_man_handler_service[i].sub_func_mark[j]); */ if (data_len > strlen(ulog_man_handler_service[i].func_mark) + 1 + subfunc_len + 1) { /*jump off the space and the '='*/ val_str = &p[subfunc_len + 1 + 1]; param[j] = strtoul(val_str, NULL, 10); /* printf("%s %d find ulog sub func mark %s param value %s param %d \r\n", __FILE__, __LINE__, ulog_man_handler_service[i].sub_func_mark[j], val_str, param[j]); */ } else { /*there is no param for this cmd ,set true */ param[j] = 1; /* printf("%s %d find ulog sub func mark %s param %d \r\n", __FILE__, __LINE__, ulog_man_handler_service[i].sub_func_mark[j], param[j]); */ } } } if ((param[0] != -1 || param[1] != -1) && (ulog_man_handler_service[i].handler != NULL)) { /* printf("%s %d find ulog man handler %d param0 %d param1 %d\r\n", __FILE__, __LINE__, i, param[0], param[1]); */ ulog_man_handler_service[i].handler(param[0], param[1]); } } break; } } }
YifuLiu/AliOS-Things
components/ulog/src/ulog_async.c
C
apache-2.0
6,220
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include "ulog_session_file.h" #include <string.h> #include <fcntl.h> #include "aos/kernel.h" #include "cJSON.h" #include "errno.h" #include "ulog_api.h" #define ULOG_CFG_PARA_KEY_SIZE 12 typedef struct { ulog_cfg_type_t type; char* desription; char* cfg_key[ulog_cfg_para_cnt]; } ulog_cfg_key_list_t; typedef struct { char ulog_cfg_val[ULOG_CFG_PARA_VAL_SIZE]; } ulog_cfg_t; typedef struct _ulog_cfg_node_t { ulog_cfg_type_t type; unsigned short file_idx; ulog_cfg_t *cfg[ulog_cfg_para_cnt]; struct _ulog_cfg_node_t *next; } ulog_cfg_node_t; static aos_mutex_t mutex_entry_cfg_mm; static ulog_cfg_node_t *ulog_cfg_header = NULL; ulog_cfg_key_list_t cfg_key_list[ulog_cfg_type_cnt] = { {ulog_cfg_type_working, "working_idx", {NULL, NULL}}, {ulog_cfg_type_list, "file_idx", {"start", "end"}} }; static void parser_cfg_file(const char* cfg); static ulog_cfg_key_list_t *get_ulog_cfg_key(const ulog_cfg_type_t type) { ulog_cfg_key_list_t *rc = NULL; uint8_t i = 0; for (; i < ulog_cfg_type_cnt; i++) { if (type == cfg_key_list[i].type) { rc = &cfg_key_list[i]; break; } } return rc; } void cfg_init_mutex(void) { aos_mutex_new(&mutex_entry_cfg_mm); } bool cfg_get_mutex(void) { return 0 == aos_mutex_lock(&mutex_entry_cfg_mm, AOS_WAIT_FOREVER); } void cfg_release_mutex(void) { aos_mutex_unlock(&mutex_entry_cfg_mm); } int aos_get_ulog_list(char* buf, const unsigned short len) { int rc = -EINVAL; if(NULL!=buf && (len>=strlen(LOG_LIST_PREFIX)+strlen(LOG_LIST_SUFFIX)+1) ) { rc = -EIO; if(aos_mutex_is_valid(&mutex_entry_cfg_mm)) { if(cfg_get_mutex()) { rc = 0; ulog_cfg_node_t *p = ulog_cfg_header; if(NULL!=p) { char time_buf[24]; snprintf(buf, len-strlen(LOG_LIST_SUFFIX)-1, LOG_LIST_PREFIX, ulog_format_time(time_buf, sizeof(time_buf))); unsigned short off = strlen(buf); while (p != NULL && rc == 0) { if (p->type == ulog_cfg_type_list) { const int empty_room = len-strlen(LOG_LIST_SUFFIX)-1-off; int result = 0; if(empty_room>(result=snprintf(&buf[off], empty_room, LOG_LIST_NODE,p->file_idx, p->cfg[0]==NULL?"":p->cfg[0]->ulog_cfg_val,p->cfg[1]==NULL?"":p->cfg[1]->ulog_cfg_val))) { off += result; } else { rc = -ENOMEM; } } p = p->next; } if(rc==0) { if(buf[off-1]==',') { off--; } snprintf(&buf[off], len-strlen(LOG_LIST_SUFFIX)-1-off, LOG_LIST_SUFFIX); } } else { rc = -EIO; } cfg_release_mutex(); } } } return rc; } int update_mm_cfg(const ulog_cfg_type_t type, const unsigned short idx, const ulog_cfg_para_t para_type, char val[ULOG_CFG_PARA_VAL_SIZE]) { int rc = -1; if(cfg_get_mutex()) { if (NULL == ulog_cfg_header) { ulog_cfg_header = (ulog_cfg_node_t *)aos_malloc(sizeof(ulog_cfg_node_t)); if (NULL != ulog_cfg_header) { ulog_cfg_header->next = NULL; ulog_cfg_header->type = type; ulog_cfg_header->file_idx = idx; uint8_t i = 0; for(; i<ulog_cfg_para_cnt; i++) { if(NULL!=get_ulog_cfg_key(type)->cfg_key[i]) { ulog_cfg_header->cfg[i] = (ulog_cfg_t *)aos_malloc(sizeof(ulog_cfg_t)); memset(ulog_cfg_header->cfg[para_type], 0, sizeof(ulog_cfg_t)); } } if (ulog_cfg_para_none != para_type) { strncpy(ulog_cfg_header->cfg[para_type]->ulog_cfg_val, val, ULOG_CFG_PARA_VAL_SIZE - 1); } rc = 0; } else { SESSION_FS_INFO("alloc memory fail for type %d idx %d\n", type, idx); } } else { ulog_cfg_node_t *p = ulog_cfg_header; while (p != NULL && rc != 0) { if (p->type == type && (ulog_cfg_para_none == para_type || p->file_idx == idx)) { /* found it alredy in list, just update */ if (ulog_cfg_para_none == para_type) { /* no cfg, just update file list, apply to type working */ p->file_idx = idx; rc = 0; break; } else { uint8_t i = 0; for(; i<ulog_cfg_para_cnt; i++) { if(NULL!=get_ulog_cfg_key(type)->cfg_key[i] && NULL==p->cfg[i]) { p->cfg[i] = (ulog_cfg_t *)aos_malloc(sizeof(ulog_cfg_t)); memset(p->cfg[i], 0, sizeof(ulog_cfg_t)); } } strncpy(p->cfg[para_type]->ulog_cfg_val, val, ULOG_CFG_PARA_VAL_SIZE - 1); rc = 0; } break; } if (p->next == NULL) { /* last node */ p->next = (ulog_cfg_node_t*)aos_malloc(sizeof(ulog_cfg_node_t)); if (NULL != p->next) { p->next->next = NULL; p->next->type = type; p->next->file_idx = idx; uint8_t i = 0; for(; i<ulog_cfg_para_cnt; i++) { if(NULL!=get_ulog_cfg_key(type)->cfg_key[i]) { p->next->cfg[i] = (ulog_cfg_t *)aos_malloc(sizeof(ulog_cfg_t)); memset(p->next->cfg[i], 0, sizeof(ulog_cfg_t)); } } if (ulog_cfg_para_none != para_type) { strncpy(p->next->cfg[para_type]->ulog_cfg_val, val, ULOG_CFG_PARA_VAL_SIZE - 1); } rc = 0; } else { SESSION_FS_INFO("alloc memory fail for type %d idx %d\n", type, idx); } break; } else { p = p->next; } } } cfg_release_mutex(); } return rc; } /** * * Sync cfg from cfg file to memory * * return 0 if this step pass, else indicates this step fail * */ int load_cfg_2_mm(void) { int rc = -1; char one_cfg_item[ULOG_CFG_LINE_MAX_SIZE]; int off = 0; int read_len = 0; int fd = open_log_file(ULOG_FILE_CFG_IDX, O_RDONLY, 0); if (fd < 0) { SESSION_FS_DEBUG("%s %d open log cfg file fail\r\n", __FILE__, __LINE__); return rc; } do { read_len = get_log_line(fd, one_cfg_item, sizeof(one_cfg_item)); parser_cfg_file(one_cfg_item); }while (read_len > 0); aos_close(fd); ulog_cfg_node_t *p = ulog_cfg_header; while (p != NULL) { SESSION_FS_DEBUG("check cfg item in mm type %d idx %d\n", p->type, p->file_idx); uint8_t i = 0; for(; i<ulog_cfg_para_cnt; i++) { if(p->cfg[i]!=NULL) { SESSION_FS_DEBUG("check cfg item in mm cfg value %s @ %d\n", p->cfg[i]->ulog_cfg_val, i); } } p = p->next; } return rc; } /** * * Sync cfg from memory to file * * return 0 if this step pass, else indicates this step fail * */ int cfg_mm_2_file(const int fd) { int rc = -EINVAL; if (fd >= 0 && NULL != ulog_cfg_header) { ulog_cfg_node_t *p = ulog_cfg_header; while (NULL != p) { switch (p->type) { case ulog_cfg_type_working: { cJSON *ulog_cfg_obj = cJSON_CreateObject(); if (NULL != ulog_cfg_obj) { cJSON_AddItemToObject(ulog_cfg_obj, get_ulog_cfg_key(p->type)->desription, cJSON_CreateNumber(p->file_idx)); char *cfg_line = cJSON_PrintUnformatted(ulog_cfg_obj); cJSON_Delete(ulog_cfg_obj); if (NULL != cfg_line) { write_log_line(fd, cfg_line, true); SESSION_FS_INFO("sync cfg to file %s\n", cfg_line); cJSON_free(cfg_line); cfg_line = NULL; rc = 0; } else { rc = -EIO; } } else { rc = -ENOMEM; SESSION_FS_INFO("[%s#%d]create cjson obj fail\n", __FILE__, __LINE__); } } break; case ulog_cfg_type_list: { cJSON *ulog_cfg_obj = cJSON_CreateObject(); if (NULL != ulog_cfg_obj) { uint8_t i = 0; cJSON_AddItemToObject(ulog_cfg_obj, get_ulog_cfg_key(p->type)->desription, cJSON_CreateNumber(p->file_idx)); for (; i < ulog_cfg_para_cnt; i++) { if (p->cfg[i] != NULL) { cJSON_AddItemToObject(ulog_cfg_obj, get_ulog_cfg_key(p->type)->cfg_key[i], cJSON_CreateString(p->cfg[i]->ulog_cfg_val)); } } char *cfg_line = cJSON_PrintUnformatted(ulog_cfg_obj); cJSON_Delete(ulog_cfg_obj); if (NULL != cfg_line) { write_log_line(fd, cfg_line, true); SESSION_FS_INFO("sync cfg to file %s\n", cfg_line); cJSON_free(cfg_line); cfg_line = NULL; rc = 0; } else { rc = -EIO; } } else { rc = -ENOMEM; SESSION_FS_INFO("[%s#%d]create cjson obj fail\n", __FILE__, __LINE__); } } break; default: break; } p = p->next; } } else { SESSION_FS_INFO("sync fail as mm illegal\n"); } return rc; } static void parser_cfg_file(const char* cfg) { uint8_t i = 0; uint8_t j = 0; cJSON *root = NULL; cJSON *config_para = NULL; cJSON *config_node = NULL; if (NULL == cfg) { return ; } root = cJSON_Parse(cfg); if (NULL == root) { return ; } SESSION_FS_DEBUG("parser_cfg_file input %s %d \n", cfg, __LINE__); for (; i < ulog_cfg_type_cnt; i++) { SESSION_FS_DEBUG("key list description %s @ %d\n", cfg_key_list[i].desription, i); config_node = cJSON_GetObjectItem(root, cfg_key_list[i].desription); if (NULL == config_node) { continue; } if (cJSON_IsNumber(config_node)) { if (ulog_cfg_type_working == cfg_key_list[i].type) { update_mm_cfg(cfg_key_list[i].type, (ulog_idx_type)config_node->valueint, ulog_cfg_para_none, NULL); } for (; j < ulog_cfg_para_cnt; j++) { if (cfg_key_list[i].cfg_key[j] != NULL) { SESSION_FS_DEBUG("key list description %s cfg key %s @ %d %d\n", cfg_key_list[i].desription, cfg_key_list[i].cfg_key[j], i, j); config_para = cJSON_GetObjectItem(root, cfg_key_list[i].cfg_key[j]); if (NULL != config_para && cJSON_IsString(config_para)) { update_mm_cfg(cfg_key_list[i].type, (ulog_idx_type)config_node->valueint, j, config_para->valuestring); } } } } break; } cJSON_Delete(root); root = NULL; } ulog_idx_type get_working_from_cfg_mm() { ulog_idx_type rc = ULOG_FILE_IDX_INVALID; ulog_cfg_node_t *p = ulog_cfg_header; while (p != NULL) { if (p->type == ulog_cfg_type_working) { /* found it alredy in list, just update */ rc = p->file_idx; break; } else { p = p->next; } } return rc; }
YifuLiu/AliOS-Things
components/ulog/src/ulog_fs_cfg.c
C
apache-2.0
12,866
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include "ulog/ulog.h" #include "ulog_api.h" #include <string.h> #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include "aos/kernel.h" #if ULOG_POP_CLOUD_ENABLE #include "uagent_type.h" #endif bool aos_ulog_init = false; extern void (*aos_cust_output_func)(const char *fmt, ...); #if AOS_COMP_CLI #include "aos/cli.h" __attribute__((weak)) void update_net_cli(const char cmd, const char *param) { /* Will be overwrite in session_udp, as this implement take effect only the UDP feature support, I don't like so many compile switcher in the code which result reader is not so comfortable, so weak attribute used here. */ } __attribute__((weak)) void fs_control_cli(const char cmd, const char *param) { /* Will be overwrite in session_fs */ } __attribute__((weak)) void on_show_ulog_file() { /* Will be overwrite in session_fs */ } #if ULOG_CONFIG_ASYNC static void cmd_cli_ulog(char *pwbuf, int blen, int argc, char *argv[]) { bool exit_loop = false; uint8_t session = 0xFF; uint8_t level = 0xFF; uint8_t i; if (argc == 2) { const char* option = argv[1]; switch (option[0]) { case 'f': on_show_ulog_file(); break; case 'x': { #if ULOG_CONFIG_POP_FS char *buf = (char*)aos_malloc(512); if (NULL != buf) { aos_cli_printf("get ulog list %d\n", aos_get_ulog_list(buf, 512)); puts(buf); aos_free(buf); } #else aos_cli_printf("pop log to fs is off"); #endif /* ULOG_CONFIG_POP_FS */ } break; default: break; } } for (i = 1; i < argc && !exit_loop; i += 2) { const char* option = argv[i]; const char* param = argv[i + 1]; if (option != NULL && param != NULL && strlen(option) == 1) { switch (option[0]) { case 's':/* session */ session = strtoul(param, NULL, 10); break; case 'l':/* level */ level = strtoul(param, NULL, 10); break; case 'a':/* syslog watcher address */ update_net_cli(option[0], param); break; case 'p': /* syslog wacher port*/ update_net_cli(option[0], param); break; case 'n': /*tcpip on/off*/ update_net_cli(option[0], param); break; case 't':/* terminate record on fs */ fs_control_cli(option[0], param); break; default: /* unknown option */ exit_loop = true; break; } } else {/* unknown format */ break; } } if ((session < ulog_session_size) && (level <= LOG_NONE)) { on_filter_level_changes((ulog_session_type_t)session, level); } } #endif extern int aos_cli_printf(const char *fmt, ...); static void sync_log_cmd(char *buf, int len, int argc, char **argv) { if (argc < 2) { aos_cli_printf("log level : %s\r\n", get_sync_stop_level()); return; } else if (argc == 2) { const char* option = argv[1]; switch (option[0]) { case 'A': case 'F': case 'E': case 'W': case 'I': case 'D': case 'N': on_sync_filter_level_change(ulog_session_std, option[0]); break; default: aos_cli_printf("unknown option %c, only support[AFEWID]\r\n", option[0]); break; } } } static struct cli_command ulog_cli_cmd[] = { { "loglevel","set sync log level", sync_log_cmd }, #if ULOG_CONFIG_ASYNC { "ulog", "ulog [option param]", cmd_cli_ulog }, #endif }; #endif /* AOS_COMP_CLI */ #if (ULOG_POP_CLOUD_ENABLE || ULOG_UPLOAD_LOG_FILE) #include "cJSON.h" static int on_ulog_handler(void *p, const unsigned short len, void *cmd) { int rc = -1; cJSON *root = NULL; root = cJSON_Parse(cmd); if (NULL != root) { cJSON *ulog_cmd = NULL; #if ULOG_POP_CLOUD_ENABLE ulog_cmd = cJSON_GetObjectItem(root, "ulog level"); if (ulog_cmd != NULL && cJSON_IsNumber(ulog_cmd)) { if(ULOG_POLICY_RQST == ulog_cmd->valueint) { char buf[64]; snprintf(buf, sizeof(buf), ULOG_LEVEL_RSP, ulog_stop_filter_level(ulog_session_cloud)); rc = uagent_send(UAGENT_MOD_ULOG, ULOG_POLICY, strlen(buf), buf, send_policy_object); } if (ulog_cmd->valueint <= LOG_NONE) { on_filter_change(ulog_session_cloud, ulog_cmd->valueint); rc = 0; } } #endif #if ULOG_UPLOAD_LOG_FILE /* log list requset */ ulog_cmd = cJSON_GetObjectItem(root, "ulog list"); if (ulog_cmd != NULL && cJSON_IsString(ulog_cmd)) { if (0 == strlen(ulog_cmd->valuestring)) { char *buf = (char*)aos_malloc(1024); memset(buf, 0, 1024); if (NULL != buf) { if (0 == aos_get_ulog_list(buf, 1024)) { rc = uagent_send(UAGENT_MOD_ULOG, ULOG_LOG_LIST, strlen(buf), buf, send_policy_object); } aos_free(buf); } } } /* request upload ulog file */ ulog_cmd = cJSON_GetObjectItem(root, "url"); if (NULL != ulog_cmd && cJSON_IsString(ulog_cmd)) { cJSON *ulog_idx = cJSON_GetObjectItem(root, "idx"); if (NULL != ulog_idx && cJSON_IsNumber(ulog_idx)) { rc = http_start(ulog_cmd->valuestring, ulog_idx->valueint); } } #endif cJSON_Delete(root); } return rc; } #ifndef MOD_VER #define MOD_VER "1.0.0" #endif static uagent_func_node_t ulog_uagent_funclist[] = { {ULOG_LEVEL_CHANGE, "uloglevel", on_ulog_handler, NULL, &ulog_uagent_funclist[1]}, {ULOG_POLICY, "ulogpolicy", NULL, NULL, &ulog_uagent_funclist[2]}, #if ULOG_POP_CLOUD_ENABLE #if ULOG_UPLOAD_LOG_FILE {ULOG_SHOW, "ulogshow", NULL, NULL, &ulog_uagent_funclist[3]}, #else /* !ULOG_UPLOAD_LOG_FILE */ {ULOG_SHOW, "ulogshow", NULL, NULL, NULL}, #endif #endif /* ULOG_POP_CLOUD_ENABLE */ #if ULOG_UPLOAD_LOG_FILE {ULOG_LOG_LIST, "loglist", NULL, NULL, NULL} #endif }; static mod_func_t ulog_uagent_func = { { UAGENT_MOD_ULOG, sizeof(ulog_uagent_funclist) / sizeof(ulog_uagent_funclist[0]), "uLOG", MOD_VER }, ulog_uagent_funclist }; #endif void ulog_init(void) { if (!aos_ulog_init) { log_init_mutex(); on_filter_level_changes(ulog_session_size, LOG_NONE); #if ULOG_CONFIG_ASYNC ulog_async_init(); #endif #if AOS_COMP_CLI aos_cli_register_commands(&ulog_cli_cmd[0], sizeof(ulog_cli_cmd) / sizeof(struct cli_command)); #endif /*set default log output*/ if (aos_cust_output_func == NULL) { aos_set_log_output(printf); } aos_ulog_init = true; #if (ULOG_POP_CLOUD_ENABLE || ULOG_UPLOAD_LOG_FILE) uagent_func_node_t * p = ulog_uagent_func.header; if (NULL != p) { while (NULL != p) { if (0 != uagent_register(UAGENT_MOD_ULOG, "uLog", MOD_VER, p->func, p->func_name, p->service, p->argu)) { LOGE("ULOG", "register into uagent fail"); } p = p->next; } } else { LOGE("ULOG", "register into uagent fail, table is null"); } #endif } }
YifuLiu/AliOS-Things
components/ulog/src/ulog_init.c
C
apache-2.0
7,808
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include "ulog_ring_fifo.h" #include <string.h> #include <stdio.h> #include "aos/kernel.h" #include "ulog_config.h" static aos_queue_t ulog_queue; static uint8_t* ulog_buffer; /** * This function will create a ring fifo for ulog. * * * @return 0: success. */ int uring_fifo_init() { int rc = -1; if (ulog_buffer == NULL) { ulog_buffer = aos_malloc(DEFAULT_ASYNC_BUF_SIZE); if (ulog_buffer != NULL) { rc = aos_queue_new(&ulog_queue, ulog_buffer, DEFAULT_ASYNC_BUF_SIZE, ULOG_SIZE); if (0 != rc) { aos_free(ulog_buffer); ulog_buffer = NULL; } } } return rc; } /** * Thread Safe to put the msg into ring - fifo. * * @param[in] queue pointer to the queue. * @param[in] msg msg to send. * @param[in] size size of the msg. * * @return 0: success. */ int uring_fifo_push_s(const void* buf, const uint16_t len) { return aos_queue_send(&ulog_queue, (void*)buf, len); } int uring_fifo_pop_cb(pop_callback cb, void* cb_arg) { char tmp_buf[ULOG_SIZE]; unsigned int rcv_size = 0; int rc = aos_queue_recv(&ulog_queue, AOS_WAIT_FOREVER, tmp_buf, &rcv_size); if ((0 == rc) && (cb != NULL)) { cb(cb_arg, tmp_buf, (uint16_t)rcv_size); } return rc; }
YifuLiu/AliOS-Things
components/ulog/src/ulog_ring_fifo.c
C
apache-2.0
1,361
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include "ulog_session_file.h" #include <fcntl.h> #include <stdlib.h> #include <string.h> #include "aos/errno.h" #include "aos/kernel.h" #include "cJSON.h" #include "uagent.h" #include "ulog/ulog.h" #include "ulog_api.h" /** * record the log files operating. Recover(reset or get) in reload_log_argu() * used and count in write_log_line() */ static uint32_t operating_file_offset = 0; static uint32_t gu32_log_file_size = LOCAL_FILE_SIZE; static char guc_logfile_path[ULOG_FILE_PATH_SIZE / 2] = { 0 }; /** * indicates if log on fs feature initialized * */ static uint8_t session_fs_init = 0; static uint8_t log_file_failed = 0; #if ULOG_RESERVED_FS static char *ulog_fs_tmp[ULOG_RESERVED_FS_SIZE] = { NULL }; static uint16_t tmp_queue_in = 0; static uint16_t tmp_queue_out = 0; static void stop_operating(); static int push_fs_tmp(const char *data, const unsigned short len) { int rc = -1; if (NULL != data && len != 0 && ((tmp_queue_in + 1) % ULOG_RESERVED_FS_SIZE) != tmp_queue_out) { if (NULL == ulog_fs_tmp[tmp_queue_in]) { ulog_fs_tmp[tmp_queue_in] = (char *)aos_malloc(len + 1); if (NULL != ulog_fs_tmp[tmp_queue_in]) { memcpy(ulog_fs_tmp[tmp_queue_in], data, len); ulog_fs_tmp[tmp_queue_in][len] = '\0'; tmp_queue_in = (tmp_queue_in + 1) % ULOG_RESERVED_FS_SIZE; rc = 0; } } } return rc; } static int pop_fs_tmp(char *data, const unsigned short len) { int rc = -EINVAL; if (NULL != data && len != 0) { if (tmp_queue_in == tmp_queue_out) { rc = -1; } else { if (NULL != ulog_fs_tmp[tmp_queue_out]) { strncpy(data, ulog_fs_tmp[tmp_queue_out], len - 1); aos_free(ulog_fs_tmp[tmp_queue_out]); ulog_fs_tmp[tmp_queue_out] = NULL; tmp_queue_out = (tmp_queue_out + 1) % ULOG_RESERVED_FS_SIZE; rc = 0; } else { rc = -EIO; } } } return rc; } #endif #if ULOG_UPLOAD_LOG_FILE #include "httpclient.h" #include "sys/socket.h" static httpclient_t *httpc_handle = NULL; static char *up_uri = NULL; static bool http_client_initd = false; static int get_server_uri(const char *url, char **server, char **uri) { int rc = -1; if (NULL != url) { uint8_t pos = -1; if (0 == strncmp(url, URL_PREFIX_HTTP, strlen(URL_PREFIX_HTTP))) { pos = strlen(URL_PREFIX_HTTP); } else if (0 == strncmp(url, URL_PREFIX_HTTPS, strlen(URL_PREFIX_HTTPS))) { pos = strlen(URL_PREFIX_HTTPS); } if (pos > 0) { char *p = NULL; p = strchr(&url[pos], '/'); if (NULL != p) { p++; *server = (char *)aos_malloc(p - url + 1); if (NULL != *server) { memcpy(*server, url, p - url); (*server)[p - url] = '\0'; const short n = strlen(p); *uri = (char *)aos_malloc(n + 1); if (NULL != *uri) { memcpy(*uri, p, n); (*uri)[n] = '\0'; rc = 0; } else { aos_free(*server); *server = NULL; } } } } } return rc; } static void report_up_process(const http_upload_fail_t status, const char process, const ulog_idx_type idx) { cJSON *resp = cJSON_CreateObject(); if (NULL != resp) { char *text = NULL; cJSON_AddItemToObject(resp, "idx", cJSON_CreateNumber(idx)); if (status >= http_upload_start) { cJSON_AddItemToObject(resp, "process", cJSON_CreateNumber(process)); } else { cJSON_AddItemToObject(resp, "error", cJSON_CreateNumber(status)); } text = cJSON_PrintUnformatted(resp); cJSON_Delete(resp); uagent_send(UAGENT_MOD_ULOG, ULOG_LOG_LIST, strlen(text), text, send_policy_object); cJSON_free(text); } } int http_start(const char *url, const unsigned short idx) { int rc = -1; if (!http_client_initd) { http_client_initd = true; } if (httpc_handle == NULL) { LOGI(ULOG_TAG_SELF, "http start %s idx %d", url, idx); httpc_handle = (httpclient_t *)aos_malloc(sizeof(httpclient_t)); if (NULL != httpc_handle) { up_uri = (uint8_t *)aos_malloc(strlen(url)); if (NULL != up_uri) { strncpy(up_uri, url, strlen(url)); char buf[16]; snprintf(buf, 16, "up idx=%d", idx); rc = ulog_man(buf); } else { aos_free(httpc_handle); httpc_handle = NULL; } } else { LOGE(ULOG_TAG_SELF, "allock http connect instanse fail"); } } else { LOGE(ULOG_TAG_SELF, "Last upload not finish"); } return rc; } static uint8_t *rsp_buf = NULL; static uint8_t *req_buf = NULL; void on_fs_upload(const uint32_t idx, const uint32_t start) { if (get_working_from_cfg_mm() == idx) { on_fs_record_pause(1, 0); } int fd = open_log_file(idx, O_RDONLY, 0); http_upload_fail_t http_operate = http_upload_common_fail; if (fd >= 0) { char *customer_header = "Accept: text/xml,text/javascript,text/html,application/json\r\n"; httpclient_set_custom_header(httpc_handle, customer_header); char *upload_stream = (char *)aos_malloc(gu32_log_file_size + ULOG_SIZE); if (NULL != upload_stream) { int n = -1; n = aos_read(fd, upload_stream, gu32_log_file_size + ULOG_SIZE); if (0 < n) { char retry = HTTP_REQ_RETRY; httpclient_data_t client_data = { 0 }; rsp_buf = (uint8_t *)aos_malloc(RSP_BUF_SIZE); req_buf = (uint8_t *)aos_malloc(RSP_BUF_SIZE); if (rsp_buf != NULL && req_buf != NULL) { memset(req_buf, 0, sizeof(req_buf)); client_data.header_buf = req_buf; client_data.header_buf_len = sizeof(req_buf); memset(rsp_buf, 0, sizeof(rsp_buf)); client_data.response_buf = rsp_buf; client_data.response_buf_len = sizeof(rsp_buf); client_data.post_buf = upload_stream; client_data.post_buf_len = n; client_data.post_content_type = "text/plain"; while (HTTP_SUCCESS != httpclient_put(httpc_handle, up_uri, &client_data)) { if (--retry <= 0) { break; } else { LOGW(ULOG_TAG_SELF, "fs rqst %d fail", n); aos_msleep(1000); } } if (retry > 0) { http_operate = http_upload_finish; } else { http_operate = http_upload_memory_fail; } } } else { http_operate = http_upload_text_empty; LOGW(ULOG_TAG_SELF, "nothing read"); } aos_free(upload_stream); } else { http_operate = http_upload_memory_fail; LOGE(ULOG_TAG_SELF, "allocate file fail"); } } else { LOGE(ULOG_TAG_SELF, "http construct header fail"); } aos_close(fd); report_up_process(http_operate, http_operate == http_upload_finish ? 100 : 0, idx); httpclient_clse(httpc_handle); aos_free(rsp_buf); rsp_buf = NULL; aos_free(req_buf); req_buf = NULL; aos_free(up_uri); up_uri = NULL; aos_free(httpc_handle); httpc_handle = NULL; /* try re-start record, no impact even the record no abort before */ on_fs_record_pause(0, 1); } #endif /** * * Check if file already exist * * @param file_idx file index to be checked * @return true indicats it is existed, or else not. */ static bool log_file_exist(const uint16_t file_idx) { bool rc = false; char ulog_file_name[ULOG_FILE_PATH_SIZE] = { 0 }; int fd = -1; if (file_idx <= LOCAL_FILE_CNT) { snprintf(ulog_file_name, sizeof(ulog_file_name), ULOG_FILE_FORMAT, guc_logfile_path, file_idx); fd = aos_open(ulog_file_name, (O_RDWR | O_CREAT | O_EXCL) #ifdef CSP_LINUXHOST , 0644 #endif ); SESSION_FS_DEBUG("check if file %s exist %d\n", ulog_file_name, fd); if (fd < 0) { #ifdef CSP_LINUXHOST if (EEXIST == errno) { SESSION_FS_DEBUG("file %s alreay exist\n", ulog_file_name); rc = true; } #else /* !CSP_LINUXHOST */ if (fd == -EEXIST) { SESSION_FS_DEBUG("file %s alreay exist\n", ulog_file_name); rc = true; } #endif /* CSP_LINUXHOST */ } else { /*TODO:why not close*/ aos_close(fd); aos_unlink(ulog_file_name); } } return rc; } static int open_create_log_file(const ulog_idx_type file_idx, const bool keep_open) { int fd = -1; char ulog_file_name[ULOG_FILE_PATH_SIZE] = { 0 }; snprintf(ulog_file_name, sizeof(ulog_file_name), ULOG_FILE_FORMAT, guc_logfile_path, file_idx); SESSION_FS_DEBUG("open create log %s\n", ulog_file_name); aos_unlink(ulog_file_name); fd = aos_open(ulog_file_name, (O_RDWR | O_CREAT | O_TRUNC) #ifdef CSP_LINUXHOST , 0644 #endif ); if (fd >= 0) { if (!keep_open) { aos_close(fd); } } else { SESSION_FS_INFO("open create file %s fail fd %d, errno %d\n", ulog_file_name, fd, errno); } return fd; } int open_log_file(const ulog_idx_type file_idx, int flag, const off_t off) { int fd = -1; char ulog_file_name[ULOG_FILE_PATH_SIZE]; memset(ulog_file_name, 0, sizeof(ulog_file_name)); snprintf(ulog_file_name, sizeof(ulog_file_name), ULOG_FILE_FORMAT, guc_logfile_path, file_idx); fd = aos_open(ulog_file_name, flag); if (fd >= 0) { const int seek_off = aos_lseek(fd, off, SEEK_SET); if (seek_off != off) { SESSION_FS_INFO("seek fail %s %d\n", ulog_file_name, seek_off); aos_close(fd); fd = -1; } } else { SESSION_FS_INFO("open %s flag %d fail fd %d\n", ulog_file_name, flag, fd); } return fd; } /** * * Copies one line from file_instanse into buf, On sucessful the destination buf * buf is changed into NULL terminated C String. If log content size is longer * than buf_len-1, remain will be not saved and NULL terminatated is implicitly * appended at the end of destination. * * @param file_instanse file description from aos_open() before * @param buf local buffer use for saved, ZERO format is not MUST * @param buf_len buffer size * @return actual log text length readed in argumenent buf; * '\n',' is counted. Expected value: 1~buf_len-1 * 0 indicates EOF of the file, buf_len indicates the possible passing * value is limited to read the whole line. */ int get_log_line(const int fd, char *buf, const uint16_t buf_len) { int rc = -1; int cnt = 0; if (fd < 0 || NULL == buf || buf_len <= 0) { return -1; } memset(buf, 0, buf_len); while ((cnt < buf_len) && (0 < aos_read(fd, &buf[cnt], 1))) { if (buf[cnt] == LOG_LINE_SEPARATOR) { break; } cnt++; } if (cnt == 0) { /* Nothing read, this is an empty file */ rc = 0; } else if (cnt < buf_len) { if (buf[cnt - 1] == LOG_LINE_SEPARATOR) { /* replacement/end with null terminated */ buf[cnt - 1] = 0; } else { buf[cnt] = 0; } rc = cnt; } else { /* cnt == buf_len */ /* two possible result */ /* buffer len is just fit */ /* buffer is not sufficient to save whole line, last characher will be missed and replace of null-terminated */ rc = cnt; /* replacement with null terminated */ buf[cnt - 1] = 0; } return rc; } /** * * Write one line into specify log file, which instance is file_instanse. Append * a LOG_LINE_SEPARATOR after log context to separate logs * * @param file_instanse file description from aos_open() before * @param buf local buffer use for write * @param keep_open keep opening after write finished * @param operating indicates the rolling-back mechanism used. * @return actual writen text length(includes length of LOG_LINE_SEPARATOR). * -EINVAL indicates parameter illegal, other value indicates call * aos_write failure */ int write_log_line(const int file_instanse, const char *buf, const bool keep_open) { int rtn = -EINVAL; if (file_instanse >= 0 && buf != NULL) { int rc = -1; rtn = aos_write(file_instanse, buf, strlen(buf)); if (rtn > 0) { rc = aos_write(file_instanse, LOG_LINE_END_STR, 1); if (1 == rc) { rtn++; } else { rtn = rc; } aos_sync(file_instanse); } else { SESSION_FS_INFO("write fail rc %d\n", rtn); } if (!keep_open) { aos_close(file_instanse); } } return rtn; } /** * * Refresh ulog cfg item and saved in cfg file, also create the new ulog file * * * @return 0 indicates create new log file sucessfully, but not means update * config pass; -1 create new log file fail */ static int update_new_log_file(const ulog_idx_type idx) { int rc = -1; int fd = -1; if (0 == update_mm_cfg(ulog_cfg_type_working, idx, ulog_cfg_para_none, NULL)) { /* read it for test */ if (get_working_from_cfg_mm() == idx) { /* create log file */ if (open_create_log_file(idx, false) >= 0) { rc = 0; char time_start[24]; ulog_format_time(time_start, sizeof(time_start)); update_mm_cfg(ulog_cfg_type_list, idx, ulog_cfg_para_start, time_start); fd = open_create_log_file(ULOG_FILE_CFG_IDX, true); if (fd >= 0) { /* need update cfg file */ if (0 != cfg_mm_2_file(fd)) { /* sync to cfg file fail, have no impact unless the * board boot-up before it sync write */ SESSION_FS_INFO("sync to cfg file fail %d\n", fd); } aos_close(fd); } else { SESSION_FS_INFO("refresh ulog cfg fail fd %d\n", fd); } } else { SESSION_FS_INFO("sync to cfg file fail %d\n", fd); } } else { SESSION_FS_INFO("Fatal Error Operate ulog mm cfg\n"); } } else { SESSION_FS_INFO("Fatal Error update ulog mm cfg\n"); } return rc; } /** * * Reload log history arguments from ulog cfg file(ulog_000.log) in fs, * includes operating_file_idx & operating_file_offset. New ulog_000.log * will be created if none ulog_000.log found or text is illegal. * This is vital for ulog pop via fs, ulog pop via fs will be forbidden if * this step fail. * * return 0 if this step pass, else indicates this step fail * */ static int reload_log_argu() { int rc = -1; struct aos_stat st_logstat = { 0 }; char ulog_file_name[ULOG_FILE_PATH_SIZE] = { 0 }; ulog_idx_type tmp_idx = ULOG_FILE_IDX_INVALID; operating_file_offset = 0; if (log_file_exist(ULOG_FILE_CFG_IDX)) { /* ulog cfg exist, try to read it */ load_cfg_2_mm(); tmp_idx = get_working_from_cfg_mm(); SESSION_FS_INFO("[%s]log file idx %d\n", ULOG_TAG_SELF, tmp_idx); if (tmp_idx <= LOCAL_FILE_CNT) { snprintf(ulog_file_name, sizeof(ulog_file_name), ULOG_FILE_FORMAT, guc_logfile_path, tmp_idx); rc = aos_stat(ulog_file_name, &st_logstat); if (rc == 0) { operating_file_offset += st_logstat.st_size; } else { /* no such log file exist, then create it */ rc = update_new_log_file(tmp_idx); } } } if (LOCAL_FILE_CNT < tmp_idx) { rc = update_new_log_file(ULOG_FILE_IDX_START); } return rc; } void on_show_ulog_file() { aos_dir_t *dp; SESSION_FS_INFO("log files in %s\n", guc_logfile_path); dp = (aos_dir_t *)aos_opendir(guc_logfile_path); if (dp != NULL) { aos_dirent_t *out_dirent; while (1) { out_dirent = (aos_dirent_t *)aos_readdir(dp); if (out_dirent != NULL) { SESSION_FS_INFO("file name is %s\n", out_dirent->d_name); } else { break; } } } aos_closedir(dp); } static void stop_operating() { char time_stop[24]; ulog_format_time(time_stop, sizeof(time_stop)); update_mm_cfg(ulog_cfg_type_list, get_working_from_cfg_mm(), ulog_cfg_para_end, time_stop); } static void write_fail_retry() { int8_t retry = ULOG_FILE_FAIL_COUNT; char log_file_name[ULOG_FILE_PATH_SIZE]; char buf[ULOG_SIZE]; log_file_failed++; if (log_file_failed >= ULOG_FILE_FAIL_COUNT) { snprintf(log_file_name, ULOG_FILE_PATH_SIZE, ULOG_FILE_FORMAT, guc_logfile_path, get_working_from_cfg_mm()); while (0 != aos_unlink(log_file_name)) { if (--retry <= 0) { SESSION_FS_INFO("file %s error on remove, retry %d\n", log_file_name, retry); break; } } if (retry > 0) { SESSION_FS_INFO("remove file %s, then create new one %d\n", log_file_name, get_working_from_cfg_mm()); if (0 == update_new_log_file(get_working_from_cfg_mm())) { #if ULOG_RESERVED_FS memset(buf, 0, ULOG_SIZE); while (0 == pop_fs_tmp(buf, ULOG_SIZE)) { pop_out_on_fs(buf, strlen(buf)); memset(buf, 0, ULOG_SIZE); } #endif /* ULOG_RESERVED_FS */ } } } } /** * @brief not thread-safe, but only be used in one task(ulog), so not necessary * considering mutex * @param data * @param len * * @return -1 indicates not send out sucessfully * */ int32_t pop_out_on_fs(const char *data, const uint16_t len) { int32_t rc = -1; int fd = 0; int write_rlt = 0; ulog_idx_type idx = ULOG_FILE_IDX_INVALID; idx = get_working_from_cfg_mm(); if (idx > LOCAL_FILE_CNT) { SESSION_FS_INFO("fail to get working log file idx %d update working cfg\n", idx); rc = reload_log_argu(); if (rc < 0) { SESSION_FS_INFO("fail to pop log to fs for reload log cfg fail \n"); return -1; } /*this time idx will be fine not need to check*/ idx = get_working_from_cfg_mm(); } fd = open_log_file(idx, O_CREAT | O_WRONLY, operating_file_offset); if (fd < 0) { SESSION_FS_INFO( "fail to pop log to fs for open working log file %d offset fail %d " "\n", idx, operating_file_offset, errno); rc = -1; #if ULOG_RESERVED_FS rc = push_fs_tmp(data, len); if (0 != rc) { SESSION_FS_INFO("*(%d)", rc); } return rc; #endif } write_rlt = write_log_line(fd, data, true); aos_sync(fd); aos_close(fd); if (write_rlt < 0) { SESSION_FS_INFO("write fail %d retry %d\n", write_rlt, log_file_failed); rc = -1; #if ULOG_RESERVED_FS /* save them temporary */ rc = push_fs_tmp(data, len); if (0 != rc) { SESSION_FS_INFO("*(%d)", rc); } #endif /* ULOG_RESERVED_FS */ /* check fail count */ write_fail_retry(); return rc; } log_file_failed = 0; operating_file_offset += write_rlt; if (operating_file_offset >= gu32_log_file_size) { stop_operating(); /* roll back if working index reaches end */ idx++; if (idx > LOCAL_FILE_CNT) { idx = ULOG_FILE_IDX_START; } operating_file_offset = 0; rc = update_new_log_file(idx); if (rc) { SESSION_FS_INFO("creat new log file %d fail %d in pop to fs\n", idx, rc); } } return 0; } void on_fs_record_pause(const uint32_t on, const uint32_t off) { if ((on ^ off) == 0) { return; } SESSION_FS_INFO(ULOG_TAG_SELF, "ulog fs ctrl on %d off %d\n", on, off); if (1 == on) { stop_operating(); } else { /* resume the file record */ if (0 == reload_log_argu()) { LOGI(ULOG_TAG_SELF, "reload ulog idx %d off %d", get_working_from_cfg_mm(), operating_file_offset); #if ULOG_RESERVED_FS char buf[ULOG_SIZE]; memset(buf, 0, ULOG_SIZE); while (0 == pop_fs_tmp(buf, ULOG_SIZE)) { pop_out_on_fs(buf, strlen(buf)); memset(buf, 0, ULOG_SIZE); } #endif } else { LOGE(ULOG_TAG_SELF, "restart ulog fs fail"); } } } void fs_control_cli(const char cmd, const char *param) { if (param != NULL) { switch (cmd) { case 't': { int control_cmd = strtoul(param, NULL, 10); if (control_cmd) { ulog_man("fspause on=1"); } else { ulog_man("fspause off=1"); } break; } default: break; } } } #if ULOG_POP_FS_ENABLE int ulog_fs_log_file_size(unsigned int filesize) { if (filesize < ULOG_SIZE) { return -1; } gu32_log_file_size = filesize; return 0; } int ulog_fs_log_file_path(char *filepath) { size_t len = 0; size_t max_len = 0; int ret = 0; aos_dir_t *pstdir = NULL; bool is_last_char_slash = false; if (NULL == filepath) { return -1; } len = strlen(filepath); /*we need to reserve one byte for /0 and one byte for / */ max_len = (ULOG_FILE_PATH_SIZE / 2) - 1; if (len > max_len) { SESSION_FS_INFO("log file path length %d over size %d", len, max_len - 1); return -1; } memset(guc_logfile_path, 0, sizeof(guc_logfile_path)); memcpy(guc_logfile_path, filepath, len); /*remove / at first to make dir ,then and / */ is_last_char_slash = (filepath[len - 1] == '/'); if (is_last_char_slash) { guc_logfile_path[len - 1] = 0; } /*check logfile path exist */ pstdir = aos_opendir(guc_logfile_path); if (NULL == pstdir) { /*log file path doesn't exist , creat it*/ ret = aos_mkdir(guc_logfile_path); if (ret) { SESSION_FS_INFO("%s %d log dir path %s doesn't exist and mkdir fail %d \r\n", __FILE__, __LINE__, guc_logfile_path, ret); goto finish; } } else { aos_closedir(pstdir); } finish: /*and / for log file process*/ if (is_last_char_slash) { guc_logfile_path[len - 1] = '/'; } return ret; } #endif /** * @brief ulog on fs init * * @return 0 indicates initialized sucessfully, or else fail * */ int32_t ulog_fs_init() { int32_t rc = -1; if (0 == session_fs_init) { session_fs_init = 1; cfg_init_mutex(); ulog_fs_log_file_path(ULOG_DEAULT_FS_PATH); rc = reload_log_argu(); if (rc == 0) { SESSION_FS_INFO("reload ulog idx %d len %d \n", get_working_from_cfg_mm(), operating_file_offset); } } return rc; }
YifuLiu/AliOS-Things
components/ulog/src/ulog_session_file.c
C
apache-2.0
24,094
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include "ulog_api.h" #include "ulog/ulog.h" #if ULOG_POP_UDP_ENABLE #include <string.h> #include <stdlib.h> #include "sys/socket.h" #include "aos/kernel.h" static struct sockaddr_in* syslog_watcher_addr = NULL; static int32_t syslog_watcher_fd = -1; static uint16_t syslog_watcher_port = SYSLOG_WATCHER_DEFAULT_PORT; static uint32_t syslog_watcher_ip_nl = 0x0100007F; static bool tcpip_service_on = false; /* We have to use sync debug to debug async debug .... */ /* #define SESSION_UDP_INFO printf */ #define SESSION_UDP_INFO(...) /** * @brief update address for log pop out via udp * prototype is align to the ulog service mapping(refer ulog_man_handler_service) * @param ip_d ip address of syslog listener, if input 0 then former ip used, MUST BE network byte order * @param port port of syslog listener, is 0 input then before port used. Default is syslog standard 514 used * * @return n.a. * */ void on_update_syslog_watcher_addr(const uint32_t ip_nl, const uint32_t port) { if (syslog_watcher_addr == NULL) { syslog_watcher_addr = (struct sockaddr_in*)aos_malloc(sizeof(struct sockaddr_in)); } if (syslog_watcher_addr != NULL) { memset(syslog_watcher_addr, 0, sizeof(struct sockaddr_in)); syslog_watcher_addr->sin_family = AF_INET; if (0xFFFF != (port & 0xFFFF)) { syslog_watcher_port = port; SESSION_UDP_INFO("ulog port %d\n", syslog_watcher_port); } syslog_watcher_addr->sin_port = syslog_watcher_port; if (-1 != ip_nl && 0 != ip_nl) { syslog_watcher_ip_nl = ip_nl; SESSION_UDP_INFO("ulog ip %s\n", inet_ntoa(*(struct in_addr *)(&syslog_watcher_ip_nl))); } syslog_watcher_addr->sin_addr.s_addr = syslog_watcher_ip_nl; SESSION_UDP_INFO("ulog udp ip %s ort %d \r\n", inet_ntoa(*(struct in_addr *)(&syslog_watcher_addr->sin_addr.s_addr)), syslog_watcher_addr->sin_port); } } /** * @brief hook function which used notice this module that the tcpip is ready for use * not thread-safe, but only be used in one task(ulog), so not necessary considering mutex. * prototype is align to the ulog service mapping(refer ulog_man_handler_service) * @param on * @param off * * @return n.a. * */ void on_tcpip_service_on(const uint32_t on, const uint32_t off) { if (on == -1 && off == 1) { /*means turn off syslog pop out*/ tcpip_service_on = false; if (syslog_watcher_fd != -1) { close(syslog_watcher_fd); syslog_watcher_fd = -1; } } else if (on == 1 && off == -1) { /*means turn on syslog pop out*/ if (NULL == syslog_watcher_addr) { SESSION_UDP_INFO("fail to turn on syslog pop out for syslog server ip info haven't set yet\n"); return; } if (syslog_watcher_fd != -1) { SESSION_UDP_INFO("syslog pop out have already started socket\n"); } else { syslog_watcher_fd = socket(AF_INET, SOCK_DGRAM, 0); SESSION_UDP_INFO("ulog sys log socket %d\n", syslog_watcher_fd); } tcpip_service_on = true; } else { SESSION_UDP_INFO("ulog sys log start invalid param on %d, off %d\n", on, off); } } /** * @brief not thread-safe, but only be used in one task(ulog), so not necessary considering mutex * @param data * @param len * * @return -1 indicates not send out sucessfully * */ int32_t pop_out_on_udp(const char* data, const uint16_t len) { int32_t ret = -1; if (tcpip_service_on && syslog_watcher_fd >= 0) { ret = sendto(syslog_watcher_fd, data, len, 0, (struct sockaddr *)syslog_watcher_addr, sizeof(struct sockaddr)); } return ret; } void update_net_cli(const char cmd, const char* param) { struct in_addr listen_addr; uint16_t listen_port = 0x0; char buf[24] = {0}; if (param != NULL) { switch (cmd) { case 'a': { inet_aton(param, &listen_addr); snprintf(buf, 24, "listen ip=%u", listen_addr.s_addr); SESSION_UDP_INFO("%s %d ulog set syslog server ip addr %s \r\n", __FILE__, __LINE__, buf); ulog_man(buf); } break; case 'p': { listen_port = strtoul(param, NULL, 10); snprintf(buf, 24, "listen port=%d", listen_port); SESSION_UDP_INFO("%s %d ulog set syslog server ip port %s \r\n", __FILE__, __LINE__, buf); ulog_man(buf); } break; case 'n': { snprintf(buf, 24, "tcpip %s", param); SESSION_UDP_INFO("%s %d ulog set network swtich %s \r\n", __FILE__, __LINE__, buf); ulog_man(buf); } break; default: break; } } } #endif
YifuLiu/AliOS-Things
components/ulog/src/ulog_session_udp.c
C
apache-2.0
4,869
/* * Copyright (C) 2015-2019 Alibaba Group Holding Limited */ #include <string.h> #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <time.h> #include "ulog/ulog.h" #include "ulog_api.h" #include "aos/kernel.h" #include "aos/errno.h" #include "ulog_ring_fifo.h" #if SYSLOG_TIME_FORMAT static const char months[][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; #endif static aos_mutex_t log_mutex; /* log init mutex */ void log_init_mutex(void) { aos_mutex_new(&log_mutex); } bool log_get_mutex() { return 0 == aos_mutex_lock(&log_mutex, AOS_WAIT_FOREVER); } void log_release_mutex() { aos_mutex_unlock(&log_mutex); } /* result like 99.356 ,i.e. s.ms */ /* Result is like "Nov 28 15:19:20.122" */ char *ulog_format_time(char *buffer, const int len) { if(NULL!=buffer && len>4) { long long ms = aos_now_ms(); #if SYSLOG_TIME_FORMAT time_t rawtime; time(&rawtime); struct tm *tm = localtime(&rawtime); /* %b format of strftime() is platform-dependent, so we realized it by-self */ snprintf(buffer, len, "%s ", months[tm->tm_mon < 12 ? tm->tm_mon : 0]); strftime(&buffer[4], len - 4, "%d %H:%M:%S", tm); const int32_t milli = ms % 1000; char ms_str[8] = ""; memset(ms_str, 0, sizeof(ms_str)); snprintf(ms_str, sizeof(ms_str), ".%03d", milli); strncat(buffer, ms_str, len - strlen(buffer) - 1); #else /* !SYSLOG_TIME_FORMAT */ snprintf(buffer, len, "%4d.%03d", (int)(ms / 1000), (int)(ms % 1000)); #endif /* SYSLOG_TIME_FORMAT */ } return buffer; } char* trim_file_path(const char* path) { #if SYNC_ABS_PATH return path; #else char* filename = (char*)path; if (path != NULL) { if ((filename = strrchr(path, '/')) != NULL) { filename++; } } if (filename != NULL) { const size_t filename_len = strlen(filename); if (filename_len > 0) { if (filename_len > TAG_FILE_NAME_MAX_LEN) { /* trig it using last 32 string */ filename += filename_len - TAG_FILE_NAME_MAX_LEN; } } else { /* cannot get file name if input path is like "/d/timer/" */ filename = UNDEFINE_FILE_NAME; } } else { /* using UNDEFINE_FILE_NAME */ filename = UNDEFINE_FILE_NAME; } return filename; #endif } int ulog_man(const char* cmd_str) { #if ULOG_CONFIG_ASYNC int rc = -EINVAL; if (NULL != cmd_str && strlen(cmd_str) > 0) { rc = -EPERM; if (aos_ulog_init) { const uint16_t cmd_str_size = strlen(cmd_str) + strlen(ULOG_CMD_PREFIX) + 1; char* tmpbuf = (char*)aos_malloc(cmd_str_size); strncpy(tmpbuf, ULOG_CMD_PREFIX, cmd_str_size); strncat(tmpbuf, cmd_str, cmd_str_size - strlen(ULOG_CMD_PREFIX) - 1); rc = uring_fifo_push_s(tmpbuf, cmd_str_size); aos_free(tmpbuf); } } #else /*!ULOG_CONFIG_ASYNC */ int rc = -EACCES; #endif return rc; }
YifuLiu/AliOS-Things
components/ulog/src/ulog_utility.c
C
apache-2.0
3,140
Import('defconfig') defconfig.library_yaml()
YifuLiu/AliOS-Things
components/uservice/SConscript
Python
apache-2.0
45
#include "dm_export.h" #include <uservice/uservice.h> #include <uservice/eventid.h> SYMBOL_EXPORT(event_service_init); SYMBOL_EXPORT(event_subscribe);
YifuLiu/AliOS-Things
components/uservice/export.c
C
apache-2.0
153
/* * Copyright (C) 2019-2020 Alibaba Group Holding Limited */ #ifndef YOC_USERVICE_EVENT_H #define YOC_USERVICE_EVENT_H #include <stdint.h> #ifdef __cplusplus extern "C" { #endif typedef void (*event_callback_t)(uint32_t event_id, const void *data, void *context); #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
components/uservice/include/uservice/event.h
C
apache-2.0
308
/* * Copyright (C) 2019-2020 Alibaba Group Holding Limited */ #ifndef YOC_EVENT_ID_H #define YOC_EVENT_ID_H #include "event.h" #ifdef __cplusplus extern "C" { #endif /* net driver event * from 0x100 to 0x1FF * netdrv.h */ /* Netmgr */ #define EVENT_NETMGR_BASE 0x01000 #define EVENT_NETMGR_WIFI_DISCONNECTED (EVENT_NETMGR_BASE + 1) // Connection disconected #define EVENT_NETMGR_WIFI_SCAN_STARTED (EVENT_NETMGR_BASE + 2) // Scan start #define EVENT_NETMGR_WIFI_SCAN_FAILED (EVENT_NETMGR_BASE + 3) // Scan failed #define EVENT_NETMGR_WIFI_SCAN_DONE (EVENT_NETMGR_BASE + 4) // Scan failed #define EVENT_NETMGR_WIFI_NETWORK_NOT_FOUND (EVENT_NETMGR_BASE + 5) // no AP found #define EVENT_NETMGR_WIFI_AUTHENTICATING (EVENT_NETMGR_BASE + 6) // Authentication start #define EVENT_NETMGR_WIFI_AUTH_REJECT (EVENT_NETMGR_BASE + 7) // Authentication rejected by AP #define EVENT_NETMGR_WIFI_AUTH_TIMEOUT (EVENT_NETMGR_BASE + 8) // Authentication timeout with AP #define EVENT_NETMGR_WIFI_ASSOCIATING (EVENT_NETMGR_BASE + 9) // Association starts #define EVENT_NETMGR_WIFI_ASSOC_REJECT (EVENT_NETMGR_BASE + 10) // Association rejected by AP #define EVENT_NETMGR_WIFI_ASSOC_TIMEOUT (EVENT_NETMGR_BASE + 11) // Association timeout with AP #define EVENT_NETMGR_WIFI_ASSOCIATED (EVENT_NETMGR_BASE + 12) // Authentication succeed #define EVENT_NETMGR_WIFI_4WAY_HANDSHAKE (EVENT_NETMGR_BASE + 13) // 4way-handshark start #define EVENT_NETMGR_WIFI_HANDSHAKE_FAILED (EVENT_NETMGR_BASE + 14) // 4way-handshake fails #define EVENT_NETMGR_WIFI_4WAY_HANDSHAKE_DONE (EVENT_NETMGR_BASE + 15) // 4way-handshark done #define EVENT_NETMGR_WIFI_GROUP_HANDSHAKE (EVENT_NETMGR_BASE + 16) // group-handshark start #define EVENT_NETMGR_WIFI_GROUP_HANDSHAKE_DONE (EVENT_NETMGR_BASE + 17) // group-handshark done = completed #define EVENT_NETMGR_WIFI_CONNECTED (EVENT_NETMGR_BASE + 18) // Connection to AP done #define EVENT_NETMGR_WIFI_CONN_TIMEOUT (EVENT_NETMGR_BASE + 19) // Connection timeout #define EVENT_NETMGR_WIFI_DEAUTH (EVENT_NETMGR_BASE + 20) // Deauth received from AP #define EVENT_NETMGR_WIFI_MAX (EVENT_NETMGR_WIFI_DEAUTH) #define EVENT_NETMGR_DHCP_BASE (EVENT_NETMGR_WIFI_MAX) #define EVENT_NETMGR_DHCP_START_FAILED (EVENT_NETMGR_DHCP_BASE + 1) // DHCP start fails #define EVENT_NETMGR_DHCP_TIMEOUT (EVENT_NETMGR_DHCP_BASE + 2) // DHCP timeout #define EVENT_NETMGR_DHCP_SUCCESS (EVENT_NETMGR_DHCP_BASE + 3) // DHCP success #define EVENT_NETMGR_DHCP_MAX (EVENT_NETMGR_DHCP_SUCCESS) #define EVENT_NETMGR_SNTP_BASE (EVENT_NETMGR_DHCP_MAX) #define EVENT_NETMGR_SNTP_SUCCESS (EVENT_NETMGR_SNTP_BASE + 1) // SNTP success #define EVENT_NETMGR_SNTP_FAILED (EVENT_NETMGR_SNTP_BASE + 2 ) // SNTP failure #define EVENT_NETMGR_SNTP_MAX (EVENT_NETMGR_SNTP_FAILED) #define EVENT_NETMGR_CONN_BASE (EVENT_NETMGR_SNTP_MAX) #define EVENT_NETMGR_CONN_RECONNECT (EVENT_NETMGR_CONN_BASE + 1) // Reconnect AP #define EVENT_NETMGR_CONN_MAX (EVENT_NETMGR_CONN_RECONNECT) #define EVENT_NETMGR_GOT_IP (EVENT_NETMGR_DHCP_SUCCESS) #define EVENT_NETMGR_NET_BASE (EVENT_NETMGR_CONN_MAX) #define EVENT_NETMGR_NET_DISCON (EVENT_NETMGR_WIFI_DISCONNECTED) #define EVENT_NETMGR_NET_CONFIG (EVENT_NETMGR_NET_BASE + 1) #define EVENT_NETMGR_MAX (EVENT_NETMGR_NET_CONFIG) /* NET */ #define EVENT_NET_GOT_IP 0x100 /* Wi-Fi */ #define EVENT_WIFI_BASE (EVENT_NETMGR_MAX) #define EVENT_WIFI_DISCONNECTED (EVENT_WIFI_BASE + 1) // Connection disconected #define EVENT_WIFI_SCAN_STARTED (EVENT_WIFI_BASE + 2) // Scan start #define EVENT_WIFI_SCAN_FAILED (EVENT_WIFI_BASE + 3) // Scan failed #define EVENT_WIFI_SCAN_DONE (EVENT_WIFI_BASE + 4) // Scan failed #define EVENT_WIFI_NETWORK_NOT_FOUND (EVENT_WIFI_BASE + 5) // no AP found #define EVENT_WIFI_AUTHENTICATING (EVENT_WIFI_BASE + 6) // Authentication start #define EVENT_WIFI_AUTH_REJECT (EVENT_WIFI_BASE + 7) // Authentication rejected by AP #define EVENT_WIFI_AUTH_TIMEOUT (EVENT_WIFI_BASE + 8) // Authentication timeout with AP #define EVENT_WIFI_ASSOCIATING (EVENT_WIFI_BASE + 9) // Association starts #define EVENT_WIFI_ASSOC_REJECT (EVENT_WIFI_BASE + 10) // Association rejected by AP #define EVENT_WIFI_ASSOC_TIMEOUT (EVENT_WIFI_BASE + 11) // Association timeout with AP #define EVENT_WIFI_ASSOCIATED (EVENT_WIFI_BASE + 12) // Authentication succeed #define EVENT_WIFI_4WAY_HANDSHAKE (EVENT_WIFI_BASE + 13) // 4way-handshark start #define EVENT_WIFI_HANDSHAKE_FAILED (EVENT_WIFI_BASE + 14) // 4way-handshake fails #define EVENT_WIFI_4WAY_HANDSHAKE_DONE (EVENT_WIFI_BASE + 15) // 4way-handshark done #define EVENT_WIFI_GROUP_HANDSHAKE (EVENT_WIFI_BASE + 16) // group-handshark start #define EVENT_WIFI_GROUP_HANDSHAKE_DONE (EVENT_WIFI_BASE + 17) // group-handshark done = completed #define EVENT_WIFI_CONNECTED (EVENT_WIFI_BASE + 18) // Connection to AP done #define EVENT_WIFI_CONN_TIMEOUT (EVENT_WIFI_BASE + 19) // Connection timeout #define EVENT_WIFI_DEAUTH (EVENT_WIFI_BASE + 20) // Deauth received from AP #define EVENT_WIFI_AP_UP (EVENT_WIFI_BASE + 21) // AP UP #define EVENT_WIFI_AP_DOWN (EVENT_WIFI_BASE + 22) // AP DOWN #define EVENT_WIFI_MAX (EVENT_WIFI_AP_DOWN) #define EVENT_DHCP_BASE (EVENT_WIFI_MAX) #define EVENT_DHCP_START_FAILED (EVENT_DHCP_BASE + 1) // DHCP start fails #define EVENT_DHCP_TIMEOUT (EVENT_DHCP_BASE + 2) // DHCP timeout #define EVENT_DHCP_SUCCESS (EVENT_DHCP_BASE + 3) // DHCP success #define EVENT_DHCP_MAX (EVENT_DHCP_SUCCESS) #define EVENT_SNTP_BASE (EVENT_DHCP_MAX) #define EVENT_SNTP_SUCCESS (EVENT_SNTP_BASE + 1) // SNTP success #define EVENT_SNTP_FAILED (EVENT_SNTP_BASE + 2) // SNTP failure #define EVENT_SNTP_MAX (EVENT_SNTP_FAILED) #define EVENT_CONN_BASE (EVENT_SNTP_MAX) #define EVENT_CONN_RECONNECT (EVENT_CONN_BASE + 1) // Reconnect AP #define EVENT_CONN_MAX (EVENT_CONN_RECONNECT) /* IOT */ #define EVENT_IOT_BASE (EVENT_CONN_MAX) #define EVENT_IOT_CONNECT_SUCCESS (EVENT_IOT_BASE + 1) #define EVENT_IOT_CONNECT_FAILED (EVENT_IOT_BASE + 2) #define EVENT_IOT_DISCONNECTED (EVENT_IOT_BASE + 3) #define EVENT_IOT_PUSH_SUCCESS (EVENT_IOT_BASE + 4) #define EVENT_IOT_PUSH_FAILED (EVENT_IOT_BASE + 5) #define EVENT_IOT_MAX (EVENT_IOT_PUSH_FAILED) /* OS */ #define EVENT_OS_BASE (EVENT_IOT_MAX) #define EVENT_OS_REBOOT (EVENT_OS_BASE + 1) #define EVENT_CLOCK_ALARM (EVENT_OS_BASE + 2) #define EVENT_CLOCK_TIMEOUT (EVENT_OS_BASE + 3) #define EVENT_OS_MAX (EVENT_CLOCK_TIMEOUT) /* FOTA */ #define EVENT_FOTA_BASE (EVENT_OS_MAX) #define EVENT_FOTA_START (EVENT_FOTA_BASE + 1) #define EVENT_FOTA_UPDATE (EVENT_FOTA_BASE + 2) #define EVENT_FOTA_MAX (EVENT_FOTA_UPDATE) /* BLE */ #define EVENT_BLE_BASE (EVENT_FOTA_MAX) #define EVENT_BLE (EVENT_BLE_BASE + 1) #define EVENT_BLE_MESH (EVENT_BLE_BASE + 2) #define EVENT_BLE_MAX (EVENT_BLE_MESH) /* USER */ #define EVENT_USER_BASE (EVENT_BLE_MAX) #define EVENT_USER (EVENT_BLE_BASE + 1) #define EVENT_USER_MAX (EVENT_USER) /* ETHERNET */ #define EVENT_ETHERNET_BASE (EVENT_USER_MAX) #define EVENT_ETHERNET_LINK_UP (EVENT_ETHERNET_BASE + 1) #define EVENT_ETHERNET_DHCP_SUCCESS (EVENT_ETHERNET_BASE + 2) #define EVENT_ETHERNET_LINK_DOWN (EVENT_ETHERNET_BASE + 3) #define EVENT_ETHERNET_MAX (EVENT_ETHERNET_LINK_DOWN) #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
components/uservice/include/uservice/eventid.h
C
apache-2.0
8,967
/* * Copyright (C) 2019-2020 Alibaba Group Holding Limited */ #ifndef YOC_USERVICE_H #define YOC_USERVICE_H #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <uservice/event.h> #ifdef __cplusplus extern "C" { #endif #define QUEUE_MSG_COUNT 8 typedef struct uservice uservice_t; typedef struct utask utask_t; typedef struct rpc_buffer rpc_buffer_t; /** * rpc_t - remote procedure call struct * * @srv: * @cmd_id: * @timeout_ms: * @data: */ typedef struct _rpc_t { uservice_t *srv; uint32_t cmd_id; rpc_buffer_t *data; } rpc_t; typedef int (*process_t)(void *context, rpc_t *rpc); typedef struct { int cmd_id; process_t process; } rpc_process_t; /** * rpc_init() - initialise a rpc * * This function initialise a rpc. Returns zero or a negative error code * * @rpc: the rpc to initialise, Cannot be an empty pointer. * @cmd_id: the rpc command id * @timeout_ms: the rpc call wait time. * >0: wait time (ms) * =0: is asynchronous rpc comamnd * =AOS_WAIT_FOREVER: is synchronous rpc command * * Returns: * %0 on success * -%ENOMEM when memory allocation fails. * -%EINVAL on an invalid param. * */ int rpc_init(rpc_t *rpc, int cmd_id, int timeout_ms); /** * rpc_put_reset - reset rpc data buffer * * This function destroy the rpc data buffer, and reset put status * * @rpc: the initialized rpc pointer, cannot be an empty pointer * */ void rpc_put_reset(rpc_t *rpc); /** * rpc_put_int - put integer value into the rpc * rpc_put_uint8 - put uint8_t value into the rpc * rpc_put_double - put double value into the rpc * rpc_put_point - put point value into the rpc * * @rpc: the initialized rpc pointer, cannot be an empty pointer * @v: the value * * Returns: * -%0 on success * -%ENOMEM when memory allocation fails. */ int rpc_put_int(rpc_t *rpc, int v); int rpc_put_uint8(rpc_t *rpc, uint8_t v); int rpc_put_double(rpc_t *rpc, double v); int rpc_put_point(rpc_t *rpc, const void *v); /** * rpc_put_buffer - put buffer into the rpc * * @rpc: the initialized rpc pointer, cannot be an empty pointer * @data: buffer pointer * @size: buffer memory size * * Returns: * -%0 on success * -%ENOMEM when memory allocation fails. * -%EINVAL on an invalid data or size, data is NULL or size is zero */ int rpc_put_buffer(rpc_t *rpc, const void *data, size_t size); /** * rpc_put_buffer - put string into the rpc * * @rpc: the initialized rpc pointer, cannot be an empty pointer * @str: string pointer * * Returns: * -%0 on success * -%ENOMEM when memory allocation fails. * -%EINVAL on an invalid str pointer */ int rpc_put_string(rpc_t *rpc, char *str); /** * rpc_get_reset - reset rpc data buffer * * This function destroy the rpc data buffer, and reset put status * * @rpc: the initialized rpc pointer, cannot be an empty pointer * */ void rpc_get_reset(rpc_t *rpc); /** * rpc_get_int - put integer value into the rpc * rpc_get_uint8 - put uint8_t value into the rpc * rpc_get_double - put double value into the rpc * rpc_get_string - put point value into the rpc * rpc_get_point * * @rpc: the initialized rpc pointer, cannot be an empty pointer * @v: the value * * Returns: * -%0 on success * -%ENOMEM when memory allocation fails. */ int rpc_get_int(rpc_t *rpc); uint8_t rpc_get_uint8(rpc_t *rpc); double rpc_get_double(rpc_t *rpc); char *rpc_get_string(rpc_t *rpc); void *rpc_get_point(rpc_t *rpc); void *rpc_get_buffer(rpc_t *rpc, int *count); void rpc_reply(rpc_t *rpc); void rpc_deinit(rpc_t *rpc); uservice_t *uservice_new(const char *name, process_t process_rpc, void *context); void uservice_destroy(uservice_t *srv); int uservice_call_sync(uservice_t *srv, int cmd, void *param, void *resp, size_t resp_size); int uservice_call_async(uservice_t *srv, int cmd, void *param, size_t param_size); int uservice_call(uservice_t *srv, rpc_t *rpc); void uservice_lock(uservice_t *srv); void uservice_unlock(uservice_t *srv); int uservice_process(void *context, rpc_t *rpc, const rpc_process_t rpcs[]); void uservice_subscribe(uservice_t *srv, uint32_t event_id); utask_t *utask_new(const char *name, size_t stack_size, int queue_length, int prio); void utask_destroy(utask_t *task); void utask_join(utask_t *task); void utask_add(utask_t *task, uservice_t *srv); void utask_remove(utask_t *task, uservice_t *srv); void utask_lock(utask_t *task); void utask_unlock(utask_t *task); void utask_set_softwdt_timeout(int ms); int event_service_init(utask_t *task); void event_subscribe(uint32_t event_id, event_callback_t cb, void *context); void event_unsubscribe(uint32_t event_id, event_callback_t cb, void *context); void event_publish(uint32_t event_id, void *data); void event_publish_delay(uint32_t event_id, void *data, int timeout_ms); void event_subscribe_fd(uint32_t fd, event_callback_t cb, void *context); void event_unsubscribe_fd(uint32_t fd, event_callback_t cb, void *context); void event_publish_fd(uint32_t fd, void *data, int sync); void tasks_debug(); #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
components/uservice/include/uservice/uservice.h
C
apache-2.0
5,173
/* * Copyright (C) 2019-2020 Alibaba Group Holding Limited */ #include <stdlib.h> #include <stdint.h> #include <string.h> #include <unistd.h> #include <aos/kernel.h> #include <uservice/event.h> #include <sys/select.h> #include "internal.h" #define FD_MASK (1UL << 31) typedef struct event { uint32_t event_id; slist_t sub_list; slist_t next; } event_t; typedef struct event_subscription { event_callback_t ecb; void *context; slist_t next; } event_subscription_t; static event_t *find_event(event_list_t *evlist, uint32_t event_id) { event_t *node; slist_for_each_entry(&evlist->events, node, event_t, next) { if (node->event_id == event_id) { return node; } } return NULL; } static event_subscription_t *find_event_sub(event_t *ev, event_callback_t cb, void *context) { event_subscription_t *node; slist_for_each_entry(&ev->sub_list, node, event_subscription_t, next) { if (node->ecb == cb && node->context == context) { return node; } } return NULL; } int eventlist_init(event_list_t *evlist) { aos_assert(evlist); memset(evlist, 0, sizeof(event_list_t)); slist_init(&evlist->events); if (aos_mutex_new(&evlist->mutex) != 0) { return -1; } return 0; } void eventlist_uninit(event_list_t *evlist) { aos_assert(evlist); event_t *node; slist_t *tmp_1; aos_mutex_lock(&evlist->mutex, AOS_WAIT_FOREVER); slist_for_each_entry_safe(&evlist->events, tmp_1, node, event_t, next) { event_subscription_t *node_sub; slist_t *tmp_2; slist_for_each_entry_safe(&node->sub_list, tmp_2, node_sub, event_subscription_t, next) { slist_del(&node_sub->next, &node->sub_list); aos_free(node_sub); } slist_del(&node->next, &evlist->events); aos_free(node); } aos_mutex_unlock(&evlist->mutex); aos_mutex_free(&evlist->mutex); } static int __yoc_event_subscribe(event_list_t *evlist, uint32_t event_id, event_callback_t cb, void *context) { int ret = -1; aos_mutex_lock(&evlist->mutex, AOS_WAIT_FOREVER); event_t *ev = find_event(evlist, event_id); if (ev == NULL) { ev = (event_t *)aos_zalloc(sizeof(event_t)); if (ev != NULL) { ev->event_id = event_id; slist_init(&ev->sub_list); slist_add(&ev->next, &evlist->events); } } if (ev != NULL) { event_subscription_t *e_sub; e_sub = find_event_sub(ev, cb, context); if (e_sub == NULL) { e_sub = (event_subscription_t *)aos_zalloc(sizeof(event_subscription_t)); if (e_sub) { e_sub->ecb = cb; e_sub->context = context; slist_add(&e_sub->next, &ev->sub_list); ret = 0; } } } aos_mutex_unlock(&evlist->mutex); return ret; } int eventlist_subscribe_fd(event_list_t *evlist, uint32_t fd, event_callback_t cb, void *context) { aos_assert(evlist && cb); if (fd & FD_MASK) { return -1; } fd |= FD_MASK; return __yoc_event_subscribe(evlist, fd, cb, context); } int eventlist_subscribe(event_list_t *evlist, uint32_t event_id, event_callback_t cb, void *context) { aos_assert(evlist && cb); if (event_id & FD_MASK) { return -1; } return __yoc_event_subscribe(evlist, event_id, cb, context); } static int __yoc_event_unsubscribe(event_list_t *evlist, uint32_t event_id, event_callback_t cb, void *context) { int ret = -1; aos_mutex_lock(&evlist->mutex, AOS_WAIT_FOREVER); event_t *ev = find_event(evlist, event_id); if (ev) { event_subscription_t *e_sub = find_event_sub(ev, cb, context); if (e_sub) { slist_del(&e_sub->next, &ev->sub_list); aos_free(e_sub); if (slist_empty(&ev->sub_list)) { slist_del(&ev->next, &evlist->events); aos_free(ev); } ret = 0; } } aos_mutex_unlock(&evlist->mutex); return ret; } static int __yoc_event_remove(event_list_t *evlist, uint32_t event_id) { int ret = -1; aos_mutex_lock(&evlist->mutex, AOS_WAIT_FOREVER); event_t *ev = find_event(evlist, event_id); if (ev) { event_subscription_t *node; slist_t *tmp; slist_for_each_entry_safe(&ev->sub_list, tmp, node, event_subscription_t, next) { slist_del(&ev->next, &evlist->events); aos_free(ev); } slist_del(&ev->next, &evlist->events); aos_free(ev); } aos_mutex_unlock(&evlist->mutex); return ret; } int eventlist_unsubscribe_fd(event_list_t *evlist, uint32_t fd, event_callback_t cb, void *context) { aos_assert(evlist && cb); if (fd & FD_MASK) { return -1; } fd |= FD_MASK; return __yoc_event_unsubscribe(evlist, fd, cb, context); } int eventlist_unsubscribe(event_list_t *evlist, uint32_t event_id, event_callback_t cb, void *context) { aos_assert(evlist && cb); if (event_id & FD_MASK) { return -1; } return __yoc_event_unsubscribe(evlist, event_id, cb, context); } static void __event_publish(event_list_t *evlist, uint32_t event_id, void *data) { aos_mutex_lock(&evlist->mutex, AOS_WAIT_FOREVER); event_t *ev = find_event(evlist, event_id); if (ev) { event_subscription_t *node; slist_for_each_entry(&ev->sub_list, node, event_subscription_t, next) { if (node->ecb) { node->ecb(ev->event_id, data, node->context); } } } aos_mutex_unlock(&evlist->mutex); } int eventlist_publish(event_list_t *evlist, uint32_t event_id, void *data) { aos_assert(evlist); if (event_id & FD_MASK) { return -1; } __event_publish(evlist, event_id, data); return 0; } int eventlist_publish_fd(event_list_t *evlist, uint32_t fd, void *data) { aos_assert(evlist); if (fd & FD_MASK) { return -1; } fd |= FD_MASK; __event_publish(evlist, fd, data); return 0; } int eventlist_remove(event_list_t *evlist, uint32_t event_id) { aos_assert(evlist); if (event_id & FD_MASK) { return -1; } __yoc_event_remove(evlist, event_id); return 0; } int eventlist_remove_fd(event_list_t *evlist, uint32_t fd) { aos_assert(evlist); if (fd & FD_MASK) { return -1; } fd |= FD_MASK; __yoc_event_remove(evlist, fd); return 0; } int eventlist_setfd(event_list_t *evlist, void *data) { aos_assert(evlist && data); int max_fd = 0; fd_set *readfds = (fd_set *)data; FD_ZERO(readfds); aos_mutex_lock(&evlist->mutex, AOS_WAIT_FOREVER); event_t *node; slist_for_each_entry(&evlist->events, node, event_t, next) { if (node->event_id > FD_MASK) { uint32_t fd = node->event_id & (~FD_MASK); FD_SET(fd, readfds); if (fd > max_fd) { max_fd = fd; } } } aos_mutex_unlock(&evlist->mutex); return max_fd; }
YifuLiu/AliOS-Things
components/uservice/src/event.c
C
apache-2.0
7,184
/* * Copyright (C) 2019-2020 Alibaba Group Holding Limited */ #include <stdlib.h> #include <stdint.h> #include <string.h> //#include <aos/osal_debug.h> #include <aos/list.h> #include <uservice/uservice.h> #include <uservice/event.h> #include <sys/socket.h> #include "internal.h" #define FD_MAX_STEMP 8 static struct event_call { uservice_t *svr; event_list_t event; dlist_t timeouts; int event_id; int is_event_service_inited; void *data; aos_task_t select_task; aos_sem_t select_sem; aos_event_t wait_event; } ev_service; struct event_param { uint32_t event_id; union { event_callback_t cb; uint32_t timeout; }; void *data; dlist_t next; }; enum { CMD_SUB_FD_EVENT, CMD_SUB_EVENT, CMD_REMOVE_FD_EVENT, CMD_REMOVE_EVENT, CMD_PUBLISH_EVENT, CMD_PUBLISH_FD_EVENT, }; #define EVENT_SUBSCRIBE 0x0000FF00 #define EVENT_UNSUBSCRIBE 0x000000FF static void select_task_entry(void *arg); static int process_rpc(void *context, rpc_t *rpc) { int size = -1; struct event_param *param = (struct event_param *)rpc_get_buffer(rpc, &size); aos_assert(size == sizeof(struct event_param)); switch (rpc->cmd_id) { case CMD_SUB_FD_EVENT: eventlist_subscribe_fd(&ev_service.event, param->event_id, param->cb, param->data); aos_sem_signal(&ev_service.select_sem); break; case CMD_REMOVE_FD_EVENT: eventlist_unsubscribe_fd(&ev_service.event, param->event_id, param->cb, param->data); break; case CMD_PUBLISH_FD_EVENT: eventlist_publish_fd(&ev_service.event, param->event_id, param->data); break; case CMD_SUB_EVENT: eventlist_subscribe(&ev_service.event, param->event_id, param->cb, param->data); break; case CMD_REMOVE_EVENT: eventlist_unsubscribe(&ev_service.event, param->event_id, param->cb, param->data); break; case CMD_PUBLISH_EVENT: if (param->timeout > 0) { struct event_param *timer = aos_malloc(sizeof(struct event_param)); if (timer == NULL) break; timer->timeout = aos_now_ms() + param->timeout; timer->event_id = param->event_id; timer->data = param->data; struct event_param *node; dlist_for_each_entry(&ev_service.timeouts, node, struct event_param, next) { if (timer->timeout < node->timeout) break; } dlist_add_tail(&timer->next, &node->next); aos_sem_signal(&ev_service.select_sem); } else { eventlist_publish(&ev_service.event, param->event_id, param->data); } break; } rpc_reply(rpc); return 0; } int event_service_init(utask_t *task) { if (ev_service.is_event_service_inited != 0) { return 0; } ev_service.is_event_service_inited = 1; if (task == NULL) task = utask_new("event_svr", 2*1024, QUEUE_MSG_COUNT * 5, AOS_DEFAULT_APP_PRI); if (task == NULL) { ev_service.is_event_service_inited = 0; return -1; } eventlist_init(&ev_service.event); dlist_init(&ev_service.timeouts); if (aos_sem_new(&ev_service.select_sem, 0) < 0) { utask_destroy(task); ev_service.is_event_service_inited = 0; return -1; } if (aos_event_new(&ev_service.wait_event, 0) < 0) { utask_destroy(task); aos_sem_free(&ev_service.select_sem); ev_service.is_event_service_inited = 0; return -1; } ev_service.svr = uservice_new("event_svr", process_rpc, NULL); if (ev_service.svr == NULL) { utask_destroy(task); aos_sem_free(&ev_service.select_sem); aos_event_free(&ev_service.select_sem); ev_service.is_event_service_inited = 0; return -1; } aos_task_new_ext(&ev_service.select_task, "select", select_task_entry, NULL, 1024, AOS_DEFAULT_APP_PRI); utask_add(task, ev_service.svr); return 0; } static void event_call(struct event_param *param, int cmd_id, int sync) { rpc_t rpc; if (rpc_init(&rpc, cmd_id, sync ? AOS_WAIT_FOREVER : 0) == 0) { rpc_put_buffer(&rpc, param, sizeof(struct event_param )); uservice_call(ev_service.svr, &rpc); rpc_deinit(&rpc); } } void event_publish_fd(uint32_t event_id, void *data, int sync) { struct event_param param; param.event_id = event_id; param.data = data; param.cb = NULL; event_call(&param, CMD_PUBLISH_FD_EVENT, sync); } void event_subscribe_fd(uint32_t fd, event_callback_t cb, void *context) { aos_assert(cb); struct event_param param; param.event_id = fd; param.cb = cb; param.data = context; event_call(&param, CMD_SUB_FD_EVENT, 0); } void event_unsubscribe_fd(uint32_t event_id, event_callback_t cb, void *context) { struct event_param param; param.event_id = event_id; param.cb = cb; param.data = context; event_call(&param, CMD_REMOVE_FD_EVENT, 0); } void event_publish(uint32_t event_id, void *data) { struct event_param param; param.event_id = event_id; param.data = data; param.timeout = 0; event_call(&param, CMD_PUBLISH_EVENT, 0); } void event_publish_delay(uint32_t event_id, void *data, int timeout) { struct event_param param; param.event_id = event_id; param.data = data; param.timeout = timeout; event_call(&param, CMD_PUBLISH_EVENT, 0); } void event_subscribe(uint32_t event_id, event_callback_t cb, void *context) { aos_assert(cb); struct event_param param; param.event_id = event_id; param.cb = cb; param.data = context; event_call(&param, CMD_SUB_EVENT, 0); } void event_unsubscribe(uint32_t event_id, event_callback_t cb, void *context) { aos_assert(cb); struct event_param param; param.event_id = event_id; param.cb = cb; param.data = context; event_call(&param, CMD_REMOVE_EVENT, 0); } static int do_time_event() { int delayed_ms = -1; struct event_param *node; dlist_t *tmp; uservice_lock(ev_service.svr); dlist_for_each_entry_safe(&ev_service.timeouts, tmp, node, struct event_param, next) { long long now = aos_now_ms(); if (now >= node->timeout) { event_publish(node->event_id, node->data); dlist_del(&node->next); aos_free(node); } else { delayed_ms = node->timeout - now; break; } } uservice_unlock(ev_service.svr); return delayed_ms; } #define SELECT_TIMEOUT (10) static void select_task_entry(void *arg) { #ifdef CONFIG_LWIP_V200 aos_task_exit(0); #else event_list_t *evlist = &ev_service.event; utask_t *task = ev_service.svr->task; #if defined(CONFIG_SAL) || defined(CONFIG_TCPIP) extern void sys_init(void); sys_init(); #endif while (1) { fd_set readfds; struct timeval timeout; int time_ms = do_time_event(); int max_fd = eventlist_setfd(evlist, &readfds); timeout.tv_sec = time_ms / 1000; timeout.tv_usec = (time_ms % 1000) * 1000; int ret = select2(max_fd + 1, &readfds, NULL, NULL, time_ms == -1 ? NULL : &timeout, &ev_service.select_sem); if (ret > 0) { for (int fd = 0; fd <= max_fd; fd++) { if (FD_ISSET(fd, &readfds)) { if(aos_queue_get_count(&task->queue) < (task->queue_count*3/4)) { event_publish_fd(fd, NULL, 1); // eventlist_remove_fd(evlist, fd); } } } } } aos_task_exit(0); #endif }
YifuLiu/AliOS-Things
components/uservice/src/event_svr.c
C
apache-2.0
7,877
/* * Copyright (C) 2019-2020 Alibaba Group Holding Limited */ #ifndef USERVICE_INTERNAL_H #define USERVICE_INTERNAL_H #include <stdint.h> #include <aos/list.h> #include <aos/kernel.h> #include <uservice/uservice.h> #ifdef __cplusplus extern "C" { #endif struct uservice { const char *name; void *context; process_t process_rpc; utask_t *task; slist_t next; }; struct rpc_record { uint32_t cmd_id; uint32_t count; struct uservice *srv; slist_t next; }; struct utask { aos_task_t task; int8_t running; uint8_t queue_count; #if defined(CONFIG_DEBUG) && defined(CONFIG_DEBUG_UTASK) uint8_t queue_max_used; slist_t rpc_reclist; #endif void *queue_buffer; aos_queue_t queue; aos_mutex_t mutex; rpc_t *current_rpc; aos_sem_t running_wait; slist_t uservice_lists; slist_t rpc_buffer_gc_cache; slist_t node; }; struct rpc_buffer { int timeout_ms; uint8_t * buffer; uint16_t buf_size; uint16_t pos; aos_sem_t sem; slist_t next; }; #define TASK_LOCK(task) aos_mutex_lock(&(task->mutex), AOS_WAIT_FOREVER) #define TASK_UNLOCK(task) aos_mutex_unlock(&(task->mutex)) void rpc_free(rpc_t *rpc); int rpc_wait(rpc_t *rpc); typedef struct event_list { slist_t events; aos_mutex_t mutex; } event_list_t; int eventlist_init(event_list_t *evlist); void eventlist_uninit(event_list_t *evlist); int eventlist_subscribe(event_list_t *evlist, uint32_t event_id, event_callback_t cb, void *context); int eventlist_unsubscribe(event_list_t *evlist, uint32_t event_id, event_callback_t cb, void *context); int eventlist_publish(event_list_t *evlist, uint32_t event_id, void *data); int eventlist_remove(event_list_t *evlist, uint32_t event_id); int eventlist_subscribe_fd(event_list_t *evlist, uint32_t fd, event_callback_t cb, void *context); int eventlist_unsubscribe_fd(event_list_t *evlist, uint32_t fd, event_callback_t cb, void *context); int eventlist_publish_fd(event_list_t *evlist, uint32_t fd, void *data); int eventlist_remove_fd(event_list_t *evlist, uint32_t fd); int eventlist_setfd(event_list_t *evlist, void *readfds); #ifdef __cplusplus } #endif #endif
YifuLiu/AliOS-Things
components/uservice/src/internal.h
C
apache-2.0
2,267
/* * Copyright (C) 2019-2020 Alibaba Group Holding Limited */ #include <stdlib.h> #include <string.h> #include <errno.h> #include <aos/kernel.h> //#include <aos/osal_debug.h> #include "internal.h" static void rpc_buffer_free(rpc_buffer_t *data) { if (data->buffer) { aos_free(data->buffer); data->buffer = NULL; } if (aos_sem_is_valid(&data->sem)) aos_sem_free(&data->sem); aos_free(data); } int rpc_init(rpc_t *rpc, int cmd_id, int timeout_ms) { aos_assert(rpc); int ret = 0; memset(rpc, 0, sizeof(rpc_t)); rpc->cmd_id = cmd_id; if (timeout_ms != 0) { rpc->data = aos_zalloc(sizeof(rpc_buffer_t)); if (rpc->data == NULL) return -ENOMEM; rpc->data->timeout_ms = timeout_ms; ret = aos_sem_new(&rpc->data->sem, 0); if (ret != 0) { aos_free(rpc->data); rpc->data = NULL; } } return ret; } int rpc_wait(rpc_t *rpc) { aos_assert(rpc); int ret = 0; if (rpc->data && aos_sem_is_valid(&rpc->data->sem)) ret = aos_sem_wait(&rpc->data->sem, rpc->data->timeout_ms); return ret; } void rpc_free(rpc_t *rpc) { aos_assert(rpc); if (rpc->data) rpc_buffer_free(rpc->data); } void rpc_deinit(rpc_t *rpc) { aos_assert(rpc); if (rpc->data == NULL) return; int cached = 0; utask_t *task = rpc->srv->task; aos_assert(task); TASK_LOCK(task); rpc_buffer_t *data; slist_for_each_entry(&task->rpc_buffer_gc_cache, data, rpc_buffer_t, next) { if (data == rpc->data) { slist_del(&data->next, &task->rpc_buffer_gc_cache); rpc_buffer_free(data); cached = 1; break; } } if (cached == 0) { slist_add_tail(&rpc->data->next, &task->rpc_buffer_gc_cache); } TASK_UNLOCK(task); } void rpc_reply(rpc_t *rpc) { aos_assert(rpc); aos_assert(rpc->srv); aos_assert(rpc->srv->task); if (rpc->data) { if (aos_sem_is_valid(&rpc->data->sem)) { aos_sem_signal(&(rpc->data->sem)); } else { // is async call, free this data. // LOGI("RPC", "async rpc cannot have return value."); // rpc_buffer_free(rpc->data); } rpc_deinit(rpc); } } static uint8_t *rpc_buffer_need_size(rpc_buffer_t *rpc, int size) { void *p = NULL; aos_assert(rpc); uint8_t *buf = aos_malloc(size + rpc->buf_size); if (buf) { if (rpc->buffer) { memcpy(buf, rpc->buffer, rpc->buf_size); aos_free(rpc->buffer); } rpc->buffer = buf; p = rpc->buffer + rpc->buf_size; rpc->buf_size += size; } return p; }; void rpc_put_reset(rpc_t *rpc) { aos_assert(rpc); if (rpc->data && rpc->data->buffer) { aos_free(rpc->data->buffer); rpc->data->buffer = NULL; rpc->data->buf_size = 0; rpc->data->pos = 0; } } void rpc_get_reset(rpc_t *rpc) { aos_assert(rpc); if (rpc->data) rpc->data->pos = 0; } #define RPC_PUT(rpc, type, v) return rpc_put_buffer(rpc, &v, sizeof(v)) int rpc_put_int(rpc_t *rpc, int i) { RPC_PUT(rpc, int, i); } int rpc_put_uint8(rpc_t *rpc, uint8_t c) { RPC_PUT(rpc, uint8_t, c); } int rpc_put_double(rpc_t *rpc, double c) { RPC_PUT(rpc, double, c); } int rpc_put_point(rpc_t *rpc, const void *p) { RPC_PUT(rpc, void *, p); } int rpc_put_buffer(rpc_t *rpc, const void *data, size_t size) { aos_assert(rpc); if (data == NULL || size == 0) return -EINVAL; if (rpc->data == NULL) { rpc->data = aos_zalloc(sizeof(rpc_buffer_t)); if (rpc->data == NULL) return -ENOMEM; } uint8_t *p = rpc_buffer_need_size(rpc->data, size + sizeof(uint32_t)); if (p) { memcpy(p, (uint8_t *)&size, sizeof(uint32_t)); p += sizeof(uint32_t); memcpy(p, data, size); } return p ? 0 : -ENOMEM; } int rpc_put_string(rpc_t *rpc, char *text) { return rpc_put_buffer(rpc, text, strlen(text) + 1); } #define RPC_GET(rpc, type) \ do { \ int count = -1; \ void *p = rpc_get_buffer(rpc, &count); \ aos_assert(count == sizeof(type)); \ type v; \ memcpy(&v, p, sizeof(type)); \ return v; \ } while (0) int rpc_get_int(rpc_t *rpc) { RPC_GET(rpc, int); } uint8_t rpc_get_uint8(rpc_t *rpc) { RPC_GET(rpc, uint8_t); } double rpc_get_double(rpc_t *rpc) { RPC_GET(rpc, double); } void *rpc_get_point(rpc_t *rpc) { RPC_GET(rpc, void *); } char *rpc_get_string(rpc_t *rpc) { return rpc_get_buffer(rpc, NULL); } void *rpc_get_buffer(rpc_t *rpc, int *count) { aos_assert(rpc); void *p = NULL; if (rpc->data) { int len; memcpy((uint8_t *)&len, (int *)(rpc->data->buffer + rpc->data->pos), sizeof(int)); p = rpc->data->buffer + rpc->data->pos + sizeof(uint32_t); rpc->data->pos += sizeof(uint32_t) + len; if (count) *count = len; } return p; }
YifuLiu/AliOS-Things
components/uservice/src/rpc.c
C
apache-2.0
5,710
/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <aos/kernel.h> #include <sys/select.h> //#include "lwip/opt.h" //#include "lwip/sockets.h" __attribute__((weak)) int select2(int maxfdp1, fd_set *readset, fd_set *writeset, fd_set *exceptset, struct timeval *timeout, void *semaphore) { uint32_t tomeout_ms; if (timeout) { tomeout_ms = timeout->tv_sec * 1000 + timeout->tv_usec / 1000; } else { tomeout_ms = AOS_WAIT_FOREVER; } if (semaphore && aos_sem_is_valid(semaphore)) { aos_sem_wait(semaphore, tomeout_ms); } else { aos_msleep(tomeout_ms); } return 0; } /* dummy select, fix compile error with no net evn */ __attribute__((weak)) int select(int maxfdp1, fd_set *readset, fd_set *writeset, fd_set *exceptset, struct timeval *timeout) { return select2(maxfdp1, readset, writeset, exceptset, timeout, NULL); }
YifuLiu/AliOS-Things
components/uservice/src/select.c
C
apache-2.0
978
/* * Copyright (C) 2019-2020 Alibaba Group Holding Limited */ #include <string.h> //#include <aos/osal_debug.h> #include <aos/kernel.h> #include "internal.h" #define TAG "uSrv" void uservice_lock(uservice_t *srv) { aos_assert(srv); if (srv->task) TASK_LOCK(srv->task); } void uservice_unlock(uservice_t *srv) { aos_assert(srv); if (srv->task) TASK_UNLOCK(srv->task); } int uservice_call(uservice_t *srv, rpc_t *rpc) { aos_assert(srv); aos_assert(srv->task); rpc->srv = srv; #ifdef CONFIG_DEBUG if(rpc->data && rpc->data->timeout_ms != 0) { aos_assert(aos_task_self() != srv->task->task); } #endif int count = 10; while (count--) { if (aos_queue_send(&srv->task->queue, rpc, sizeof(rpc_t)) == 0) { return rpc_wait(rpc); } else { if ( count == 1) { printf("uService %s queue full,send id:%d cur id: %d", srv->name,rpc->cmd_id, srv->task->current_rpc->cmd_id); } //if (!aos_irq_context()) aos_msleep(100); } } return -1; } int uservice_call_sync(uservice_t *srv, int cmd, void *param, void *resp, size_t size) { aos_assert(srv); rpc_t rpc; int ret; ret = rpc_init(&rpc, cmd, AOS_WAIT_FOREVER); if (ret < 0) return ret; if (param) rpc_put_point(&rpc, param); ret = uservice_call(srv, &rpc); if (resp != NULL && size > 0 && ret == 0) { int count; void *data = rpc_get_buffer(&rpc, &count); aos_assert(count == size && data != NULL); if (data) memcpy(resp, data, size); } rpc_deinit(&rpc); return ret; } int uservice_call_async(uservice_t *srv, int cmd, void *param, size_t param_size) { aos_assert(srv); rpc_t rpc; int ret; ret = rpc_init(&rpc, cmd, 0); if (ret == 0) { if (param && param_size > 0) rpc_put_buffer(&rpc, param, param_size); ret = uservice_call(srv, &rpc); rpc_deinit(&rpc); } return ret; } uservice_t *uservice_new(const char *name, process_t process_rpc, void *context) { aos_assert(process_rpc && name); uservice_t *srv = aos_zalloc(sizeof(uservice_t)); if (srv == NULL) return NULL; srv->name = name; srv->context = context; srv->process_rpc = process_rpc; return srv; } void uservice_destroy(uservice_t *srv) { aos_assert(srv); aos_free(srv); } int uservice_process(void *context, rpc_t *rpc, const rpc_process_t rpcs[]) { for (int i = 0; rpcs[i].process != NULL; i++) { if (rpcs[i].cmd_id == rpc->cmd_id) { if (rpcs[i].process(context, rpc) >= 0) rpc_reply(rpc); return 0; } } return -1; } static void uservice_event_process(uint32_t event_id, const void *data, void *context) { uservice_t *srv = (uservice_t*)context; rpc_t rpc; aos_assert(srv); if (rpc_init(&rpc, event_id, 0) == 0) { rpc_put_point(&rpc, data); uservice_call(srv, &rpc); rpc_deinit(&rpc); } } void uservice_subscribe(uservice_t *srv, uint32_t event_id) { aos_assert(srv); event_subscribe(event_id, uservice_event_process, srv); }
YifuLiu/AliOS-Things
components/uservice/src/uservice.c
C
apache-2.0
3,279
/* * Copyright (C) 2019-2020 Alibaba Group Holding Limited */ #include <stdint.h> #include <string.h> #include <aos/kernel.h> //#include <aos/osal_debug.h> #include <uservice/uservice.h> #include "internal.h" #define TAG "utask" static int g_utask_softwdt_timeout = 0; static AOS_SLIST_HEAD(utask_list); #define LOOP_TIME_MS 1000 #define MIN_SOFTWDT_TIME 2000 /*ms*/ #if 0 static void task_will(void *args) { utask_t *task = (utask_t*)args; LOGE(TAG, "utask: %s crash!", aos_task_get_name(&task->task)); if (task->current_rpc) { LOGE(TAG, "uservice_name: %s, rpc_cmd: %d", task->current_rpc->srv->name, task->current_rpc->cmd_id); } } #endif static void utask_entry(void *data) { utask_t *task = (utask_t *)data; rpc_t rpc; size_t size; while (task->running) { if (aos_queue_recv(&task->queue, LOOP_TIME_MS, &rpc, &size) == 0) { #if defined(CONFIG_DEBUG) && defined(CONFIG_DEBUG_UTASK) int count = aos_queue_get_count(&task->queue) + 1; if (count > task->queue_max_used) task->queue_max_used = count; struct rpc_record *node; int found = 0; slist_for_each_entry(&task->rpc_reclist, node, struct rpc_record, next) { if (node->cmd_id == rpc.cmd_id && node->srv == rpc.srv) { node->count++; found = 1; break; } } if (found == 0) { node = aos_zalloc(sizeof(struct rpc_record)); node->cmd_id = rpc.cmd_id; node->srv = rpc.srv; node->count = 1; slist_add(&node->next, &task->rpc_reclist); } #endif if (rpc.srv->process_rpc) { task->current_rpc = &rpc; if (g_utask_softwdt_timeout >= MIN_SOFTWDT_TIME) { //aos_task_wdt_attach(task_will, task); //aos_task_wdt_feed(g_utask_softwdt_timeout); // simulaton timeout // sleep(11); //uservice_lock(rpc.srv); rpc.srv->process_rpc(rpc.srv->context, &rpc); //uservice_unlock(rpc.srv); //aos_task_wdt_detach(); } else { //uservice_lock(rpc.srv); rpc.srv->process_rpc(rpc.srv->context, &rpc); //uservice_unlock(rpc.srv); } task->current_rpc = NULL; } else { rpc_reply(&rpc); } } } aos_sem_signal(&task->running_wait); } utask_t *utask_new(const char *name, size_t stack_size, int queue_count, int prio) { if (stack_size <= 0 || queue_count <= 0) return NULL; int queue_buffer_size = queue_count * sizeof(rpc_t); utask_t *task = aos_zalloc(sizeof(utask_t) + queue_buffer_size); if (task == NULL) return NULL; task->running = 1; slist_init(&task->uservice_lists); slist_init(&task->rpc_buffer_gc_cache); slist_add_tail(&task->node, &utask_list); task->queue_count = queue_count; task->queue_buffer = (uint8_t*)task + sizeof(utask_t); if (aos_queue_new(&task->queue, task->queue_buffer, queue_buffer_size, sizeof(rpc_t)) != 0) goto out0; if (aos_mutex_new(&task->mutex) != 0) goto out1; if (aos_sem_new(&task->running_wait, 0) != 0) goto out2; if (aos_task_new_ext(&task->task, name ? name : "utask", utask_entry, task, stack_size, prio) != 0) goto out3; return task; out3: aos_sem_free(&task->running_wait); out2: aos_mutex_free(&task->mutex); out1: aos_queue_free(&task->queue); out0: aos_free(task); return NULL; } void utask_join(utask_t *task) { aos_assert(task); task->running = 0; aos_sem_wait(&task->running_wait, AOS_WAIT_FOREVER); slist_del(&task->node, &utask_list); uservice_t *node; slist_t *tmp; slist_for_each_entry_safe(&task->uservice_lists, tmp, node, uservice_t, next) { utask_remove(task, node); } aos_sem_free(&task->running_wait); aos_mutex_free(&task->mutex); aos_queue_free(&task->queue); aos_free(task); } void utask_destroy(utask_t *task) { aos_assert(task); utask_join(task); } void utask_add(utask_t *task, uservice_t *srv) { aos_assert(task && srv); if (srv->task == NULL) { TASK_LOCK(task); srv->task = task; slist_add_tail(&srv->next, &task->uservice_lists); TASK_UNLOCK(task); } } void utask_remove(utask_t *task, uservice_t *srv) { aos_assert(task && srv); TASK_LOCK(task); #if defined(CONFIG_DEBUG) && defined(CONFIG_DEBUG_UTASK) struct rpc_record *node; slist_t *tmp; slist_for_each_entry_safe(&task->rpc_reclist, tmp, node, struct rpc_record, next) { if (node->srv == srv) { slist_del(&node->next, &task->rpc_reclist); free(node); } } #endif slist_del(&srv->next, &task->uservice_lists); srv->task = NULL; TASK_UNLOCK(task); } void utask_lock(utask_t *task) { aos_assert(task); TASK_LOCK(task); } void utask_unlock(utask_t *task) { aos_assert(task); TASK_UNLOCK(task); } void utask_set_softwdt_timeout(int ms) { if (ms == 0) { g_utask_softwdt_timeout = 0; } else { g_utask_softwdt_timeout = (ms < MIN_SOFTWDT_TIME) ? MIN_SOFTWDT_TIME : ms; } } uservice_t *task_get(utask_t *task, const char *name) { aos_assert(task); uservice_t *node; TASK_LOCK(task); slist_for_each_entry(&task->uservice_lists, node, uservice_t, next) { if (strcmp(node->name, name) == 0) { TASK_UNLOCK(task); return node; } } TASK_UNLOCK(task); return NULL; } void tasks_debug() { utask_t *utask; slist_for_each_entry(&utask_list, utask, utask_t, node) { #if defined(CONFIG_DEBUG) && defined(CONFIG_DEBUG_UTASK) struct rpc_record *rpc; printf("utask: %s, queue total count: %d, max used: %d\n------------------------------------------------------\n", aos_task_get_name(&utask->task), utask->queue_count, utask->queue_max_used); printf("\t%05s\t\%05s\tSERVER\n", "CMD_ID", "COUNT"); slist_for_each_entry(&utask->rpc_reclist, rpc, struct rpc_record, next) { printf("\t%05d\t%05d\t%s\n", rpc->cmd_id, rpc->count, rpc->srv->name); } printf("\n"); #endif } }
YifuLiu/AliOS-Things
components/uservice/src/utask.c
C
apache-2.0
6,569
cmake_minimum_required (VERSION 2.8) project(uvoice) option(target_os "set target os type") option(target_host "set target host type") option(uvoice_release "build uvoice release version" off) link_libraries(-lpthread -lm) link_directories(${PROJECT_SOURCE_DIR}/out/libs ${PROJECT_SOURCE_DIR}/out/prebuilt) set(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/out/libs) set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/out/bin) if (target_os STREQUAL "linux") add_definitions(-D __os_linux__) else() message(FATAL_ERROR "target os type not specified !!!") endif() if (target_host STREQUAL "x64") add_definitions(-D __cpu_x86_64__) else() message(FATAL_ERROR "target host type not specified !!!") endif() message("-- target os is ${target_os}") message("-- target host is ${target_host}") set(SRC_LIST test/test_main.c test/test_player.c test/test_recorder.c test/test_tts.c uvoice.c common/event.c common/ringbuffer.c common/message.c common/gbk2utf8.c media/uvoice_format.c media/uvoice_codec.c media/uvoice_stream.c media/uvoice_wave.c media/uvoice_fade.c media/uvoice_mlist.c media/uvoice_player.c media/uvoice_recorder.c stream/uvoice_file.c stream/uvoice_partition.c stream/uvoice_http.c stream/uvoice_cache.c stream/uvoice_download.c stream/uvoice_hls.c audio/audio_stream.c audio/audio_common.c audio/audio_mixer.c audio/audio_process.c audio/audio_trigger.c audio/process/proc_equalizer.c audio/process/proc_resample.c audio/hal/linux/uvoice_pcm.c application/alicloudtts/tts.c application/alicloudtts/alicloudtts.c) set(SRC_CODEC_LIST codec/pvmp3_decoder.c codec/helixaac_decoder.c codec/ogg_decoder.c codec/flac_decoder.c codec/faad2aac_decoder.c codec/faad2m4a_decoder.c codec/opus_encoder.c codec/opus_decoder.c codec/spx_encoder.c codec/spx_decoder.c codec/amr_encoder.c codec/amr_decoder.c codec/amrwb_encoder.c codec/amrwb_decoder.c) add_definitions( -D UVOICE_PROJECT -D UVOICE_PLAYER_ENABLE -D UVOICE_EVENT_ENABLE -D UVOICE_EVENT_BY_MESSAGE_QUEUE -D UVOICE_FILE_ENABLE -D UVOICE_PARTITION_ENABLE -D UVOICE_HTTP_ENABLE -D UVOICE_MLIST_ENABLE -D AUDIO_CACHE_ENABLE -D UVOICE_HLS_ENABLE -D ALICLOUD_TTS_SUPPORT -D UVOICE_TTS_ENABLE -D UVOICE_RESAMPLE_ENABLE -D UVOICE_EQ_ENABLE -D UVOICE_DOWNLOAD_ENABLE -D UVOICE_RELEASE_VERSION_MAIN=1 -D UVOICE_RELEASE_VERSION_SUB=0) if (uvoice_release) add_definitions(-D UVOICE_BUILD_RELEASE) endif() add_definitions( -D DECODER_PV_MP3_ENABLE -D DECODER_OGG_ENABLE -D DECODER_FLAC_ENABLE -D DECODER_APE_ENABLE -D ENCODER_OPUS_ENABLE -D DECODER_OPUS_ENABLE -D ENCODER_SPEEX_ENABLE -D DECODER_SPEEX_ENABLE -D ENCODER_AMR_ENABLE -D DECODER_AMR_ENABLE -D ENCODER_AMRWB_ENABLE -D DECODER_AMRWB_ENABLE -D DECODER_FAAD2_M4A_ENABLE -D DECODER_FAAD2_AAC_ENABLE) include_directories( include internal audio codec connect application/alicloudtts/include) add_subdirectory(codec/opensource/pvmp3) #add_subdirectory(codec/opensource/helixaac) #add_subdirectory(codec/opensource/libogg) #add_subdirectory(codec/opensource/libvorbis) #add_subdirectory(codec/opensource/flac) #add_subdirectory(codec/opensource/faad2) #add_subdirectory(codec/opensource/opus) #add_subdirectory(codec/opensource/speex) #add_subdirectory(codec/opensource/amr) #add_subdirectory(codec/opensource/amrwb) #add_subdirectory(codec/opensource/wma) #add_subdirectory(audio/process/opensource/libsox) add_subdirectory(audio/process/opensource/speexdsp) add_executable(uvoice ${SRC_LIST} ${SRC_CODEC_LIST}) if (target_os STREQUAL "linux") target_link_libraries(uvoice asound) endif() target_link_libraries(uvoice pvmp3) target_link_libraries(uvoice helixaac) target_link_libraries(uvoice vorbis) target_link_libraries(uvoice ogg) target_link_libraries(uvoice flac) target_link_libraries(uvoice faad2) target_link_libraries(uvoice opus) target_link_libraries(uvoice speex) target_link_libraries(uvoice amr) target_link_libraries(uvoice amrwb) target_link_libraries(uvoice wma) target_link_libraries(uvoice resampler) target_link_libraries(uvoice sox)
YifuLiu/AliOS-Things
components/uvoice/CMakeLists.txt
CMake
apache-2.0
4,055
/* * 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_tts.h" #include "../../../internal/uvoice_os.h" #include "../../../internal/uvoice_common.h" #include "../../../internal/uvoice_play.h" #include "alicloudtts_intf.h" #include "alicloudtts.h" #include "httpclient.h" #define ALIYUN_TTS_HTTP_URL "https://nls-gateway.cn-shanghai.aliyuncs.com/stream/v1/tts?" /* https://help.aliyun.com/document_detail/84435.html?spm=a2c4g.11186623.6.581.16a75275MJHPrH */ static const voice_spec_t voice_spec[] = { { "xiaoyun", { VOICE_CHINESE, VOICE_CN_EN_MIX, VOICE_NULL }, { TTS_ALIYUN_SAMPLE_RATE_8K, TTS_ALIYUN_SAMPLE_RATE_16K, 0 } }, { "xiaogang", { VOICE_CHINESE, VOICE_CN_EN_MIX, VOICE_NULL }, { TTS_ALIYUN_SAMPLE_RATE_8K, TTS_ALIYUN_SAMPLE_RATE_16K, 0 } }, { "ruoxi", { VOICE_CHINESE, VOICE_CN_EN_MIX, VOICE_NULL }, { TTS_ALIYUN_SAMPLE_RATE_8K, TTS_ALIYUN_SAMPLE_RATE_16K, TTS_ALIYUN_SAMPLE_RATE_24K } }, { "xiaomeng", { VOICE_CHINESE, VOICE_CN_EN_MIX, VOICE_NULL }, { TTS_ALIYUN_SAMPLE_RATE_8K, TTS_ALIYUN_SAMPLE_RATE_16K, 0 } }, { "xiaowei", { VOICE_CHINESE, VOICE_CN_EN_MIX, VOICE_NULL }, { TTS_ALIYUN_SAMPLE_RATE_8K, TTS_ALIYUN_SAMPLE_RATE_16K, 0 } }, { "amei", { VOICE_CHINESE, VOICE_CN_EN_MIX, VOICE_NULL }, { TTS_ALIYUN_SAMPLE_RATE_8K, TTS_ALIYUN_SAMPLE_RATE_16K, 0 } }, { "xiaoxue", { VOICE_CHINESE, VOICE_CN_EN_MIX, VOICE_NULL }, { TTS_ALIYUN_SAMPLE_RATE_8K, TTS_ALIYUN_SAMPLE_RATE_16K, 0 } }, { "siqi", { VOICE_CHINESE, VOICE_CN_EN_MIX, VOICE_NULL }, { TTS_ALIYUN_SAMPLE_RATE_8K, TTS_ALIYUN_SAMPLE_RATE_16K, TTS_ALIYUN_SAMPLE_RATE_24K } }, { "sijia", { VOICE_CHINESE, VOICE_CN_EN_MIX, VOICE_NULL }, { TTS_ALIYUN_SAMPLE_RATE_8K, TTS_ALIYUN_SAMPLE_RATE_16K, TTS_ALIYUN_SAMPLE_RATE_24K } }, { "sicheng", { VOICE_CHINESE, VOICE_CN_EN_MIX, VOICE_NULL }, { TTS_ALIYUN_SAMPLE_RATE_8K, TTS_ALIYUN_SAMPLE_RATE_16K, TTS_ALIYUN_SAMPLE_RATE_24K } }, { "siyue", { VOICE_CHINESE, VOICE_CN_EN_MIX, VOICE_NULL }, { TTS_ALIYUN_SAMPLE_RATE_8K, TTS_ALIYUN_SAMPLE_RATE_16K, TTS_ALIYUN_SAMPLE_RATE_24K } }, { "xiaomei", { VOICE_CHINESE, VOICE_CN_EN_MIX, VOICE_NULL }, { TTS_ALIYUN_SAMPLE_RATE_8K, TTS_ALIYUN_SAMPLE_RATE_16K, TTS_ALIYUN_SAMPLE_RATE_24K } }, { "sitong", { VOICE_CHINESE, VOICE_NULL, VOICE_NULL }, { TTS_ALIYUN_SAMPLE_RATE_8K, TTS_ALIYUN_SAMPLE_RATE_16K, TTS_ALIYUN_SAMPLE_RATE_24K } }, { "ninger", { VOICE_CHINESE, VOICE_NULL, VOICE_NULL }, { TTS_ALIYUN_SAMPLE_RATE_8K, TTS_ALIYUN_SAMPLE_RATE_16K, TTS_ALIYUN_SAMPLE_RATE_24K } }, { "xiaobei", { VOICE_CHINESE, VOICE_NULL, VOICE_NULL }, { TTS_ALIYUN_SAMPLE_RATE_8K, TTS_ALIYUN_SAMPLE_RATE_16K, TTS_ALIYUN_SAMPLE_RATE_24K } }, { "yina", { VOICE_CHINESE, VOICE_NULL, VOICE_NULL }, { TTS_ALIYUN_SAMPLE_RATE_8K, TTS_ALIYUN_SAMPLE_RATE_16K, TTS_ALIYUN_SAMPLE_RATE_24K } }, { "sijing", { VOICE_CHINESE, VOICE_NULL, VOICE_NULL }, { TTS_ALIYUN_SAMPLE_RATE_8K, TTS_ALIYUN_SAMPLE_RATE_16K, TTS_ALIYUN_SAMPLE_RATE_24K } }, { "wendy", { VOICE_ENGLISH, VOICE_NULL, VOICE_NULL }, { TTS_ALIYUN_SAMPLE_RATE_8K, TTS_ALIYUN_SAMPLE_RATE_16K, TTS_ALIYUN_SAMPLE_RATE_24K } }, { "william", { VOICE_ENGLISH, VOICE_NULL, VOICE_NULL }, { TTS_ALIYUN_SAMPLE_RATE_8K, TTS_ALIYUN_SAMPLE_RATE_16K, TTS_ALIYUN_SAMPLE_RATE_24K } }, { "halen", { VOICE_ENGLISH, VOICE_NULL, VOICE_NULL }, { TTS_ALIYUN_SAMPLE_RATE_8K, TTS_ALIYUN_SAMPLE_RATE_16K, 0 } }, { "harry", { VOICE_ENGLISH, VOICE_NULL, VOICE_NULL }, { TTS_ALIYUN_SAMPLE_RATE_8K, TTS_ALIYUN_SAMPLE_RATE_16K, 0 } }, }; static aliyun_tts_config_t g_tts_config; static int tts_state = ALIYUN_TTS_STATE_NULL; static char *tts_format[4] = { "null", "pcm", "wav", "mp3" }; int uvoice_tts_aliyun_init(tts_config_t *config) { int i = 0; int j = 0; int flag = 0; if (!config) { M_LOGE("config is null!"); return -1; } if (!config->app_key) { M_LOGE("app_key is null!"); return -1; } if (!config->token) { M_LOGE("token is null!"); return -1; } if ((config->format != MEDIA_FMT_PCM) && (config->format != MEDIA_FMT_WAV) && (config->format != MEDIA_FMT_MP3)) { M_LOGE("format %d is not supported !", config->format); return -1; } if ((config->sample_rate != TTS_ALIYUN_SAMPLE_RATE_8K) && (config->sample_rate != TTS_ALIYUN_SAMPLE_RATE_16K) && (config->sample_rate != TTS_ALIYUN_SAMPLE_RATE_24K)) { M_LOGE("sample rate %d is not supported !", config->sample_rate); return -1; } if ((config->speech_rate < TTS_SPEECH_RATE_MIN) || (config->speech_rate > TTS_SPEECH_RATE_MAX)) { M_LOGE("speech rate %d is not supported !", config->speech_rate); return -1; } if ((config->pitch_rate < TTS_PITCH_RATE_MIN) || (config->pitch_rate > TTS_PITCH_RATE_MAX)) { M_LOGE("pitch rate %d is not supported !", config->pitch_rate); return -1; } if ((config->volume < TTS_VOLUME_MIN) || (config->volume > TTS_VOLUME_MAX)) { M_LOGE("volume %d is not supported !", config->volume); return -1; } for (i = 0; i < sizeof(voice_spec) / sizeof(voice_spec_t); i++) { if (!strcmp(voice_spec[i].voice_people, config->voice)) { for (j = 0; j < 3; j++) { if ((voice_spec[i].sample_rate[j] == config->sample_rate) && (voice_spec[i].sample_rate[j] != 0)) { flag = 1; break; } } } if (flag == 1) break; } if (flag == 0) { M_LOGE("sample rate %d not match %s !", config->sample_rate, config->voice); return -1; } memset(&g_tts_config, 0, sizeof(aliyun_tts_config_t)); //strncpy(g_tts_config.app_key, config->app_key, strlen(config->app_key)); //strncpy(g_tts_config.token, config->token, strlen(config->token)); snprintf(g_tts_config.app_key, sizeof(g_tts_config.app_key), "%s", config->app_key); snprintf(g_tts_config.token, sizeof(g_tts_config.token), "%s", config->token); g_tts_config.format = config->format; /* tts output format, now only support wav, pcm, mp3 */ g_tts_config.sample_rate = config->sample_rate; /* support 8000Hz��16000Hz */ //strncpy(g_tts_config.voice, config->voice, strlen(config->voice)); /* voice people */ snprintf(g_tts_config.voice, sizeof(g_tts_config.voice), "%s", config->voice); g_tts_config.volume = config->volume; /* 0 ~ 100 */ g_tts_config.speech_rate = config->speech_rate; /* -500 ~ 500 */ g_tts_config.pitch_rate = config->pitch_rate; /* -500 ~ 500 */ g_tts_config.text_encode_type = config->text_encode_type; tts_state = ALIYUN_TTS_STATE_INITED; return 0; } static void http_download(char *req_url, tts_recv_callback_t *recv_cb) { char *rsp_buf = malloc(2048); char *req_buf = malloc(1024 + strlen(req_url)); httpclient_t client = { 0 }; httpclient_data_t client_data = { 0 }; int num = 0; int ret = 0; int idx = 0; memset(req_buf, 0, sizeof(req_buf)); client_data.header_buf = req_buf; client_data.header_buf_len = 1024 + strlen(req_url); memset(rsp_buf, 0, 2048); client_data.response_buf = rsp_buf; client_data.response_buf_len = 2048; ret = httpclient_conn(&client, req_url); if (!ret) { ret = httpclient_send(&client, req_url, HTTP_GET, &client_data); do { ret = httpclient_recv(&client, &client_data); M_LOGD("response_content_len=%d, retrieve_len=%d,content_block_len=%d\n", client_data.response_content_len, client_data.retrieve_len, client_data.content_block_len); M_LOGD("ismore = %d\n", client_data.is_more); num = recv_cb->recv_data(client_data.response_buf, client_data.content_block_len, idx++); if (num > 0) { printf("aos_write num=%d\n", num); } } while (client_data.is_more); } httpclient_clse(&client); free(rsp_buf); free(req_buf); return; } //by: alicloud_tts_download_task() int uvoice_tts_aliyun_request(char *text, tts_recv_type_e recv_type, tts_recv_callback_t *recv_cb) { int i = 0; int ret = 0; char *tts_text = NULL; char *utf8_text = NULL; int tts_text_len; char *tts_get_url = NULL; if (tts_state != ALIYUN_TTS_STATE_INITED) { M_LOGE("aliyun tts: not initialized\n"); return -1; } if (!recv_cb) { M_LOGE("aliyun tts: recv callback is null\n"); return -1; } tts_text_len = strlen(text); if (tts_text_len > UVOICE_TTS_MAX_TEXT_LEN) { tts_text_len = UVOICE_TTS_MAX_TEXT_LEN; if (recv_cb->event) { recv_cb->event(TTS_WARNING, "text length too long, cut to " UVOICE_TTS_MAX_TEXT_LEN_STR); } } tts_text = snd_zalloc(tts_text_len * 3 + 1, AFM_EXTN); if (!tts_text) { M_LOGE("alloc tts text buffer fail !\n"); return -1; } snprintf(tts_text, tts_text_len * 3 + 1, "%s", text); #ifdef UVOICE_TTS_SUPPORT_GBK_ENCODE if (g_tts_config.text_encode_type == TTS_ENCODE_GBK) { utf8_text = snd_zalloc(tts_text_len * 2 * 3 + 1, AFM_EXTN); if (!utf8_text) { M_LOGE("alloc utf8 text buffer fail !\n"); goto exit_free; } uvoice_gbk2utf8(tts_text, utf8_text, tts_text_len * 2); M_LOGI("text encode type GBK\n"); } else #endif { utf8_text = tts_text; M_LOGI("text encode type UTF-8\n"); } uvoice_urlencode(utf8_text); tts_get_url = snd_zalloc(UVOICE_TTS_HTTPGET_URL_LENGTH, AFM_MAIN); if (!tts_get_url) { M_LOGE("alloc url buffer fail !\n"); goto exit_free; } snprintf(tts_get_url, UVOICE_TTS_HTTPGET_URL_LENGTH, "%sappkey=%s&token=%s&text=%s&format=%s&sample_rate=%u&voice=%s&volume=%d&speech_rate=%d&pitch_rate=%d", ALIYUN_TTS_HTTP_URL, g_tts_config.app_key, g_tts_config.token, utf8_text, tts_format[g_tts_config.format], g_tts_config.sample_rate, g_tts_config.voice, g_tts_config.volume, g_tts_config.speech_rate, g_tts_config.pitch_rate); if (recv_type == TTS_RECV_URL) { if (recv_cb->recv_url) { printf("tts url is %s\n", tts_get_url); recv_cb->recv_url(tts_get_url); } if (recv_cb->event) recv_cb->event(TTS_TRANS_COMPLETE, "OK"); ret = 0; goto exit_free; } if (recv_type == TTS_RECV_DATA) { media_loader_t *mloader; uint8_t *buffer = NULL; int size = 2048; int ret_size = 0; int index = 0; if (recv_cb->recv_data == NULL) { M_LOGE("recv_cb->recv_data is null !\n"); ret = -1; goto exit_free; } http_download(tts_get_url, recv_cb); goto exit_free; mloader = snd_zalloc(sizeof(media_loader_t), AFM_EXTN); if (!mloader) { M_LOGE("alloc mloader failed !\n"); ret = -1; goto exit_free; } M_LOGD("url %s\n", tts_get_url); ret = http_loader_create(mloader, tts_get_url); if (ret) { M_LOGE("alloc mloader failed !\n"); ret = -1; goto exit_free; } buffer = snd_zalloc(size, AFM_EXTN); if (!buffer) { M_LOGE("alloc buffer fail !\n"); ret = -1; http_loader_release(mloader); goto exit_free; } if (recv_cb->event) recv_cb->event(TTS_RECV_START, ""); if (mloader->action(mloader, PLAYER_START, NULL)) { M_LOGE("start http load failed !\n"); ret = -1; snd_free(buffer); http_loader_release(mloader); snd_free(mloader); goto exit_free; } while (1) { ret_size = mloader->read(mloader, buffer, size); if (ret_size > 0) { recv_cb->recv_data(buffer, ret_size, index); index++; } else { break; } } mloader->action(mloader, PLAYER_STOP, NULL); if (recv_cb->event) recv_cb->event(TTS_RECV_COMPLETE, NULL); snd_free(buffer); http_loader_release(mloader); snd_free(mloader); } exit_free: if (tts_text) snd_free(tts_text); #ifdef UVOICE_TTS_SUPPORT_GBK_ENCODE if (utf8_text) snd_free(utf8_text); #endif if (tts_get_url) snd_free(tts_get_url); return ret; } int uvoice_tts_aliyun_stop() { return 0; }
YifuLiu/AliOS-Things
components/uvoice/application/alicloudtts/alicloudtts.c
C
apache-2.0
12,984
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifndef __UVOICE_AIYUNTTS_INTF_H__ #define __UVOICE_AIYUNTTS_INTF_H__ #define UVOICE_TTS_MAX_TEXT_LEN 200 #define UVOICE_TTS_MAX_TEXT_LEN_STR "200" #define UVOICE_TTS_HTTPGET_URL_LENGTH 1024 #define TTS_ALIYUN_SAMPLE_RATE_8K 8000 #define TTS_ALIYUN_SAMPLE_RATE_16K 16000 #define TTS_ALIYUN_SAMPLE_RATE_24K 24000 #define TTS_SPEECH_RATE_MIN (-500) #define TTS_SPEECH_RATE_MAX (500) #define TTS_PITCH_RATE_MIN (-500) #define TTS_PITCH_RATE_MAX (500) #define TTS_VOLUME_MIN (0) #define TTS_VOLUME_MAX (100) #define ALIYUN_TTS_STATE_NULL 0 #define ALIYUN_TTS_STATE_INITED 1 #define ALIYUN_TTS_STATE_STOP 2 typedef enum { VOICE_CHINESE = 0, /* Chinese */ VOICE_ENGLISH = 1, /* English */ VOICE_CN_EN_MIX = 2, /* Mixed Chinese & English */ VOICE_NULL = 0xFFFF, } voice_language_e; typedef struct { char *voice_people; voice_language_e lang[3]; int sample_rate[3]; } voice_spec_t; #endif /* end of __UVOICE_AIYUNTTS_INTF_H__ */
YifuLiu/AliOS-Things
components/uvoice/application/alicloudtts/alicloudtts_intf.h
C
apache-2.0
1,056
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifndef __UVOICE_TTS_H__ #define __UVOICE_TTS_H__ #include "uvoice_types.h" typedef enum { TTS_AICLOUD_ALIYUN = 0, /* aliyun tts service */ /*if use aliyun tts service, please get app_key、token from aliyun,see https://help.aliyun.com/document_detail/84435.html?spm=a2c4g.11186623.2.30.355b5275kgR9PT to get the config guide*/ } tts_aicloud_type_e; typedef enum { TTS_ENCODE_GBK = 0, TTS_ENCODE_UTF8, } tts_encode_type_e; typedef struct { char *app_key; /* get it form the cloud service */ char *token; /* get it form the cloud service */ media_format_t format; /* tts output format, now only support wav, pcm, mp3 */ int sample_rate; /* support 8000Hz、16000Hz */ char *voice; /* voice people */ int volume; /* 0 ~ 100 */ int speech_rate; /* -500 ~ 500 */ int pitch_rate; /* -500 ~ 500 */ tts_encode_type_e text_encode_type; } tts_config_t; typedef enum { TTS_RECV_URL = 0, TTS_RECV_DATA = 1, } tts_recv_type_e; typedef enum { TTS_TRANS_START = 0, TTS_TRANS_COMPLETE = 1, TTS_RECV_START = 2, TTS_RECV_COMPLETE = 3, TTS_INFO = 4, TTS_WARNING = 5, TTS_ERROR = 6, } tts_event_e; typedef struct { int (*recv_url)(char *tts_url); int (*recv_data)(uint8_t *buffer, int nbytes, int index); int (*event)(tts_event_e event, char *info); } tts_recv_callback_t; typedef struct { int (*tts_init)(tts_aicloud_type_e aicloud_type, tts_config_t *config); int (*tts_request)(char *text, tts_recv_type_e recv_type, tts_recv_callback_t *recv_cb); int (*tts_stop)(); void *priv; } uvoice_tts_t; #ifdef UVOICE_TTS_ENABLE uvoice_tts_t *uvoice_tts_create(void); int uvoice_tts_release(uvoice_tts_t *uvoice_tts); #endif #endif /* __UVOICE_TTS_H__ */
YifuLiu/AliOS-Things
components/uvoice/application/alicloudtts/include/uvoice_tts.h
C
apache-2.0
1,880
/* * 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_tts.h" #include "../../../internal/uvoice_os.h" static tts_aicloud_type_e g_aicloud_type; static uvoice_tts_t *g_uvoice_tts; static int uvoice_tts_init(tts_aicloud_type_e aicloud_type, tts_config_t *config) { g_aicloud_type = aicloud_type; if (aicloud_type == TTS_AICLOUD_ALIYUN) { #ifdef ALICLOUD_TTS_SUPPORT return uvoice_tts_aliyun_init(config); #else return -1; #endif } return -1; } static int uvoice_tts_request(char *text, tts_recv_type_e recv_type, tts_recv_callback_t *recv_cb) { if(g_aicloud_type == TTS_AICLOUD_ALIYUN) { #ifdef ALICLOUD_TTS_SUPPORT return uvoice_tts_aliyun_request(text, recv_type, recv_cb); #else return -1; #endif } return -1; } static int uvoice_tts_stop() { if(g_aicloud_type == TTS_AICLOUD_ALIYUN) { #ifdef ALICLOUD_TTS_SUPPORT return uvoice_tts_stop(); #else return -1; #endif } return -1; } uvoice_tts_t *uvoice_tts_create(void) { uvoice_tts_t *uvoice_tts = g_uvoice_tts; if (uvoice_tts) return uvoice_tts; uvoice_tts = snd_zalloc(sizeof(uvoice_tts_t), AFM_EXTN); if (!uvoice_tts) { M_LOGE("alloc uvoice_tts failed !\n"); return NULL; } g_uvoice_tts = uvoice_tts; uvoice_tts->tts_init = uvoice_tts_init; uvoice_tts->tts_request = uvoice_tts_request; uvoice_tts->tts_stop = uvoice_tts_stop; M_LOGI("uvoice tts create\n"); return uvoice_tts; } int uvoice_tts_release(uvoice_tts_t *uvoice_tts) { if (uvoice_tts) { snd_free(uvoice_tts); g_uvoice_tts = NULL; M_LOGI("uvoice tts release\n"); } return 0; }
YifuLiu/AliOS-Things
components/uvoice/application/alicloudtts/tts.c
C
apache-2.0
1,712
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited * */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <signal.h> #include <math.h> #include "uvoice_types.h" #include "uvoice_player.h" #include "uvoice_event.h" #include "uvoice_os.h" #include "uvoice_comb.h" #include "uvoice_list.h" #include "cJSON.h" #define TONE_SOURCE_PREFIX "" #define TONE_SOURCE_SUFFIX "" #define TONE_SOURCE_LEN_MAX 64 #define FILE_LIST_COUNT_MAX 32 #define HTTP_LIST_COUNT_MAX 32 #define BUILD_FOR_WTK_PAYBOX enum { COMB_PLAY_STAT_STOP = 0, COMB_PLAY_STAT_RUNNING, }; typedef struct { uint8_t running:1; uint8_t stop:1; uint8_t listplay_stop:1; int comb_play_state; int listplay_count; uvoice_player_t *player; uvoice_list_t list; uvoice_list_t url_list; os_sem_t listplay_stop_sem; os_mutex_t list_lock; os_mutex_t url_list_lock; os_task_t task; void (*state_cb)(int); } comb_handler_t; typedef struct { char source[TONE_SOURCE_LEN_MAX]; int index; int final; void (*cplt_cb)(void *args, int event); void *userdata; uvoice_list_t list; } comb_node_t; typedef struct { char *url; int index; uvoice_list_t list; } url_node_t; static char *tonename_numb[] = { "num_0", "num_1", "num_2", "num_3", "num_4", "num_5", "num_6", "num_7", "num_8", "num_9", "num_10", }; static char *tonename_unit[] = { "none", "ten", "hundred", "thousand", }; static char *tonename_hunit[] = { "ten_thousand", "hundred_million", }; static comb_handler_t *g_comb_handler; static int add_amount(uvoice_list_t *head, double num, int index) { comb_node_t *node; int slot; int depth = 0; int factor = 0; int ret = -1; long long numb = (long long)num; double deci = num - (double)numb; long long target = numb; int sub_target; int sub_number; bool prev_slot_zero = false; bool hundred_million_exist = false; bool ten_thousand_exist = false; char deci_desc[16]; char *ptr; int i; int count = 0; if (!head) { M_LOGE("list head null !\n"); return -1; } if (numb < 0 || numb >= 1000000000000) { M_LOGE("numb overrange !\n"); return -1; } if (deci < 0.0001 && deci > 0.0) { M_LOGW("deci reset\n"); deci = 0.0001; } M_LOGD("num %lf deci %lf numb %ld\n", num, deci, numb); for (i = 2; i >= 0; i--) { factor = pow(10000, i); if (target < factor) continue; sub_target = (int)(target / factor); target %= factor; if (sub_target == 0) continue; if (i == 2) hundred_million_exist = true; else if (i == 1) ten_thousand_exist = true; sub_number = sub_target; prev_slot_zero = false; for (depth = 3; depth >= 0; depth--) { if (sub_number == 0) break; factor = pow(10, depth); if ((hundred_million_exist || ten_thousand_exist) && i == 0) { M_LOGD("%s: nop\n", __func__); } else if (hundred_million_exist && ten_thousand_exist && (depth > 0) && sub_target < factor) { M_LOGD("%s: nop\n", __func__); } else if (sub_target < factor) { continue; } slot = (int)(sub_number / factor); sub_number %= factor; if (slot == 0 && depth == 0) continue; if ((sub_target < 20 && depth == 1) || (slot == 0 && prev_slot_zero) || (slot == 0 && depth == 0)) { M_LOGD("%s: nop\n", __func__); } else { node = snd_zalloc(sizeof(comb_node_t), AFM_EXTN); if (!node) { M_LOGE("alloc tone list failed !\n"); return -1; } snprintf(node->source, sizeof(node->source), "%s", tonename_numb[slot]); node->index = index; uvoice_list_add_tail(&node->list, head); count++; if (slot == 0 && !prev_slot_zero) prev_slot_zero = true; else if (prev_slot_zero && slot != 0) prev_slot_zero = false; } if (slot > 0 && depth > 0) { node = snd_zalloc(sizeof(comb_node_t), AFM_EXTN); if (!node) { M_LOGE("alloc tone list failed !\n"); return -1; } snprintf(node->source, sizeof(node->source), "%s", tonename_unit[depth]); node->index = index; uvoice_list_add_tail(&node->list, head); count++; } } if (i > 0) { node = snd_zalloc(sizeof(comb_node_t), AFM_EXTN); if (!node) { M_LOGE("alloc tone list failed !\n"); return -1; } snprintf(node->source, sizeof(node->source), "%s", tonename_hunit[i - 1]); node->index = index; uvoice_list_add_tail(&node->list, head); count++; } } if (count == 0 && numb == 0) { node = snd_zalloc(sizeof(comb_node_t), AFM_EXTN); if (!node) { M_LOGE("alloc tone list failed !\n"); return -1; } snprintf(node->source, sizeof(node->source), "num_0"); node->index = index; uvoice_list_add_tail(&node->list, head); count++; } if (deci >= 0.0001) { M_LOGD("add deci part\n"); node = snd_zalloc(sizeof(comb_node_t), AFM_EXTN); if (!node) { M_LOGE("alloc tone list failed !\n"); return -1; } snprintf(node->source, sizeof(node->source), "dot"); node->index = index; uvoice_list_add_tail(&node->list, head); snprintf(deci_desc, sizeof(deci_desc), "%lf", deci); memmove(deci_desc, (char *)deci_desc + 2, strlen((char *)deci_desc + 2)); ptr = (char *)deci_desc + (strlen(deci_desc) - 1); while (*ptr == '0' || (ptr - deci_desc >= 4)) { *ptr = '\0'; ptr--; if (ptr == deci_desc) break; } for (i = 0; i < strlen(deci_desc); i++) { sub_number = deci_desc[i] - '0'; node = snd_zalloc(sizeof(comb_node_t), AFM_EXTN); if (!node) { M_LOGE("alloc tone list failed !\n"); return -1; } snprintf(node->source, sizeof(node->source), "%s", tonename_numb[sub_number]); node->index = index; uvoice_list_add_tail(&node->list, head); } } return 0; } static int add_number(uvoice_list_t *head, const char *number, int index) { comb_node_t *node; char *ptr; int number_len; int i; char num_code; if (!number) { M_LOGE("number null !\n"); return -1; } number_len = strlen(number); for (i = 0; i < number_len; i++) { num_code = *(number + i); if (num_code < '0' || num_code > '9') return -1; } for (i = 0; i < number_len; i++) { num_code = *(number + i); if (num_code < '0' || num_code > '9') continue; num_code -= '0'; node = snd_zalloc(sizeof(comb_node_t), AFM_EXTN); if (!node) { M_LOGE("alloc tone list failed !\n"); continue; } snprintf(node->source, sizeof(node->source), "%s", tonename_numb[num_code]); node->index = index; uvoice_list_add_tail(&node->list, head); } return 0; } static int add_file_source(uvoice_list_t *head, const char *source, int index, int final, void (*cb)(void *args, int event), void *userdata) { comb_node_t *node; if (!head) { M_LOGE("list head null !\n"); return -1; } if (!source) { M_LOGE("source null !\n"); return -1; } if (strlen(source) >= TONE_SOURCE_LEN_MAX || strlen(source) <= 0) { M_LOGE("source %s length overrange !\n", source); return -1; } node = snd_zalloc(sizeof(comb_node_t), AFM_EXTN); if (!node) { M_LOGE("alloc tone list failed !\n"); return -1; } node->index = index; node->final = final; if (node->final) { node->cplt_cb = cb; node->userdata = userdata; } snprintf(node->source, sizeof(node->source), "%s", source); uvoice_list_add_tail(&node->list, head); return 0; } static int add_http_source(uvoice_list_t *head, const char *url, int index) { url_node_t *node; if (!head) { M_LOGE("list head null !\n"); return -1; } if (!url) { M_LOGE("url null !\n"); return -1; } if (strncmp(url, "http://", strlen("http://")) && strncmp(url, "https://", strlen("https://")) && strncmp(url, "fs:", strlen("fs:"))) { M_LOGE("url invalid !\n"); return -1; } node = snd_zalloc(sizeof(url_node_t), AFM_EXTN); if (!node) { M_LOGE("alloc url node failed !\n"); return -1; } node->url = snd_zalloc(strlen(url) + 1, AFM_EXTN); if (!node->url) { M_LOGE("alloc url buffer failed !\n"); snd_free(node); return -1; } node->index = index; snprintf(node->url, strlen(url) + 1, "%s", url); M_LOGI("play %s\n", node->url); uvoice_list_add_tail(&node->list, head); return 0; } static int file_is_accessed(char *source) { if (os_access(source, OS_F_OK)) { M_LOGE("file %s not exist\n", source); return 0; } if (os_access(source, OS_R_OK)) { M_LOGE("file %s not readable\n", source); return 0; } return 1; } static int __comb_play_url(comb_handler_t *handler) { uvoice_player_t *player; player_state_t state = -1; url_node_t *node; uvoice_list_t *temp; player = handler->player; os_mutex_lock(handler->url_list_lock, OS_WAIT_FOREVER); if (uvoice_list_empty(&handler->url_list)) { os_mutex_unlock(handler->url_list_lock); return 0; } if (player->get_state(&state)) { M_LOGE("get player state failed !\n"); os_mutex_unlock(handler->url_list_lock); return -1; } if (state != PLAYER_STAT_IDLE) { os_mutex_unlock(handler->url_list_lock); return 0; } uvoice_list_for_each_entry_safe(&handler->url_list, temp, node, url_node_t, list) { if (node->url) { if (player->set_source(node->url)) { uvoice_list_del(&node->list); snd_free(node->url); snd_free(node); continue; } if (player->start()) { handler->player->clr_source(); } uvoice_list_del(&node->list); snd_free(node->url); snd_free(node); break; } } os_mutex_unlock(handler->url_list_lock); return 0; } static void __comb_task(void *arg) { comb_handler_t *handler = (comb_handler_t *)arg; uvoice_player_t *player; player_state_t state = -1; comb_node_t *node; uvoice_list_t *temp; media_format_t format; bool player_paused = false; bool stream_open = false; int file_size; int read_size; int buffer_size = 1200; char *buffer; os_file_t fp; int ret; int first_buffer = 0; int list_play_count = 0; if (!handler) { M_LOGE("handler null !\n"); return -1; } player = handler->player; buffer = snd_zalloc(buffer_size, AFM_MAIN); if (!buffer) { M_LOGE("alloc buffer failed !\n"); os_task_exit(handler->task); return; } handler->running = 1; handler->comb_play_state = PLAYER_STAT_LIST_PLAY_STOP; M_LOGI("comb running\n"); while (!handler->stop) { os_mutex_lock(handler->list_lock, OS_WAIT_FOREVER); if (uvoice_list_empty(&handler->list)) { os_mutex_unlock(handler->list_lock); __comb_play_url(handler); os_msleep(100); continue; } player->get_state(&state); if (state == PLAYER_STAT_RUNNING || state == PLAYER_STAT_COMPLETE) { #ifdef BUILD_FOR_WTK_PAYBOX player->stop(); player->clr_source(); player_paused = false; #else player->pause(); player_paused = true; #endif } uvoice_list_for_each_entry_safe(&handler->list, temp, node, comb_node_t, list) { if (handler->listplay_stop) { uvoice_list_del(&node->list); snd_free(node); if (node->final) { if (node->cplt_cb) node->cplt_cb(node->userdata, 1); handler->listplay_count--; } continue; } os_mutex_unlock(handler->list_lock); if (handler->comb_play_state == PLAYER_STAT_LIST_PLAY_STOP) { handler->comb_play_state = PLAYER_STAT_LIST_PLAY_START; uvoice_event_post(UVOICE_EV_PLAYER, UVOICE_CODE_PLAYER_STATE, handler->comb_play_state); } M_LOGD("play %s, index %d\n", node->source, node->index); fp = os_fopen(node->source, "r"); if (!fp) { M_LOGE("open %s failed\n", node->source); os_mutex_lock(handler->list_lock, OS_WAIT_FOREVER); uvoice_list_del(&node->list); snd_free(node); continue; } if (!stream_open) { if (strstr(node->source, ".mp3") || strstr(node->source, ".MP3")) { format = MEDIA_FMT_MP3; buffer_size = 1200; } else if (strstr(node->source, ".amr") || strstr(node->source, ".AMR")) { format = MEDIA_FMT_AMR; buffer_size = 320; } else if (strstr(node->source, ".wav") || strstr(node->source, ".WAV")) { format = MEDIA_FMT_WAV; buffer_size = 960; } else { M_LOGE("format not support !\n"); os_mutex_lock(handler->list_lock, OS_WAIT_FOREVER); uvoice_list_del(&node->list); snd_free(node); os_fclose(fp); continue; } if (player->set_stream(format, 0, 0)) { M_LOGE("set stream failed !\n"); os_mutex_lock(handler->list_lock, OS_WAIT_FOREVER); uvoice_list_del(&node->list); snd_free(node); os_fclose(fp); continue; } list_play_count = 0; stream_open = true; } else { list_play_count++; } os_fseek(fp, 0, OS_SEEK_END); file_size = os_ftell(fp); os_fseek(fp, 0, OS_SEEK_SET); first_buffer = 2; while (1) { #if 1 ret = os_fread(buffer, 1, buffer_size, fp); if (ret < 0) { M_LOGE("read failed %d!\n", ret); break; } else if (ret == 0) { break; } read_size = ret; #else if (file_size - play_size < buffer_size) { read_size = file_size - play_size; if (read_size <= 0) break; } else { read_size = buffer_size; } ret = os_fread(buffer, 1, read_size, fp); if (ret <= 0) { M_LOGD("read end\n"); break; } play_size += read_size; #endif if (node->index == 0 && first_buffer == 2 && list_play_count > 0 && format == MEDIA_FMT_WAV) { player->put_stream(buffer + 44, read_size - 44); if (handler->listplay_stop) { M_LOGD("list playing stop\n"); break; } first_buffer = 1; continue; } if (node->index != 0 && first_buffer && format == MEDIA_FMT_WAV) { player->put_stream(buffer + 44, read_size - 44); first_buffer = 0; if (handler->listplay_stop) { M_LOGD("list playing stop\n"); break; } continue; } if (player->put_stream(buffer, read_size)) { M_LOGE("put stream failed !\n"); break; } if (handler->listplay_stop) { M_LOGD("list playing stop\n"); break; } } os_fclose(fp); os_mutex_lock(handler->list_lock, OS_WAIT_FOREVER); if (node->final) { handler->listplay_count--; if (node->cplt_cb) node->cplt_cb(node->userdata, 0); } uvoice_list_del(&node->list); snd_free(node); } player->clr_stream(0); stream_open = false; handler->comb_play_state = PLAYER_STAT_LIST_PLAY_STOP; uvoice_event_post(UVOICE_EV_PLAYER, UVOICE_CODE_PLAYER_STATE, handler->comb_play_state); if (handler->listplay_stop) { handler->listplay_stop = 0; os_sem_signal(handler->listplay_stop_sem); } if (player_paused) { player->set_fade(40, 60); player->resume(); player_paused = false; } os_mutex_unlock(handler->list_lock); } snd_free(buffer); M_LOGW("comb task exit\n"); os_task_exit(handler->task); } int comb_receipt_play(const char *req) { comb_handler_t *handler = g_comb_handler; cJSON *root, *item, *sub_item; char *ptr; int index, timestamp; int i, ret; if (!req) { M_LOGE("args invalid !\n"); return -1; } if (!handler) { M_LOGE("handler null !\n"); return -1; } if (!handler->running) { M_LOGW("comb not running, ignore\n"); return -1; } root = cJSON_Parse(req); if (!root || !cJSON_IsObject(root)) { M_LOGE("parse json root failed !\n"); return -1; } item = cJSON_GetObjectItem(root, "Timestamp"); if (!item || !cJSON_IsString(item)) { M_LOGE("receipt timestamp not found !\n"); cJSON_Delete(root); return -1; } timestamp = atoi(item->valuestring); if (timestamp < 0) { M_LOGE("receipt timestamp invalid !\n"); cJSON_Delete(root); return -1; } M_LOGI("timestamp %d\n", timestamp); item = cJSON_GetObjectItem(root, "Index"); if (!item || !cJSON_IsNumber(item)) { M_LOGE("receipt index not found !\n"); cJSON_Delete(root); return -1; } index = item->valueint; item = cJSON_GetObjectItem(root, "MSG"); if (!item || !cJSON_IsArray(item)) { M_LOGE("get receipt object failed !\n"); cJSON_Delete(root); return -1; } for (i = 0; i < cJSON_GetArraySize(item); i++) { sub_item = cJSON_GetArrayItem(item, i); if (!sub_item || !cJSON_IsString(sub_item)) { M_LOGE("parse array item %d failed !\n", i); continue; } ptr = sub_item->valuestring; if (*ptr != '$' && (*ptr < '0' || *ptr > '9')) { ret = file_is_accessed(ptr); if (!ret) return -2; } } os_mutex_lock(handler->list_lock, OS_WAIT_FOREVER); for (i = 0; i < cJSON_GetArraySize(item); i++) { sub_item = cJSON_GetArrayItem(item, i); if (!sub_item || !cJSON_IsString(sub_item)) { M_LOGE("parse array item %d failed !\n", i); continue; } ptr = sub_item->valuestring; if (*ptr == '$') { if (strlen(ptr) < 2) { M_LOGE("parse number value failed !\n"); continue; } add_amount(&handler->list, atof(ptr + 1), index); continue; } if (*ptr >= '0' && *ptr <= '9') { add_number(&handler->list, ptr, index); continue; } ret = add_file_source(&handler->list, sub_item->valuestring, index, 0, NULL, NULL); } os_mutex_unlock(handler->list_lock); cJSON_Delete(root); return 0; } int comb_content_play(const char *req) { comb_handler_t *handler = g_comb_handler; cJSON *root, *item; int index, timestamp; if (!req) { M_LOGE("args invalid !\n"); return -1; } if (!handler) { M_LOGE("handler null !\n"); return -1; } if (!handler->running) { M_LOGW("comb not running, ignore\n"); return -1; } root = cJSON_Parse(req); if (!root || !cJSON_IsObject(root)) { M_LOGE("parse json root failed !"); return -1; } item = cJSON_GetObjectItem(root, "Timestamp"); if (!item || !cJSON_IsString(item)) { M_LOGE("content timestamp not found !\n"); cJSON_Delete(root); return -1; } timestamp = atoi(item->valuestring); if (timestamp < 0) { M_LOGE("receipt timestamp invalid !\n"); cJSON_Delete(root); return -1; } M_LOGI("timestamp %d\n", timestamp); item = cJSON_GetObjectItem(root, "Index"); if (!item || !cJSON_IsNumber(item)) { M_LOGE("content index not found !\n"); cJSON_Delete(root); return -1; } index = item->valueint; item = cJSON_GetObjectItem(root, "URL"); if (!item || !cJSON_IsString(item)) { M_LOGE("get url object failed !\n"); cJSON_Delete(root); return -1; } os_mutex_lock(handler->url_list_lock, OS_WAIT_FOREVER); add_http_source(&handler->url_list, item->valuestring, index); os_mutex_unlock(handler->url_list_lock); cJSON_Delete(root); return 0; } int comb_add_amount(const char *amount, int index) { comb_handler_t *handler = g_comb_handler; double _amount; int ret; if (!handler) { M_LOGE("handler null !\n"); return -1; } if (!handler->running) { M_LOGW("comb not running, ignore\n"); return -1; } _amount = atof(amount); os_mutex_lock(handler->list_lock, OS_WAIT_FOREVER); ret = add_amount(&handler->list, _amount, index); os_mutex_unlock(handler->list_lock); return ret; } int comb_add_number(const char *number, int index) { comb_handler_t *handler = g_comb_handler; int ret; if (!handler) { M_LOGE("handler null !\n"); return -1; } if (!handler->running) { M_LOGW("comb not running, ignore\n"); return -1; } os_mutex_lock(handler->list_lock, OS_WAIT_FOREVER); ret = add_number(&handler->list, number, index); os_mutex_unlock(handler->list_lock); return ret; } int comb_add_file_source_list(comb_source_info_t *info) { comb_handler_t *handler = g_comb_handler; int i; int ret = 0; if (!handler) { M_LOGE("handler null !\n"); return -1; } if (!handler->running) { M_LOGW("comb not running, ignore\n"); return -1; } os_mutex_lock(handler->list_lock, OS_WAIT_FOREVER); if (handler->listplay_count <= FILE_LIST_COUNT_MAX) { for (i = 0; i < info->count; i++) { if (i == info->count - 1) add_file_source(&handler->list, info->sources[i], i, 1, info->callback, info->userdata); else add_file_source(&handler->list, info->sources[i], i, 0, NULL, NULL); } handler->listplay_count++; } else { M_LOGW("play list is full\n"); } os_mutex_unlock(handler->list_lock); return 0; } int comb_add_file_source_unlock(const char *source, int index, int final, void (*cb)(void *args, int event), void *userdata) { comb_handler_t *handler = g_comb_handler; int ret = 0; if (!handler) { M_LOGE("handler null !\n"); return -1; } if (!handler->running) { M_LOGW("comb not running, ignore\n"); return -1; } if (!file_is_accessed(source)) { return -1; } if (handler->listplay_count <= FILE_LIST_COUNT_MAX) { ret = add_file_source(&handler->list, source, index, final, cb, userdata); if (!ret) { if (final) handler->listplay_count++; } } else { M_LOGW("play list is full\n"); } return ret; } int comb_file_source_lock(void) { comb_handler_t *handler = g_comb_handler; if (!handler) { M_LOGE("handler null !\n"); return -1; } if (!handler->running) { M_LOGW("comb not running, ignore\n"); return -1; } return os_mutex_lock(handler->list_lock, OS_WAIT_FOREVER); } int comb_file_source_unlock(void) { comb_handler_t *handler = g_comb_handler; if (!handler) { M_LOGE("handler null !\n"); return -1; } if (!handler->running) { M_LOGW("comb not running, ignore\n"); return -1; } return os_mutex_unlock(handler->list_lock); } int comb_add_http_source(const char *source, int index) { comb_handler_t *handler = g_comb_handler; int ret = 0; if (!handler) { M_LOGE("handler null !\n"); return -1; } if (!handler->running) { M_LOGW("comb not running, ignore\n"); return -1; } os_mutex_lock(handler->url_list_lock, OS_WAIT_FOREVER); if (uvoice_list_entry_count(&handler->url_list) <= HTTP_LIST_COUNT_MAX) { ret = add_http_source(&handler->url_list, source, index); } else { M_LOGW("play list is full\n"); } os_mutex_unlock(handler->url_list_lock); return ret; } int comb_clr_http_source(void) { comb_handler_t *handler = g_comb_handler; url_node_t *node; uvoice_list_t *temp; if (!handler) { M_LOGE("handler null !\n"); return -1; } if (!handler->running) { M_LOGW("comb not running, ignore\n"); return -1; } os_mutex_lock(handler->url_list_lock, OS_WAIT_FOREVER); uvoice_list_for_each_entry_safe(&handler->url_list, temp, node, url_node_t, list) { uvoice_list_del(&node->list); snd_free(node->url); snd_free(node); } os_mutex_unlock(handler->url_list_lock); return 0; } int comb_play_stop(void) { comb_handler_t *handler = g_comb_handler; if (!handler) { M_LOGE("handler null !\n"); return -1; } if (handler->comb_play_state == PLAYER_STAT_LIST_PLAY_START) { handler->listplay_stop = 1; os_sem_wait(handler->listplay_stop_sem, 5000); } return 0; } int comb_init(void) { comb_handler_t *handler = g_comb_handler; cache_config_t config; if (handler) { M_LOGW("comb init already, ignore\n"); return -1; } handler = snd_zalloc(sizeof(comb_handler_t), AFM_EXTN); if (!handler) { M_LOGE("alloc comb handler failed !\n"); return -1; } handler->player = uvoice_player_create(); if (!handler->player) { M_LOGE("create uvoice player failed !\n"); snd_free(handler); return -1; } config.place = 2; config.mem_size = 128; handler->player->cache_config(&config); handler->player->set_standby(0); uvoice_list_init(&handler->list); uvoice_list_init(&handler->url_list); handler->list_lock = os_mutex_new(); handler->url_list_lock = os_mutex_new(); handler->listplay_stop_sem = os_sem_new(0); g_comb_handler = handler; if (os_task_create(&handler->task, "comb_player_task", __comb_task, handler, 8192, UVOICE_TASK_PRI_NORMAL)) { M_LOGE("create comb task failed !\n"); os_mutex_free(handler->list_lock); os_mutex_free(handler->url_list_lock); os_sem_free(handler->listplay_stop_sem); uvoice_player_release(handler->player); snd_free(handler); g_comb_handler = NULL; return -1; } os_msleep(20); M_LOGI("comb init success\n"); return 0; } int comb_deinit(void) { comb_handler_t *handler = g_comb_handler; if (!handler) { M_LOGE("handler null !\n"); return -1; } handler->stop = 1; os_msleep(120); os_mutex_free(handler->list_lock); os_mutex_free(handler->url_list_lock); os_sem_free(handler->listplay_stop_sem); uvoice_player_release(handler->player); snd_free(handler); g_comb_handler = NULL; return 0; }
YifuLiu/AliOS-Things
components/uvoice/application/comb/comb.c
C
apache-2.0
29,316
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #ifndef __UVOICE_COMB_H__ #define __UVOICE_COMB_H__ #define COMB_SOURCE_LIST_MAX 100 #define COMB_SOURCE_PATH_LEN 64 typedef struct { const char sources[COMB_SOURCE_LIST_MAX][COMB_SOURCE_PATH_LEN]; int count; void (*callback)(void *args, int event); void *userdata; } comb_source_info_t; int comb_add_amount(const char *amount, int index); int comb_add_number(const char *number, int index); int comb_add_file_source_list(comb_source_info_t *info); int comb_add_http_source(const char *source, int index); int comb_clr_http_source(void); int comb_alipay_number(double amount); int comb_receipt_play(const char *req); int comb_content_play(const char *req); int comb_play_stop(void); int comb_init(void); int comb_deinit(void); #endif /* __UVOICE_COMB_H__ */
YifuLiu/AliOS-Things
components/uvoice/application/comb/include/uvoice_comb.h
C
apache-2.0
852
/* * 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 "uvoice_types.h" #include "uvoice_os.h" #include "uvoice_common.h" #include "uvoice_audio.h" #include "audio_common.h" #include "audio_stream.h" #include "audio_aec.h" #define AEC_REFER_DELAY_MS 10 int audio_aec_refer_conserve(struct aec_handler *aec, uint8_t *buffer, int nbytes) { if (!aec) { snd_err("aec handler null !\n"); return -1; } os_mutex_lock(aec->lock, OS_WAIT_FOREVER); if (uvoice_ringbuff_freesize(&aec->rb) >= nbytes) uvoice_ringbuff_fill(&aec->rb, buffer, nbytes); os_mutex_unlock(aec->lock); __exit: return 0; } int audio_aec_process(struct aec_handler *aec, uint8_t *buffer, int nbytes) { if (!aec) { snd_err("aec handler null !\n"); return -1; } os_mutex_lock(aec->lock, OS_WAIT_FOREVER); if (!aec->start) goto __exit; if (uvoice_ringbuff_dirtysize(&aec->rb) >= nbytes) { uvoice_ringbuff_read(&aec->rb, aec->echo_buffer, nbytes); if (echo_cancellation_process(aec, buffer, aec->echo_buffer, nbytes)) { snd_err("aec process failed !\n"); os_mutex_unlock(aec->lock); return -1; } } __exit: os_mutex_unlock(aec->lock); return 0; } int audio_aec_init(struct in_stream *in) { struct aec_handler *aec; struct pcm_config *config; int bits; if (!in) { snd_err("in stream null !\n"); return -1; } config = &in->pcm.config; bits = pcm_format_to_bits(config->format); aec = snd_zalloc(sizeof(struct aec_handler), AFM_EXTN); if (!aec) { snd_err("alloc echo cancellation struct failed !\n"); return -1; } aec->echo_buffer_size = period_samples_to_bytes(&in->pcm.config); aec->echo_buffer = snd_zalloc(aec->echo_buffer_size, AFM_MAIN); if (!aec->echo_buffer) { snd_err("alloc echo buffer failed !\n"); snd_free(aec); return -1; } aec->refer_pool_size = aec->echo_buffer_size; aec->refer_pool = snd_zalloc(aec->refer_pool_size, AFM_EXTN); if (!aec->refer_pool) { snd_err("alloc refer pool failed !\n"); snd_free(aec->echo_buffer); snd_free(aec); return -1; } if (echo_cancellation_create(aec, config->rate, bits, config->period_size)) { snd_err("create aec failed !\n"); snd_free(aec->refer_pool); snd_free(aec->echo_buffer); snd_free(aec); return -1; } uvoice_ringbuff_init(&aec->rb, aec->refer_pool, aec->refer_pool_size); aec->lock = os_mutex_new(); aec->rd_sem = os_sem_new(0); aec->wr_sem = os_sem_new(0); in->aec = aec; snd_debug("aec init\n"); return 0; } int audio_aec_deinit(struct in_stream *in) { struct aec_handler *aec; aec = in->aec; if (!aec) { snd_err("aec handler null !\n"); return -1; } echo_cancellation_release(aec); os_sem_free(aec->wr_sem); os_sem_free(aec->rd_sem); os_mutex_free(aec->lock); snd_free(aec->refer_pool); snd_free(aec->echo_buffer); snd_free(aec); in->aec = NULL; snd_debug("aec free\n"); return 0; }
YifuLiu/AliOS-Things
components/uvoice/audio/audio_aec.c
C
apache-2.0
3,362
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited * */ #ifndef __AUDIO_AEC_H__ #define __AUDIO_AEC_H__ struct aec_handler { void *aec_inst; uint8_t bypass:1; uint8_t start:1; uint8_t rd_waiting:1; uint8_t wr_waiting:1; uint8_t *refer_pool; uint8_t *echo_buffer; int refer_pool_size; int echo_buffer_size; int wr_len; int rd_len; os_mutex_t lock; os_sem_t wr_sem; os_sem_t rd_sem; uvoice_ringbuff_t rb; }; int audio_aec_refer_conserve(struct aec_handler *aec, uint8_t *buffer, int nbytes); int audio_aec_process(struct aec_handler *aec, uint8_t *buffer, int nbytes); int audio_aec_init(struct in_stream *in); int audio_aec_deinit(struct in_stream *in); #endif /* __AUDIO_AEC_H__ */
YifuLiu/AliOS-Things
components/uvoice/audio/audio_aec.h
C
apache-2.0
715
/* * 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 "uvoice_os.h" #include "uvoice_audio.h" #include "audio_common.h" enum pcm_format bits_to_pcm_format(int bits) { switch (bits) { case 32: return PCM_FORMAT_S32_LE; case 16: return PCM_FORMAT_S16_LE; case 24: return PCM_FORMAT_S24_LE; case 8: return PCM_FORMAT_S8; } return PCM_FORMAT_S16_LE; } #ifndef UVOICE_ON_XR871 int pcm_format_to_bits(enum pcm_format format) { switch (format) { case PCM_FORMAT_S32_LE: return 32; case PCM_FORMAT_S24_LE: return 32; case PCM_FORMAT_S24_3LE: return 24; case PCM_FORMAT_S16_LE: return 16; case PCM_FORMAT_S8: return 8; }; return 0; } #endif int pcm_to_decibel(struct pcm_config *config, uint8_t *buffer, int nbytes) { double ampl_sum = 0.0; int decibel; int samples; int i; int bits = pcm_format_to_bits(config->format) >> 3; if (bits == 0) { return 0; } samples = nbytes / bits; for (i = 0; i < samples; i += config->channels) ampl_sum += abs(buffer[i]); ampl_sum /= samples; decibel = (int)(20.0 * log10(ampl_sum)); return decibel; }
YifuLiu/AliOS-Things
components/uvoice/audio/audio_common.c
C
apache-2.0
1,413
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited * */ #ifndef __AUDIO_COMMON_H__ #define __AUDIO_COMMON_H__ enum { PARAM_KEY_INVALID = 0, PARAM_KEY_NOISE_SUPPRESSION, PARAM_KEY_ECHO_CANCELLATION, PARAM_KEY_AUTO_GAIN_CONTROL, PARAM_KEY_VOICE_ACTIVE_DETECT, PARAM_KEY_EFFECT_EQUALIZER, PARAM_KEY_OUT_PCM_DUMP, }; #define PARAM_VAL_ENABLE 1 #define PARAM_VAL_DISABLE 0 static inline bool pcm_rate_valid(int rate) { switch (rate) { case 8000: case 12000: case 16000: case 11025: case 22050: case 24000: case 32000: case 44100: case 48000: case 96000: case 192000: return true; } return false; } static inline bool pcm_channel_valid(int channels) { if (channels > 0 && channels <= 8) return true; return false; } static inline bool pcm_bits_valid(int bits) { if (bits == 8 || bits == 16 || bits == 24 || bits == 32) return true; return false; } enum pcm_format bits_to_pcm_format(int bits); #ifndef UVOICE_ON_XR871 int pcm_format_to_bits(enum pcm_format format); #endif int pcm_to_decibel(struct pcm_config *config, uint8_t *buffer, int nbytes); static inline int period_samples_to_bytes(struct pcm_config *config) { return (config->period_size * config->channels * (pcm_format_to_bits(config->format) >> 3)); } #endif /* __AUDIO_COMMON_H__ */
YifuLiu/AliOS-Things
components/uvoice/audio/audio_common.h
C
apache-2.0
1,298
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited * */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <stdarg.h> #include <errno.h> #include "uvoice_types.h" #include "uvoice_os.h" #include "uvoice_audio.h" #include "uvoice_pcm.h" #include "uvoice_common.h" #include "audio_common.h" #include "audio_stream.h" #include "audio_mixer.h" #define SPK_VOLUME_ID "spk_vol" #define HPH_VOLUME_ID "hph_vol" #define REC_VOLUME_ID "rec_vol" #define SPK_AND_HPH_VOLUME_ID "spk_hph_vol" int device_select(struct audio_device *adev, snd_device_t device, bool force) { int volume; if (!adev) { snd_err("adev null !\n"); return -1; } if (device >= SND_DEVICE_OUT_BEGIN && device <= SND_DEVICE_OUT_END) { if (adev->out_device != device || force) { volume = volume_get(device); if (volume >= VOLUME_LEVEL_MIN && volume <= VOLUME_LEVEL_MAX) adev->out_volume = volume; if (adev->out) { uvoice_set_path(&adev->out->pcm, device); volume_set(device, adev->out_volume); } adev->out_device = device; snd_debug("out device %d\n", device); } } else if (device >= SND_DEVICE_IN_BEGIN && device <= SND_DEVICE_IN_END) { if (adev->in_device != device || force) { if (adev->in) uvoice_set_path(&adev->in->pcm, device); adev->in_device = device; snd_debug("in device %d\n", device); } } else { snd_err("device %d invalid !\n", device); return -1; } __exit: return 0; } int volume_set(snd_device_t device, int volume) { unsigned char curr_vol = VOLUME_LEVEL_MIN; int len = sizeof(curr_vol); char *key = NULL; int ret; if (device == SND_DEVICE_OUT_SPEAKER) key = SPK_VOLUME_ID; else if (device == SND_DEVICE_OUT_HEADPHONE || device == SND_DEVICE_OUT_HEADSET) key = HPH_VOLUME_ID; else if (device == SND_DEVICE_OUT_RECEIVER) key = REC_VOLUME_ID; else if (device == SND_DEVICE_OUT_SPEAKER_AND_HEADPHONE) key = SPK_AND_HPH_VOLUME_ID; else return -1; ret = uvoice_set_volume(device, volume); if (ret) { snd_err("set volume failed %d!\n", volume); return -1; } ret = os_kv_get(key, &curr_vol, &len); if (ret == -ENOENT) { snd_debug("%s not found\n", key); } else if (ret) { snd_err("get %s failed %d!\n", key, ret); return -1; } if (volume == curr_vol) goto __exit; curr_vol = volume; ret = os_kv_set(key, &curr_vol, len, 0); if (ret) { snd_err("set %s failed %d!\n", key, ret); return -1; } __exit: return 0; } int volume_get(snd_device_t device) { unsigned char curr_vol = VOLUME_LEVEL_MIN; int len = sizeof(curr_vol); char *key = NULL; int ret; if (device == SND_DEVICE_OUT_SPEAKER) key = SPK_VOLUME_ID; else if (device == SND_DEVICE_OUT_HEADPHONE || device == SND_DEVICE_OUT_HEADSET) key = HPH_VOLUME_ID; else if (device == SND_DEVICE_OUT_RECEIVER) key = REC_VOLUME_ID; else if (device == SND_DEVICE_OUT_SPEAKER_AND_HEADPHONE) key = SPK_AND_HPH_VOLUME_ID; else return -1; ret = os_kv_get(key, &curr_vol, &len); if (ret == -ENOENT) { snd_debug("%s not found\n", key); return -1; } else if (ret) { snd_err("get %s failed %d!\n", key, ret); return -1; } return curr_vol; }
YifuLiu/AliOS-Things
components/uvoice/audio/audio_mixer.c
C
apache-2.0
3,666
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited * */ #ifndef __VOLUME_H__ #define __VOLUME_H__ int device_select(struct audio_device *adev, snd_device_t device, bool force); int volume_set(snd_device_t device, int level); int volume_get(snd_device_t device); #endif /* __VOLUME_H__ */
YifuLiu/AliOS-Things
components/uvoice/audio/audio_mixer.h
C
apache-2.0
303
/* * 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 "uvoice_types.h" #include "uvoice_os.h" #include "uvoice_common.h" #include "uvoice_audio.h" #include "audio_common.h" #include "audio_stream.h" #include "audio_process.h" #include "audio_aec.h" #define AEC_REFER_DELAY_MS 10 int audio_out_process(struct out_stream *out, uint8_t *buffer, int nbytes) { if (!out) { snd_err("out null !\n"); return -1; } #ifdef UVOICE_EQ_ENABLE equalizer_process(&out->pcm.config, buffer, nbytes); #endif return 0; } int audio_out_process_init(struct audio_device *adev, struct out_stream *out) { #ifdef UVOICE_EQ_ENABLE struct pcm_config *config; int period_size; int bits; if (!adev || !out) { snd_err("args null !\n"); return -1; } config = &out->pcm.config; bits = pcm_format_to_bits(config->format); period_size = period_samples_to_bytes(config); if (adev->equalizer_enable && !out->eq) { out->eq = equalizer_create(period_size, config->rate, bits, config->channels); if (!out->eq) { snd_err("create equalizer failed !\n"); return -1; } } #endif return 0; } int audio_out_process_deinit(struct out_stream *out) { #ifdef UVOICE_EQ_ENABLE if (!out) { snd_err("out null !\n"); return -1; } if (out->eq) { equalizer_release(out->eq); out->eq = NULL; } #endif return 0; } int audio_out_conserve(struct audio_device *adev, uint8_t *buffer, int nbytes) { struct in_stream *in; in = adev->in; if (!in) goto __exit; #ifdef UVOICE_AEC_ENABLE if (in->state == STREAM_RUNNING) { if (in->aec) return audio_aec_refer_conserve(in->aec, buffer, nbytes); } #endif __exit: return 0; } int audio_in_process(struct in_stream *in, uint8_t *buffer, int nbytes) { if (!in) { snd_err("stream null !\n"); return -1; } if (!buffer) { snd_err("buffer null !\n"); return -1; } #ifdef UVOICE_AEC_ENABLE if (in->aec) { if (audio_aec_process(in->aec, buffer, nbytes)) { snd_err("aec process failed !\n"); return -1; } } #endif #ifdef UVOICE_ANC_ENABLE if (in->ns) { if (noise_suppression_process(in->ns, buffer, nbytes)) { snd_err("ns process failed !\n"); return -1; } } #endif #ifdef UVOICE_AGC_ENABLE if (in->agc) { if (auto_gain_control_process(in->agc, buffer, nbytes)) { snd_err("agc process failed !\n"); return -1; } } #endif return 0; } int audio_in_process_init(struct audio_device *adev, struct in_stream *in) { struct pcm_config *config; int bits; if (!adev || !in) { snd_err("args null !\n"); return -1; } #ifdef UVOICE_ANC_ENABLE if (adev->noise_suppression) { in->ns = snd_zalloc(sizeof(struct noise_suppression), AFM_EXTN); if (!in->ns) { snd_err("alloc noise supression struct failed !\n"); return -1; } } #endif #ifdef UVOICE_AGC_ENABLE if (adev->auto_gain_control) { in->agc = snd_zalloc(sizeof(struct auto_gain_control), AFM_EXTN); if (!in->agc) { snd_err("alloc auto gain control struct failed !\n"); if (in->ns) { snd_free(in->ns); in->ns = NULL; } return -1; } } #endif config = &in->pcm.config; bits = pcm_format_to_bits(config->format); #ifdef UVOICE_ANC_ENABLE if (in->ns) { if (noise_suppression_create(in->ns, config->rate, bits, config->period_size, 3)) { snd_err("create ns failed !\n"); audio_in_process_deinit(in); return -1; } } #endif #ifdef UVOICE_AGC_ENABLE if (in->agc) { if (auto_gain_control_create(in->agc, config->rate, bits, config->period_size)) { snd_err("create agc failed !\n"); audio_in_process_deinit(in); return -1; } } #endif #ifdef UVOICE_AEC_ENABLE if (adev->echo_cancellation) { if (audio_aec_init(in)) { snd_err("init audio aec failed !\n"); audio_in_process_deinit(in); return -1; } } #endif return 0; } int audio_in_process_deinit(struct in_stream *in) { if (!in) { snd_err("stream null !\n"); return -1; } #ifdef UVOICE_AEC_ENABLE if (in->aec) audio_aec_deinit(in); #endif #ifdef UVOICE_ANC_ENABLE if (in->ns) { noise_suppression_release(in->ns); snd_free(in->ns); in->ns = NULL; } #endif #ifdef UVOICE_AGC_ENABLE if (in->agc) { auto_gain_control_release(in->agc); snd_free(in->agc); in->agc = NULL; } #endif return 0; }
YifuLiu/AliOS-Things
components/uvoice/audio/audio_process.c
C
apache-2.0
5,110
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited * */ #ifndef __AUDIO_PROCESS_H__ #define __AUDIO_PROCESS_H__ int audio_out_conserve(struct audio_device *adev, uint8_t *buffer, int nbytes); int audio_in_process(struct in_stream *in, uint8_t *buffer, int nbytes); int audio_in_process_init(struct audio_device *adev, struct in_stream *in); int audio_in_process_deinit(struct in_stream *in); #endif /* __AUDIO_PROCESS_H__ */
YifuLiu/AliOS-Things
components/uvoice/audio/audio_process.h
C
apache-2.0
442
/* * 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_types.h" #include "uvoice_event.h" #include "uvoice_audio.h" #include "uvoice_common.h" #include "uvoice_os.h" #include "uvoice_pcm.h" #include "audio_common.h" #include "audio_mixer.h" #include "audio_vad.h" #include "audio_stream.h" #include "audio_process.h" #ifdef XR871_BOARD_V02 #define OUT_DEVICE_DEFAULT SND_DEVICE_OUT_SPEAKER_AND_HEADPHONE #else #define OUT_DEVICE_DEFAULT SND_DEVICE_OUT_SPEAKER #endif #define IN_DEVICE_DEFAULT SND_DEVICE_IN_PRIMARY_MIC #define OUT_VOLUME_DEFAULT 4 #ifdef __os_linux__ #define OUT_PCM_DUMP_PATH "hal_pcm_out.dump" #else #define OUT_PCM_DUMP_PATH "/sdcard/hal_pcm_out.dump" #endif static struct audio_device *g_adev; int out_volume_set(int volume) { struct audio_device *adev = g_adev; static bool first_set = true; if (!adev) { snd_err("adev null !\n"); return -1; } if (volume < VOLUME_LEVEL_MIN || volume > VOLUME_LEVEL_MAX) { snd_err("volume level %d invalid !\n", volume); return -1; } if (adev->out_volume != volume || first_set) { adev->out_volume = volume; first_set = false; snd_info("set volume %d\n", adev->out_volume); volume_set(adev->out_device, adev->out_volume); } return 0; } int out_volume_get(void) { struct audio_device *adev = g_adev; if (!adev) { snd_err("adev null !\n"); return -1; } return adev->out_volume; } int out_volume_range(int *max, int *min) { if (min) *min = VOLUME_LEVEL_MIN; if (max) *max = VOLUME_LEVEL_MAX; return 0; } int out_device_set(snd_device_t device) { struct audio_device *adev = g_adev; if (!adev) { snd_err("adev null !\n"); return -1; } if (device < SND_DEVICE_OUT_BEGIN || device > SND_DEVICE_IN_END) { snd_err("invalid device %d !\n", device); return -1; } adev->fixed_out_device = device; return 0; } int out_extpa_set(audio_extpa_info_t *info) { struct external_pa_info pa_info; pa_info.used = info->used; pa_info.active_high = info->active_high; pa_info.delay_ms = info->delay_ms; pa_info.pin = info->pin; return uvoice_extpa_config(&pa_info); } int out_stream_reset(struct out_stream *out) { if (!out) { snd_err("stream null !\n"); return -1; } snd_info("stream reset\n"); out_stream_stop(out); return 0; } int out_stream_mute(struct out_stream *out, int mute) { struct audio_device *adev = g_adev; if (!adev) { snd_err("adev null !\n"); return -1; } if (!out) { snd_err("stream null !\n"); return -1; } os_mutex_lock(out->lock, OS_WAIT_FOREVER); out->silent = mute; uvoice_dev_mute(&out->pcm, adev->out_device, 1); os_mutex_unlock(out->lock); snd_debug("mute %d\n", out->silent); return 0; } int out_stream_period_duration(struct out_stream *out) { struct pcm_config *config; int delay; if (!out) { snd_err("stream null !\n"); return -1; } config = &out->pcm.config; if (!pcm_rate_valid(config->rate)) { snd_err("sample rate invalid !\n"); return -1; } delay = config->period_size / (config->rate / 1000); delay -= 5; return delay > 0 ? delay : 1; } bool out_stream_configured(struct out_stream *out) { if (out && out->state != STREAM_STOP) return true; return false; } int out_stream_configure(struct out_stream *out, media_pcminfo_t *pcminfo) { struct audio_device *adev = g_adev; struct pcm_device *pcm; struct pcm_config *config; if (!adev) { snd_err("adev null !\n"); return -1; } if (!out) { snd_err("stream null !\n"); return -1; } if (!pcminfo) { snd_err("pcminfo null !\n"); return -1; } if (!pcm_rate_valid(pcminfo->rate)) { snd_err("rate %d invalid !\n", pcminfo->rate); return -1; } if (!pcm_channel_valid(pcminfo->channels) || pcminfo->channels > 2) { snd_err("channels %d invalid !\n", pcminfo->channels); return -1; } if (!pcm_bits_valid(pcminfo->bits)) { snd_err("bits %d invalid !\n", pcminfo->bits); return -1; } if (pcminfo->frames <= 0) { snd_err("period_size %d invalid !\n", pcminfo->frames); return -1; } os_mutex_lock(out->lock, OS_WAIT_FOREVER); if (out->state != STREAM_STOP) { snd_err("configure failed ! state %d\n", out->state); os_mutex_unlock(out->lock); return -1; } pcm = &out->pcm; config = &pcm->config; pcm->dir = PCM_OUT; config->rate = pcminfo->rate; config->channels = pcminfo->channels; config->period_size = pcminfo->frames >= 1024 ? 1024 : 640; config->period_count = 4; config->format = bits_to_pcm_format(pcminfo->bits); if (uvoice_pcm_setup(pcm)) { snd_err("pcm setup failed !\n"); os_mutex_unlock(out->lock); return -1; } if (pcminfo->rate != config->rate) pcminfo->rate = config->rate; if (pcminfo->channels != config->channels) pcminfo->channels = config->channels; if (pcminfo->bits != pcm_format_to_bits(config->format)) pcminfo->bits = pcm_format_to_bits(config->format); audio_out_process_init(adev, out); out->state = STREAM_SETUP; os_mutex_unlock(out->lock); snd_debug("stream setup\n"); return 0; } static int out_stream_start(struct out_stream *out) { struct audio_device *adev = g_adev; if (!adev) { snd_err("adev null !\n"); return -1; } if (!out) { snd_err("stream null !\n"); return -1; } uvoice_dev_mute(&out->pcm, adev->out_device, 0); if (adev->fixed_out_device >= SND_DEVICE_OUT_BEGIN && adev->fixed_out_device <= SND_DEVICE_OUT_END) device_select(adev, adev->fixed_out_device, true); else device_select(adev, adev->out_device, true); if (uvoice_pcm_open(&out->pcm)) { snd_err("pcm open failed !\n"); return -1; } #ifdef AUDIO_CACHE_ENABLE out->buffer_size = period_samples_to_bytes(&out->pcm.config); out->buffer = snd_zalloc(out->buffer_size, AFM_EXTN); if (!out->buffer) { snd_err("alloc buffer failed !\n"); uvoice_pcm_close(&out->pcm); return -1; } snd_debug("alloc out buffer %d\n", out->buffer_size); #endif out->state = STREAM_START; snd_info("stream start\n"); return 0; } int out_stream_write(struct out_stream *out, uint8_t *buffer, int nbytes) { #ifdef AUDIO_CACHE_ENABLE struct audio_device *adev = g_adev; int remaining_size = nbytes; int avail_size; int copy_size; int ret; if (!adev) { snd_err("adev null !\n"); return -1; } if (!out) { snd_err("stream null !\n"); return -1; } os_mutex_lock(out->lock, OS_WAIT_FOREVER); if (out->state == STREAM_STOP) { snd_info("stream stop\n"); goto __exit; } avail_size = remaining_size + out->buffer_dirty_size; if (avail_size < out->buffer_size) { snd_memcpy(out->buffer + out->buffer_dirty_size, buffer, remaining_size); out->buffer_dirty_size += remaining_size; goto __exit; } if (out->state == STREAM_SETUP) { if (out_stream_start(out)) { snd_err("start failed !\n"); os_mutex_unlock(out->lock); return -1; } } while (avail_size >= out->buffer_size) { copy_size = MIN(remaining_size, out->buffer_size - out->buffer_dirty_size); snd_memcpy(out->buffer + out->buffer_dirty_size, buffer + nbytes - remaining_size, copy_size); remaining_size -= copy_size; audio_out_process(out, out->buffer, out->buffer_size); if (out->dump) { fwrite(out->buffer, out->buffer_size, 1, out->dump); if (ferror(out->dump)) { snd_err("write dump failed %d!\n", ferror(out->dump)); os_mutex_unlock(out->lock); return -1; } } ret = uvoice_pcm_write(&out->pcm, out->buffer, out->buffer_size); if (ret < 0) { snd_err("write %d failed %d!\n", out->buffer_size, ret); os_mutex_unlock(out->lock); return -1; } #ifdef UVOICE_AEC_ENABLE audio_out_conserve(adev, out->buffer, out->buffer_size); #endif out->buffer_dirty_size = 0; avail_size -= out->buffer_size; if (out->state == STREAM_START) { out->state = STREAM_RUNNING; snd_debug("stream running\n"); } } if (remaining_size > 0) { snd_memcpy(out->buffer + out->buffer_dirty_size, buffer + nbytes - remaining_size, remaining_size); out->buffer_dirty_size += remaining_size; } __exit: os_mutex_unlock(out->lock); #else struct audio_device *adev = g_adev; int ret; if (out->state == STREAM_STOP) { snd_info("stream stop\n"); return 0; } if (out->state == STREAM_SETUP) { if (out_stream_start(out)) { snd_err("start failed !\n"); return -1; } } ret = uvoice_pcm_write(&out->pcm, buffer, nbytes); if (ret < 0) { snd_err("write %d failed %d!\n", nbytes, ret); return -1; } #endif return 0; } int out_stream_silent(struct out_stream *out) { #ifdef AUDIO_CACHE_ENABLE if (!out) { snd_err("stream null !\n"); return -1; } os_mutex_lock(out->lock, OS_WAIT_FOREVER); if (out->state != STREAM_RUNNING && out->state != STREAM_START) goto __exit; if (out->buffer_dirty_size > 0) { snd_debug("drain %d\n", out->buffer_dirty_size); memset(out->buffer + out->buffer_dirty_size, 0, out->buffer_size - out->buffer_dirty_size); if (out->dump) { fwrite(out->buffer, out->buffer_size, 1, out->dump); if (ferror(out->dump)) { snd_err("write dump failed %d!\n", ferror(out->dump)); os_mutex_unlock(out->lock); return -1; } } uvoice_pcm_write(&out->pcm, out->buffer, out->buffer_size); out->buffer_dirty_size = 0; } else { memset(out->buffer, 0, out->buffer_size); uvoice_pcm_write(&out->pcm, out->buffer, out->buffer_size); } __exit: os_mutex_unlock(out->lock); return 0; #else return uvoice_pcm_silence(&out->pcm); #endif } int out_stream_stop(struct out_stream *out) { struct audio_device *adev = g_adev; if (!adev) { snd_err("adev null !\n"); return -1; } if (!out) { snd_err("stream null !\n"); return -1; } os_mutex_lock(out->lock, OS_WAIT_FOREVER); if (out->state != STREAM_RUNNING && out->state != STREAM_START) { snd_debug("stream not start\n"); goto __exit; } #ifdef AUDIO_CACHE_ENABLE if (out->buffer_dirty_size > 0) { uvoice_pcm_write(&out->pcm, out->buffer, out->buffer_dirty_size); out->buffer_dirty_size = 0; } #endif if (!out->silent) uvoice_pcm_flush(&out->pcm); uvoice_dev_mute(&out->pcm, adev->out_device, 1); uvoice_pcm_close(&out->pcm); #ifdef AUDIO_CACHE_ENABLE snd_free(out->buffer); out->buffer = NULL; out->buffer_size = 0; #endif __exit: out->silent = 0; out->state = STREAM_STOP; os_mutex_unlock(out->lock); snd_info("stream stop\n"); return 0; } struct out_stream *out_stream_create(void) { struct audio_device *adev = g_adev; struct out_stream *out; if (!adev) { snd_err("adev null !\n"); return NULL; } out = snd_zalloc(sizeof(struct out_stream), AFM_EXTN); if (!out) { snd_err("alloc out stream failed !\n"); return NULL; } if (adev->out_pcm_dump) { snd_debug("open out dump\n"); out->dump = fopen(OUT_PCM_DUMP_PATH, "wb+"); if (!out->dump) { snd_err("open out dump failed !\n"); snd_free(out); return NULL; } } out->lock = os_mutex_new(); out->state = STREAM_STOP; adev->out = out; snd_info("stream create\n"); return out; } int out_stream_release(struct out_stream *out) { struct audio_device *adev = g_adev; if (!adev) { snd_err("adev null !\n"); return -1; } if (!out) { snd_err("stream null !\n"); return -1; } if (out->state != STREAM_STOP) { snd_err("stream not stop !\n"); return -1; } if (out->dump) { snd_debug("close out dump\n"); fclose(out->dump); } audio_out_process_deinit(out); os_mutex_free(out->lock); snd_free(out); adev->out = NULL; snd_info("stream release\n"); return 0; } bool in_stream_configured(struct in_stream *in) { if (in && in->state != STREAM_STOP) return true; return false; } int in_stream_configure(struct in_stream *in, media_pcminfo_t *pcminfo) { struct audio_device *adev = g_adev; struct pcm_device *pcm; if (!adev) { snd_err("adev null !\n"); return -1; } if (!in) { snd_err("stream null !\n"); return -1; } if (!pcminfo) { snd_err("pcminfo null !\n"); return -1; } if (in->state != STREAM_STOP) { snd_err("state %d, error !\n", in->state); return -1; } if (!pcm_rate_valid(pcminfo->rate)) { snd_err("rate %d invalid !\n", pcminfo->rate); return -1; } if (!pcm_channel_valid(pcminfo->channels)) { snd_err("channels %d invalid !\n", pcminfo->channels); return -1; } if (!pcm_bits_valid(pcminfo->bits)) { snd_err("bits %d invalid !\n", pcminfo->bits); return -1; } if (pcminfo->frames <= 0) { snd_err("frames %d invalid !\n", pcminfo->frames); return -1; } os_mutex_lock(in->lock, OS_WAIT_FOREVER); pcm = &in->pcm; pcm->dir = PCM_IN; pcm->config.rate = pcminfo->rate; pcm->config.channels = pcminfo->channels; pcm->config.period_size = pcminfo->frames; pcm->config.format = bits_to_pcm_format(pcminfo->bits); if (uvoice_pcm_setup(pcm)) { snd_err("pcm setup failed !\n"); os_mutex_unlock(in->lock); return -1; } if (pcminfo->rate != pcm->config.rate) pcminfo->rate = pcm->config.rate; if (pcminfo->channels != pcm->config.channels) pcminfo->channels = pcm->config.channels; if (pcminfo->bits != pcm_format_to_bits(pcm->config.format)) pcminfo->bits = pcm_format_to_bits(pcm->config.format); if (audio_in_process_init(adev, in)) { snd_err("audio process init failed !\n"); os_mutex_unlock(in->lock); return -1; } #ifdef UVOICE_VAD_ENABLE if (adev->vad_enable) { in->vad = audio_vad_create(pcm->config.rate, pcm->config.period_size); if (!in->vad) { snd_err("create vad failed !\n"); audio_in_process_deinit(in); os_mutex_unlock(in->lock); return -1; } } #endif in->state = STREAM_SETUP; os_mutex_unlock(in->lock); snd_debug("stream setup\n"); return 0; } static FILE *in_stream_dump; static int in_stream_start(struct in_stream *in) { struct audio_device *adev = g_adev; struct pcm_device *pcm; if (!adev) { snd_err("adev null !\n"); return -1; } if (!in) { snd_err("stream null !\n"); return -1; } pcm = &in->pcm; pcm->dir = PCM_IN; if (uvoice_pcm_open(pcm)) { snd_err("pcm open failed !\n"); return -1; } #if 0 if (in_stream_dump) fclose(in_stream_dump); in_stream_dump = fopen("/sdcard/in_dump_before_anc.pcm", "wb+"); if (!in_stream_dump) { snd_err("open in stream dump fail !\n"); uvoice_pcm_close(pcm); return -1; } snd_info("in stream dump open\n"); #endif device_select(adev, adev->in_device, true); in->state = STREAM_START; adev->in = in; snd_info("stream start\n"); return 0; } int in_stream_read(struct in_stream *in, uint8_t *buffer, int nbytes) { int ret; if (!in) { snd_err("stream null !\n"); return -1; } os_mutex_lock(in->lock, OS_WAIT_FOREVER); if (in->state == STREAM_STOP) { snd_err("stream stop !\n"); os_mutex_unlock(in->lock); return -1; } else if (in->state == STREAM_SETUP) { if (in_stream_start(in)) { snd_err("start failed !\n"); os_mutex_unlock(in->lock); return -1; } } ret = uvoice_pcm_read(&in->pcm, buffer, nbytes); if (ret < 0) { snd_err("read %d failed %d!\n", nbytes, ret); os_mutex_unlock(in->lock); return -1; } if (in_stream_dump) { fwrite(buffer, ret, 1, in_stream_dump); if (ferror(in_stream_dump)) { snd_err("write in stream dump fail %d!\n", ferror(in_stream_dump)); } } if (audio_in_process(in, buffer, ret)) { snd_err("audio process failed !\n"); os_mutex_unlock(in->lock); return -1; } #ifdef UVOICE_VAD_ENABLE if (in->vad) { if (audio_vad_process(in->vad, buffer, ret)) { snd_err("audio process failed !\n"); os_mutex_unlock(in->lock); return -1; } } #endif if (in->state == STREAM_START) in->state = STREAM_RUNNING; os_mutex_unlock(in->lock); return ret; } int in_stream_stop(struct in_stream *in) { struct audio_device *adev = g_adev; if (!adev) { snd_err("adev null !\n"); return -1; } if (!in) { snd_err("stream null !\n"); return -1; } os_mutex_lock(in->lock, OS_WAIT_FOREVER); if (in->state != STREAM_RUNNING && in->state != STREAM_START) { snd_err("stop failed ! state %d\n", in->state); os_mutex_unlock(in->lock); return -1; } if (in_stream_dump) { fclose(in_stream_dump); in_stream_dump = NULL; snd_info("in stream dump close\n"); } uvoice_pcm_close(&in->pcm); in->state = STREAM_STOP; snd_info("stream stop\n"); os_mutex_unlock(in->lock); return 0; } struct in_stream *in_stream_create(void) { struct audio_device *adev = g_adev; struct in_stream *in; if (!adev) { snd_err("adev null !\n"); return NULL; } in = snd_zalloc(sizeof(struct in_stream), AFM_EXTN); if (!in) { snd_err("alloc in stream failed !\n"); return NULL; } in->lock = os_mutex_new(); in->state = STREAM_STOP; adev->in = in; snd_info("stream create\n"); return in; } int in_stream_release(struct in_stream *in) { struct audio_device *adev = g_adev; if (!adev) { snd_err("adev null !\n"); return -1; } if (!in) { snd_err("stream null !\n"); return -1; } #ifdef UVOICE_VAD_ENABLE audio_vad_release(in->vad); #endif audio_in_process_deinit(in); os_mutex_free(in->lock); snd_free(in); adev->in = NULL; snd_info("stream release\n"); return 0; } int audio_param_set(int key, int value) { struct audio_device *adev = g_adev; if (!adev) { snd_err("adev null !\n"); return -1; } switch (key) { case PARAM_KEY_NOISE_SUPPRESSION: if (value == PARAM_VAL_ENABLE) adev->noise_suppression = 1; else if (value == PARAM_VAL_DISABLE) adev->noise_suppression = 0; break; case PARAM_KEY_ECHO_CANCELLATION: if (value == PARAM_VAL_ENABLE) adev->echo_cancellation = 1; else if (value == PARAM_VAL_DISABLE) adev->echo_cancellation = 0; break; case PARAM_KEY_AUTO_GAIN_CONTROL: if (value == PARAM_VAL_ENABLE) adev->auto_gain_control = 1; else if (value == PARAM_VAL_DISABLE) adev->auto_gain_control = 0; break; case PARAM_KEY_VOICE_ACTIVE_DETECT: if (value == PARAM_VAL_ENABLE) adev->vad_enable = 1; else if (value == PARAM_VAL_DISABLE) adev->vad_enable = 0; break; case PARAM_KEY_EFFECT_EQUALIZER: if (value == PARAM_VAL_ENABLE) adev->equalizer_enable = 1; else if (value == PARAM_VAL_DISABLE) adev->equalizer_enable = 0; break; case PARAM_KEY_OUT_PCM_DUMP: if (value == PARAM_VAL_ENABLE) adev->out_pcm_dump = 1; else if (value == PARAM_VAL_DISABLE) adev->out_pcm_dump = 0; break; default: break; } return 0; } int audio_pcm_notify(pcm_message_t msg) { switch (msg) { case PCM_MSG_TX_WAITING: break; case PCM_MSG_TX_UNDERRUN: snd_warn("tx underrun\n"); break; case PCM_MSG_TX_OVERRUN: snd_warn("tx overrun\n"); break; case PCM_MSG_RX_UNDERRUN: snd_warn("rx underrun\n"); break; case PCM_MSG_RX_OVERRUN: snd_warn("rx overrun\n"); break; default: break; } return 0; } static void audio_sw_event_handle(uvoice_event_t *event, void *data) { struct audio_device *adev = (struct audio_device *)data; if (!adev) { snd_err("adev null !\n"); return; } if (event->type != UVOICE_EV_SW) { snd_warn("event type not match\n"); return; } if (event->code == UVOICE_CODE_HEADPHONE) { if (event->value == 1) device_select(adev, SND_DEVICE_OUT_HEADPHONE, false); else if (event->value == 0) device_select(adev, SND_DEVICE_OUT_SPEAKER, false); if (!adev->in_device_fix) device_select(adev, SND_DEVICE_IN_PRIMARY_MIC, false); } else if (event->code == UVOICE_CODE_HEADSET) { if (event->value == 1) { device_select(adev, SND_DEVICE_OUT_HEADSET, false); if (!adev->in_device_fix) device_select(adev, SND_DEVICE_IN_HEADSET_MIC, false); } else if (event->value == 0) { device_select(adev, SND_DEVICE_OUT_SPEAKER, false); if (!adev->in_device_fix) device_select(adev, SND_DEVICE_IN_PRIMARY_MIC, false); } } } int audio_device_init(void) { struct audio_device *adev; int ret; adev = snd_zalloc(sizeof(struct audio_device), AFM_EXTN); if (!adev) { snd_err("alloc audio device failed !\n"); return -1; } adev->out_device = OUT_DEVICE_DEFAULT; adev->in_device = IN_DEVICE_DEFAULT; adev->in_device_fix = 1; ret = volume_get(adev->out_device); if (ret < 0) { adev->out_volume = OUT_VOLUME_DEFAULT; snd_debug("default volume %d\n", adev->out_volume); } else { adev->out_volume = ret; } g_adev = adev; uvoice_event_register(UVOICE_EV_SW, audio_sw_event_handle, adev); uvoice_pcm_init(); return 0; } int audio_device_deinit(void) { struct audio_device *adev = g_adev; if (!adev) { snd_err("adev null !\n"); return -1; } uvoice_event_unregister(UVOICE_EV_SW, audio_sw_event_handle, NULL); snd_free(adev); g_adev = NULL; return 0; }
YifuLiu/AliOS-Things
components/uvoice/audio/audio_stream.c
C
apache-2.0
23,957
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited * */ #ifndef __AUDIO_STREAM_H__ #define __AUDIO_STREAM_H__ enum stream_state { STREAM_STOP = 0, STREAM_SETUP, STREAM_START, STREAM_RUNNING, }; struct noise_suppression { void *handler; }; struct auto_gain_control { void *handler; }; struct out_stream { #ifdef AUDIO_CACHE_ENABLE uint8_t *buffer; int buffer_size; int buffer_dirty_size; #endif uint8_t silent:1; enum stream_state state; void *eq; FILE *dump; os_mutex_t lock; struct pcm_device pcm; }; struct in_stream { enum stream_state state; os_mutex_t lock; struct noise_suppression *ns; struct auto_gain_control *agc; void *aec; void *vad; struct pcm_device pcm; }; struct audio_device { struct out_stream *out; struct in_stream *in; uint8_t noise_suppression:1; uint8_t echo_cancellation:1; uint8_t auto_gain_control:1; uint8_t vad_enable:1; uint8_t equalizer_enable:1; uint8_t out_pcm_dump:1; uint8_t vad_start:1; uint8_t in_device_fix:1; int out_volume; snd_device_t out_device; snd_device_t in_device; snd_device_t fixed_out_device; }; int out_volume_set(int volume); int out_volume_get(void); int out_volume_range(int *max, int *min); int out_device_set(snd_device_t device); int out_extpa_set(audio_extpa_info_t *info); int out_stream_reset(struct out_stream *out); int out_stream_mute(struct out_stream *out, int mute); bool out_stream_configured(struct out_stream *out); int out_stream_configure(struct out_stream *out, media_pcminfo_t *pcminfo); int out_stream_period_duration(struct out_stream *out); int out_stream_write(struct out_stream *out, uint8_t *buffer, int nbytes); int out_stream_silent(struct out_stream *out); int out_stream_stop(struct out_stream *out); struct out_stream *out_stream_create(void); int out_stream_release(struct out_stream *out); bool in_stream_configured(struct in_stream *in); int in_stream_configure(struct in_stream *in, media_pcminfo_t *pcminfo); int in_stream_read(struct in_stream *in, uint8_t *buffer, int nbytes); int in_stream_stop(struct in_stream *in); struct in_stream *in_stream_create(void); int in_stream_release(struct in_stream *in); int audio_param_set(int key, int value); int audio_device_init(void); int audio_device_deinit(void); #endif /* __AUDIO_STREAM_H__ */
YifuLiu/AliOS-Things
components/uvoice/audio/audio_stream.h
C
apache-2.0
2,405
/* * 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 "audio_trigger.h" int audio_trigger_init(void) { return 0; } int audio_trigger_deinit(void) { return 0; }
YifuLiu/AliOS-Things
components/uvoice/audio/audio_trigger.c
C
apache-2.0
318
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited * */ #ifndef __AUDIO_TRIGGER_H__ #define __AUDIO_TRIGGER_H__ typedef struct { int devid; char name[32]; } st_device_t; int audio_trigger_init(void); int audio_trigger_deinit(void); #endif /* __AUDIO_TRIGGER_H__ */
YifuLiu/AliOS-Things
components/uvoice/audio/audio_trigger.h
C
apache-2.0
284
/* * 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_types.h" #include "uvoice_os.h" #include "uvoice_types.h" #include "uvoice_event.h" #include "uvoice_common.h" #include "uvoice_audio.h" #include "audio_common.h" #include "audio_stream.h" #include "audio_vad.h" #define VAD_END_DEBOUNCE_TIME_MS 990 /* muliti of 30 */ int audio_vad_process(struct voice_active_detect *vad, const uint8_t *buffer, int nbytes) { int ret; if (!vad) { snd_err("vad null !\n"); return -1; } ret = vad_process(vad, buffer, nbytes); if (ret < 0) { snd_err("vad process error %d !\n", ret); return -1; } if (ret == VAD_STAT_SPEECH) { if (vad->state == VAD_STAT_NOISE) { vad->state = VAD_STAT_SPEECH; uvoice_event_post(UVOICE_EV_ST, UVOICE_CODE_VAD_START, 0); } if (vad->end_count > 0) vad->end_count = 0; } else if (ret == VAD_STAT_NOISE) { if (vad->state == VAD_STAT_SPEECH) { if (vad->end_count++ >= vad->end_target && os_current_time() - vad->start_time >= 2000) { vad->state = VAD_STAT_NOISE; vad->end_count = 0; uvoice_event_post(UVOICE_EV_ST, UVOICE_CODE_VAD_END, 0); } } } return 0; } struct voice_active_detect *audio_vad_create(int rate, int period_size) { struct voice_active_detect *vad; int proc_samples; vad = snd_zalloc(sizeof(struct voice_active_detect), AFM_EXTN); if (!vad) { snd_err("alloc vad struct failed !\n"); return NULL; } proc_samples = MIN((rate / 100) * 3, period_size); vad->state = VAD_STAT_NOISE; vad->end_target = VAD_END_DEBOUNCE_TIME_MS / ((proc_samples * 1000) / rate); if (vad_create(vad, rate, proc_samples, 0)) { snd_err("create vad failed !\n"); snd_free(vad); return NULL; } vad->start_time = os_current_time(); snd_debug("vad create, end target %d\n", vad->end_target); return vad; } int audio_vad_release(struct voice_active_detect *vad) { if (vad) { vad_release(vad); snd_free(vad); snd_debug("vad release\n"); } return 0; }
YifuLiu/AliOS-Things
components/uvoice/audio/audio_vad.c
C
apache-2.0
2,425
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited * */ #ifndef __AUDIO_VAD_H__ #define __AUDIO_VAD_H__ enum { VAD_STAT_NOISE = 0, VAD_STAT_SPEECH, }; struct voice_active_detect { void *handler; int state; int end_count; int end_target; long long start_time; }; #ifdef UVOICE_VAD_ENABLE int audio_vad_process(struct voice_active_detect *vad, const uint8_t *buffer, int nbytes); struct voice_active_detect *audio_vad_create(int rate, int period_size); int audio_vad_release(struct voice_active_detect *vad); #endif #endif /* __AUDIO_VAD_H__ */
YifuLiu/AliOS-Things
components/uvoice/audio/audio_vad.h
C
apache-2.0
568
/* * uVoice audio hardware adapt layer */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include "sound_pcm.h" #include "sound_mixer.h" #include "ulog/ulog.h" #include <uvoice_audio.h> #define LOG_TAG "[uVoice_a2sa]" aos_pcm_t *pb_pcm = NULL, *cap_pcm = NULL; int uvoice_set_volume(snd_device_t device, int volume) { aos_set_master_volume(volume * 10); return 0; } int uvoice_set_path(struct pcm_device *pcm, snd_device_t device) { return 0; } int uvoice_dev_mute(struct pcm_device *pcm, snd_device_t device, int mute) { aos_set_mute_state(mute); return 0; } void uvoice_pcm_notify(pcm_message_t msg) { } int uvoice_pcm_setup(struct pcm_device *pcm) { return 0; } int uvoice_pcm_open(struct pcm_device *pcm) { int ret = -1; aos_pcm_format_t format = AOSRV_PCM_FORMAT_S16_LE; if (!pcm) { LOGE(LOG_TAG, "%s:%d: pcm is null ", __func__, __LINE__); return -1; } switch (pcm->config.format) { case PCM_FORMAT_S8: format = AOSRV_PCM_FORMAT_S8; break; case PCM_FORMAT_S16_LE: format = AOSRV_PCM_FORMAT_S16_LE; break; case PCM_FORMAT_S24_LE: case PCM_FORMAT_S24_3LE: format = AOSRV_PCM_FORMAT_S24_LE; break; case PCM_FORMAT_S32_LE: format = AOSRV_PCM_FORMAT_S16_LE; break; default: break; } if (pcm->dir == PCM_OUT) { ret = aos_pcm_open(&pb_pcm, "default", AOS_PCM_STREAM_PLAYBACK, 0); if (!ret) { aos_pcm_hw_params_alloca(&pb_pcm->hw_params); aos_pcm_sw_params_alloca(&pb_pcm->sw_params); aos_pcm_sw_params_any(pb_pcm->sw_params); aos_pcm_set_params(pb_pcm, format, AOS_PCM_ACCESS_RW_INTERLEAVED, pcm->config.channels, pcm->config.rate, 0, 0); aos_pcm_prepare(pb_pcm); aos_pcm_start(pb_pcm); } else { LOGE(LOG_TAG, "%s:%d: open pb stream failed. ", __func__, __LINE__); } } else if (pcm->dir == PCM_IN) { /* open capture stream */ ret = aos_pcm_open(&cap_pcm, "default", AOS_PCM_STREAM_CAPTURE, 0); if (!ret) { aos_pcm_hw_params_alloca(&cap_pcm->hw_params); aos_pcm_sw_params_alloca(&cap_pcm->sw_params); aos_pcm_sw_params_any(cap_pcm->sw_params); aos_pcm_set_params(cap_pcm, format, AOS_PCM_ACCESS_RW_INTERLEAVED, pcm->config.channels, pcm->config.rate, 0, 0); aos_pcm_prepare(cap_pcm); aos_pcm_start(cap_pcm); } else { LOGE(LOG_TAG, "%s:%d: open cap stream failed. ", __func__, __LINE__); } } return 0; } int uvoice_pcm_read(struct pcm_device *pcm, uint8_t *buffer, int nbytes) { int ret = -1; if (pcm->dir == PCM_IN && cap_pcm) { ret = aos_pcm_readi(cap_pcm, buffer, aos_pcm_bytes_to_frames(cap_pcm, nbytes)); ret = aos_pcm_frames_to_bytes(cap_pcm, ret); } return ret; } int uvoice_pcm_write(struct pcm_device *pcm, uint8_t *buffer, int nbytes) { int ret = -1; if (pcm->dir == PCM_OUT && pb_pcm) { ret = aos_pcm_writei(pb_pcm, buffer, aos_pcm_bytes_to_frames(pb_pcm, nbytes)); ret = aos_pcm_frames_to_bytes(pb_pcm, ret); } return ret; } int uvoice_extpa_config(struct external_pa_info *info) { return 0; } int uvoice_pcm_silence(struct pcm_device *pcm) { return 0; } int uvoice_pcm_flush(struct pcm_device *pcm) { return 0; } int uvoice_pcm_close(struct pcm_device *pcm) { if (pb_pcm && (pcm->dir == PCM_OUT)) { //aos_pcm_drain(pb_pcm); aos_pcm_stop(pb_pcm); aos_pcm_close(pb_pcm); pb_pcm = NULL; } if (cap_pcm && (pcm->dir == PCM_IN)) { aos_pcm_stop(cap_pcm); aos_pcm_close(cap_pcm); cap_pcm = NULL; } return 0; } // extern int audio_install_codec_driver(); int uvoice_pcm_init(void) { // audio_install_codec_driver(); return 0; }
YifuLiu/AliOS-Things
components/uvoice/audio/hal/haas100/uvoice_pcm.c
C
apache-2.0
4,019
/* * uVoice audio hardware adapt layer */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include "ulog/ulog.h" #include <uvoice_audio.h> int uvoice_set_volume(snd_device_t device, int volume) { return 0; } int uvoice_set_path(struct pcm_device *pcm, snd_device_t device) { return 0; } int uvoice_dev_mute(struct pcm_device *pcm, snd_device_t device, int mute) { return 0; } void uvoice_pcm_notify(pcm_message_t msg) { } int uvoice_pcm_setup(struct pcm_device *pcm) { return 0; } int uvoice_pcm_open(struct pcm_device *pcm) { return 0; } int uvoice_pcm_read(struct pcm_device *pcm, uint8_t *buffer, int nbytes) { int ret = -1; return ret; } int uvoice_pcm_write(struct pcm_device *pcm, uint8_t *buffer, int nbytes) { int ret = -1; return ret; } int uvoice_extpa_config(struct external_pa_info *info) { return 0; } int uvoice_pcm_silence(struct pcm_device *pcm) { return 0; } int uvoice_pcm_flush(struct pcm_device *pcm) { return 0; } int uvoice_pcm_close(struct pcm_device *pcm) { return 0; } int uvoice_pcm_init(void) { return 0; }
YifuLiu/AliOS-Things
components/uvoice/audio/hal/haas200/uvoice_pcm.c
C
apache-2.0
1,140
/* * uVoice audio hardware adapt layer */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <uvoice_audio.h> #ifndef UVOICE_PCM_NO_ALSA #include <alsa/asoundlib.h> static int alsa_pcm_open(struct pcm_device *pcm) { struct pcm_config *config; snd_pcm_t *pcm_handle; snd_pcm_stream_t stream; snd_pcm_hw_params_t *hw_params; snd_pcm_sw_params_t *sw_params; snd_pcm_uframes_t period_size; snd_pcm_uframes_t buffer_size; snd_pcm_uframes_t start_threshold; snd_pcm_access_t access; snd_pcm_format_t format; unsigned int sample_rate; unsigned int channels; unsigned int periods; unsigned int buffer_time; unsigned int period_time; unsigned int period_count; int dir = 0; int ret; config = &pcm->config; if (pcm->dir == PCM_OUT) stream = SND_PCM_STREAM_PLAYBACK; else if (pcm->dir == PCM_IN) stream = SND_PCM_STREAM_CAPTURE; else return -1; ret = snd_pcm_open(&pcm_handle, "default", stream, 0); if (ret < 0) { snd_err("open pcm failed %d!\n", ret); goto __exit; } ret = snd_pcm_hw_params_malloc(&hw_params); if (ret < 0) { snd_err("alloc hw params failed %d!\n", ret); goto __exit1; } ret = snd_pcm_hw_params_any(pcm_handle, hw_params); if (ret < 0) { snd_err("init hw params failed %d!\n", ret); goto __exit2; } access = SND_PCM_ACCESS_RW_INTERLEAVED; ret = snd_pcm_hw_params_set_access(pcm_handle, hw_params, access); if (ret < 0) { snd_err("set access failed %d!\n", ret); goto __exit2; } switch (config->format) { case PCM_FORMAT_S16_LE: format = SND_PCM_FORMAT_S16_LE; break; case PCM_FORMAT_S24_LE: format = SND_PCM_FORMAT_S24_LE; break; case PCM_FORMAT_S24_3LE: format = SND_PCM_FORMAT_S24_3LE; break; case PCM_FORMAT_S8: format = SND_PCM_FORMAT_S8; break; default: ret = -1; snd_err("unsupport format %d\n", config->format); goto __exit2; } ret = snd_pcm_hw_params_set_format(pcm_handle, hw_params, format); if (ret < 0) { snd_err("set format failed %d!\n", ret); goto __exit2; } sample_rate = config->rate; dir = 0; ret = snd_pcm_hw_params_set_rate_near(pcm_handle, hw_params, &sample_rate, &dir); if (ret < 0) { snd_err("set sample rate failed %d!\n", ret); goto __exit2; } channels = config->channels; ret = snd_pcm_hw_params_set_channels(pcm_handle, hw_params, channels); if (ret < 0) { snd_err("set channels failed %d!\n", ret); goto __exit2; } period_size = config->period_size; dir = 0; ret = snd_pcm_hw_params_set_period_size_near(pcm_handle, hw_params, &period_size, &dir); if (ret < 0) { snd_err("set period size failed %d!\n", ret); goto __exit2; } dir = 0; ret = snd_pcm_hw_params_get_period_size(hw_params, &period_size, &dir); if (ret < 0) { snd_err("get period size failed %d!\n", ret); goto __exit2; } snd_info("period_size %lu\n", period_size); periods = config->period_count; buffer_size = period_size * periods; ret = snd_pcm_hw_params_set_buffer_size_near(pcm_handle, hw_params, &buffer_size); if (ret < 0) { snd_err("set buffer size failed %d!\n", ret); goto __exit2; } ret = snd_pcm_hw_params(pcm_handle, hw_params); if (ret < 0) { snd_err("set hw params failed %d!\n", ret); goto __exit2; } ret = snd_pcm_hw_params_get_channels(hw_params, &channels); if (ret < 0) { snd_err("get channels failed %d!\n", ret); goto __exit2; } snd_info("channels %u\n", channels); dir = 0; ret = snd_pcm_hw_params_get_rate(hw_params, &sample_rate, &dir); if (ret < 0) { snd_err("get rate failed %d!\n", ret); goto __exit2; } config->rate = sample_rate; snd_info("sample_rate %u\n", sample_rate); ret = snd_pcm_hw_params_get_sbits(hw_params); if (ret < 0) { snd_err("get sbits failed !\n"); goto __exit2; } snd_info("sbits %d\n", ret); ret = snd_pcm_hw_params_get_format(hw_params, &format); if (ret < 0) { snd_err("get format failed !\n"); goto __exit2; } snd_info("format %d\n", format); ret = snd_pcm_hw_params_get_access(hw_params, &access); if (ret < 0) { snd_err("get access failed !\n"); goto __exit2; } snd_info("access %d\n", access); periods = 0; dir = 0; ret = snd_pcm_hw_params_get_periods(hw_params, &periods, &dir); if (ret < 0) { snd_err("get periods failed %d!\n", ret); goto __exit2; } config->period_count = periods; snd_info("periods %u\n", periods); ret = snd_pcm_hw_params_get_buffer_size(hw_params, &buffer_size); if (ret < 0) { snd_err("get buffer size failed %d!\n", ret); goto __exit2; } snd_info("buffer_size %lu\n", buffer_size); ret = snd_pcm_sw_params_malloc(&sw_params); if (ret < 0) { snd_err("alloc sw params failed %d!\n", ret); goto __exit1; } ret = snd_pcm_sw_params_current(pcm_handle, sw_params); if (ret < 0) { snd_err("get sw params failed %d!\n", ret); goto __exit3; } start_threshold = buffer_size; ret = snd_pcm_sw_params_set_start_threshold(pcm_handle, sw_params, start_threshold); if (ret < 0) { snd_err("set start threshold failed %d!\n", ret); goto __exit3; } ret = snd_pcm_sw_params(pcm_handle, sw_params); if (ret < 0) { snd_err("set sw params failed %d!\n", ret); goto __exit3; } ret = snd_pcm_sw_params_get_start_threshold(sw_params, &start_threshold); if (ret < 0) { snd_err("get start threshold failed %d!\n", ret); goto __exit3; } snd_info("start_threshold %lu\n", start_threshold); snd_pcm_sw_params_free(sw_params); snd_pcm_hw_params_free(hw_params); pcm->private_data = pcm_handle; return 0; __exit3: snd_pcm_sw_params_free(sw_params); __exit2: snd_pcm_hw_params_free(hw_params); __exit1: snd_pcm_close(pcm_handle); __exit: return -1; } static int alsa_pcm_drain(struct pcm_device *pcm) { snd_pcm_t *pcm_handle; pcm_handle = (snd_pcm_t *)pcm->private_data; if (!pcm_handle) { snd_err("pcm_handle null !\n"); return -1; } return snd_pcm_drain(pcm_handle); } static int alsa_pcm_close(struct pcm_device *pcm) { snd_pcm_t *pcm_handle; pcm_handle = (snd_pcm_t *)pcm->private_data; if (!pcm_handle) { snd_err("pcm_handle null !\n"); return -1; } return snd_pcm_close(pcm_handle); } static int alsa_pcm_read(struct pcm_device *pcm, uint8_t *buffer, int nbytes) { snd_pcm_t *pcm_handle; snd_pcm_uframes_t frames; int ret; pcm_handle = (snd_pcm_t *)pcm->private_data; if (!pcm_handle) { snd_err("pcm_handle null !\n"); return -1; } frames = snd_pcm_bytes_to_frames(pcm_handle, nbytes); while ((ret = snd_pcm_readi(pcm_handle, buffer, frames)) < 0) { if (ret == -EPIPE) { snd_err("overrun occurued\n"); snd_pcm_prepare(pcm_handle); } else if (ret < 0) { snd_err("writei error: %s\n", snd_strerror(ret)); } } return nbytes; } static int alsa_pcm_write(struct pcm_device *pcm, uint8_t *buffer, int nbytes) { snd_pcm_t *pcm_handle; snd_pcm_uframes_t frames; int ret; pcm_handle = (snd_pcm_t *)pcm->private_data; if (!pcm_handle) { snd_err("pcm_handle null !\n"); return -1; } frames = snd_pcm_bytes_to_frames(pcm_handle, nbytes); while ((ret = snd_pcm_writei(pcm_handle, buffer, frames)) < 0) { if (ret == -EPIPE) { snd_err("underrun occurued\n"); snd_pcm_prepare(pcm_handle); } else if (ret < 0) { snd_err("writei error: %s\n", snd_strerror(ret)); } } return nbytes; } #endif int uvoice_set_volume(snd_device_t device, int volume) { return 0; } int uvoice_set_path(struct pcm_device *pcm, snd_device_t device) { if (!pcm) { snd_err("pcm null !\n"); return -1; } return 0; } int uvoice_dev_mute(struct pcm_device *pcm, snd_device_t device, int mute) { if (!pcm) { snd_err("pcm null !\n"); return -1; } return 0; } int uvoice_pcm_setup(struct pcm_device *pcm) { if (!pcm) { snd_err("pcm null !\n"); return -1; } if (pcm->dir == PCM_OUT) { pcm->config.period_count = 4; pcm->config.period_size = 960; // pcm->config.rate = 48000; } else if (pcm->dir == PCM_IN) { pcm->config.period_count = 4; pcm->config.period_size = 640; } pcm->state = PCM_STATE_SETUP; return 0; } int uvoice_pcm_open(struct pcm_device *pcm) { #ifndef UVOICE_PCM_NO_ALSA snd_pcm_t *pcm_handle; struct pcm_config *config; snd_pcm_hw_params_t *hw_params; int ret; if (!pcm) { snd_err("pcm null !\n"); return -1; } if (pcm->state != PCM_STATE_SETUP) { snd_err("pcm not setup !\n"); goto __exit; } config = &pcm->config; snd_debug("rate %d channels %d format %d period_size %d period_count %d dir %u\n", config->rate, config->channels, config->format, config->period_size, config->period_count, pcm->dir); if (alsa_pcm_open(pcm)) { snd_err("open alsa pcm failed !\n"); return -1; } #endif pcm->state = PCM_STATE_OPEN; __exit: return 0; } int uvoice_pcm_read(struct pcm_device *pcm, uint8_t *buffer, int nbytes) { int ret = 0; if (!pcm) { snd_err("pcm null !\n"); return -1; } if (pcm->state == PCM_STATE_OPEN) pcm->state = PCM_STATE_RUNNING; #ifndef UVOICE_PCM_NO_ALSA if (pcm->state == PCM_STATE_RUNNING) { ret = alsa_pcm_read(pcm, buffer, nbytes); } else { snd_err("pcm not running !\n"); return -1; } #endif return ret; } int uvoice_pcm_write(struct pcm_device *pcm, uint8_t *buffer, int nbytes) { int ret = 0; if (!pcm) { snd_err("pcm null !\n"); return -1; } if (pcm->state == PCM_STATE_OPEN) pcm->state = PCM_STATE_RUNNING; #ifndef UVOICE_PCM_NO_ALSA if (pcm->state == PCM_STATE_RUNNING) { ret = alsa_pcm_write(pcm, buffer, nbytes); if (ret < 0) { snd_err("write failed %d!\n", ret); ret = -1; } } else { snd_err("pcm not running !\n"); return -1; } #endif return ret; } int uvoice_pcm_silence(struct pcm_device *pcm) { return 0; } int uvoice_pcm_flush(struct pcm_device *pcm) { if (!pcm) { snd_err("pcm null !\n"); return -1; } #ifndef UVOICE_PCM_NO_ALSA if (pcm->dir == PCM_OUT) alsa_pcm_drain(pcm); #endif return 0; } int uvoice_extpa_config(struct external_pa_info *info) { return 0; } int uvoice_pcm_init(void) { return 0; } int uvoice_pcm_close(struct pcm_device *pcm) { if (!pcm) { snd_err("pcm null !\n"); return -1; } if (pcm->state == PCM_STATE_CLOSED) { snd_err("close already, ignore\n"); goto __exit; } #ifndef UVOICE_PCM_NO_ALSA alsa_pcm_close(pcm); #endif pcm->state = PCM_STATE_CLOSED; snd_debug("pcm close\n"); __exit: return 0; }
YifuLiu/AliOS-Things
components/uvoice/audio/hal/linux/uvoice_pcm.c
C
apache-2.0
11,669
/* * 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_audio.h" #include "uvoice_common.h" #include "audio_common.h" #include "audio_stream.h" #include "audio_aec.h" #include "opensource/webrtc/modules/audio_processing/aec/include/echo_cancellation.h" typedef struct { int16_t *out; int16_t *far; int16_t *near; int samples; int band_samples; int band_num; void *inst; } webrtc_aec_t; static int aec_buffer_alloc(webrtc_aec_t *webrtc_aec) { if (!webrtc_aec) { snd_err("webrtc_aec null !\n"); return -1; } webrtc_aec->out = snd_zalloc( webrtc_aec->samples * sizeof(int16_t), AFM_MAIN); if (!webrtc_aec->out) { snd_err("alloc out buffer failed !\n"); return -1; } webrtc_aec->far = snd_zalloc( webrtc_aec->samples * sizeof(int16_t), AFM_MAIN); if (!webrtc_aec->far) { snd_err("alloc far buffer failed !\n"); return -1; } webrtc_aec->near = snd_zalloc( webrtc_aec->samples * sizeof(int16_t), AFM_MAIN); if (!webrtc_aec->near) { snd_err("alloc near buffer failed !\n"); return -1; } return 0; } static int aec_buffer_free(webrtc_aec_t *webrtc_aec) { if (!webrtc_aec) { snd_err("webrtc_aec null !\n"); return -1; } if (webrtc_aec->near) { snd_free(webrtc_aec->near); webrtc_aec->near = NULL; } if (webrtc_aec->far) { snd_free(webrtc_aec->far); webrtc_aec->far = NULL; } if (webrtc_aec->out) { snd_free(webrtc_aec->out); webrtc_aec->out = NULL; } return 0; } int echo_cancellation_process(struct aec_handler *ec, uint8_t *near, uint8_t *far, int nbytes) { webrtc_aec_t *webrtc_aec; int proc_size; int ret; int i; if (!ec) { snd_err("ec null !\n"); return -1; } webrtc_aec = ec->aec_inst; if (!webrtc_aec) { snd_err("webrtc_aec null !\n"); return -1; } proc_size = webrtc_aec->samples * sizeof(int16_t); if (nbytes % proc_size != 0) { snd_err("invalid input size !\n"); return -1; } for (i = 0; i < nbytes; i += proc_size) { memcpy(webrtc_aec->far, far + i, proc_size); WebRtcAec_BufferFarend(webrtc_aec->inst, webrtc_aec->far, webrtc_aec->samples); memcpy(webrtc_aec->near, near + i, proc_size); WebRtcAec_Process(webrtc_aec->inst, webrtc_aec->near, NULL, webrtc_aec->out, NULL, webrtc_aec->samples, 10, 0); memcpy(near + i, webrtc_aec->out, proc_size); } return 0; } int echo_cancellation_create(struct aec_handler *aec, int rate, int bits, int samples) { webrtc_aec_t *webrtc_aec; int ret; if (!aec) { snd_err("aec null !\n"); return -1; } if (bits != 16) { snd_err("bits %d ns not support !\n", bits); return -1; } if (samples % (rate / 100) != 0) { snd_err("samples and rate not mulitple !\n"); return -1; } webrtc_aec = snd_zalloc(sizeof(webrtc_aec_t), AFM_EXTN); if (!webrtc_aec) { snd_err("alloc webrtc ns failed !\n"); return -1; } webrtc_aec->samples = rate / 100; if (aec_buffer_alloc(webrtc_aec)) { snd_err("alloc buffer failed !\n"); snd_free(webrtc_aec); return -1; } ret = WebRtcAec_Create(&webrtc_aec->inst); if (ret) { snd_err("create webrtc aec failed %d!\n", ret); snd_free(webrtc_aec); return -1; } ret = WebRtcAec_Init(webrtc_aec->inst, rate, rate); if (ret) { snd_err("init webrtc aec failed !\n"); WebRtcAec_Free(webrtc_aec->inst); aec_buffer_free(webrtc_aec); snd_free(webrtc_aec); return -1; } snd_info("echo cancellation create\n"); aec->aec_inst = webrtc_aec; return 0; } int echo_cancellation_release(struct aec_handler *aec) { webrtc_aec_t *webrtc_aec; if (!aec) { snd_err("aec null !\n"); return -1; } webrtc_aec = aec->aec_inst; if (!webrtc_aec) { snd_err("webrtc_aec null !\n"); return -1; } aec_buffer_free(webrtc_aec); WebRtcAec_Free(webrtc_aec->inst); snd_free(webrtc_aec); aec->aec_inst = NULL; snd_info("echo cancellation release\n"); return 0; }
YifuLiu/AliOS-Things
components/uvoice/audio/process/proc_aec.c
C
apache-2.0
3,960
/* * 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_audio.h" #include "audio_common.h" #include "audio_stream.h" #include "opensource/webrtc/modules/audio_processing/agc/gain_control.h" typedef struct { int16_t *in[2]; int16_t *out[2]; int32_t *filter_state[4]; int samples; int band_samples; int band_num; void *inst; } webrtc_agc_t; static int agc_buffer_alloc(webrtc_agc_t *webrtc_agc) { int i; if (!webrtc_agc) { snd_err("webrtc_agc null !\n"); return -1; } for (i = 0; i < webrtc_agc->band_num; i++) { webrtc_agc->in[i] = snd_zalloc( webrtc_agc->band_samples * sizeof(int16_t), AFM_MAIN); if (!webrtc_agc->in[i]) { snd_err("alloc in buffer failed !\n"); return -1; } webrtc_agc->out[i] = snd_zalloc( webrtc_agc->band_samples * sizeof(short), AFM_MAIN); if (!webrtc_agc->out) { snd_err("alloc out buffer failed !\n"); return -1; } } if (webrtc_agc->band_num == 2) { for (i = 0; i < 4; i++) { webrtc_agc->filter_state[i] = snd_zalloc( 6 * sizeof(int32_t), AFM_MAIN); if (!webrtc_agc->filter_state[i]) { snd_err("alloc filter state failed !\n"); return -1; } } } return 0; } static int agc_buffer_free(webrtc_agc_t *webrtc_agc) { int i; if (!webrtc_agc) { snd_err("webrtc_agc null !\n"); return -1; } for (i = 0; i < 4; i++) { if (webrtc_agc->filter_state[i]) { snd_free(webrtc_agc->filter_state[i]); webrtc_agc->filter_state[i] = NULL; } } for (i = 0; i < webrtc_agc->band_num; i++) { if (webrtc_agc->in[i]) { snd_free(webrtc_agc->in[i]); webrtc_agc->in[i] = NULL; } if (webrtc_agc->out[i]) { snd_free(webrtc_agc->out[i]); webrtc_agc->out[i] = NULL; } } return 0; } int auto_gain_control_process(struct auto_gain_control *agc, uint8_t *buffer, int nbytes) { webrtc_agc_t *webrtc_agc; int level_in = 0; int level_out = 0; uint8_t saturation_warning; int proc_size; int ret; int i; if (!agc) { snd_err("agc null !\n"); return -1; } webrtc_agc = agc->handler; if (!webrtc_agc) { snd_err("webrtc_agc null !\n"); return -1; } proc_size = webrtc_agc->samples * sizeof(int16_t); if (nbytes % proc_size != 0) { snd_err("invalid input size !\n"); return -1; } if (webrtc_agc->band_num == 1) { for (i = 0; i < nbytes; i += proc_size) { memcpy(webrtc_agc->in[0], buffer + i, proc_size); level_in = level_out; ret = WebRtcAgc_Process(webrtc_agc->inst, webrtc_agc->in, 1, webrtc_agc->samples, webrtc_agc->out, level_in, &level_out, 0, &saturation_warning); if (ret) { snd_err("agc process failed %d!\n", ret); return -1; } memcpy(buffer + i, webrtc_agc->out[0], proc_size); } } else if (webrtc_agc->band_num == 2) { for (i = 0; i < nbytes; i += proc_size) { WebRtcSpl_AnalysisQMF(buffer + i, webrtc_agc->samples, webrtc_agc->in[0], webrtc_agc->in[1], webrtc_agc->filter_state[0], webrtc_agc->filter_state[1]); level_in = level_out; ret = WebRtcAgc_Process(webrtc_agc->inst, webrtc_agc->in, 2, webrtc_agc->band_samples, webrtc_agc->out, level_in, &level_out, 0, &saturation_warning); if (ret) { snd_err("agc process failed %d!\n", ret); return -1; } WebRtcSpl_SynthesisQMF(webrtc_agc->out[0], webrtc_agc->out[1], webrtc_agc->band_samples, buffer + i, webrtc_agc->filter_state[2], webrtc_agc->filter_state[3]); } } return 0; } int auto_gain_control_create(struct auto_gain_control *agc, int rate, int bits, int samples) { webrtc_agc_t *webrtc_agc; WebRtcAgcConfig config; int ret; if (!agc) { snd_err("agc null !\n"); return -1; } if (bits != 16) { snd_err("bits %d ns not support !\n", bits); return -1; } webrtc_agc = snd_zalloc(sizeof(webrtc_agc_t), AFM_EXTN); if (!webrtc_agc) { snd_err("alloc webrtc ns failed !\n"); return -1; } if (rate == 32000 || rate == 48000) { webrtc_agc->samples = 320; webrtc_agc->band_samples = 160; webrtc_agc->band_num = 2; } else { webrtc_agc->samples = rate / 100; webrtc_agc->band_samples = webrtc_agc->samples; webrtc_agc->band_num = 1; } if (samples % webrtc_agc->samples != 0) { snd_err("samples and rate not mulitple !\n"); snd_free(webrtc_agc); return -1; } if (agc_buffer_alloc(webrtc_agc)) { snd_err("alloc buffer failed !\n"); snd_free(webrtc_agc); return -1; } webrtc_agc->inst = WebRtcAgc_Create(); if (!webrtc_agc->inst) { snd_err("create webrtc agc failed !\n"); snd_free(webrtc_agc); return -1; } ret = WebRtcAgc_Init(webrtc_agc->inst, 0, 255, kAgcModeFixedDigital, rate); if (ret) { snd_err("init webrtc agc failed !\n"); WebRtcAgc_Free(webrtc_agc->inst); agc_buffer_free(webrtc_agc); snd_free(webrtc_agc); return -1; } WebRtcAgc_get_config(webrtc_agc->inst, &config); config.compressionGaindB = 20; config.limiterEnable = 1; config.targetLevelDbfs = 3; WebRtcAgc_set_config(webrtc_agc->inst, config); snd_info("auto gain control create\n"); agc->handler = webrtc_agc; return 0; } int auto_gain_control_release(struct auto_gain_control *agc) { webrtc_agc_t *webrtc_agc; if (!agc) { snd_err("agc null !\n"); return -1; } webrtc_agc = agc->handler; if (!webrtc_agc) { snd_err("webrtc_agc null !\n"); return -1; } agc_buffer_free(webrtc_agc); WebRtcAgc_Free(webrtc_agc->inst); snd_free(webrtc_agc); agc->handler = NULL; snd_info("auto gain control release\n"); return 0; }
YifuLiu/AliOS-Things
components/uvoice/audio/process/proc_agc.c
C
apache-2.0
5,617
/* * 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_audio.h" #include "audio_common.h" #include "audio_stream.h" #include "opensource/webrtc/modules/audio_processing/ns/noise_suppression_x.h" typedef struct { short *in[2]; short *out[2]; int32_t *filter_state[4]; int samples; int band_samples; int band_num; NsxHandle *inst; } webrtc_ns_t; static int ns_buffer_alloc(webrtc_ns_t *webrtc_ns) { int i; if (!webrtc_ns) { snd_err("webrtc_ns null !\n"); return -1; } for (i = 0; i < webrtc_ns->band_num; i++) { webrtc_ns->in[i] = snd_zalloc( webrtc_ns->band_samples * sizeof(short), AFM_MAIN); if (!webrtc_ns->in) { snd_err("alloc in buffer failed !\n"); return -1; } webrtc_ns->out[i] = snd_zalloc( webrtc_ns->band_samples * sizeof(short), AFM_MAIN); if (!webrtc_ns->out) { snd_err("alloc out buffer failed !\n"); return -1; } } if (webrtc_ns->band_num == 2) { for (i = 0; i < 4; i++) { webrtc_ns->filter_state[i] = snd_zalloc( 6 * sizeof(int32_t), AFM_MAIN); if (!webrtc_ns->filter_state[i]) { snd_err("alloc filter state failed !\n"); return -1; } } } return 0; } static int ns_buffer_free(webrtc_ns_t *webrtc_ns) { int i; if (!webrtc_ns) { snd_err("webrtc_ns null !\n"); return -1; } for (i = 0; i < 4; i++) { if (webrtc_ns->filter_state[i]) { snd_free(webrtc_ns->filter_state[i]); webrtc_ns->filter_state[i] = NULL; } } for (i = 0; i < webrtc_ns->band_num; i++) { if (webrtc_ns->in[i]) { snd_free(webrtc_ns->in[i]); webrtc_ns->in[i] = NULL; } if (webrtc_ns->out[i]) { snd_free(webrtc_ns->out[i]); webrtc_ns->out[i] = NULL; } } return 0; } int noise_suppression_process(struct noise_suppression *ns, uint8_t *buffer, int nbytes) { webrtc_ns_t *webrtc_ns; int proc_size; int ret; int i; if (!ns) { snd_err("ns null !\n"); return -1; } webrtc_ns = ns->handler; if (!webrtc_ns) { snd_err("webrtc_ns null !\n"); return -1; } proc_size = webrtc_ns->samples * sizeof(short); if (nbytes % proc_size != 0) { snd_err("invalid input size !\n"); return -1; } if (webrtc_ns->band_num == 1) { for (i = 0; i < nbytes; i += proc_size) { memcpy(webrtc_ns->in[0], buffer + i, proc_size); WebRtcNsx_Process(webrtc_ns->inst, webrtc_ns->in, 1, webrtc_ns->out); memcpy(buffer + i, webrtc_ns->out[0], proc_size); } } else if (webrtc_ns->band_num == 2) { for (i = 0; i < nbytes; i += proc_size) { WebRtcSpl_AnalysisQMF(buffer + i, webrtc_ns->samples, webrtc_ns->in[0], webrtc_ns->in[1], webrtc_ns->filter_state[0], webrtc_ns->filter_state[1]); WebRtcNsx_Process(webrtc_ns->inst, webrtc_ns->in, 2, webrtc_ns->out); WebRtcSpl_SynthesisQMF(webrtc_ns->out[0], webrtc_ns->out[1], webrtc_ns->band_samples, buffer + i, webrtc_ns->filter_state[2], webrtc_ns->filter_state[3]); } } return 0; } int noise_suppression_create(struct noise_suppression *ns, int rate, int bits, int samples, int mode) { webrtc_ns_t *webrtc_ns; int ret; if (!ns) { snd_err("ns null !\n"); return -1; } if (bits != 16) { snd_err("bits %d ns not support !\n", bits); return -1; } if (samples % (rate / 100) != 0) { snd_err("samples and rate not mulitple !\n"); return -1; } webrtc_ns = snd_zalloc(sizeof(webrtc_ns_t), AFM_EXTN); if (!webrtc_ns) { snd_err("alloc webrtc ns failed !\n"); return -1; } webrtc_ns->inst = WebRtcNsx_Create(); if (!webrtc_ns->inst) { snd_err("create webrtc nsx failed !\n"); snd_free(webrtc_ns); return -1; } ret = WebRtcNsx_Init(webrtc_ns->inst, rate); if (ret) { snd_err("init webrtc nsx failed !\n"); WebRtcNsx_Free(webrtc_ns->inst); snd_free(webrtc_ns); return -1; } webrtc_ns->samples = rate / 100; if (rate == 48000 || rate == 32000) { webrtc_ns->band_num = 2; webrtc_ns->band_samples = webrtc_ns->samples / 2; } else { webrtc_ns->band_num = 1; webrtc_ns->band_samples = webrtc_ns->samples; } ret = WebRtcNsx_set_policy(webrtc_ns->inst, mode); if (ret) { snd_err("set webrtc policy failed %d!\n", ret); WebRtcNsx_Free(webrtc_ns->inst); snd_free(webrtc_ns); return -1; } if (ns_buffer_alloc(webrtc_ns)) { snd_err("alloc ns buffer failed !\n"); ns_buffer_free(webrtc_ns); WebRtcNsx_Free(webrtc_ns->inst); snd_free(webrtc_ns); return -1; } snd_info("noise suppression create\n"); ns->handler = webrtc_ns; return 0; } int noise_suppression_release(struct noise_suppression *ns) { webrtc_ns_t *webrtc_ns; if (!ns) { snd_err("ns null !\n"); return -1; } webrtc_ns = ns->handler; if (!webrtc_ns) { snd_err("webrtc_ns null !\n"); return -1; } ns_buffer_free(webrtc_ns); WebRtcNsx_Free(webrtc_ns->inst); snd_free(webrtc_ns); ns->handler = NULL; snd_info("noise suppression release\n"); return 0; }
YifuLiu/AliOS-Things
components/uvoice/audio/process/proc_ns.c
C
apache-2.0
4,977
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited * */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <math.h> #include "uvoice_os.h" #include "uvoice_audio.h" #include "uvoice_common.h" #include "audio_common.h" #include "audio_stream.h" #include "opensource/speexdsp/include/speex/speex_resampler.h" #define SPEEX_RESAMPLE_ENABLE typedef struct { int sbits; int channels; int src_rate; int dst_rate; uint8_t *out_buffer; float *fin; float *fout; int out_buffer_size; int fin_samples; int fout_samples; int out_coeff; int sample_bytes; int quality; SpeexResamplerState *speex_state; os_mutex_t lock; } resampler_inst_t; static void float_to_short_interleave(short *output, float *input, int samples_per_channel, int channels) { int channel_index; int sample_index; for (channel_index = 0; channel_index < channels; channel_index++) { input += samples_per_channel * channel_index; for (sample_index = 0; sample_index < samples_per_channel; sample_index++) output[channels * sample_index + channel_index] = (short)input[sample_index]; //floor(.5 + input[sample_index]); } } static void short_to_float_deinterleave(float *output, short *input, int samples_per_channel, int channels, int channel_gap) { int channel_index; int sample_index; for (channel_index = 0; channel_index < channels; channel_index++) { for (sample_index = 0; sample_index < samples_per_channel; sample_index++) output[sample_index] = (float)input[channels * sample_index + channel_index]; output += channel_gap; } } int uvoice_resampler_process(void *resampler, uint8_t *input, int input_len, uint8_t **output, int *output_len) { resampler_inst_t *inst = (resampler_inst_t *)resampler; spx_uint32_t ilen; spx_uint32_t olen; int input_samples; int fin_samples; int fout_samples; int out_buffer_size; spx_uint32_t output_samples; int channels; int temp; int ret; int i; if (!inst) { *output = input; *output_len = input_len; return 0; } os_mutex_lock(inst->lock, OS_WAIT_FOREVER); if (inst->src_rate == inst->dst_rate) { *output = input; *output_len = input_len; os_mutex_unlock(inst->lock); return 0; } channels = inst->channels; input_samples = (input_len / inst->sample_bytes) / channels; fin_samples = (input_samples / 100 + 1) * 100; fout_samples = fin_samples * inst->out_coeff; #ifdef SPEEX_RESAMPLE_ENABLE if (fin_samples != inst->fin_samples) { if (inst->fin) { snd_free(inst->fin); inst->fin = NULL; inst->fin_samples = 0; } inst->fin = snd_zalloc( fin_samples * sizeof(float) * inst->channels, AFM_EXTN); if (!inst->fin) { M_LOGE("alloc fin buffer fail !\n"); os_mutex_unlock(inst->lock); return -1; } inst->fin_samples = fin_samples; } if (fout_samples != inst->fout_samples) { if (inst->fout) { snd_free(inst->fout); inst->fout = NULL; inst->fout_samples = 0; } inst->fout = snd_zalloc( fout_samples * sizeof(float) * inst->channels, AFM_EXTN); if (!inst->fout) { M_LOGE("alloc fout buffer fail !\n"); os_mutex_unlock(inst->lock); return -1; } inst->fout_samples = fout_samples; } #endif out_buffer_size = fout_samples * channels * inst->sample_bytes; if (inst->out_buffer_size != out_buffer_size) { if (inst->out_buffer) snd_free(inst->out_buffer); inst->out_buffer = snd_zalloc(out_buffer_size, AFM_MAIN); if (!inst->out_buffer) { M_LOGE("alloc out buffer fail !\n"); os_mutex_unlock(inst->lock); return -1; } inst->out_buffer_size = out_buffer_size; } #ifdef SPEEX_RESAMPLE_ENABLE short_to_float_deinterleave(inst->fin, (short *)input, input_samples, channels, inst->fin_samples); output_samples = 0; for (i = 0; i < channels; i++) { ilen = (spx_uint32_t)input_samples; olen = (spx_uint32_t)inst->fout_samples; ret = speex_resampler_process_float(inst->speex_state, i, (const float *)(inst->fin + inst->fin_samples * i), &ilen, inst->fout + output_samples, &olen); if (ret != RESAMPLER_ERR_SUCCESS) { M_LOGE("resampler error %d\n", ret); } if (ilen < input_samples) { M_LOGW("input %d samples, consum %u samples\n", input_samples, ilen); } output_samples += olen; } float_to_short_interleave((short *)inst->out_buffer, inst->fout, output_samples / channels, channels); *output = inst->out_buffer; *output_len = output_samples * inst->sample_bytes; #else short *input_ptr = (short *)input; short *output_ptr = (short *)inst->out_buffer; int sample_value; for (i = 0; i < input_samples; i++) { output_ptr[i * 2] = input_ptr[i]; if (i == input_samples - 1) sample_value = input_ptr[i]; else sample_value = (input_ptr[i] + input_ptr[i + 1]) / 2; output_ptr[i * 2 + 1] = (short)sample_value; } *output = inst->out_buffer; *output_len = input_samples * 2 * inst->sample_bytes; #endif os_mutex_unlock(inst->lock); return 0; } int uvoice_resampler_update(void *resampler, int src_rate, int dst_rate, int channels, int sbits) { resampler_inst_t *inst = (resampler_inst_t *)resampler; int out_coeff; int i; if (!inst) { M_LOGE("no resampler !\n"); return -1; } os_mutex_lock(inst->lock, OS_WAIT_FOREVER); if (inst->channels == channels && inst->sbits == sbits && inst->src_rate == src_rate && inst->dst_rate == dst_rate) { os_mutex_unlock(inst->lock); return 0; } if (inst->channels != channels) inst->channels = channels; if (inst->sbits != sbits) { inst->sbits = sbits; inst->sample_bytes = sbits >> 3; } if (inst->src_rate != src_rate || inst->dst_rate != dst_rate) { inst->src_rate = src_rate; inst->dst_rate = dst_rate; out_coeff = (inst->dst_rate / inst->src_rate) + 1; if (inst->out_coeff != out_coeff) { inst->out_coeff = out_coeff; M_LOGD("update coeff %d\n", inst->out_coeff); } #ifdef SPEEX_RESAMPLE_ENABLE M_LOGI("speex resampler update, %d->%d\n", inst->src_rate, inst->dst_rate); speex_resampler_set_rate(inst->speex_state, (spx_uint32_t)inst->src_rate, (spx_uint32_t)inst->dst_rate); #endif } os_mutex_unlock(inst->lock); return 0; } int uvoice_resampler_create(void **resampler, int src_rate, int dst_rate, int channels, int sbits) { resampler_inst_t *inst; int err = 0; int ret; if (!resampler) return -1; inst = snd_zalloc(sizeof(resampler_inst_t), AFM_EXTN); if (!inst) { M_LOGE("alloc resampler inst fail !\n"); return -1; } inst->lock = os_mutex_new(); inst->src_rate = src_rate; inst->dst_rate = dst_rate; inst->sbits = sbits; inst->channels = channels; inst->quality = 0; inst->out_coeff = (dst_rate / src_rate) + 1; inst->sample_bytes = sbits >> 3; #ifdef SPEEX_RESAMPLE_ENABLE inst->speex_state = speex_resampler_init((spx_uint32_t)channels, (spx_uint32_t)src_rate, (spx_uint32_t)dst_rate, inst->quality, &err); if (!inst->speex_state) { M_LOGE("init speex resampler fail %d!\n", err); os_mutex_free(inst->lock); snd_free(inst); return -1; } speex_resampler_skip_zeros(inst->speex_state); #endif *resampler = inst; M_LOGI("speex resampler create, %d->%d\n", inst->src_rate, inst->dst_rate); return 0; } int uvoice_resampler_release(void *resampler) { resampler_inst_t *inst = (resampler_inst_t *)resampler; if (!inst) { M_LOGI("no resampler\n"); return 0; } if (inst->fout) snd_free(inst->fout); if (inst->fin) snd_free(inst->fin); if (inst->out_buffer) snd_free(inst->out_buffer); #ifdef SPEEX_RESAMPLE_ENABLE speex_resampler_destroy(inst->speex_state); #endif os_mutex_free(inst->lock); snd_free(inst); M_LOGI("speex resampler release\n"); return 0; }
YifuLiu/AliOS-Things
components/uvoice/audio/process/proc_resample.c
C
apache-2.0
7,642
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited * */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include "uvoice_common.h" #include "uvoice_os.h" #include "uvoice_audio.h" #include "audio_common.h" #include "audio_stream.h" #include "audio_vad.h" #include "opensource/webrtc/common_audio/vad/include/webrtc_vad.h" typedef struct { short *in[2]; short *out[2]; int32_t *filter_state[4]; int rate; int samples; int band_samples; int band_num; VadInst *inst; } webrtc_vad_t; static int vad_buffer_alloc(webrtc_vad_t *webrtc_vad) { int i; if (!webrtc_vad) { snd_err("webrtc_vad null !\n"); return -1; } for (i = 0; i < webrtc_vad->band_num; i++) { webrtc_vad->in[i] = snd_zalloc( webrtc_vad->band_samples * sizeof(short), AFM_MAIN); if (!webrtc_vad->in) { snd_err("alloc in buffer failed !\n"); return -1; } webrtc_vad->out[i] = snd_zalloc( webrtc_vad->band_samples * sizeof(short), AFM_MAIN); if (!webrtc_vad->out) { snd_err("alloc out buffer failed !\n"); return -1; } } if (webrtc_vad->band_num == 2) { for (i = 0; i < 4; i++) { webrtc_vad->filter_state[i] = snd_zalloc( 6 * sizeof(int32_t), AFM_MAIN); if (!webrtc_vad->filter_state[i]) { snd_err("alloc filter state failed !\n"); return -1; } } } return 0; } static int vad_buffer_free(webrtc_vad_t *webrtc_vad) { int i; if (!webrtc_vad) { snd_err("webrtc_vad null !\n"); return -1; } for (i = 0; i < 4; i++) { if (webrtc_vad->filter_state[i]) { snd_free(webrtc_vad->filter_state[i]); webrtc_vad->filter_state[i] = NULL; } } for (i = 0; i < webrtc_vad->band_num; i++) { if (webrtc_vad->in[i]) { snd_free(webrtc_vad->in[i]); webrtc_vad->in[i] = NULL; } if (webrtc_vad->out[i]) { snd_free(webrtc_vad->out[i]); webrtc_vad->out[i] = NULL; } } return 0; } /* * return value: 0 - noise, 1 - speech */ int vad_process(struct voice_active_detect *vad, const uint8_t *buffer, int nbytes) { webrtc_vad_t *webrtc_vad; int proc_size; int ret = 0; int i; if (!vad) { snd_err("vad null !\n"); return -1; } webrtc_vad = vad->handler; if (!webrtc_vad) { snd_err("webrtc_vad null !\n"); return -1; } proc_size = webrtc_vad->samples * sizeof(short); if (nbytes % proc_size != 0) { snd_err("invalid input size !\n"); return -1; } if (webrtc_vad->band_num == 1) { for (i = 0; i < nbytes; i += proc_size) { memcpy(webrtc_vad->in[0], buffer + i, proc_size); ret = WebRtcVad_Process(webrtc_vad->inst, webrtc_vad->rate, webrtc_vad->in[0], webrtc_vad->samples); } } else if (webrtc_vad->band_num == 2) { for (i = 0; i < nbytes; i += proc_size) { WebRtcSpl_AnalysisQMF(buffer + i, webrtc_vad->samples, webrtc_vad->in[0], webrtc_vad->in[1], webrtc_vad->filter_state[0], webrtc_vad->filter_state[1]); ret = WebRtcVad_Process(webrtc_vad->inst, webrtc_vad->rate, webrtc_vad->in[0], webrtc_vad->samples); } } return ret; } int vad_create(struct voice_active_detect *vad, int rate, int samples, int mode) { webrtc_vad_t *webrtc_vad; int ret; if (!vad) { snd_err("vad null !\n"); return -1; } if (samples % (rate / 100) != 0) { snd_err("samples and rate not mulitple !\n"); return -1; } webrtc_vad = snd_zalloc(sizeof(webrtc_vad_t), AFM_EXTN); if (!webrtc_vad) { snd_err("alloc webrtc ns failed !\n"); return -1; } webrtc_vad->inst = WebRtcVad_Create(); if (!webrtc_vad->inst) { snd_err("create webrtc vad failed !\n"); snd_free(webrtc_vad); return -1; } ret = WebRtcVad_Init(webrtc_vad->inst); if (ret) { snd_err("init webrtc vad failed %d!\n", ret); WebRtcVad_Free(webrtc_vad->inst); snd_free(webrtc_vad); return -1; } webrtc_vad->samples = samples; if (rate == 48000 || rate == 32000) { webrtc_vad->band_num = 2; webrtc_vad->band_samples = webrtc_vad->samples / 2; } else { webrtc_vad->band_num = 1; webrtc_vad->band_samples = webrtc_vad->samples; } webrtc_vad->band_num = 1; webrtc_vad->band_samples = webrtc_vad->samples; webrtc_vad->rate = rate; ret = WebRtcVad_set_mode(webrtc_vad->inst, mode); if (ret) { snd_err("set webrtc vad mode failed %d!\n", ret); WebRtcVad_Free(webrtc_vad->inst); snd_free(webrtc_vad); return -1; } if (vad_buffer_alloc(webrtc_vad)) { snd_err("alloc vad buffer failed !\n"); vad_buffer_free(webrtc_vad); WebRtcVad_Free(webrtc_vad->inst); snd_free(webrtc_vad); return -1; } snd_debug("vad create\n"); vad->handler = webrtc_vad; return 0; } int vad_release(struct voice_active_detect *vad) { webrtc_vad_t *webrtc_vad; if (!vad) { snd_err("vad null !\n"); return -1; } webrtc_vad = vad->handler; if (!webrtc_vad) { snd_err("webrtc_vad null !\n"); return -1; } vad_buffer_free(webrtc_vad); WebRtcVad_Free(webrtc_vad->inst); snd_free(webrtc_vad); vad->handler = NULL; snd_debug("vad release\n"); return 0; }
YifuLiu/AliOS-Things
components/uvoice/audio/process/proc_vad.c
C
apache-2.0
4,959
/* * 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_common.h" #include "uvoice_play.h" #include "opensource/amr/sp_dec.h" #define AMR_MAGIC_NUMBER "#!AMR\n" typedef struct { int frame_type; /* 0: IF1, 1: IF2 */ void *amrdec; } amr_decoder_t; static int amr_decoder_reset(void *priv) { media_decoder_t *mdecoder = (media_decoder_t *)priv; amr_decoder_t *amr; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } amr = mdecoder->decoder; if (!amr) { M_LOGE("amr decoder null !\n"); return -1; } Decoder_Interface_reset(amr->amrdec); M_LOGD("amr decoder reset\n"); return 0; } static int amr_decoder_process(void *priv, const uint8_t *buffer, int nbytes) { media_decoder_t *mdecoder = (media_decoder_t *)priv; amr_decoder_t *amr; const uint8_t *readptr = buffer; uint8_t frame_header; int rem_size = nbytes; int frame_size; short *out_buffer; int ret; enum Mode dec_mode; short block_size[16] = { 12, 13, 15, 17, 19, 20, 26, 31, 5, 0, 0, 0, 0, 0, 0, 0 }; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } amr = mdecoder->decoder; if (!amr) { M_LOGE("amr decoder null !\n"); return -1; } if (rem_size < strlen(AMR_MAGIC_NUMBER)) { M_LOGE("invalid input buffer size %d\n", rem_size); return -1; } out_buffer = mdecoder->buffer_out; if (!mdecoder->running) { if (memcmp(buffer, AMR_MAGIC_NUMBER, strlen(AMR_MAGIC_NUMBER))) { M_LOGE("amr magic number not found !\n"); return -1; } readptr += strlen(AMR_MAGIC_NUMBER); rem_size -= strlen(AMR_MAGIC_NUMBER); media_pcminfo_t pcm_info; memset(&pcm_info, 0, sizeof(pcm_info)); pcm_info.rate = 8000; pcm_info.frames = 160; pcm_info.channels = 1; pcm_info.bits = 16; mdecoder->message(mdecoder->priv, PLAYER_MSG_PCM_INFO, &pcm_info); media_info_t media_info; memset(&media_info, 0, sizeof(media_info_t)); media_info.bitrate = 12000; mdecoder->message(mdecoder->priv, PLAYER_MSG_MEDIA_INFO, &media_info); mdecoder->running = 1; } while (1) { frame_header = readptr[0]; dec_mode = (frame_header >> 3) & 0xf; rem_size--; frame_size = block_size[dec_mode]; if (rem_size < frame_size) { mdecoder->unproc_size = rem_size + 1; break; } if (frame_header & 0x04) { //M_LOGD("frame_size %d rem_size %d\n", frame_size, rem_size); Decoder_Interface_Decode(amr->amrdec, readptr, out_buffer, 0); if (mdecoder->output(mdecoder->priv, out_buffer, mdecoder->buffer_out_size)) { M_LOGE("output failed !\n"); return -1; } } else { M_LOGW("bad frame\n"); } readptr += frame_size + 1; rem_size -= frame_size; if (rem_size <= 0) { mdecoder->unproc_size = 0; break; } } return 0; } static int amr_decoder_action(void *priv, player_action_t action, void *arg) { return 0; } int amr_decoder_create(media_decoder_t *mdecoder) { amr_decoder_t *amr; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } amr = snd_zalloc(sizeof(amr_decoder_t), AFM_MAIN); if (!amr) { M_LOGE("alloc amr decoder failed !\n"); return -1; } amr->amrdec = Decoder_Interface_init(); if (!amr->amrdec) { M_LOGE("init amrdec failed !\n"); snd_free(amr); return -1; } mdecoder->buffer_out_size = sizeof(short) * 160; mdecoder->buffer_out = snd_zalloc(mdecoder->buffer_out_size, AFM_MAIN); if (!mdecoder->buffer_out) { M_LOGE("alloc out buffer failed !\n"); snd_free(amr); return -1; } mdecoder->input_size = 128; mdecoder->decode = amr_decoder_process; mdecoder->action = amr_decoder_action; mdecoder->reset = amr_decoder_reset; mdecoder->decoder = amr; M_LOGD("amr decoder create\n"); return 0; } int amr_decoder_release(media_decoder_t *mdecoder) { amr_decoder_t *amr; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } if (mdecoder->buffer_out) { snd_free(mdecoder->buffer_out); mdecoder->buffer_out = NULL; mdecoder->buffer_out_size = 0; } amr = mdecoder->decoder; if (!amr) { M_LOGE("amr null !\n"); return -1; } Decoder_Interface_exit(amr->amrdec); snd_free(amr); M_LOGD("amr decoder release\n"); return 0; }
YifuLiu/AliOS-Things
components/uvoice/codec/amr_decoder.c
C
apache-2.0
4,320
/* * 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_recorder.h" #include "uvoice_common.h" #include "uvoice_record.h" #include "opensource/amr/sp_enc.h" #define AMR_MAGIC_NUMBER "#!AMR\n" typedef struct { void *amrenc; uint8_t *enc_buffer; } amr_encoder_t; static int amr_encode_process(void *priv, uint8_t *buffer, int nbytes) { media_encoder_t *mencoder = (media_encoder_t *)priv; if (!mencoder) { M_LOGE("mencoder null !\n"); return -1; } amr_encoder_t *amr = mencoder->encoder; if (!amr) { M_LOGE("speex null !\n"); return -1; } enum Mode req_mode = MR515; int rem_size = nbytes; uint8_t *ptr = buffer; uint8_t *enc_ptr = buffer; int enc_sum = 0; int enc_ret; int i; if (rem_size < 320) { M_LOGE("samples too less !\n"); return -1; } while (1) { enc_ret = Encoder_Interface_Encode(amr->amrenc, req_mode, ptr, amr->enc_buffer, 0); snd_memcpy(enc_ptr, amr->enc_buffer, enc_ret); enc_ptr += enc_ret; enc_sum += enc_ret; rem_size -= 320; //M_LOGD("enc_ret %d rem_size %d\n", enc_ret, rem_size); if (rem_size < 320) { if (rem_size > 0) M_LOGW("discard unproc data %d\n", rem_size); break; } ptr += 320; } return enc_sum; } static int amr_encode_header_gen(void *priv, void *arg) { media_encoder_t *mencoder = (media_encoder_t *)priv; if (!mencoder) { M_LOGE("mencoder null !\n"); return -1; } mencoder->header_size = strlen(AMR_MAGIC_NUMBER); char *header = snd_zalloc(mencoder->header_size, AFM_EXTN); if (!header) { M_LOGE("alloc header failed !\n"); return -1; } memcpy(header, AMR_MAGIC_NUMBER, strlen(AMR_MAGIC_NUMBER)); mencoder->header = header; mencoder->header_cplt = 1; return 0; } static int amr_encode_action(void *priv, recorder_action_t action, void *arg) { return 0; } int amr_encoder_create(media_encoder_t *mencoder) { amr_encoder_t *amr; if (!mencoder) { M_LOGE("mencoder null !\n"); return -1; } amr = snd_zalloc(sizeof(amr_encoder_t), AFM_MAIN); if (!amr) { M_LOGE("alloc speex encoder failed !\n"); return -1; } amr->amrenc = Encoder_Interface_init(1); if (!amr->amrenc) { M_LOGE("init amrenc failed !\n"); snd_free(amr); return -1; } amr->enc_buffer = snd_zalloc(160 * sizeof(short), AFM_MAIN); if (!amr->enc_buffer) { M_LOGE("alloc enc buffer failed !\n"); Encoder_Interface_exit(amr->amrenc); snd_free(amr); return -1; } mencoder->encoder = amr; mencoder->encode = amr_encode_process; mencoder->action = amr_encode_action; mencoder->header_gen = amr_encode_header_gen; M_LOGD("amr encoder create\n"); return 0; } int amr_encoder_release(media_encoder_t *mencoder) { amr_encoder_t *amr; if (!mencoder) { M_LOGE("mencoder null !\n"); return -1; } amr = mencoder->encoder; if (!amr) { M_LOGE("amr encoder null !\n"); return -1; } snd_free(amr->enc_buffer); Encoder_Interface_exit(amr->amrenc); snd_free(amr); mencoder->encoder = NULL; M_LOGD("amr encoder release\n"); return 0; }
YifuLiu/AliOS-Things
components/uvoice/codec/amr_encoder.c
C
apache-2.0
3,152
/* * 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_common.h" #include "uvoice_play.h" #include "opensource/amrwb/dec_if.h" #define AMRWB_MAGIC_NUMBER "#!AMR-WB\n" typedef struct { void *amrwbdec; } amrwb_decoder_t; extern const UWord8 block_size[]; static int amrwb_decoder_reset(void *priv) { media_decoder_t *mdecoder = (media_decoder_t *)priv; amrwb_decoder_t *amrwb; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } amrwb = mdecoder->decoder; if (!amrwb) { M_LOGE("amrwb decoder null !\n"); return -1; } D_IF_reset(amrwb->amrwbdec); M_LOGD("amrwb decoder reset\n"); return 0; } static int amrwb_decoder_process(void *priv, const uint8_t *buffer, int nbytes) { media_decoder_t *mdecoder = (media_decoder_t *)priv; amrwb_decoder_t *amrwb; const uint8_t *readptr = buffer; uint8_t frame_header; int rem_size = nbytes; int frame_size; short *out_buffer; int ret; int16_t dec_mode; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } amrwb = mdecoder->decoder; if (!amrwb) { M_LOGE("amrwb decoder null !\n"); return -1; } out_buffer = mdecoder->buffer_out; if (!mdecoder->running) { #ifndef IF2 if (rem_size < strlen(AMRWB_MAGIC_NUMBER)) { M_LOGE("invalid input buffer size %d\n", rem_size); return -1; } if (memcmp(buffer, AMRWB_MAGIC_NUMBER, strlen(AMRWB_MAGIC_NUMBER))) { M_LOGE("amrwb magic number not found !\n"); return -1; } readptr += strlen(AMRWB_MAGIC_NUMBER); rem_size -= strlen(AMRWB_MAGIC_NUMBER); #endif media_pcminfo_t pcm_info; memset(&pcm_info, 0, sizeof(pcm_info)); pcm_info.rate = 16000; pcm_info.frames = L_FRAME16k; pcm_info.channels = 1; pcm_info.bits = 16; mdecoder->message(mdecoder->priv, PLAYER_MSG_PCM_INFO, &pcm_info); media_info_t media_info; memset(&media_info, 0, sizeof(media_info_t)); media_info.bitrate = 12000; mdecoder->message(mdecoder->priv, PLAYER_MSG_MEDIA_INFO, &media_info); mdecoder->running = 1; } while (1) { frame_header = readptr[0]; #ifdef IF2 dec_mode = (frame_header >> 4); #else dec_mode = (frame_header >> 3) & 0xf; #endif rem_size--; frame_size = block_size[dec_mode] - 1; if (rem_size < frame_size) { mdecoder->unproc_size = rem_size + 1; break; } if (frame_header & 0x04) { //M_LOGD("frame_size %d rem_size %d\n", frame_size, rem_size); D_IF_decode(amrwb->amrwbdec, readptr, out_buffer, _good_frame); if (mdecoder->output(mdecoder->priv, out_buffer, mdecoder->buffer_out_size)) { M_LOGE("output failed !\n"); return -1; } } else { M_LOGW("bad frame\n"); } readptr += frame_size + 1; rem_size -= frame_size; if (rem_size <= 0) { mdecoder->unproc_size = 0; break; } } return 0; } static int amrwb_decoder_action(void *priv, player_action_t action, void *arg) { return 0; } int amrwb_decoder_create(media_decoder_t *mdecoder) { amrwb_decoder_t *amrwb; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } amrwb = snd_zalloc(sizeof(amrwb_decoder_t), AFM_MAIN); if (!amrwb) { M_LOGE("alloc amrwb decoder failed !\n"); return -1; } amrwb->amrwbdec = D_IF_init(); if (!amrwb->amrwbdec) { M_LOGE("init amrwbdec failed !\n"); snd_free(amrwb); return -1; } mdecoder->buffer_out_size = sizeof(short) * L_FRAME16k; mdecoder->buffer_out = snd_zalloc(mdecoder->buffer_out_size, AFM_MAIN); if (!mdecoder->buffer_out) { M_LOGE("alloc out buffer failed !\n"); snd_free(amrwb); return -1; } mdecoder->input_size = 256; mdecoder->decode = amrwb_decoder_process; mdecoder->action = amrwb_decoder_action; mdecoder->reset = amrwb_decoder_reset; mdecoder->decoder = amrwb; M_LOGD("amrwb decoder create\n"); return 0; } int amrwb_decoder_release(media_decoder_t *mdecoder) { amrwb_decoder_t *amrwb; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } if (mdecoder->buffer_out) { snd_free(mdecoder->buffer_out); mdecoder->buffer_out = NULL; mdecoder->buffer_out_size = 0; } amrwb = mdecoder->decoder; if (!amrwb) { M_LOGE("amrwb null !\n"); return -1; } D_IF_exit(amrwb->amrwbdec); snd_free(amrwb); M_LOGD("amrwb decoder release\n"); return 0; }
YifuLiu/AliOS-Things
components/uvoice/codec/amrwb_decoder.c
C
apache-2.0
4,410
/* * 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_recorder.h" #include "uvoice_common.h" #include "uvoice_record.h" #include "opensource/amrwb/enc_if.h" #define AMRWB_MAGIC_NUMBER "#!AMR-WB\n" typedef struct { void *amrwbenc; uint8_t *enc_buffer; } amrwb_encoder_t; static int amrwb_encode_process(void *priv, uint8_t *buffer, int nbytes) { media_encoder_t *mencoder = (media_encoder_t *)priv; if (!mencoder) { M_LOGE("mencoder null !\n"); return -1; } amrwb_encoder_t *amrwb = mencoder->encoder; if (!amrwb) { M_LOGE("speex null !\n"); return -1; } int16_t mode = 4; int16_t allow_dtx = 0; int rem_size = nbytes; uint8_t *ptr = buffer; uint8_t *enc_ptr = buffer; int enc_sum = 0; int enc_ret; int i; if (rem_size < 640) { /* 640: L_FRAME16k * sizeof(short) */ M_LOGE("samples too less !\n"); return -1; } while (1) { enc_ret = E_IF_encode(amrwb->amrwbenc, mode, ptr, amrwb->enc_buffer, allow_dtx); snd_memcpy(enc_ptr, amrwb->enc_buffer, enc_ret); enc_ptr += enc_ret; enc_sum += enc_ret; rem_size -= 640; //M_LOGD("enc_ret %d rem_size %d\n", enc_ret, rem_size); if (rem_size < 640) { if (rem_size > 0) M_LOGW("discard unproc data %d\n", rem_size); break; } ptr += 640; } return enc_sum; } static int amrwb_encode_header_gen(void *priv, void *arg) { media_encoder_t *mencoder = (media_encoder_t *)priv; if (!mencoder) { M_LOGE("mencoder null !\n"); return -1; } mencoder->header_size = strlen(AMRWB_MAGIC_NUMBER); char *header = snd_zalloc(mencoder->header_size, AFM_EXTN); if (!header) { M_LOGE("alloc header failed !\n"); return -1; } memcpy(header, AMRWB_MAGIC_NUMBER, strlen(AMRWB_MAGIC_NUMBER)); mencoder->header = header; mencoder->header_cplt = 1; return 0; } static int amrwb_encode_action(void *priv, recorder_action_t action, void *arg) { return 0; } int amrwb_encoder_create(media_encoder_t *mencoder) { amrwb_encoder_t *amrwb; if (!mencoder) { M_LOGE("mencoder null !\n"); return -1; } amrwb = snd_zalloc(sizeof(amrwb_encoder_t), AFM_MAIN); if (!amrwb) { M_LOGE("alloc speex encoder failed !\n"); return -1; } amrwb->amrwbenc = E_IF_init(); if (!amrwb->amrwbenc) { M_LOGE("init amrwb encoder failed !\n"); snd_free(amrwb); return -1; } amrwb->enc_buffer = snd_zalloc(L_FRAME16k * sizeof(short), AFM_MAIN); if (!amrwb->enc_buffer) { M_LOGE("alloc enc buffer failed !\n"); E_IF_exit(amrwb->amrwbenc); snd_free(amrwb); return -1; } mencoder->encoder = amrwb; mencoder->encode = amrwb_encode_process; mencoder->action = amrwb_encode_action; mencoder->header_gen = amrwb_encode_header_gen; M_LOGD("amrwb encoder create\n"); return 0; } int amrwb_encoder_release(media_encoder_t *mencoder) { amrwb_encoder_t *amrwb; if (!mencoder) { M_LOGE("mencoder null !\n"); return -1; } amrwb = mencoder->encoder; if (!amrwb) { M_LOGE("amrwb encoder null !\n"); return -1; } snd_free(amrwb->enc_buffer); E_IF_exit(amrwb->amrwbenc); snd_free(amrwb); mencoder->encoder = NULL; M_LOGD("amrwb encoder release\n"); return 0; }
YifuLiu/AliOS-Things
components/uvoice/codec/amrwb_encoder.c
C
apache-2.0
3,270
/* * 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_os.h" #include "uvoice_common.h" #include "uvoice_play.h" #include "opensource/libogg/include/ogg/ogg.h" #include "opensource/libvorbis/include/vorbis/codec.h" #define OGG_DECODE_INPUT_SIZE 4096 #define OGG_DECODE_OUTPUT_SAMPLES_MAX 1024 enum { OGG_FLOW_FIND_IDENTIFY_HEADER = 0, OGG_FLOW_FIND_COMMENT_AND_CODEBOOK, OGG_FLOW_DECODE_PACKET, }; typedef struct { uint8_t *input_buffer; int flow; ogg_sync_state state; ogg_page page; ogg_packet packet; ogg_stream_state stream; vorbis_info vb_info; vorbis_comment vb_comment; vorbis_dsp_state vb_dsp_state; vorbis_block vb_block; } ogg_decoder_t; static int ogg_decoder_reset(void *priv) { media_decoder_t *mdecoder = (media_decoder_t *)priv; ogg_decoder_t *ogg; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } ogg = mdecoder->decoder; if (!ogg) { M_LOGE("ogg decoder null !\n"); return -1; } ogg_sync_clear(&ogg->state); ogg_sync_reset(&ogg->state); ogg->flow = OGG_FLOW_FIND_IDENTIFY_HEADER; M_LOGD("ogg reset\n"); return 0; } static int ogg_decoder_process(void *priv, const uint8_t *buffer, int nbytes) { media_decoder_t *mdecoder = (media_decoder_t *)priv; ogg_decoder_t *ogg; char *ogg_buffer; int serial; int out_len; static int index = 0; static bool stream_end = false; int ret; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } ogg = mdecoder->decoder; if (!ogg) { M_LOGE("ogg null !\n"); return -1; } ogg_buffer = ogg_sync_buffer(&ogg->state, nbytes); if (!ogg_buffer) { M_LOGE("sync buffer failed !\n"); return -1; } memcpy(ogg_buffer, buffer, nbytes); ret = ogg_sync_wrote(&ogg->state, nbytes); if (ret) { M_LOGE("ogg sync buffer failed %d!\n", ret); return -1; } if (ogg->flow == OGG_FLOW_FIND_COMMENT_AND_CODEBOOK) { //M_LOGD("find comment and codebook headers index %d\n", index); goto __find_comment_and_codebook; } else if (ogg->flow == OGG_FLOW_DECODE_PACKET) { //M_LOGD("find and decode packet\n"); goto __find_and_decode_packet; } ret = ogg_sync_pageout(&ogg->state, &ogg->page); if (ret != 1) { if (nbytes != mdecoder->input_size) { M_LOGW("tail buffer %d discard\n", nbytes); goto __exit; } M_LOGE("input not ogg stream !\n"); return -1; } serial = ogg_page_serialno(&ogg->page); if (ogg_page_bos(&ogg->page)) { //M_LOGD("init ogg stream with serial %d\n", serial); ret = ogg_stream_init(&ogg->stream, serial); if (ret) { M_LOGE("ogg stream init failed %d!\n", ret); return -1; } } else { M_LOGE("not ogg stream bos !\n"); return -1; } vorbis_info_init(&ogg->vb_info); vorbis_comment_init(&ogg->vb_comment); ret = ogg_stream_pagein(&ogg->stream, &ogg->page); if (ret < 0) { M_LOGE("read first page failed %d!\n", ret); goto __exit_err; } ret = ogg_stream_packetout(&ogg->stream, &ogg->packet); if (ret != 1){ M_LOGE("read initial header packet failed %d!\n", ret); goto __exit_err; } ret = vorbis_synthesis_headerin(&ogg->vb_info, &ogg->vb_comment, &ogg->packet); if (ret < 0) { M_LOGE("ogg stream not contain vorbis %d!\n", ret); goto __exit_err; } index = 0; ogg->flow = OGG_FLOW_FIND_COMMENT_AND_CODEBOOK; __find_comment_and_codebook: while (index < 2) { while (index < 2) { ret = ogg_sync_pageout(&ogg->state, &ogg->page); if (ret == 0) { //M_LOGD("need more input\n"); break; } if (ret == 1) { ogg_stream_pagein(&ogg->stream, &ogg->page); while (index < 2) { ret = ogg_stream_packetout(&ogg->stream, &ogg->packet); if (ret == 0) break; if (ret < 0) { M_LOGE("second header corrupt %d!\n", ret); goto __exit_err; } ret = vorbis_synthesis_headerin(&ogg->vb_info, &ogg->vb_comment, &ogg->packet); if (ret < 0) { M_LOGE("secondary header corrupt %d!\n", ret); goto __exit_err; } index++; } } } //M_LOGD("need more input, fill %d returned %d storage %d\n", // ogg->state.fill, ogg->state.returned, ogg->state.storage); goto __exit; } //M_LOGD("rate %d channels %d\n", // ogg->vb_info.rate, ogg->vb_info.channels); if (!mdecoder->running) { media_pcminfo_t pcm_info; memset(&pcm_info, 0, sizeof(pcm_info)); pcm_info.rate = ogg->vb_info.rate; pcm_info.frames = 1024; if (mdecoder->stere_enable) pcm_info.channels = ogg->vb_info.channels; else pcm_info.channels = 1; mdecoder->buffer_out_size = OGG_DECODE_OUTPUT_SAMPLES_MAX * pcm_info.channels * 2; M_LOGD("alloc out buffer %u\n", mdecoder->buffer_out_size); mdecoder->buffer_out = snd_zalloc(mdecoder->buffer_out_size, AFM_EXTN); if (!mdecoder->buffer_out) { M_LOGE("alloc mdecoder failed !\n"); goto __exit_err; } pcm_info.bits = 16; mdecoder->message(mdecoder->priv, PLAYER_MSG_PCM_INFO, &pcm_info); mdecoder->running = 1; } ogg->flow = OGG_FLOW_DECODE_PACKET; ret = vorbis_synthesis_init(&ogg->vb_dsp_state, &ogg->vb_info); if (ret != 0) { M_LOGW("vorbis synthesis init failed %d!\n", ret); goto __exit2; } vorbis_block_init(&ogg->vb_dsp_state, &ogg->vb_block); stream_end = false; //M_LOGD("decode packet, returned %d fill %d\n", // ogg->state.fill, ogg->state.returned); __find_and_decode_packet: /* The rest is just a straight decode loop until end of stream */ while (!stream_end) { while (!stream_end) { ret = ogg_sync_pageout(&ogg->state, &ogg->page); if (ret == 0) { //M_LOGD("require more input\n"); break; } if (ret < 0) { /* missing or corrupt data at this page position */ M_LOGW("corrupt or missing data in bitstream, continue\n"); } else { ogg_stream_pagein(&ogg->stream, &ogg->page); /* can safely ignore errors at this point */ while (1) { ret = ogg_stream_packetout(&ogg->stream, &ogg->packet); if (ret == 0) { //M_LOGD("require more data\n"); break; } if (ret < 0) { /* missing or corrupt data at this page position */ /* no reason to complain; already complained above */ M_LOGW("corrupt or missing data in bitstream, continue\n"); } else { /* we have a packet. Decode it */ float **pcm; int samples; if (vorbis_synthesis(&ogg->vb_block, &ogg->packet) == 0) vorbis_synthesis_blockin(&ogg->vb_dsp_state, &ogg->vb_block); /* pcm is a multichannel float vector. In stereo, for * example, pcm[0] is left, and pcm[1] is right. samples is * the size of each channel. Convert the float values * (-1.<=range<=1.) to whatever PCM format and write it out */ while ((samples = vorbis_synthesis_pcmout(&ogg->vb_dsp_state, &pcm)) > 0) { int i, j; int clip = 0; int bout = samples <= OGG_DECODE_OUTPUT_SAMPLES_MAX ? samples : OGG_DECODE_OUTPUT_SAMPLES_MAX; int channels = mdecoder->stere_enable ? ogg->vb_info.channels : 1; ogg_int16_t *convbuffer = (ogg_int16_t *)mdecoder->buffer_out; /* convert floats to 16 bit signed ints (host order) and * interleave */ for (i = 0; i < channels; i++) { ogg_int16_t *ptr = convbuffer + i; float *mono = pcm[i]; for (j = 0; j < bout; j++) { #if 1 int val = floor(mono[j] * 32767.f + .5f); #else /* optional dither */ int val=mono[j]*32767.f+drand48()-0.5f; #endif /* might as well guard against clipping */ if (val > 32767) { val = 32767; clip = 1; } if (val < -32768){ val = -32768; clip = 1; } *ptr = val; ptr += channels; } } if (clip) M_LOGW("clipping in frame %ld\n", (long)(ogg->vb_dsp_state.sequence)); out_len = bout * channels * 2; //M_LOGD("bout %d out_len %d channels %d\n", // bout, out_len, ogg->vb_info.channels); if (out_len > mdecoder->buffer_out_size) { M_LOGE("output size %d overrange !\n", out_len); goto __exit_err; } if (mdecoder->output(mdecoder->priv, mdecoder->buffer_out, out_len)) { M_LOGE("output failed !\n"); goto __exit_err; } /* tell libvorbis how many samples we actually consumed */ vorbis_synthesis_read(&ogg->vb_dsp_state, bout); } } } if (ogg_page_eos(&ogg->page)) { M_LOGD("stream end\n"); stream_end = true; } } } if (!stream_end) { if (nbytes != mdecoder->input_size) { M_LOGD("tail buffer %d\n", nbytes); stream_end = true; continue; } //M_LOGD("require more input, fill %d returned %d storage %d\n", // ogg->state.fill, ogg->state.returned, ogg->state.storage); goto __exit; } } ogg->flow = OGG_FLOW_FIND_IDENTIFY_HEADER; vorbis_block_clear(&ogg->vb_block); vorbis_dsp_clear(&ogg->vb_dsp_state); __exit2: ogg_stream_clear(&ogg->stream); vorbis_comment_clear(&ogg->vb_comment); vorbis_info_clear(&ogg->vb_info); __exit: return 0; __exit_err: ogg_stream_clear(&ogg->state); vorbis_comment_clear(&ogg->vb_comment); vorbis_info_clear(&ogg->vb_info); return -1; } static int ogg_decoder_action(void *priv, player_action_t action, void *arg) { return 0; } int ogg_decoder_create(media_decoder_t *mdecoder) { ogg_decoder_t *ogg; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } ogg = snd_zalloc(sizeof(ogg_decoder_t), AFM_MAIN); if (!ogg) { M_LOGE("alloc ogg decoder failed !\n"); return -1; } ogg_sync_init(&ogg->state); ogg->flow = OGG_FLOW_FIND_IDENTIFY_HEADER; mdecoder->input_size = OGG_DECODE_INPUT_SIZE; mdecoder->decode = ogg_decoder_process; mdecoder->action = ogg_decoder_action; mdecoder->reset = ogg_decoder_reset; mdecoder->decoder = ogg; M_LOGD("ogg create\n"); return 0; } int ogg_decoder_release(media_decoder_t *mdecoder) { ogg_decoder_t *ogg; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } if (mdecoder->buffer_out) { snd_free(mdecoder->buffer_out); mdecoder->buffer_out = NULL; mdecoder->buffer_out_size = 0; } ogg = mdecoder->decoder; if (!ogg) { M_LOGE("ogg null !\n"); return -1; } ogg_sync_clear(&ogg->state); snd_free(ogg); M_LOGD("ogg release\n"); return 0; }
YifuLiu/AliOS-Things
components/uvoice/codec/ogg_decoder.c
C
apache-2.0
10,470
#!/usr/bin/env python import os import sys import shutil download_fail_times = 0 pvmp3_path = sys.path[0] download_path = os.path.join(pvmp3_path, "platform_external_opencore") final_src_path = os.path.join(pvmp3_path, "src") print('download pvmp3 source file') if not os.path.exists(final_src_path): while True: if not os.path.exists(download_path): #os.system("git clone https://github.com/aosp-mirror/platform_external_opencore.git -b android-2.2.3_r2.1 " + str(download_path)) os.system("git clone https://gitee.com/mirrors_aosp-mirror/platform_external_opencore.git -b android-2.2.3_r2.1 \"" + str(download_path) + "\"") if os.path.exists(download_path): print("Download pvaac source success!\n") break else: download_fail_times = download_fail_times + 1 if download_fail_times >= 3: print("Download pvaac fail!\n") break break shutil.copytree('platform_external_opencore/codecs_v2/audio/aac/dec/src', 'src') shutil.copytree('platform_external_opencore/codecs_v2/audio/aac/dec/include', 'include') shutil.copyfile('platform_external_opencore/oscl/oscl/osclerror/src/oscl_error_codes.h', "include/oscl_error_codes.h") shutil.copyfile('platform_external_opencore/codecs_v2/audio/aac/patent_disclaimer.txt', 'patent_disclaimer.txt') os.rename('src/fft_rx4_tables_fxp.cpp', 'src/fft_rx4_tables_fxp.c') print('Download opencore aac source file success!')
YifuLiu/AliOS-Things
components/uvoice/codec/opensource/pvaac/get_pv_aac.py
Python
apache-2.0
1,543
#ifndef OSCL_BASE_INCLUDED_H #define OSCL_BASE_INCLUDED_H #include "stdint.h" typedef char int8; typedef unsigned char uint8; typedef short int16; typedef unsigned short uint16; typedef int int32; typedef unsigned int uint32; typedef long long int64; typedef unsigned long long uint64; #define OSCL_UNUSED_ARG(vbl) (void)(vbl) #define OSCL_IMPORT_REF #define OSCL_EXPORT_REF #define OSCL_LEAVE(err_code) do \ { \ return NULL; \ } while(0) #endif
YifuLiu/AliOS-Things
components/uvoice/codec/opensource/pvaac/oscl/oscl_base.h
C
apache-2.0
451
#define OSCL_DLL_ENTRY_POINT_DEFAULT()
YifuLiu/AliOS-Things
components/uvoice/codec/opensource/pvaac/oscl/oscl_dll.h
C
apache-2.0
38
#ifndef OSCL_MEM_INCLUDED_H #define OSCL_MEM_INCLUDED_H #include "stdlib.h" #include "string.h" #define oscl_memcpy memcpy #define oscl_memset memset #define oscl_memmove memmove #define OSCL_ARRAY_DELETE(ptr) delete [] ptr #define OSCL_ARRAY_NEW(T, count) new T[count] #define OSCL_DELETE(ptr) {\ if(ptr){delete(ptr);}\ } #endif
YifuLiu/AliOS-Things
components/uvoice/codec/opensource/pvaac/oscl/oscl_mem.h
C
apache-2.0
339
set(SRC_LIST src/pvmp3_normalize.c src/pvmp3_alias_reduction.c src/pvmp3_crc.c src/pvmp3_decode_header.c src/pvmp3_decode_huff_cw.c src/pvmp3_getbits.c src/pvmp3_dequantize_sample.c src/pvmp3_framedecoder.c src/pvmp3_get_main_data_size.c src/pvmp3_get_side_info.c src/pvmp3_get_scale_factors.c src/pvmp3_mpeg2_get_scale_data.c src/pvmp3_mpeg2_get_scale_factors.c src/pvmp3_mpeg2_stereo_proc.c src/pvmp3_huffman_decoding.c src/pvmp3_huffman_parsing.c src/pvmp3_tables.c src/pvmp3_imdct_synth.c src/pvmp3_mdct_6.c src/pvmp3_dct_6.c src/pvmp3_poly_phase_synthesis.c src/pvmp3_equalizer.c src/pvmp3_seek_synch.c src/pvmp3_stereo_proc.c src/pvmp3_reorder.c src/pvmp3_polyphase_filter_window.c src/pvmp3_mdct_18.c src/pvmp3_dct_9.c src/pvmp3_dct_16.c) include_directories( include) add_definitions( -D PV_ARM_MSC_EVC_V5) add_library(pvmp3 STATIC ${SRC_LIST}) set_target_properties(pvmp3 PROPERTIES OUTPUT_NAME "pvmp3") set(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/out/libs)
YifuLiu/AliOS-Things
components/uvoice/codec/opensource/pvmp3/CMakeLists.txt
CMake
apache-2.0
1,006
#!/usr/bin/env python import os import sys import shutil download_fail_times = 0 pvmp3_path = sys.path[0] download_path = os.path.join(pvmp3_path, "source") final_src_path = os.path.join(pvmp3_path, "src") pvmp3_source = ['pvmp3_normalize.c', 'pvmp3_alias_reduction.c', 'pvmp3_crc.c', 'pvmp3_decode_header.c', 'pvmp3_decode_huff_cw.c', 'pvmp3_getbits.c', 'pvmp3_dequantize_sample.c', 'pvmp3_framedecoder.c', 'pvmp3_get_main_data_size.c', 'pvmp3_get_side_info.c', 'pvmp3_get_scale_factors.c', 'pvmp3_mpeg2_get_scale_data.c', 'pvmp3_mpeg2_get_scale_factors.c', 'pvmp3_mpeg2_stereo_proc.c', 'pvmp3_huffman_decoding.c', 'pvmp3_huffman_parsing.c', 'pvmp3_tables.c', 'pvmp3_imdct_synth.c', 'pvmp3_mdct_6.c', 'pvmp3_dct_6.c', 'pvmp3_poly_phase_synthesis.c', 'pvmp3_equalizer.c', 'pvmp3_seek_synch.c', 'pvmp3_stereo_proc.c', 'pvmp3_reorder.c', 'pvmp3_polyphase_filter_window.c', 'pvmp3_mdct_18.c', 'pvmp3_dct_9.c', 'pvmp3_dct_16.c'] print('download pvmp3 source file') if not os.path.exists(final_src_path): while True: if not os.path.exists(download_path): #download_cmd = "git clone https://github.com/aosp-mirror/platform_external_opencore.git -b android-2.2.3_r2.1 " + str(download_path) download_cmd = "git clone https://gitee.com/mirrors_aosp-mirror/platform_external_opencore.git -b android-2.2.3_r2.1 \"" + str(download_path) + "\"" print(download_cmd) os.system(download_cmd) if os.path.exists(download_path): print("Download pvmp3 source success!\n") break else: download_fail_times = download_fail_times + 1 if download_fail_times >= 3: print("Download pvmp3 fail!\n") break break src = os.path.join(pvmp3_path, 'source/codecs_v2/audio/mp3/dec/src') dst = os.path.join(pvmp3_path, "src") print(src) print(dst) shutil.copytree(src, dst) os.remove(os.path.join(pvmp3_path, 'src/pvmp3_decoder.cpp')) src = os.path.join(pvmp3_path, 'source/codecs_v2/audio/mp3/dec/include') dst = os.path.join(pvmp3_path, 'include') #shutil.rmtree(dst) print(src) print(dst) shutil.copytree(src, dst) n = 0 filelist = os.listdir(final_src_path) for i in filelist: oldname = os.path.join(final_src_path, filelist[n]) suffix = oldname.split('.')[-1] if suffix == 'h' or suffix == 'cpp': code ='' with open(oldname, 'r') as f: code = f.read() code = code.replace('double(', '(double)(') code = code.replace('int32(', '(int32)(') code = code.replace('huffcodetab ht[HUFF_TBL];', 'struct huffcodetab ht[HUFF_TBL];') code = code.replace('huffcodetab *pHuff;', 'struct huffcodetab *pHuff;') code = code.replace('__inline', 'static inline') code = code.replace('inline int16 saturate16', 'static int16 saturate16') code = code.replace('new_slen[4];', 'new_slen[4] = {0,0,0,0};') with open(oldname, 'w') as f: f.write(code) if suffix == 'cpp': newname = oldname[:-4] + '.c' os.rename(oldname, newname) print(oldname,'->', newname) n = n + 1 shutil.copyfile('oscl_base.h', 'include/oscl_base.h') shutil.copyfile('oscl_mem.h', 'include/oscl_mem.h') shutil.rmtree(download_path) print('Download pvmp3 source file success!')
YifuLiu/AliOS-Things
components/uvoice/codec/opensource/pvmp3/get_pvmp3.py
Python
apache-2.0
3,992
#ifndef OSCL_BASE_INCLUDED_H #define OSCL_BASE_INCLUDED_H #include "stdint.h" typedef char int8; typedef unsigned char uint8; typedef short int16; typedef unsigned short uint16; typedef int int32; typedef unsigned int uint32; typedef long long int64; typedef unsigned long long uint64; #define OSCL_UNUSED_ARG(vbl) (void)(vbl) #define OSCL_IMPORT_REF #define OSCL_EXPORT_REF #define OSCL_LEAVE(err_code) do \ { \ return NULL; \ } while(0) #endif
YifuLiu/AliOS-Things
components/uvoice/codec/opensource/pvmp3/oscl_base.h
C
apache-2.0
451
#ifndef OSCL_MEM_INCLUDED_H #define OSCL_MEM_INCLUDED_H #include "stdlib.h" #include "string.h" #define oscl_memcpy memcpy #define oscl_memset memset #define oscl_memmove memmove #define OSCL_ARRAY_DELETE(ptr) delete [] ptr #define OSCL_ARRAY_NEW(T, count) new T[count] #define OSCL_DELETE(ptr) {\ if(ptr){delete(ptr);}\ } #endif
YifuLiu/AliOS-Things
components/uvoice/codec/opensource/pvmp3/oscl_mem.h
C
apache-2.0
339
/* * 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_common.h" #include "uvoice_play.h" #include "opensource/opus/source/include/opus.h" #define OPUS_FRAME_LEN_MAX 1500 #define OPUS_FRAME_SAMPLES_MAX 1280 typedef struct { OpusDecoder *handler; int rate; int channels; } opus_decoder_t; static int opus_rate; static int opus_channels; static uint32_t char_to_int(uint8_t ch[4]) { return ((uint32_t)ch[0] << 24) | ((uint32_t)ch[1] << 16) | ((uint32_t)ch[2] << 8) | (uint32_t)ch[3]; } static bool opus_rate_valid(int rate) { switch (rate) { case 8000: case 12000: case 16000: case 24000: case 48000: return true; } return false; } static bool opus_channels_valid(int channels) { if (channels == 1 || channels == 2) return true; return false; } static int opus_decode_reset(void *priv) { media_decoder_t *mdecoder = (media_decoder_t *)priv; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } opus_decoder_t *opus = mdecoder->decoder; if (!opus) { M_LOGE("opus decoder null !\n"); return -1; } M_LOGI("opus decoder reset\n"); return 0; } static int opus_decode_process(void *priv, uint8_t *buffer, int nbytes) { media_decoder_t *mdecoder = (media_decoder_t *)priv; opus_decoder_t *opus; uint8_t *frame_ptr = buffer; int remaining_len = nbytes; int frame_len; int out_samples; short sample; int ret; int i; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } char *pcm_out = mdecoder->buffer_out; short *dec_out = mdecoder->buffer_out; opus = mdecoder->decoder; if (!opus) { M_LOGE("opus decoder null !\n"); return -1; } while (1) { if (remaining_len <= 8) { mdecoder->unproc_size = remaining_len; break; } frame_len = char_to_int(frame_ptr); frame_ptr += 8; remaining_len -= 8; if (frame_len > remaining_len) { mdecoder->unproc_size = remaining_len + 8; break; } if (frame_len > OPUS_FRAME_LEN_MAX || frame_len <= 0) { M_LOGE("frame len %d invalid !\n", frame_len); return -1; } out_samples = opus_decode(opus->handler, frame_ptr, frame_len, mdecoder->buffer_out, OPUS_FRAME_SAMPLES_MAX, 0); frame_ptr += frame_len; remaining_len -= frame_len; if (out_samples <= 0) { M_LOGE("decoder error %d!\n", out_samples); continue; } if (!mdecoder->running) { if (mdecoder->message) { media_pcminfo_t pcm_info; memset(&pcm_info, 0, sizeof(pcm_info)); pcm_info.rate = opus->rate; pcm_info.frames = out_samples; if (mdecoder->stere_enable) pcm_info.channels = opus->channels; else pcm_info.channels = 1; pcm_info.bits = 16; mdecoder->message(mdecoder->priv, PLAYER_MSG_PCM_INFO, &pcm_info); } mdecoder->running = 1; } if (out_samples > OPUS_FRAME_SAMPLES_MAX) { M_LOGE("out samples %d overrange !\n", out_samples); return -1; } if (out_samples * opus->channels * sizeof(short) > mdecoder->buffer_out_size) { M_LOGE("out size %d over buffer length !\n", out_samples * opus->channels * sizeof(short)); return -1; } /*temp = 0; ret = opus_decoder_ctl(opus->handler, OPUS_GET_SAMPLE_RATE(&temp)); if (ret) { M_LOGE("get sample rate failed %d!\n", ret); } else { M_LOGI("sample rate %d\n", temp); }*/ for (i = 0; i < out_samples * opus->channels; i++) { sample = dec_out[i]; pcm_out[2 * i] = sample & 0xff; pcm_out[2 * i + 1] = (sample >> 8) & 0xff; if (!mdecoder->stere_enable && opus->channels == 2) i++; } if (mdecoder->output(mdecoder->priv, mdecoder->buffer_out, out_samples * opus->channels * sizeof(short))) { M_LOGE("output failed !\n"); return -1; } } return 0; } static int opus_decode_action(void *priv, player_action_t action, void *arg) { media_decoder_t *mdecoder = (media_decoder_t *)priv; opus_decoder_t *opus; int ret; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } opus = mdecoder->decoder; if (!opus) { M_LOGE("opus decoder null !\n"); return -1; } if (action == PLAYER_CONFIGURE) { media_pcminfo_t *pcminfo = arg; if (!pcminfo) { M_LOGE("pcm info null !\n"); return -1; } if (!opus_rate_valid(pcminfo->rate)) { M_LOGE("sample rate invalid !\n"); return -1; } opus->rate = pcminfo->rate; opus_rate = opus->rate; if (!opus_channels_valid(pcminfo->channels)) { M_LOGE("channels invalid !\n"); return -1; } opus->channels = pcminfo->channels; opus_channels = opus->channels; M_LOGI("rate %d channels %d\n", opus->rate, opus->channels); } else if (action == PLAYER_START || action == PLAYER_RESUME || action == STREAM_MGR_START) { int error = -1; if (!opus_rate_valid(opus->rate)) { if (opus_rate_valid(opus_rate)) { opus->rate = opus_rate; } else { M_LOGE("no valid rate !\n"); return -1; } } if (!opus_channels_valid(opus->channels)) { if (opus_channels_valid(opus_channels)) { opus->channels = opus_channels; } else { M_LOGE("no valid channels !\n"); return -1; } } opus->handler = opus_decoder_create(opus->rate, opus->channels, &error); if (!opus->handler) { M_LOGE("create opus decoder failed !\n"); return -1; } M_LOGI("opus decoder create, rate %d channels %d\n", opus->rate, opus->channels); } else if (action == PLAYER_STOP || action == PLAYER_PAUSE || action == STREAM_MGR_STOP) { if (opus->handler) { opus_decoder_destroy(opus->handler); opus->handler = NULL; M_LOGI("opus decoder release\n"); } } return 0; } int opus_decode_create(media_decoder_t *mdecoder) { opus_decoder_t *opus; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } mdecoder->buffer_out_size = OPUS_FRAME_SAMPLES_MAX * sizeof(int16_t) * 2; M_LOGI("out buffer %u\n", mdecoder->buffer_out_size); mdecoder->buffer_out = snd_zalloc( mdecoder->buffer_out_size, AFM_EXTN); if (!mdecoder->buffer_out) { M_LOGE("alloc out buffer failed !\n"); return -1; } mdecoder->input_size = 1024; opus = snd_zalloc(sizeof(opus_decoder_t), AFM_MAIN); if (!opus) { M_LOGE("alloc opus decoder failed !\n"); return -1; } mdecoder->decoder = opus; mdecoder->decode = opus_decode_process; mdecoder->action = opus_decode_action; mdecoder->reset = opus_decode_reset; M_LOGI("opus decoder create\n"); return 0; } int opus_decode_release(media_decoder_t *mdecoder) { opus_decoder_t *opus; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } snd_free(mdecoder->buffer_out); mdecoder->buffer_out_size = 0; mdecoder->input_size = 0; opus = mdecoder->decoder; if (!opus) { M_LOGE("opus decoder null !\n"); return -1; } snd_free(opus); mdecoder->decoder = NULL; M_LOGI("opus decoder release\n"); return 0; }
YifuLiu/AliOS-Things
components/uvoice/codec/opus_decoder.c
C
apache-2.0
6,934
/* * 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_recorder.h" #include "uvoice_common.h" #include "uvoice_record.h" #include "opensource/opus/source/include/opus.h" #define UVOICE_OPUS_HEAD_SIZE 8 typedef struct { void *handler; short *in; char *out; int rate; int channels; } opus_encoder_t; static void int_to_char(uint32_t i, uint8_t ch[4]) { ch[0] = i>>24; ch[1] = (i>>16)&0xFF; ch[2] = (i>>8)&0xFF; ch[3] = i&0xFF; } static int opus_encode_process(void *priv, uint8_t *buffer, int nbytes) { media_encoder_t *mencoder = (media_encoder_t *)priv; opus_encoder_t *opus; uint32_t enc_final_range = 0; char ch[4]; int sample; int enc_len = 0; int out_len = 0; int len; int i; int time_ms = os_current_time(); if (!mencoder) { M_LOGE("mencoder null !\n"); return -1; } opus = mencoder->encoder; if (!opus) { M_LOGE("opus encoder null !\n"); return -1; } if (!opus->in) { opus->in = snd_zalloc(nbytes, AFM_MAIN); if (!opus->in) { M_LOGE("alloc opus in failed !\n"); return -1; } } if (!opus->out) { opus->out = snd_zalloc(nbytes, AFM_MAIN); if (!opus->out) { M_LOGE("alloc opus out failed !\n"); snd_free(opus->in); opus->in = NULL; return -1; } } for (i = 0; i < nbytes/sizeof(short); i++) { sample = buffer[2 * i + 1] << 8 | buffer[2 * i]; opus->in[i] = ((sample & 0xffff) ^ 0x8000) - 0x8000; } while(1) { len = opus_encode(opus->handler, opus->in + enc_len, (nbytes - enc_len) / sizeof(short), opus->out, nbytes); if (len <= 0) { M_LOGE("encoder error %d !\n", len); return -1; } enc_len += opus_packet_get_samples_per_frame(opus->out, opus->rate) * opus_packet_get_nb_frames(opus->out, len); if (enc_len == 0) { M_LOGE("encoder output zero !\n"); break; } snd_memcpy(buffer + out_len + UVOICE_OPUS_HEAD_SIZE, opus->out, len); /* playload */ int_to_char(len, ch); snd_memcpy(buffer + out_len, ch, sizeof(int)); /* playload len */ opus_encoder_ctl(opus->handler, OPUS_GET_FINAL_RANGE(&enc_final_range)); int_to_char(enc_final_range, ch); snd_memcpy(buffer + out_len + UVOICE_OPUS_HEAD_SIZE - sizeof(int), ch, sizeof(int)); out_len += len + UVOICE_OPUS_HEAD_SIZE; if (enc_len >= nbytes / sizeof(short)) break; } //time_ms = os_current_time() - time_ms; //M_LOGD("time %dms ratio %d/%d\n", time_ms, out_len, nbytes); return out_len; } static int opus_encode_action(void *priv, recorder_action_t action, void *arg) { media_encoder_t *mencoder = (media_encoder_t *)priv; opus_encoder_t *opus; int ret; if (!mencoder) { M_LOGE("mencoder null !\n"); return -1; } opus = mencoder->encoder; if (!opus) { M_LOGE("opus encoder null !\n"); return -1; } if (action == RECORDER_START) { int mem_size = opus_encoder_get_size(mencoder->channels); if (mem_size <= 0) { M_LOGE("get mem size failed %d!\n", mem_size); return -1; } M_LOGD("opus mem size %d\n", mem_size); opus->handler = snd_zalloc(mem_size, AFM_MAIN); if (!opus->handler) { M_LOGE("alloc opus mem failed !\n"); return -1; } ret = opus_encoder_init(opus->handler, mencoder->rate, mencoder->channels, OPUS_APPLICATION_VOIP); if (ret != OPUS_OK) { snd_free(opus->handler); opus->handler = NULL; M_LOGE("opus init failed %d!\n", ret); return -1; } M_LOGD("rate %d channels %d bitrate %d\n", mencoder->rate, mencoder->channels, mencoder->bitrate); opus->rate = mencoder->rate; opus_encoder_ctl(opus->handler, OPUS_SET_SIGNAL(OPUS_SIGNAL_VOICE)); opus_encoder_ctl(opus->handler, OPUS_SET_BANDWIDTH(OPUS_BANDWIDTH_NARROWBAND)); opus_encoder_ctl(opus->handler, OPUS_SET_FORCE_CHANNELS(mencoder->channels)); opus_encoder_ctl(opus->handler, OPUS_SET_BITRATE(mencoder->bitrate)); opus_encoder_ctl(opus->handler, OPUS_SET_COMPLEXITY(1)); opus_encoder_ctl(opus->handler, OPUS_SET_VBR(0)); opus_encoder_ctl(opus->handler, OPUS_SET_PACKET_LOSS_PERC(0)); opus_encoder_ctl(opus->handler, OPUS_SET_LSB_DEPTH(16)); opus_encoder_ctl(opus->handler, OPUS_SET_INBAND_FEC(0)); opus_encoder_ctl(opus->handler, OPUS_SET_DTX(0)); M_LOGD("opus encoder init\n"); } else if (action == RECORDER_STOP) { if (opus->in) { snd_free(opus->in); opus->in = NULL; } if (opus->out) { snd_free(opus->out); opus->out = NULL; } snd_free(opus->handler); M_LOGD("opus encoder free\n"); } return 0; } int opus_encode_create(media_encoder_t *mencoder) { opus_encoder_t *opus; if (!mencoder) { M_LOGE("mencoder null !\n"); return -1; } opus = snd_zalloc(sizeof(opus_encoder_t), AFM_MAIN); if (!opus) { M_LOGE("alloc opus encoder failed !\n"); return -1; } mencoder->encoder = opus; mencoder->encode = opus_encode_process; mencoder->action = opus_encode_action; M_LOGI("opus encoder create\n"); return 0; } int opus_encode_release(media_encoder_t *mencoder) { opus_encoder_t *opus; if (!mencoder) { M_LOGE("mencoder null !\n"); return -1; } opus = mencoder->encoder; if (!opus) { M_LOGE("opus encoder null !\n"); return -1; } snd_free(opus); mencoder->encoder = NULL; M_LOGI("opus encoder release\n"); return 0; }
YifuLiu/AliOS-Things
components/uvoice/codec/opus_encoder.c
C
apache-2.0
5,348
/* * 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_os.h" #include "uvoice_common.h" #include "uvoice_play.h" #include "pvmp4audiodecoder_api.h" #define BOX_TYPE_LEN 4 #define DECODER_PREPARED 2 #define ASC_BUFF_LEN 12 #define MP4_ES_DESC_TAG 0x03 #define MP4_DEC_CFG_DESC_TAG 0x04 #define MP4_DEC_SPEC_DESC_TAG 0x05 #define MP4_DECODE_NEXT 0 #define MP4_DECODE_STOP 1 #define MP4_DECODE_END 2 typedef struct { uint32_t box_size; char box_type[BOX_TYPE_LEN]; }box_header_t; typedef struct { char major_brand[BOX_TYPE_LEN]; int minor_version; char compatible_brands[12]; }box_ftyp_t; typedef struct { uint32_t box_size; char box_type[BOX_TYPE_LEN]; uint8_t version; uint8_t flags[3]; uint32_t creation_time; uint32_t modification_time; uint32_t time_scale; uint32_t duration; uint32_t rate; uint8_t reserved[10]; uint8_t matrix[36]; uint32_t preview_time; uint32_t post_time; uint32_t selection_time; uint32_t selection_duration; uint32_t current_time; uint32_t next_track_id; }box_mvhd_t; typedef struct { uint8_t version; uint8_t flag[3]; uint32_t entry_num; }box_stco_t; typedef struct { uint8_t version; uint8_t flag[3]; uint32_t entry_num; }box_stsc_t; typedef struct { uint32_t chunk_id; uint32_t samples; uint32_t id; }entry_info_t; typedef struct { uint8_t version; uint8_t flag[3]; uint32_t sample_size; uint32_t sample_count; }box_stsz_t; typedef struct { uint32_t sample_len; uint32_t sample_off; }sample_info_t; typedef struct { char decoder_status; char decoder_find; /* bit 0 esds, bit 1 stsz, bit 2 mdat*/ char seek_head; char resv; uint32_t audio_spec_config_len; uint8_t audio_spec_config_info[ASC_BUFF_LEN]; uint32_t sample_count; uint32_t *sample_size_info; uint32_t sample_index; uint32_t unproc_size; uint32_t sample_rate; uint32_t frame_length; int channels; }m4a_decoder_t; static tPVMP4AudioDecoderExternal g_dec_ext; static void *dec_mem = NULL; static uint32_t dec_mem_len = 0; static media_decoder_t *g_aac_mdecoder = NULL; static int aac_dec_init(int channels) { int status = 0; if (dec_mem == NULL) { dec_mem_len = PVMP4AudioDecoderGetMemRequirements(); dec_mem = malloc(dec_mem_len); if (0 == dec_mem) { return -1; } memset(dec_mem, 0, dec_mem_len); } else { memset(dec_mem, 0, dec_mem_len); } memset(&g_dec_ext, 0, sizeof(tPVMP4AudioDecoderExternal)); g_dec_ext.inputBufferCurrentLength = 0; g_dec_ext.remainderBits = 0; g_dec_ext.inputBufferMaxLength = PVMP4AUDIODECODER_INBUFSIZE; g_dec_ext.outputFormat = OUTPUTFORMAT_16PCM_INTERLEAVED; g_dec_ext.desiredChannels = (int)channels; g_dec_ext.aacPlusEnabled = TRUE; status = PVMP4AudioDecoderInitLibrary(&g_dec_ext, dec_mem); return status; } static int aac_dec_deinit() { if (NULL != dec_mem) { snd_free(dec_mem); dec_mem = NULL; } dec_mem_len = 0; return 0; } static int aac_decoder_config(const uint8_t *in_buffer, uint32_t in_size, int *samplerate, int *channels, int *framelength) { int status = 0; g_dec_ext.pInputBuffer = in_buffer; g_dec_ext.inputBufferCurrentLength = in_size; g_dec_ext.pOutputBuffer = NULL; status = PVMP4AudioDecoderConfig(&g_dec_ext, dec_mem); *samplerate = g_dec_ext.samplingRate; *channels = g_dec_ext.encodedChannels; aac_dec_init(*channels); g_dec_ext.pInputBuffer = in_buffer; g_dec_ext.inputBufferCurrentLength = in_size; g_dec_ext.pOutputBuffer = NULL; status = PVMP4AudioDecoderConfig(&g_dec_ext, dec_mem); *framelength = g_dec_ext.frameLength; return status; } static int aac_decoder_frame(const uint8_t *in_buffer, uint32_t *in_size, uint8_t *out_buffer, uint32_t *out_size) { int status = 0; g_dec_ext.pInputBuffer = in_buffer; g_dec_ext.pOutputBuffer = out_buffer; g_dec_ext.inputBufferCurrentLength = *in_size; g_dec_ext.inputBufferUsedLength = 0; status = PVMP4AudioDecodeFrame(&g_dec_ext, dec_mem); if (MP4AUDEC_SUCCESS == status || SUCCESS == status) { *in_size -= g_dec_ext.inputBufferUsedLength; *out_size = g_dec_ext.frameLength * g_dec_ext.desiredChannels; return status; } else if (MP4AUDEC_INCOMPLETE_FRAME == status) { } else { *in_size = 0; } return status; } static int find_box_head(const char *box_type, const uint8_t *in_buf, uint32_t size) { char *f; uint32_t i = 0; int flag = 1; if (size < strlen(box_type)) { return -1; } do { f = (char *)in_buf + i; i++; flag = memcmp(box_type, f, strlen(box_type)); } while ((i < size) && (flag)); if (flag != 0) { return -1; } return i - 1 + strlen(box_type); } static int m4aac_get_sample_size_info(m4a_decoder_t *m4adec, const uint8_t *buffer, uint32_t buff_size) { int i = 0; int offset = 0; int count = 0; uint32_t *sample_size = NULL; int boxtype_offset = 0; uint32_t *sample_size_buf = NULL; m4adec->sample_index = 0; offset = find_box_head("stsz", buffer, buff_size); if ((offset < 0) || (offset >= buff_size)) { m4adec->unproc_size = buff_size - BOX_TYPE_LEN + 1; return 0; } boxtype_offset = offset; if (buff_size - offset < sizeof(box_stsz_t)) { m4adec->unproc_size = buff_size - boxtype_offset; return 0; } box_stsz_t *stsz = (box_stsz_t *)(buffer + offset); memcpy(&count, &stsz->sample_count, sizeof(int)); count = UINT32_BIG_2_LIT(count); offset += sizeof(box_stsz_t); if (count * sizeof(uint32_t) < count || count * sizeof(uint32_t) + 256 < 256) { m4adec->unproc_size = buff_size - offset; return 0; } sample_size_buf = (uint32_t *)((uint32_t)buffer + offset); sample_size = (uint32_t *)calloc(count * sizeof(uint32_t) + 256, 1); m4adec->sample_count = count; count = MIN(m4adec->sample_count, (buff_size - offset) / sizeof(int)); for (i = 0; i < count; i++) { memcpy(&sample_size[i], sample_size_buf + i, sizeof(int)); sample_size[i] = UINT32_BIG_2_LIT(sample_size[i]); } m4adec->sample_size_info = sample_size; m4adec->sample_index = count; offset += count * sizeof(int); m4adec->unproc_size = buff_size - offset; return 0; } static int m4aac_get_sample_size_remain(m4a_decoder_t *m4adec, const uint8_t *buffer, uint32_t buff_size) { int i = 0; int offset = 0; int count = 0; uint32_t *sample_size = NULL; int boxtype_offset = 0; uint32_t *sample_size_buf = NULL; sample_size_buf = (uint32_t *)buffer; sample_size = m4adec->sample_size_info; count = MIN(m4adec->sample_count - m4adec->sample_index, (buff_size) / sizeof(int)); for (i = 0; i < count; i++) { memcpy(&sample_size[i + m4adec->sample_index], sample_size_buf + i, sizeof(int)); sample_size[i + m4adec->sample_index] = UINT32_BIG_2_LIT(sample_size[i + m4adec->sample_index]); } m4adec->sample_index += count; offset += count * sizeof(int); m4adec->unproc_size = buff_size - offset; return 0; } static int m4aac_get_mdat(m4a_decoder_t *m4adec, const uint8_t *buffer, uint32_t buff_size) { int offset = 0; offset = find_box_head("mdat", buffer, buff_size); if (offset < 0) { m4adec->unproc_size = buff_size - BOX_TYPE_LEN + 1; return -1; } m4adec->unproc_size = buff_size - offset; return 0; } static void convert_to_local_endian(short *buffer, uint32_t samples, char *out_buffer) { int i; for (i = 0; i < samples; i++) { out_buffer[i * 2] = (char)(buffer[i] & 0xFF); out_buffer[i * 2 + 1] = (char)((buffer[i] >> 8) & 0xFF); } } static void pcm_output(m4a_decoder_t *m4adec, uint8_t *in_buf, uint32_t samples) { media_decoder_t *mdecoder = g_aac_mdecoder; media_pcminfo_t pcm_info; memset(&pcm_info, 0, sizeof(pcm_info)); if (!mdecoder->running) { M_LOGD("samplerate %d, channels %d, samples %d\n", m4adec->sample_rate, m4adec->channels, samples); pcm_info.rate = m4adec->sample_rate; if (mdecoder->stere_enable) { pcm_info.frames = samples * m4adec->channels; pcm_info.channels = m4adec->channels; } else { pcm_info.channels = 1; pcm_info.frames = samples; } pcm_info.bits = 16; mdecoder->message(mdecoder->priv, PLAYER_MSG_PCM_INFO, &pcm_info); media_info_t media_info; memset(&media_info, 0, sizeof(media_info_t)); media_info.bitrate = 0; mdecoder->message(mdecoder->priv, PLAYER_MSG_MEDIA_INFO, &media_info); mdecoder->running = 1; } if (mdecoder->output && mdecoder->output(mdecoder->priv, in_buf, samples * 2)) { M_LOGE("output failed !\n"); return -1; } } static int m4aac_decode_sample(m4a_decoder_t *m4adec, const uint8_t *buffer, uint32_t buff_size) { int ret = 0; int offset = 0; int i = 0; uint32_t start_sample = m4adec->sample_index; uint32_t sample_count = m4adec->sample_count; uint32_t *sample_size_info = m4adec->sample_size_info; uint8_t *readPtr = NULL; uint8_t *sample_buffer = NULL; uint8_t *sample_addr = (uint8_t *)buffer; uint32_t dec_size = 0; uint32_t out_size = 0; offset = 0; sample_buffer = malloc(m4adec->frame_length * 4); for (i = start_sample; i < sample_count; i++) { m4adec->sample_index = i; offset += sample_size_info[i]; if (buff_size < offset) { m4adec->unproc_size = buff_size - offset + sample_size_info[i]; free(sample_buffer); return 0; } dec_size = sample_size_info[i]; out_size = 0; memset(sample_buffer, 0, m4adec->frame_length * 4); aac_decoder_frame(sample_addr, &dec_size, sample_buffer, &out_size); if (out_size != 0) { pcm_output(m4adec, sample_buffer, out_size); } sample_addr += sample_size_info[i]; } m4adec->sample_index = sample_count; m4adec->unproc_size = 0; free(sample_buffer); return 0; } static int m4aac_get_audio_config(m4a_decoder_t *m4adec, const uint8_t *buffer, uint32_t buff_size) { int i = 0; int flag = 0; int offset = 0; int esds_size = 0; int boxtype_offset = 0; int next_offset = 0; int asc_size = 0; offset = find_box_head("esds", buffer, buff_size); if ((offset < 0) || (offset >= buff_size)) { m4adec->unproc_size = BOX_TYPE_LEN - 1; return -1; } boxtype_offset = offset; if (buff_size - offset < 10) { goto config_exit; } offset += 4; if (*(buffer + offset) != MP4_ES_DESC_TAG) { goto config_exit; } offset += 1; esds_size = *(buffer + offset); if (esds_size == 0x80) { offset += 3; esds_size = *(buffer + offset); } if (buff_size - offset < esds_size) { goto config_exit; } offset += 1; for (i = 0; i < esds_size; i++) { if (*(buffer + offset + i) == MP4_DEC_CFG_DESC_TAG) { flag = MP4_DEC_CFG_DESC_TAG; } else if ((*(buffer + offset + i) == MP4_DEC_SPEC_DESC_TAG) && (flag == MP4_DEC_CFG_DESC_TAG)) { asc_size = *(buffer + offset + i + 1); if (asc_size == 0x80) { next_offset = 3; asc_size = *(buffer + offset + i + 1 + next_offset); } if ((asc_size > ASC_BUFF_LEN) || (i + 1 + next_offset + asc_size > esds_size)) { continue; } memcpy(m4adec->audio_spec_config_info, buffer + offset + i + 2 + next_offset, asc_size); offset += i + 2 + next_offset + asc_size; m4adec->audio_spec_config_len = asc_size; m4adec->unproc_size = buff_size - offset; return 0; } } config_exit: m4adec->unproc_size = buff_size - boxtype_offset; return -1; } /* esds stsz mdat */ static int m4aac_get_audio_info(m4a_decoder_t *m4adec, const uint8_t *buffer, uint32_t buff_size) { const char *f; int i = 0; int j = 0; int flag = 1; const char *box_type[3] = { "esds", "stsz", "mdat" }; if (buff_size < strlen(box_type[0])) { return -1; } do { f = (const char *)buffer + i; i++; for (j = 0; j < 3; j++) { if ((m4adec->decoder_find & (1 << j)) != 0) { continue; } flag = memcmp(box_type[j], f, strlen(box_type[j])); if (flag == 0) { if (j != 2) { m4adec->decoder_status = j; } m4adec->decoder_find |= 1 << j; m4adec->unproc_size = buff_size - (i - 1); return 0; } } } while (i < buff_size); return -1; } static int m4a_decode_buffer(m4a_decoder_t *m4adec, const uint8_t *buffer, uint32_t buff_size) { uint32_t len = 0; int ret = 0; unsigned long samplerate = 0; uint8_t channels = 0; static int decode_status = -1; static uint32_t sample_index = 0; static uint32_t *sample_size_info = NULL; static uint32_t sample_count = 0; m4adec->unproc_size = 0; switch (m4adec->decoder_status) { case -1: m4aac_get_audio_info(m4adec, buffer, buff_size); return MP4_DECODE_NEXT; break; case 0: ret = m4aac_get_audio_config(m4adec, buffer, buff_size); if (ret < 0) { return MP4_DECODE_NEXT; } ret = aac_decoder_config(m4adec->audio_spec_config_info, m4adec->audio_spec_config_len, &m4adec->sample_rate, &m4adec->channels, &m4adec->frame_length); if (ret != 0) { M_LOGE("aac_decoder_config fail, ret %d\n", ret); return MP4_DECODE_STOP; } m4adec->decoder_find |= 1; if (m4adec->decoder_find == 3) { m4adec->decoder_status = 3; } else if (m4adec->decoder_find == 7) { m4adec->decoder_status = 3; m4adec->seek_head = 1; } else { m4adec->decoder_status = 1; } return MP4_DECODE_NEXT; case 1: ret = m4aac_get_sample_size_info(m4adec, buffer, buff_size); if (m4adec->sample_count == 0) { return MP4_DECODE_NEXT; } if (m4adec->sample_count == m4adec->sample_index) { m4adec->sample_index = 0; m4adec->decoder_find |= 2; if (m4adec->decoder_find == 3) { m4adec->decoder_status = 3; } else if (m4adec->decoder_find == 7) { m4adec->decoder_status = 3; m4adec->seek_head = 1; } else { m4adec->decoder_status = 0; } return MP4_DECODE_NEXT; } m4adec->decoder_status = 2; return MP4_DECODE_NEXT; case 2: ret = m4aac_get_sample_size_remain(m4adec, buffer, buff_size); if (m4adec->sample_count == m4adec->sample_index) { m4adec->sample_index = 0; m4adec->decoder_find |= 2; if (m4adec->decoder_find == 3) { m4adec->decoder_status = 3; } else if (m4adec->decoder_find == 7) { m4adec->decoder_status = 3; m4adec->seek_head = 1; } else { m4adec->decoder_status = 0; } } return MP4_DECODE_NEXT; case 3: ret = m4aac_get_mdat(m4adec, buffer, buff_size); if (ret == 0) { m4adec->decoder_status = 4; } return MP4_DECODE_NEXT; case 4: ret = m4aac_decode_sample(m4adec, buffer, buff_size); if (m4adec->sample_count == m4adec->sample_index) { free(m4adec->sample_size_info); m4adec->sample_size_info = NULL; return MP4_DECODE_END; } return MP4_DECODE_NEXT; default: break; } return MP4_DECODE_STOP; } static int m4a_decoder_process(void *priv, const uint8_t *buffer, int nbytes) { media_decoder_t *mdecoder = priv; m4a_decoder_t *m4adec; int ret = 0; int unproc_size = 0; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } g_aac_mdecoder = mdecoder; m4adec = mdecoder->decoder; if (!m4adec) { M_LOGE("pvm4adec null !\n"); return -1; } ret = m4a_decode_buffer(m4adec, buffer, nbytes); mdecoder->unproc_size = m4adec->unproc_size; if (ret == MP4_DECODE_END) { ret = 0; } return ret; } static int m4a_decoder_action(void *priv, player_action_t action, void *arg) { return 0; } int pvm4a_decoder_create(media_decoder_t *mdecoder) { m4a_decoder_t *m4adec; int a1 = 0; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } m4adec = snd_zalloc(sizeof(m4a_decoder_t), AFM_MAIN); if (!m4adec) { M_LOGE("alloc pvm4a decoder failed !\n"); return -1; } g_aac_mdecoder = mdecoder; mdecoder->decode = m4a_decoder_process; mdecoder->action = m4a_decoder_action; mdecoder->decoder = m4adec; aac_dec_init(1); M_LOGD("pvm4a decoder create\n"); return 0; } int pvm4a_decoder_release(media_decoder_t *mdecoder) { m4a_decoder_t *m4adec; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } m4adec = mdecoder->decoder; if (!m4adec) { M_LOGE("pvm4a_decoder null !\n"); return -1; } aac_dec_deinit(); snd_free(m4adec); mdecoder->decode = NULL; mdecoder->action = NULL; g_aac_mdecoder = NULL; M_LOGD("pvm4a decoder release\n"); return 0; }
YifuLiu/AliOS-Things
components/uvoice/codec/pvaac_decoder.c
C
apache-2.0
18,195
/* * 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_os.h" #include "uvoice_common.h" #include "uvoice_play.h" #include "pvmp3decoder_api.h" #define NO_DECODING_ERROR 0 #define FRAME_HEADER_MASK 0xfffe0c00 #define FRAME_HEADER_SIZE 4 #define HEADER_PACK(ptr) \ ((ptr)[0] << 24 | (ptr)[1] << 16 | (ptr)[2] << 8 | (ptr)[3]) enum { PVMP3_CONTINUE = 0, PVMP3_BREAK, PVMP3_STOP, }; typedef struct { void *handler; uint8_t *frame_ptr; int32_t pos; int32_t proc_sum; int32_t rate; int32_t channels; int32_t bitrate; int32_t frame_size; int32_t frame_samples; int32_t skip_id3_size; uint32_t fixed_header; tPVMP3DecoderExternal *config; } pvmp3_decoder_t; /* * Taken from PVMP3 src */ static int pvmp3_parse_header(pvmp3_decoder_t *decoder, uint32_t header) { if ((header & 0xffe00000) != 0xffe00000) return -1; uint8_t version = (uint8_t)((header >> 19) & 3); if (version == 0x01) return -1; uint8_t layer = (uint8_t)((header >> 17) & 3); if (layer == 0x00) return -1; uint8_t bitrate_idx = (uint8_t)((header >> 12) & 0x0f); if (bitrate_idx == 0 || bitrate_idx == 0x0f) return -1; uint8_t rate_idx = (uint8_t)((header >> 10) & 3); if (rate_idx == 3) return -1; static const int rate_v1[] = { 44100, 48000, 32000 }; int sample_rate = rate_v1[rate_idx]; if (version == 2 /* V2 */) sample_rate /= 2; else if (version == 0 /* V2.5 */) sample_rate /= 4; uint8_t padding = (header >> 9) & 1; if (layer == 3) { /* layer I */ static const int bitrate_v1[] = { 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448 }; static const int bitrate_v2[] = { 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256 }; decoder->bitrate = (version == 3) ? bitrate_v1[bitrate_idx - 1] : bitrate_v2[bitrate_idx - 1]; decoder->frame_size = (12000 * decoder->bitrate / sample_rate + padding) * 4; //M_LOGD("layer1 bitrate %d rate %d padding %u frame_size %d pos %d\n", // decoder->bitrate, // sample_rate, padding, decoder->frame_size, decoder->pos); decoder->frame_samples = 384; } else { /* layer II or III */ static const int bitrate_v1_l2[] = { 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384 }; static const int bitrate_v1_l3[] = { 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320 }; static const int bitrate_v2[] = { 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 }; if (version == 3) { /* V1 */ decoder->bitrate = (layer == 2 /* L2 */) ? bitrate_v1_l2[bitrate_idx - 1] : bitrate_v1_l3[bitrate_idx - 1]; decoder->frame_samples = 1152; } else { /* V2 (or 2.5) */ decoder->bitrate = bitrate_v2[bitrate_idx - 1]; decoder->frame_samples = (layer == 1 /* L3 */) ? 576 : 1152; } if (version == 3) { /* V1 */ decoder->frame_size = 144000 * decoder->bitrate / sample_rate + padding; //M_LOGD("v1 bitrate %d rate %d padding %u frame_size %d pos %d\n", // decoder->bitrate, // sample_rate, // padding, decoder->frame_size, decoder->pos); } else { /* V2 or V2.5 */ int tmp = (layer == 1) ? 72000 : 144000; decoder->frame_size = tmp * decoder->bitrate / sample_rate + padding; //M_LOGD("v2 bitrate %d rate %d padding %u frame_size %d pos %d\n", // decoder->bitrate, // sample_rate, // padding, decoder->frame_size, decoder->pos); } } decoder->rate = sample_rate; decoder->channels = (((header >> 6) & 3) == 3) ? 1 : 2; return 0; } static int pvmp3_frame_locate(media_decoder_t *mdecoder, uint8_t *buffer, int len) { if (!mdecoder) { M_LOGE("mdecoder null !\n"); return PVMP3_STOP; } pvmp3_decoder_t *decoder = mdecoder->decoder; int skip_size; if (decoder->proc_sum == 0) { uint8_t ID3_desc[10]; int32_t ID3_size; if (len - decoder->pos < sizeof(ID3_desc)) { mdecoder->unproc_size = len - decoder->pos; M_LOGW("buffer too short !\n"); return PVMP3_BREAK; } memcpy(ID3_desc, buffer + decoder->pos, sizeof(ID3_desc)); if (!memcmp("ID3", ID3_desc, 3)) { ID3_size = ((ID3_desc[6] & 0x7f) << 21) | ((ID3_desc[7] & 0x7f) << 14) | ((ID3_desc[8] & 0x7f) << 7) | (ID3_desc[9] & 0x7f); ID3_size += 10; decoder->skip_id3_size = ID3_size; //M_LOGD("ID3 size %d pos %d len %d\n", // decoder->skip_id3_size, decoder->pos, len); skip_size = MIN(decoder->skip_id3_size, (len - decoder->pos)); decoder->skip_id3_size -= skip_size; decoder->proc_sum += skip_size; decoder->pos += skip_size; if (decoder->pos >= len) { mdecoder->unproc_size = 0; return PVMP3_BREAK; } } } if (decoder->skip_id3_size > 0) { skip_size = MIN(decoder->skip_id3_size, (len - decoder->pos)); decoder->skip_id3_size -= skip_size; decoder->pos += skip_size; decoder->proc_sum += skip_size; if (decoder->pos >= len) { //M_LOGD("skip_size %d skip_id3_size %d pos %d\n", // skip_size, decoder->skip_id3_size, decoder->pos); mdecoder->unproc_size = 0; return PVMP3_BREAK; } else { //M_LOGD("skip id3 cplt, skip_id3_size %d pos %d proc_sum %d\n", // decoder->skip_id3_size, // decoder->pos, decoder->proc_sum); } } int frame_pos = decoder->pos; int frame_size_bak = 0; int next_frame_pos = 0; uint32_t header = 0; uint32_t next_header = 0; char frame_found = 0; char assert_cnt = len >= 1045 ? len/1045 : 1; char i; do { if (frame_pos + FRAME_HEADER_SIZE > len) { mdecoder->unproc_size = len - frame_pos; decoder->proc_sum += frame_pos - decoder->pos; //M_LOGD("too less: frame_pos %d frame_size %d pos %d proc_sum %d unproc_size %u\n", // frame_pos, // decoder->frame_size, // decoder->pos, decoder->proc_sum, mdecoder->unproc_size); return PVMP3_BREAK; } header = HEADER_PACK(buffer + frame_pos); if (decoder->fixed_header != 0 && (header & FRAME_HEADER_MASK) != (decoder->fixed_header & FRAME_HEADER_MASK)) { frame_pos++; continue; } if (pvmp3_parse_header(decoder, header)) { frame_pos++; continue; } //M_LOGD("frame maybe: frame_pos %d frame_size %d pos %d g_pos %d unproc_size %u\n", // frame_pos, // decoder->frame_size, // decoder->pos, decoder->proc_sum, mdecoder->unproc_size); /* Assert frame validation */ frame_size_bak = decoder->frame_size; frame_found = 1; next_frame_pos = frame_pos; for (i = 0; i < assert_cnt; i++) { next_frame_pos += decoder->frame_size; //M_LOGD("i %d frame_pos %d next_frame_pos %d\n", // i, frame_pos, next_frame_pos); if (next_frame_pos + FRAME_HEADER_SIZE > len) { decoder->proc_sum += frame_pos - decoder->pos; mdecoder->unproc_size = len - frame_pos; //M_LOGD("require more: frame_pos %d frame_size %d pos %d proc_sum %d unproc_size %u\n", // frame_pos, // decoder->frame_size, // decoder->pos, decoder->proc_sum, mdecoder->unproc_size); return PVMP3_BREAK; } next_header = HEADER_PACK(buffer + next_frame_pos); if (decoder->fixed_header != 0 && (next_header & FRAME_HEADER_MASK) != (decoder->fixed_header & FRAME_HEADER_MASK)) { frame_pos++; frame_found = 0; break; } if (pvmp3_parse_header(decoder, next_header)) { frame_pos++; frame_found = 0; break; } } if (!frame_found) continue; if (decoder->fixed_header == 0) { decoder->fixed_header = header; //M_LOGD("fixed header 0x%x\n", decoder->fixed_header); } decoder->frame_size = frame_size_bak; decoder->frame_ptr = buffer + frame_pos; decoder->proc_sum += frame_pos + decoder->frame_size - decoder->pos; decoder->pos = frame_pos + decoder->frame_size; mdecoder->unproc_size = len - decoder->pos; //M_LOGD("frame found: frame_pos %d next_frame_pos %d frame_size %d pos %d g_pos %d unproc_size %d\n", // frame_pos, // next_frame_pos, // decoder->frame_size, // decoder->pos, decoder->proc_sum, mdecoder->unproc_size); } while (!frame_found); return PVMP3_CONTINUE; } static int pvmp3_decoder_reset(void *priv) { media_decoder_t *mdecoder = (media_decoder_t *)priv; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } pvmp3_decoder_t *decoder = mdecoder->decoder; if (!decoder) { M_LOGE("decoder null !\n"); return -1; } decoder->bitrate = 0; decoder->channels = 0; decoder->rate = 0; decoder->pos = 0; decoder->proc_sum = 0; decoder->skip_id3_size = 0; decoder->frame_ptr = NULL; decoder->fixed_header = 0; decoder->frame_samples = 0; decoder->frame_size = 0; pvmp3_resetDecoder(decoder->handler); M_LOGD("pvmp3 reset\n"); return 0; } static int pvmp3_decoder_process(void *priv, uint8_t *buffer, int nbytes) { media_decoder_t *mdecoder = (media_decoder_t *)priv; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } pvmp3_decoder_t *decoder = mdecoder->decoder; if (!decoder) { M_LOGE("decoder null !\n"); return -1; } tPVMP3DecoderExternal *config = decoder->config; int16_t *out_buffer = (int16_t *)mdecoder->buffer_out; int out_samples; int i; int ret; decoder->pos = 0; if (nbytes != mdecoder->input_size) M_LOGD("tail buff %d\n", nbytes); while (1) { ret = pvmp3_frame_locate(mdecoder, buffer, nbytes); if (ret == PVMP3_BREAK) { //M_LOGD("request more data, unproc size %u\n", // mdecoder->unproc_size); break; } else if (ret == PVMP3_STOP) { M_LOGE("decoder error !\n"); return -1; } config->inputBufferCurrentLength = nbytes - (decoder->frame_ptr - buffer); config->pInputBuffer = decoder->frame_ptr; config->inputBufferMaxLength = nbytes - (decoder->frame_ptr - buffer); config->inputBufferUsedLength = 0; config->pOutputBuffer = (int16_t *)mdecoder->buffer_out; config->outputFrameSize = mdecoder->buffer_out_size / sizeof(int16_t); ret = pvmp3_framedecoder(config, decoder->handler); if (ret != NO_DECODING_ERROR) continue; if (!mdecoder->running) { //M_LOGD("rate %d channels %d bitrate %d frame_size %d\n", // config->samplingRate, // config->num_channels, // config->bitRate, config->outputFrameSize); media_pcminfo_t pcm_info; memset(&pcm_info, 0, sizeof(media_pcminfo_t)); pcm_info.rate = config->samplingRate; pcm_info.frames = config->outputFrameSize / config->num_channels; if (mdecoder->stere_enable) pcm_info.channels = config->num_channels; else pcm_info.channels = 1; pcm_info.bits = 16; mdecoder->message(mdecoder->priv, PLAYER_MSG_PCM_INFO, &pcm_info); media_info_t media_info; memset(&media_info, 0, sizeof(media_info_t)); media_info.bitrate = config->bitRate * 1000; mdecoder->message(mdecoder->priv, PLAYER_MSG_MEDIA_INFO, &media_info); mdecoder->running = 1; } out_samples = config->outputFrameSize; if (out_samples * sizeof(int16_t) > mdecoder->buffer_out_size) { M_LOGE("out samples %u overrange !\n", out_samples); return -1; } if (config->num_channels == 2 && !mdecoder->stere_enable) { out_samples = config->outputFrameSize / 2; for (i = 0; i < out_samples; i++) out_buffer[i] = out_buffer[2 * i]; } if (mdecoder->output(mdecoder->priv, (uint8_t *)out_buffer, out_samples * sizeof(int16_t))) { M_LOGE("output failed !\n"); return -1; } } return 0; } static int pvmp3_decoder_action(void *priv, player_action_t action, void *arg) { return 0; } int pvmp3_decoder_create(media_decoder_t *mdecoder) { pvmp3_decoder_t *decoder; int mem_size; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } decoder = snd_zalloc( sizeof(pvmp3_decoder_t), AFM_MAIN); if (!decoder) { M_LOGE("alloc pvmp3 decoder failed !\n"); return -1; } decoder->config = snd_zalloc( sizeof(tPVMP3DecoderExternal), AFM_MAIN); if (!decoder->config) { M_LOGE("alloc decoder config failed !\n"); snd_free(decoder); return -1; } decoder->config->equalizerType = flat; decoder->config->crcEnabled = false; mem_size = pvmp3_decoderMemRequirements(); decoder->handler = snd_zalloc(mem_size, AFM_MAIN); if (!decoder->handler) { M_LOGE("alloc decoder memory failed !\n"); snd_free(decoder->config); snd_free(decoder); return -1; } pvmp3_InitDecoder(decoder->config, decoder->handler); mdecoder->decode = pvmp3_decoder_process; mdecoder->action = pvmp3_decoder_action; mdecoder->reset = pvmp3_decoder_reset; mdecoder->decoder = decoder; M_LOGD("pvmp3 create\n"); return 0; } int pvmp3_decoder_release(media_decoder_t *mdecoder) { pvmp3_decoder_t *decoder; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } decoder = mdecoder->decoder; if (!decoder) { M_LOGE("decoder null !\n"); return -1; } snd_free(decoder->handler); snd_free(decoder->config); snd_free(decoder); mdecoder->decoder = NULL; M_LOGD("pvmp3 release\n"); return 0; }
YifuLiu/AliOS-Things
components/uvoice/codec/pvmp3_decoder.c
C
apache-2.0
12,988
/* * 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_common.h" #include "uvoice_play.h" #include "opensource/speex/include/speex/speex_callbacks.h" typedef struct { void *speex; SpeexBits bits; int frame_size; int bitwidth; int rate; int channels; int bitrate; } spx_decoder_t; static int spx_rate; static int spx_channels; static bool spx_rate_valid(int rate) { switch (rate) { case 8000: case 12000: case 16000: case 24000: case 48000: return true; } return false; } static bool spx_channels_valid(int channels) { if (channels == 1 || channels == 2) return true; return false; } static int spx_decoder_reset(void *priv) { media_decoder_t *mdecoder = (media_decoder_t *)priv; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } spx_decoder_t *spx = mdecoder->decoder; if (!spx) { M_LOGE("spx decoder null !\n"); return -1; } M_LOGD("speex decoder reset\n"); return 0; } static int spx_decoder_process(void *priv, uint8_t *buffer, int nbytes) { media_decoder_t *mdecoder = (media_decoder_t *)priv; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } spx_decoder_t *spx = mdecoder->decoder; if (!spx) { M_LOGE("speex null !\n"); return -1; } SpeexBits *bits = &spx->bits; spx_int16_t *out_buffer = (spx_int16_t *)mdecoder->buffer_out; int offset = 0; int frame_size; int ret; int i; while (1) { frame_size = *(int *)(buffer + offset); offset += 4; if (frame_size > nbytes - offset) { mdecoder->unproc_size = nbytes - offset + 4; break; } snd_memcpy(bits->chars, buffer + offset, frame_size); bits->nbBits = frame_size << 3; speex_bits_rewind(&spx->bits); ret = speex_decode_int(spx->speex, bits, out_buffer); offset += frame_size; if (!mdecoder->running) { if (mdecoder->message) { spx_int32_t temp = 0; speex_decoder_ctl(spx->speex, SPEEX_GET_BITRATE, &temp); spx->bitrate = temp; //M_LOGD("rate %d, channels %d, bitrate %d, frame_size %d, bits %d\n", // spx->rate, // spx->channels, // spx->bitrate, // spx->frame_size, 16); media_pcminfo_t pcm_info; memset(&pcm_info, 0, sizeof(pcm_info)); pcm_info.rate = spx->rate; pcm_info.frames = spx->frame_size / spx->channels; if (mdecoder->stere_enable) pcm_info.channels = spx->channels; else pcm_info.channels = 1; pcm_info.bits = 16; mdecoder->message(mdecoder->priv, PLAYER_MSG_PCM_INFO, &pcm_info); media_info_t media_info; memset(&media_info, 0, sizeof(media_info_t)); media_info.bitrate = spx->bitrate; mdecoder->message(mdecoder->priv, PLAYER_MSG_MEDIA_INFO, &media_info); } mdecoder->running = 1; } if (mdecoder->output(mdecoder->priv, mdecoder->buffer_out, spx->frame_size * sizeof(short))) { M_LOGE("output failed !\n"); return -1; } } speex_bits_reset(&spx->bits); __exit: return 0; } static int spx_decoder_action(void *priv, player_action_t action, void *arg) { media_decoder_t *mdecoder = (media_decoder_t *)priv; spx_decoder_t *spx; spx_int32_t temp; int ret; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } spx = mdecoder->decoder; if (!spx) { M_LOGE("spx decoder null !\n"); return -1; } if (action == PLAYER_CONFIGURE) { media_pcminfo_t *pcminfo = arg; if (!pcminfo) { M_LOGE("pcm info null !\n"); return -1; } if (!spx_rate_valid(pcminfo->rate)) { M_LOGE("sample rate invalid !\n"); return -1; } spx->rate = pcminfo->rate; spx_rate = spx->rate; temp = spx->rate; speex_decoder_ctl(spx->speex, SPEEX_SET_SAMPLING_RATE, &temp); if (!spx_channels_valid(pcminfo->channels)) { M_LOGE("channels invalid !\n"); return -1; } spx->channels = pcminfo->channels; spx_channels = spx->channels; M_LOGD("rate %d channels %d\n", spx->rate, spx->channels); } else if (action == PLAYER_START || action == PLAYER_RESUME || action == STREAM_MGR_START) { int error = -1; if (!spx_rate_valid(spx->rate)) { if (spx_rate_valid(spx_rate)) { spx->rate = spx_rate; } else { M_LOGE("no valid rate !\n"); return -1; } } if (!spx_channels_valid(spx->channels)) { if (spx_channels_valid(spx_channels)) { spx->channels = spx_channels; } else { M_LOGE("no valid channels !\n"); return -1; } } M_LOGD("rate %d channels %d\n", spx->rate, spx->channels); } return 0; } int spx_decoder_create(media_decoder_t *mdecoder) { spx_decoder_t *spx; spx_int32_t temp; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } spx = snd_zalloc(sizeof(spx_decoder_t), AFM_MAIN); if (!spx) { M_LOGE("alloc speex decoder failed !\n"); return -1; } spx->speex = speex_decoder_init( speex_lib_get_mode(SPEEX_MODEID_NB)); if (!spx->speex) { M_LOGE("init speex failed !\n"); snd_free(spx); return -1; } speex_bits_init(&spx->bits); temp = 1; speex_decoder_ctl(spx->speex, SPEEX_SET_HIGHPASS, &temp); temp = 1; speex_decoder_ctl(spx->speex, SPEEX_SET_ENH, &temp); speex_decoder_ctl(spx->speex, SPEEX_GET_FRAME_SIZE, &temp); spx->frame_size = temp; M_LOGD("frame size %d\n", spx->frame_size); mdecoder->buffer_out_size = spx->frame_size * sizeof(short); mdecoder->buffer_out = snd_zalloc(mdecoder->buffer_out_size, AFM_EXTN); if (!mdecoder->buffer_out) { M_LOGE("alloc out buffer failed !\n"); speex_decoder_destroy(spx->speex); speex_bits_destroy(&spx->bits); snd_free(spx); return -1; } mdecoder->input_size = spx->bits.buf_size; mdecoder->decoder = spx; mdecoder->decode = spx_decoder_process; mdecoder->action = spx_decoder_action; mdecoder->reset = spx_decoder_reset; M_LOGD("speex decoder create\n"); return 0; } int spx_decoder_release(media_decoder_t *mdecoder) { spx_decoder_t *spx; if (!mdecoder) { M_LOGE("mdecoder null !\n"); return -1; } spx = mdecoder->decoder; if (!spx) { M_LOGE("speex decoder null !\n"); return -1; } speex_decoder_destroy(spx->speex); speex_bits_destroy(&spx->bits); snd_free(spx); mdecoder->decoder = NULL; M_LOGD("speex decoder release\n"); return 0; }
YifuLiu/AliOS-Things
components/uvoice/codec/spx_decoder.c
C
apache-2.0
6,300
/* * 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_recorder.h" #include "uvoice_common.h" #include "uvoice_record.h" #include "opensource/speex/include/speex/speex_callbacks.h" typedef struct { void *speex; SpeexBits bits; int frame_size; } spx_encoder_t; static int spx_encode_process(void *priv, uint8_t *buffer, int nbytes) { media_encoder_t *mencoder = (media_encoder_t *)priv; if (!mencoder) { M_LOGE("mencoder null !\n"); return -1; } spx_encoder_t *spx = mencoder->encoder; if (!spx) { M_LOGE("speex null !\n"); return -1; } spx_int16_t *ptr; int samples = nbytes / sizeof(short); int encode_sum = 0; int frame_size = 0; int ret; int i; int time_ms = os_current_time(); for (i = 0; i < samples; i += spx->frame_size) { speex_bits_reset(&spx->bits); ptr = (spx_int16_t *)buffer + i; speex_encode_int(spx->speex, ptr, &spx->bits); frame_size = speex_bits_write(&spx->bits, buffer + encode_sum + sizeof(int), spx->frame_size * sizeof(spx_int16_t)); if (frame_size + sizeof(int) >= spx->frame_size * sizeof(spx_int16_t)) { M_LOGE("encoded data overflow !\n"); return -1; } snd_memcpy(buffer + encode_sum, &frame_size, sizeof(int)); encode_sum += frame_size + sizeof(int); } //time_ms = os_current_time() - time_ms; //M_LOGD("time %dms ratio %d/%d\n", time_ms, frame_size, nbytes); return encode_sum; } static int spx_encode_action(void *priv, recorder_action_t action, void *arg) { media_encoder_t *mencoder = (media_encoder_t *)priv; spx_encoder_t *spx; int ret; if (!mencoder) { M_LOGE("mencoder null !\n"); return -1; } spx = mencoder->encoder; if (!spx) { M_LOGE("spx encoder null !\n"); return -1; } if (action == RECORDER_START) { if ((mencoder->frames * mencoder->channels) % spx->frame_size != 0) { M_LOGE("frame size is not integral multiple of %d !\n", spx->frame_size); return -1; } } return 0; } int spx_encoder_create(media_encoder_t *mencoder) { spx_encoder_t *spx; spx_int32_t temp; if (!mencoder) { M_LOGE("mencoder null !\n"); return -1; } spx = snd_zalloc(sizeof(spx_encoder_t), AFM_MAIN); if (!spx) { M_LOGE("alloc speex encoder failed !\n"); return -1; } spx->speex = speex_encoder_init( speex_lib_get_mode(SPEEX_MODEID_NB)); //nb_encoder_init() if (!spx->speex) { M_LOGE("init speex failed !\n"); snd_free(spx); return -1; } temp = 0; speex_encoder_ctl(spx->speex, SPEEX_SET_VBR, &temp); //nb_encoder_ctl() temp = 2; speex_encoder_ctl(spx->speex, SPEEX_SET_QUALITY, &temp); temp = 2; speex_encoder_ctl(spx->speex, SPEEX_SET_COMPLEXITY, &temp); speex_encoder_ctl(spx->speex, SPEEX_GET_FRAME_SIZE, &spx->frame_size); M_LOGD("speex frame size %d\n", spx->frame_size); /* frame size in sizeof(short) */ speex_bits_init(&spx->bits); mencoder->encoder = spx; mencoder->encode = spx_encode_process; mencoder->action = spx_encode_action; M_LOGI("speex encoder create\n"); return 0; } int spx_encoder_release(media_encoder_t *mencoder) { spx_encoder_t *spx; if (!mencoder) { M_LOGE("mencoder null !\n"); return -1; } spx = mencoder->encoder; if (!spx) { M_LOGE("speex encoder null !\n"); return -1; } speex_bits_destroy(&spx->bits); speex_encoder_destroy(spx->speex); snd_free(spx); mencoder->encoder = NULL; M_LOGI("speex encoder release\n"); return 0; }
YifuLiu/AliOS-Things
components/uvoice/codec/spx_encoder.c
C
apache-2.0
3,530
/* * Copyright (C) 2015-2020 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdint.h> static const unsigned char base64_encode_map[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; static const unsigned char base64_decode_map[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; static const unsigned char mod_table[] = { 0, 2, 1 }; int uvoice_base64_encode(const uint8_t *input, uint32_t input_len, uint8_t *output, uint32_t *output_len) { int i, j; uint32_t o_len = 4 * ((input_len + 2) / 3); if (!input || !output || !output_len) { return -1; } if (output_len) { *output_len = o_len; } for (i = 0, j = 0; i < input_len;) { unsigned int octet_a = i < input_len ? input[i++] : 0; unsigned int octet_b = i < input_len ? input[i++] : 0; unsigned int octet_c = i < input_len ? input[i++] : 0; unsigned int triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c; output[j++] = base64_encode_map[(triple >> 18) & 0x3F]; output[j++] = base64_encode_map[(triple >> 12) & 0x3F]; output[j++] = base64_encode_map[(triple >> 6) & 0x3F]; output[j++] = base64_encode_map[(triple >> 0) & 0x3F]; } for (i = 0; i < mod_table[input_len % 3]; i++) { output[o_len - 1 - i] = '='; } return 0; } int uvoice_basex64_decode(const uint8_t* input, uint32_t input_len, uint8_t* output, uint32_t* output_len) { int i, j; uint32_t o_len = input_len / 4 * 3; if (!input || !output || !output_len) { return -1; } if (input[input_len - 1] == '=') { o_len--; } if (input[input_len - 2] == '=') { o_len--; } if (output_len) { *output_len = o_len; } for (i = 0, j = 0; i < input_len;) { unsigned int sextet_a = base64_decode_map[input[i++]]; unsigned int sextet_b = base64_decode_map[input[i++]]; unsigned int sextet_c = base64_decode_map[input[i++]]; unsigned int sextet_d = base64_decode_map[input[i++]]; unsigned int triple = (sextet_a << 18) + (sextet_b << 12) + (sextet_c << 6) + (sextet_d << 0); if (j < o_len) { output[j++] = (triple >> 16) & 0xFF; } if (j < o_len) { output[j++] = (triple >> 8) & 0xFF; } if (j < o_len) { output[j++] = (triple >> 0) & 0xFF; } } return 0; }
YifuLiu/AliOS-Things
components/uvoice/common/base64.c
C
apache-2.0
3,908
/* * 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_event.h" #include "uvoice_list.h" #include "uvoice_message.h" // #define UVOICE_EVENT_TASK_ENABLE #ifdef MUSICBOX_APP #define EVENT_TASK_STACK_SIZE 2048 #else #define EVENT_TASK_STACK_SIZE 8192 #endif #define EVENT_TASK_PRIORITY UVOICE_TASK_PRI_LOWEST #define EVENT_MESSAGE_QUEUE_MAX 10 struct uvoice_event_node { uint16_t type_filter; uvoice_list_t list; uvoice_event_cb cb; void *data; }; static uvoice_list_t uvoice_event_client_list = UVOICE_LIST_INIT(uvoice_event_client_list); static os_task_t uvoice_event_task; #ifdef UVOICE_EVENT_TASK_ENABLE static os_message_queue_t uvoice_event_msgqueue; #endif static void uvoice_event_handle(uvoice_event_t *event) { struct uvoice_event_node *node = NULL; uvoice_list_for_each_entry(&uvoice_event_client_list, node, struct uvoice_event_node, list) { if (node->type_filter != event->type) continue; node->cb(event, node->data); } } #ifdef UVOICE_EVENT_TASK_ENABLE static void uvoice_event_loop(void *arg) { uvoice_event_t event; unsigned int size = 0; int ret; while (1) { ret = os_message_queue_recv(uvoice_event_msgqueue, &event, sizeof(event), OS_WAIT_FOREVER); if (ret < 0) continue; if (event.type == 0xffff && event.code == 0xffff && event.value == 0xccccffff) { M_LOGW("uvoice event loop exit"); break; } uvoice_event_handle(&event); } os_task_exit(uvoice_event_task); } #endif int uvoice_event_init(void) { #ifdef UVOICE_EVENT_ENABLE #ifdef UVOICE_EVENT_TASK_ENABLE uvoice_msgqueue_t *msgqueue; int ret; if (uvoice_event_msgqueue) { M_LOGW("uvoice event exist\n"); return -1; } uvoice_event_msgqueue = os_message_queue_create(EVENT_MESSAGE_QUEUE_MAX, sizeof(uvoice_event_t)); if (!uvoice_event_msgqueue) { M_LOGE("create msgqueue failed !\n"); return -1; } ret = os_task_create(&uvoice_event_task, "uvoice_event_task", uvoice_event_loop, NULL, EVENT_TASK_STACK_SIZE, EVENT_TASK_PRIORITY); if (ret) { M_LOGE("create event task failed %d!\n", ret); os_message_queue_free(uvoice_event_msgqueue); uvoice_event_msgqueue = NULL; return -1; } #endif #endif return 0; } int uvoice_event_deinit(void) { #ifdef UVOICE_EVENT_ENABLE struct uvoice_event_node *node = NULL; uvoice_list_t *temp = NULL; #ifdef UVOICE_EVENT_TASK_ENABLE uvoice_event_post(0xffff, 0xffff, 0xccccffff); os_msleep(10); if (uvoice_event_msgqueue) { os_message_queue_free(uvoice_event_msgqueue); uvoice_event_msgqueue = NULL; } #endif uvoice_list_for_each_entry_safe(&uvoice_event_client_list, temp, node, struct uvoice_event_node, list) { uvoice_list_del(&node->list); snd_free(node); } #endif return 0; } int uvoice_event_post(uint16_t type, uint16_t code, int value) { #ifdef UVOICE_EVENT_ENABLE uvoice_event_t event = { .type = type, .code = code, .value = value, }; #ifdef UVOICE_EVENT_TASK_ENABLE int ret; if (!uvoice_event_msgqueue) { M_LOGD("no event msgqueue\n"); return -1; } ret = os_message_queue_send(uvoice_event_msgqueue, &event, sizeof(uvoice_event_t), 0); if (ret < 0) { M_LOGE("send event failed %d!\n", ret); return -1; } #else struct uvoice_event_node *node = NULL; uvoice_list_for_each_entry(&uvoice_event_client_list, node, struct uvoice_event_node, list) { if (node->type_filter != type) continue; node->cb(&event, node->data); } #endif return 0; #else return os_event_post(type, code, value); #endif } int uvoice_event_register(uint16_t type, uvoice_event_cb cb, void *data) { #ifdef UVOICE_EVENT_ENABLE struct uvoice_event_node *node; #ifdef UVOICE_EVENT_TASK_ENABLE if (!uvoice_event_msgqueue) { M_LOGD("no event msgqueue\n"); return -1; } #endif if (!cb) { M_LOGE("callback function null !\n"); return -1; } node = snd_zalloc(sizeof(struct uvoice_event_node), AFM_EXTN); if (!node) { M_LOGE("alloc event node failed !\n"); return -1; } node->cb = cb; node->type_filter = type; node->data = data; uvoice_list_add_tail(&node->list, &uvoice_event_client_list); return 0; #else return os_event_register(type, cb, data); #endif } int uvoice_event_unregister(uint16_t type, uvoice_event_cb cb, void *data) { #ifdef UVOICE_EVENT_ENABLE struct uvoice_event_node *node = NULL; uvoice_list_t *temp = NULL; int ret = -1; uvoice_list_for_each_entry_safe(&uvoice_event_client_list, temp, node, struct uvoice_event_node, list) { if (node->type_filter != type) continue; if (node->cb != cb) continue; if (node->data != data) continue; uvoice_list_del(&node->list); snd_free(node); ret = 0; break; } return ret; #else return os_event_unregister(type, cb, data); #endif }
YifuLiu/AliOS-Things
components/uvoice/common/event.c
C
apache-2.0
5,391
/* * 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" #include "uvoice_message.h" int uvoice_msgqueue_recv(uvoice_msgqueue_t *msgqueue, int type, void *msg, int size, int timeout) { int flag = timeout == OS_WAIT_FOREVER ? 0 : IPC_NOWAIT; return msgrcv(msgqueue->qid, msg, size, type, flag); } int uvoice_msgqueue_send(uvoice_msgqueue_t *msgqueue, void *msg, int size, int block) { int flag = block ? 0 : IPC_NOWAIT; return msgsnd(msgqueue->qid, msg, size, flag); } uvoice_msgqueue_t *uvoice_msgqueue_create(char *filename, int id) { uvoice_msgqueue_t *msgqueue; key_t key; if (!filename) { M_LOGE("filename null !\n"); return -1; } if (id < 0 || id > 255) { M_LOGE("id %d invalid !\n", id); return -1; } msgqueue = snd_zalloc(sizeof(uvoice_msgqueue_t), AFM_EXTN); if (!msgqueue) { M_LOGE("alloc msgqueue failed !\n"); return NULL; } msgqueue->id = id; key = ftok(filename, id); if (key == -1) { M_LOGE("generate key failed !\n"); snd_free(msgqueue); return NULL; } msgqueue->id = msgget(key, IPC_CREAT|0666); if (msgqueue->id == -1) { M_LOGE("create msgqueue failed !\n"); snd_free(msgqueue); return NULL; } msgqueue->lock = os_mutex_new(); msgqueue->recv_sem = os_sem_new(0); return msgqueue; } int uvoice_msgqueue_release(uvoice_msgqueue_t *msgqueue) { if (!msgqueue) { M_LOGE("msgqueue null !\n"); return NULL; } os_sem_free(msgqueue->recv_sem); os_mutex_free(msgqueue->lock); snd_free(msgqueue); return 0; }
YifuLiu/AliOS-Things
components/uvoice/common/message.c
C
apache-2.0
1,630