#include "app_config.h"
#include "cpu.h"
#include "fs/fs.h"
#include "syscfg_id.h"
#include "server/server_core.h"
#include "server/audio_server.h"
#include "server/ai_server.h"
#include "json_c/json_object.h"
#include "json_c/json_tokener.h"
#include "network_download/net_download.h"
#include "sa_audio.h"
#include "app_sdk_localdata_audio_play.h"
#include "brtc_wrapper.h"

#include "app_power_manage.h"


#define GAIN_STEP           5


#define REQ_BUFFER_SIZE     (36 * 1024)
#define RES_BUFFER_SIZE     (30 * 1024)
#define RECV_BUFFER_SIZE    (512)
#define SEND_BUFFER_SIZE    (2160)


struct sa_audio_hdl {
    struct server *enc_server;      // 编码服务
    struct server *dec_server;      // 解码服务
    u8 volume;                      // 音频播放音量，50
    u8 reset_volue;                 // 默认恢复音量
    u8 gain;                        // 音频采集音量，100
    u8 channel;                     // 音频采集通道数，1
    char *format;                   // 音频格式，mp3
    const char *sample_source;      // 音频采集源，mic
    char *play_source;              // 音频播放源，dac
    int sample_rate;                // 音频采集采样率，16000
    u32 enc_time_msec;              // 音频采集时长ms，0：一直录; 60*1000ms

    // // 音频采集
    // volatile u8 enc_flag;           // 音频采集标志位，1：开始
    // void *mic_buf;                  // 音频采集缓冲区，大小1MB
    // u32 write_size;                 // 音频已采集大小
    // u32 send_size;                  // 音频已发送大小
    // OS_SEM mic_rsem;                // 音频读信号量

    // 音频播放
    FILE *speaker_fp;               // 音频播放文件描述符，play_file用
    void *speaker_buf;              // 音频播放（接收）缓冲区，大小1MB
    cbuffer_t speaker_cbuf;         // 音频播放（接收）循环缓冲区，基于speaker_buf
    u32 recv_size;                  // 已接收音频数据长度
    u32 play_size;                  // 当前播放长度
    OS_SEM r_sem;                   // 读音频数据信号量
    volatile u8 dec_run_flag;       // 解码器播放标志，1：开始
    volatile u8 dec_ready_flag;     // 解码器就绪标志位，1：开始
    volatile u8 dec_status;         // 解码器运行标志位，1：开始
    volatile u8 recv_status;        // 音频接收完成状态，1：完成
    u8 dec_server_status;


    // 音乐播放
    volatile u8 has_net_music;      // 是否有网络音乐需要播放，1：是
    volatile u8 is_net_music;       // 是否在播放网络音乐，1：是
    char *net_music_url;            // 网络音乐播放地址
    u16 wait_download;              // 异步等待下载音乐标志，>0:等待下载中
    int download_ready;             // 音乐缓冲完成标志，1：完成
    void *net_file;                 // 网络音乐文件
};

static struct sa_audio_hdl sa_audio_handler;
#define __this (&sa_audio_handler)

struct sa_audio_hdl* get_sa_audio_handler(void)
{
    return __this;
}

int sa_audio_is_net_music(void) {
    return __this->is_net_music;
}
int mp3_get_dec_volume() {
    return  __this->volume;
}
int mp3_set_dec_volume_reset() {
    mp3_set_dec_volume_mute(__this->reset_volue);
    app_sdk_audio_play_volume_lite();
}
int mp3_set_dec_volume_mute(int volume)
{
   union audio_req req = {0};

    if (volume == __this->volume) {
        return -EINVAL;
    }
    if (!__this->dec_server) {
        return -EFAULT;
    }
    __this->volume  = volume;
    req.dec.cmd     = AUDIO_DEC_SET_VOLUME;
    req.dec.attr = AUDIO_ATTR_FADE_INOUT;
    req.dec.volume  = volume * ceofVolume;
    server_request(__this->dec_server, AUDIO_REQ_DEC, &req);

    printf("set_dec_volume: %d\n", volume);
    return 1;
}

int mp3_set_dec_volume_fast_play(int volume)
{
   union audio_req req = {0};

    if (volume == __this->volume) {
        return -EINVAL;
    }
    if (!__this->dec_server) {
        return -EFAULT;
    }
    __this->volume  = volume;
    req.dec.cmd     = AUDIO_DEC_SET_VOLUME;
    req.dec.volume  = volume * ceofVolume;
    server_request(__this->dec_server, AUDIO_REQ_DEC, &req);


    printf("set_dec_volume: %d\n", volume);
    return 1;
}

extern int app_sdk_audio_play_stop(void);
extern void brtc_audio_device_need_used_set(bool need_used);
extern int app_sdk_audio_play_pause(bool pause);
void sa_audio_play(const char* url, int type)
{
    if (type == 1)
    {
        brtc_audio_device_need_used_set(true);
        size_t len = strlen(url);
        if (len >= 512) {
            len = 511;  // 保证留出一个位置放置 '\0'
        }

        if (__this->has_net_music == 1)
        {
            net_music_dec_end();
            //printf("sa_audio_play stop music");
        }

        __this->has_net_music = 1;
        memset(__this->net_music_url, 0, 512);

        memcpy(__this->net_music_url, url, len);
        __this->net_music_url[len] = '\0';  // 添加字符串终止符
        //printf("sa_audio_play: %d   %s", len, __this->net_music_url);

        net_music_dec_file(__this->net_music_url);
    } else if (type == 0)
    {
        brtc_audio_device_need_used_set(false);
        net_music_dec_end();
    }

}

// // 录音自定义文件写函数
// static int recorder_vfs_fwrite(void *file, void *data, u32 len)
// {
//     size_t current_length = __this->write_size;

//     // 检查缓冲区是否足够
//     if (current_length + len >= REQ_BUFFER_SIZE) {
//         printf("------Buffer overflow, response too large!\n");
//         return 0; // 返回 0 以指示错误
//     }

//     // 直接将新数据写入缓冲区
//     memcpy(__this->mic_buf  + current_length, data, len);
//     // printf("------write:start:%d, len:%d", __this->write_size, len);
//     __this->write_size += len;
//     if (__this->write_size - __this->send_size >= SEND_BUFFER_SIZE) {
//         SH_OS_TASKQ_POST("ws_task", 1, SH_WS_SEND_AUDIO);
//     }

//     return len;
// }

// // 录音自定义文件关闭函数
// static int recorder_vfs_fclose(void *file)
// {
//     return 0;
// }

// // 录音自定义虚拟文件函数集
// static const struct audio_vfs_ops recorder_vfs_ops = {
//     .fwrite = recorder_vfs_fwrite,
//     .fclose = recorder_vfs_fclose,
// };

// // 开始录音
// int open_audio_enc()
// {
//     printf("----------open_audio_enc----------\n");
//     union audio_req req = {0};

//     __this->enc_flag = 1;
//     __this->write_size = 0;
//     __this->send_size = 0;

//     req.enc.cmd = AUDIO_ENC_OPEN;
//     req.enc.channel = __this->channel;
//     req.enc.volume = __this->gain;
//     req.enc.frame_size = 1600;
//     req.enc.output_buf_len = req.enc.frame_size * 10;
//     req.enc.sample_rate = __this->sample_rate;
//     req.enc.format = __this->format;
//     req.enc.sample_source = __this->sample_source;
//     req.enc.msec = __this->enc_time_msec;
//     req.enc.vfs_ops = &recorder_vfs_ops;
//     req.enc.file = (FILE *)__this->mic_buf;
//     if (!strcmp(req.enc.format, "aac")) {
//         req.enc.bitrate = __this->sample_rate * 4;
//         req.enc.no_header = 1;
//     }
//     if (__this->channel == 4) {
//         req.enc.channel_bit_map = 0x0f;
//     } else if (__this->channel == 2) {
//         req.enc.channel_bit_map = BIT(CONFIG_AUDIO_ADC_CHANNEL_L) | BIT(CONFIG_AUDIO_ADC_CHANNEL_R);
//     } else {
//         req.enc.channel_bit_map = BIT(CONFIG_AUDIO_ADC_CHANNEL_L);
//     }

//     // 使能 VAD
//     // req.enc.use_vad = 1;
//     // req.enc.dns_enable = 1;
//     // req.enc.vad_auto_refresh = 1;

//     return server_request(__this->enc_server, AUDIO_REQ_ENC, &req);
// }

// // 停止录音
// int close_audio_enc()
// {
//     printf("----------close_audio_enc----------\n");
//     union audio_req req = {0};

//     if (!__this->enc_flag) {
//         return 0;
//     }
//     __this->enc_flag = 0;

//     if (__this->enc_server) {
//         req.enc.cmd = AUDIO_ENC_CLOSE;
//         server_request(__this->enc_server, AUDIO_REQ_ENC, &req);
//     }

//     return 0;
// }



// 播放音频文件
int play_file(const char* file_path)
{

    // 使用mp3 解码通道
    brtc_audio_device_need_used_set(true);
    app_sdk_audio_play_pause(true);
    printf("---------local_dec_file:%s----volume:%d------\n", file_path, __this->volume);
    int err = 0;
    union audio_req req = {0};

    FILE *file = NULL;
    file = __this->speaker_fp = fopen(file_path, "rb");

    if (!file) {
        printf("------file:%s open failed\n", file_path);
        return -1;
    }

    req.dec.cmd             = AUDIO_DEC_OPEN;
    req.dec.volume          = __this->volume * ceofVolume;
    req.dec.output_buf_len  = 6 * 1024;
    req.dec.file            = file;
    req.dec.channel         = 0;
    req.dec.sample_rate     = 0;
    req.dec.priority        = 1;
    req.dec.sample_source   = __this->play_source;

    err = server_request(__this->dec_server, AUDIO_REQ_DEC, &req);
    if (err) {
        printf("------audio_dec_open: err = %d\n", err);
        fclose(file);
        __this->speaker_fp = NULL;
        return err;
    }

    req.dec.cmd = AUDIO_DEC_START;

    err = server_request(__this->dec_server, AUDIO_REQ_DEC, &req);
    if (err) {
        printf("------audio_dec_start: err = %d\n", err);
        fclose(file);
        __this->speaker_fp = NULL;
        return err;
    }
    __this->dec_server_status = AUDIO_DEC_START;

    return 0;
}

// 音频播放自定义虚拟文件读函数
static int play_vfs_fread(void *file, void *data, u32 len) {
    u32 rlen = 0;
    while (__this->dec_run_flag && __this->dec_ready_flag) {
        if (__this->recv_status && __this->recv_size - __this->play_size < RECV_BUFFER_SIZE) {
            len = __this->recv_size - __this->play_size;
        }

        rlen = cbuf_read(&__this->speaker_cbuf, data, len);
        if (rlen) {
            __this->play_size += rlen;

            if (__this->recv_status && __this->play_size >= __this->recv_size) {
                __this->dec_run_flag = 0;
                __this->dec_ready_flag = 0;
                printf("------res audio play complete!, play size:%d\n", __this->play_size);
            }
            break;
        }
        printf(">>>>>read pend......\n");
        os_sem_pend(&__this->r_sem, 0);
    }

    return ((__this->recv_status && __this->play_size >= __this->recv_size) ? 0 : len);
}

// 音频播放自定义虚拟文件获取长度函数
static int play_vfs_flen(void *priv)
{
    return RES_BUFFER_SIZE;
}

// 音频播放自定义虚拟文件定位函数
static int play_vfs_seek(void *priv, u32 offset, int orig)
{
    if (offset > 0) {
        __this->dec_ready_flag = 1; //解码器开始偏移数据后，再开始播放，避免音频播放开端吞字
    }
    return 0;
}

// 音频播放自定义虚拟文件函数集
static const struct audio_vfs_ops play_vfs_ops = {
    .fread  = play_vfs_fread,
    .flen   = play_vfs_flen,
    .fseek  = play_vfs_seek,
};

// 打开解码器
int open_audio_dec(void* priv) {
    printf("----------open_audio_dec----------\n");
    int err = 0;
    union audio_req req = {0};

    req.dec.cmd             = AUDIO_DEC_OPEN;
    req.dec.volume          = __this->volume * ceofVolume;
    req.dec.output_buf      = NULL;
    req.dec.output_buf_len  = 6 * 1024;
    req.dec.channel         = 0;
    req.dec.sample_rate     = 0;
    req.dec.priority        = 1;
    req.dec.sample_source   = __this->play_source;
    req.dec.dec_type 		= __this->format;
    req.dec.vfs_ops         = &play_vfs_ops;
    req.dec.file            = (FILE *)&__this->speaker_cbuf;

    //打开解码器
    err = server_request(__this->dec_server, AUDIO_REQ_DEC, &req);
    if (err) {
        printf("------audio_dec_open: err = %d\n", err);
        return err;
    }

    //开始解码
    req.dec.cmd = AUDIO_DEC_START;
    err = server_request(__this->dec_server, AUDIO_REQ_DEC, &req);
    if (err) {
        printf("------audio_dec_start: err = %d\n", err);
        return err;
    }
    __this->dec_server_status = AUDIO_DEC_START;

    return 0;
}

// 关闭解码器
int close_audio_dec() {
    printf("----------close_audio_dec----------\n");
    __this->dec_run_flag = 0;
    __this->dec_ready_flag = 0;
    os_sem_post(&__this->r_sem);
    union audio_req req = {0};
    req.dec.cmd = AUDIO_DEC_STOP;

    if (__this->dec_server) {
        if (__this->dec_server_status != AUDIO_DEC_STOP) {
            server_request(__this->dec_server, AUDIO_REQ_DEC, &req);
            __this->dec_server_status = AUDIO_DEC_STOP;
        }
    }

    if (__this->speaker_fp) {
        fclose(__this->speaker_fp);
        __this->speaker_fp = NULL;
    }

    // 重置音频播放（接收）状态
    __this->recv_size = 0;
    __this->play_size = 0;
    __this->dec_status = 0;
    __this->recv_status = 0;
    cbuf_clear(&__this->speaker_cbuf);

    return 0;
}

// 编码器事件处理handler
static void enc_server_event_handler(void *priv, int argc, int *argv)
{
    switch (argv[0]) {
    case AUDIO_SERVER_EVENT_ERR:
    case AUDIO_SERVER_EVENT_END:
        printf("------mic record end! \n");
        close_audio_enc();
        play_mix_file(FAIL_FILE);
        break;
    case AUDIO_SERVER_EVENT_SPEAK_START:
        printf("------speak start ! \n");
        break;
    case AUDIO_SERVER_EVENT_SPEAK_STOP:
        printf("------speak stop ! \n");
        break;
    default:
        break;
    }
}

// 解码器事件处理handler
static void dec_server_event_handler(void *priv, int argc, int *argv)
{
    switch (argv[0]) {
    case AUDIO_SERVER_EVENT_ERR:
    case AUDIO_SERVER_EVENT_END:
        printf("----------audio dec end! \n");
        if (__this->is_net_music) {
            net_music_dec_end();
        } else {
            close_audio_dec();
        }
        // 不在使用mp3 解码通道
        brtc_audio_device_need_used_set(false);
        app_sdk_audio_play_pause(false);
        // if (__this->has_net_music) {
        //     __this->has_net_music = 0;
        //     net_music_dec_file(__this->net_music_url);
        // }
        break;
    default:
        break;
    }
}

// 混音解码器事件处理函数
static void mix_dec_server_event_handler(void *priv, int argc, int *argv)
{
    union audio_req r = {0};

    switch (argv[0]) {
    case AUDIO_SERVER_EVENT_ERR:
        puts("------mix_music: AUDIO_SERVER_EVENT_ERR\n");
    case AUDIO_SERVER_EVENT_END:
        puts("------mix_music: AUDIO_SERVER_EVENT_END\n");
        r.dec.cmd = AUDIO_DEC_STOP;
        server_request(priv, AUDIO_REQ_DEC, &r);
        server_close(priv);
        fclose((FILE *)argv[1]);

        // 不在使用mp3 解码通道
        brtc_audio_device_need_used_set(false);
        app_sdk_audio_play_pause(false);
        break;
    case AUDIO_SERVER_EVENT_CURR_TIME:
        break;
        printf("");
    case AUDIO_SERVER_EVENT_SPEAK_START:
        break;
    case AUDIO_SERVER_EVENT_SPEAK_STOP:
        break;
    default:
        break;
    }
}

// 混音解码器播放失败处理函数
static int play_mix_file_failed_handler(void *server, FILE *file, int err)
{
    if (server) {
        server_close(server);
    }
    if (file) {
        fclose(file);
    }

    printf("------play_mix_music_file: fail : %d\n", err);

    return err;
}

// 混音解码器播放函数
int play_mix_file(const char *path)
{
    if (brtc_aiagent_tts_busy()) {
        printf("ttttttttttttttttttttttttttttttttttts is  busy play_mix_file \r\n");
        return 1;
    }
    printf("pppppppppppppppppppppppppppppppppppppppppppppppppplay_mix_file 1\r\n");
    // 使用mp3 解码通道
    brtc_audio_device_need_used_set(true);
    app_sdk_audio_play_pause(true);

    int err = 0;
    union audio_req req = {0};

#if !defined CONFIG_AUDIO_MIX_ENABLE
    return 0;
#endif

    printf("------play_mix_file : %s, __this->volume:%d\n", path, __this->volume);

    FILE *file = fopen(path, "r");
    if (!file) {
        return -ENOENT;
    }

    void *dec_server = server_open("audio_server", "dec");
    if (!dec_server) {
        return play_mix_file_failed_handler(dec_server, file, err);
    }
    server_register_event_handler_to_task(dec_server, dec_server, mix_dec_server_event_handler, "app_core");

    req.dec.cmd             = AUDIO_DEC_OPEN;
    req.dec.volume          = __this->volume * ceofVolume;
    req.dec.output_buf_len  = 6 * 1024;
    req.dec.file            = file;
    req.dec.sample_source   = __this->play_source;

    err = server_request(dec_server, AUDIO_REQ_DEC, &req);
    if (err) {
        return play_mix_file_failed_handler(dec_server, file, err);
    }

    req.dec.cmd = AUDIO_DEC_START;

    err = server_request(dec_server, AUDIO_REQ_DEC, &req);
    if (err) {
        return play_mix_file_failed_handler(dec_server, file, err);
    }

    puts("------play_mix_music_file: suss\n");

    return 0;
}

// 网络音乐播放
//网络解码需要的数据访问句柄
static const struct audio_vfs_ops net_audio_dec_vfs_ops = {
    .fread = net_download_read,
    .fseek = net_download_seek,
    .flen  = net_download_get_file_len,
};

//检查音频需要的格式检查数据头部是否下载缓冲完成
static int __net_download_ready(void *p)
{
    __this->download_ready = net_download_check_ready(__this->net_file);
    if (__this->download_ready) {
        return 1;
    }
    return 0;
}


int sa_net_music_audio_play_pause(bool pause) {

    printf("net_music_audio_play_pause   end %d\n", __this->has_net_music);

    if (__this->has_net_music) {
        int err;
        union audio_req req;
        if (!__this->dec_server) {
            return 0;
        }
        if (pause) {

            req.dec.cmd = AUDIO_DEC_PAUSE;
        } else {
            req.dec.cmd = AUDIO_DEC_START ;
        }
        err = server_request(__this->dec_server, AUDIO_REQ_DEC, &req);

        printf("net_music_audio_play_pause  end %d err:%d\n", __this->has_net_music ,err);

    }
    return 0;
}

//停止播放
static int net_music_dec_stop(void)
{
    union audio_req r = {0};
    union ai_req req = {0};

    if (!__this->net_file) {
        return 0;
    }

    printf("net_music_dec_stop\n");

    net_download_buf_inactive(__this->net_file);

    if (__this->wait_download) {
        /*
         * 歌曲还未开始播放，删除wait
         */
        /* sys_timer_del(__this->wait_download); */
        wait_completion_del(__this->wait_download);
        __this->wait_download = 0;
    } else {
        r.dec.cmd = AUDIO_DEC_STOP;
        server_request(__this->dec_server, AUDIO_REQ_DEC, &r);

        int argv[2];
        argv[0] = AUDIO_SERVER_EVENT_END;
        argv[1] = (int)__this->net_file;
        server_event_handler_del(__this->dec_server, 2, argv);
    }

    extern int lwip_canceladdrinfo(void);
    lwip_canceladdrinfo();
    //释放网络下载资源
    net_download_close(__this->net_file);
    __this->net_file = NULL;

    return 0;
}

//播放结束
int net_music_dec_end(void)
{
    printf("net_music_dec_end\n");

    net_music_dec_stop();

    __this->is_net_music = 0;

    return 0;
}

static char* get_net_music_media_type(void)
{
    const char *format_str = "format$";
    size_t format_len = strlen(format_str);
    const char *url = __this->net_music_url; // 假设__this已正确定义且net_music_url已初始化

    if (!url) {
        printf("URL is not initialized.\n");
        return NULL;
    }

    // 查找format$的位置
    const char *start = strstr(url, format_str);
    if (!start) {
        return NULL;
    }

    // 跳过"format$"
    start += format_len;

    // 查找&符号或空格结束位置
    const char *end = strchr(start, '&');
    if (!end) {
        end = strchr(start, ' ');
        if (!end) {
            end = start + strlen(start); // 处理到字符串末尾的情况
        }
    }

    size_t len = end - start;
    char *result = (char *)malloc(len + 1); // 分配足够空间并包含空字符
    if (!result) {
        printf("Memory allocation failed.\n");
        return NULL;
    }

    memcpy(result, start, len);
    result[len] = '\0'; // 确保字符串以空字符结尾

    return result; // 返回动态分配的内存，调用者需负责释放
}

// 混音解码器播放失败处理函数
static int __net_music_dec_file_failed_handler(void *file)
{
    printf("play_net_music_faild\n");
    union audio_req req = {0};

    net_download_buf_inactive(file);

    req.dec.cmd = AUDIO_DEC_STOP;
    server_request(__this->dec_server, AUDIO_REQ_DEC, &req);

    net_download_close(file);
    __this->net_file = NULL;

    return -1;
}

//数据缓冲已完成，开始解码
static int __net_music_dec_file(void *file)
{
    int err = 0;
    union ai_req r = {0};
    union audio_req req = {0};

    __this->wait_download = 0;

    if (__this->download_ready < 0) {
        /* 网络下载失败 */
        return __net_music_dec_file_failed_handler(file);
    }

    //获取网络资源的格式
    char *media_type = get_net_music_media_type();
    if (!media_type) {
        req.dec.dec_type = "mp3";
    } else {
        req.dec.dec_type = media_type;
    }
    printf("url_file_type: %s\n", req.dec.dec_type);

    net_download_set_read_timeout(file, 5000);

    req.dec.cmd             = AUDIO_DEC_OPEN;
    req.dec.volume          = __this->volume * ceofVolume;
    req.dec.output_buf_len  = 6 * 1024;
    req.dec.file            = (FILE *)file;
    req.dec.channel         = 0;
    req.dec.sample_rate     = 0;
    req.dec.priority        = 1;
    req.dec.vfs_ops         = &net_audio_dec_vfs_ops;
    req.dec.sample_source   = CONFIG_AUDIO_DEC_PLAY_SOURCE;
    printf("net_music volume: %d", __this->volume);
    err = server_request(__this->dec_server, AUDIO_REQ_DEC, &req);
    if (err) {
        if (media_type) {
            free(media_type);
        }
        return __net_music_dec_file_failed_handler(file);
    }

    net_download_set_read_timeout(file, 0);

    req.dec.cmd = AUDIO_DEC_START;

    server_request(__this->dec_server, AUDIO_REQ_DEC, &req);

    net_download_set_pp(file, 0);
    if (media_type) {
        free(media_type);
    }

    return 0;
}

// 启动网络音乐播放
int net_music_dec_file(const char *url)
{
    int err = 0;
    struct net_download_parm parm = {0};

    // close_audio_dec();

    if (!url) {
        return -1;
    }

    printf("net_download_open\n");

    parm.url                = url;
    //网络缓冲buf大小
//#ifdef CONFIG_NO_SDRAM_ENABLE
    parm.cbuf_size          = 50 * 1024;
/*#else
    parm.cbuf_size          = 500 * 1024;
#endif
*/
    //设置网络下载超时
    parm.timeout_millsec    = 10000;
    parm.seek_threshold     = 1024 * 50;	//用户可适当调整
    /* parm.seek_low_range     = __this->dec_bp.fptr;    //恢复断点时设置网络的开始下载地址 */

    err = net_download_open(&__this->net_file, &parm);
    if (err) {
        printf("net_download_open: err = %d\n", err);
        return err;
    }

    __this->is_net_music = 1;

    /*异步等待网络下载ready，防止网络阻塞导致app_core卡住 */
    // __this->wait_download = wait_completion_add_to_task("app_core", __net_download_ready,
    //     (int (*)(void *))__net_music_dec_file, __this->net_file, NULL);
    __this->wait_download = wait_completion(__net_download_ready,
        (int (*)(void *))__net_music_dec_file, __this->net_file, NULL);

    return 0;
}

int set_dec_volume_step(int step)
{
    union audio_req req = {0};

    int volume = __this->volume + step;
    if (volume < MIN_VOLUME_VALUE) {
        volume = MIN_VOLUME_VALUE;
    } else if (volume > MAX_VOLUME_VALUE) {
#ifdef CONFIG_VOICE_PROMPT_FILE_PATH
        //play_file(CONFIG_VOICE_PROMPT_FILE_PATH"VolumeFull.mp3");
#endif
        volume = MAX_VOLUME_VALUE;
    }
    if (volume == __this->volume) {
        return -EINVAL;
    }
    __this->volume =  volume;

#ifdef CONFIG_UI_ENABLE
    os_taskq_post(POST_TASK_NAME, 2, UI_MSG_SET_VOLUME, volume);
#endif

#ifdef CONFIG_DEC_DIGITAL_VOLUME_ENABLE
#if TCFG_USER_EMITTER_ENABLE
    if (get_bt_emitter_audio_server() && __this->digital_vol_hdl && __this->dec_server) {
        return user_audio_digital_volume_set(__this->digital_vol_hdl, volume, 1);
    }
#endif
#if TCFG_USER_VIRTUAL_PLAY_ENABLE
    if (check_user_virtual_audio_if_running() && __this->digital_vol_hdl && __this->dec_server) {
        return user_audio_digital_volume_set(__this->digital_vol_hdl, volume, 1);
    }
#endif
#endif

#ifdef CONFIG_VOICE_PROMPT_FILE_PATH
    /*if (volume == MAX_VOLUME_VALUE) {
        play_file(CONFIG_VOICE_PROMPT_FILE_PATH"VolumeFull.mp3");
    } else {
        play_file(CONFIG_VOICE_PROMPT_FILE_PATH"Volume.mp3");
    }*/
#endif

    if (!__this->dec_server) {
        return -EFAULT;
    }
    __this->reset_volue = volume;

    req.dec.cmd     = AUDIO_DEC_SET_VOLUME;
    req.dec.volume  = volume * ceofVolume;
    server_request(__this->dec_server, AUDIO_REQ_DEC, &req);

    printf("set_dec_volume: %d\n", volume);
    return 1;
}

int set_dec_volume(int volume)
{
    union audio_req req = {0};

    if (volume < MIN_VOLUME_VALUE) {
        volume = MIN_VOLUME_VALUE;
    } else if (volume > MAX_VOLUME_VALUE) {
#ifdef CONFIG_VOICE_PROMPT_FILE_PATH
        //play_file(CONFIG_VOICE_PROMPT_FILE_PATH"VolumeFull.mp3");
#endif
        volume = MAX_VOLUME_VALUE;
    }
    if (volume == __this->volume) {
        return -EINVAL;
    }
    __this->volume =  volume;

#ifdef CONFIG_UI_ENABLE
    os_taskq_post(POST_TASK_NAME, 2, UI_MSG_SET_VOLUME, volume);
#endif

#ifdef CONFIG_DEC_DIGITAL_VOLUME_ENABLE
#if TCFG_USER_EMITTER_ENABLE
    if (get_bt_emitter_audio_server() && __this->digital_vol_hdl && __this->dec_server) {
        return user_audio_digital_volume_set(__this->digital_vol_hdl, volume, 1);
    }
#endif
#if TCFG_USER_VIRTUAL_PLAY_ENABLE
    if (check_user_virtual_audio_if_running() && __this->digital_vol_hdl && __this->dec_server) {
        return user_audio_digital_volume_set(__this->digital_vol_hdl, volume, 1);
    }
#endif
#endif

#ifdef CONFIG_VOICE_PROMPT_FILE_PATH
    /*if (volume == MAX_VOLUME_VALUE) {
        play_file(CONFIG_VOICE_PROMPT_FILE_PATH"VolumeFull.mp3");
    } else {
        play_file(CONFIG_VOICE_PROMPT_FILE_PATH"Volume.mp3");
    }*/
#endif

    if (!__this->dec_server) {
        return -EFAULT;
    }
    __this->reset_volue = volume;

    req.dec.cmd     = AUDIO_DEC_SET_VOLUME;
    req.dec.volume  = volume * ceofVolume;
    server_request(__this->dec_server, AUDIO_REQ_DEC, &req);

    printf("set_dec_volume: %d\n", volume);
    return 1;
}


// 模式初始化
int sa_audio_init(void)
{
    printf("------sa_audio_init\n");
    memset(__this, 0, sizeof(struct sa_audio_hdl));

    if (syscfg_read(CFG_MUSIC_VOL, &__this->volume, sizeof(__this->volume)) < 0 ||
        __this->volume < MIN_VOLUME_VALUE || __this->volume > MAX_VOLUME_VALUE) {
        printf("sa_audio_init volume---: %d \n", __this->volume);
        if(__this->volume > MAX_VOLUME_VALUE || __this->volume < MIN_VOLUME_VALUE) {
                __this->volume = INIT_VOLUME_VALUE;
                syscfg_write(CFG_MUSIC_VOL, &__this->volume, sizeof(__this->volume));
        }
    }
    printf("sa_audio_init volume: %d \n", __this->volume);
    __this->volume = INIT_VOLUME_VALUE;
    syscfg_read(CFG_MUSIC_VOL, &__this->volume, sizeof(__this->volume));
    __this->reset_volue = __this->volume;
    printf("syscfg_read-----sa_audio_init volume: %d \n", __this->volume);

    __this->gain = CONFIG_AUDIO_ADC_GAIN;
    __this->channel = CONFIG_AUDIO_RECORDER_CHANNEL;
    __this->format = CONFIG_AUDIO_RECORDER_SAVE_FORMAT;
    __this->sample_source = "mic";
    __this->play_source = CONFIG_AUDIO_DEC_PLAY_SOURCE;
    __this->sample_rate = CONFIG_AUDIO_RECORDER_SAMPLERATE;
    __this->enc_time_msec = CONFIG_AUDIO_RECORDER_DURATION;

    __this->dec_server = server_open("audio_server", "dec");
    server_register_event_handler_to_task(__this->dec_server, NULL, dec_server_event_handler, "app_core");
    __this->dec_server_status = AUDIO_DEC_STOP;

    __this->net_music_url = malloc(512);
    if (__this->net_music_url == NULL) {
        return -1;
    }

    __this->speaker_buf = malloc(RES_BUFFER_SIZE);
    if (__this->speaker_buf == NULL) {
        return -1;
    }
    cbuf_init(&__this->speaker_cbuf, __this->speaker_buf, RES_BUFFER_SIZE);
    os_sem_create(&__this->r_sem, 0);

    return 0;
}

void sa_audio_mode_exit(void)
{
    printf("------sa_audio_init exit\n");

    close_audio_dec();
    server_close(__this->dec_server);
    __this->dec_server = NULL;

    if (__this->net_music_url) {
        free(__this->net_music_url);
        __this->net_music_url = NULL;
    }

    if (__this->speaker_buf) {
        free(__this->speaker_buf);
        __this->speaker_buf = NULL;
    }
    // SH_OS_TASKQ_POST("ws_task", 1, SH_WS_EXIT);
}
