#include "stream_decoder.h"
// 内部日志函数
static void decoder_log(StreamDecoder *decoder, LogLevel level, const char *format, ...) {
if (!decoder || level > decoder->log_level) return;
const char *level_str = "DEBUG";
switch(level) {
case LOG_LEVEL_ERROR: level_str = "ERROR"; break;
case LOG_LEVEL_WARNING: level_str = "WARN"; break;
case LOG_LEVEL_INFO: level_str = "INFO"; break;
default: break;
}
va_list args;
fprintf(stderr, "[DECODER %s] ", level_str);
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
fprintf(stderr, "\n");
}
// 初始化队列
static void queue_init(struct data_queue *q) {
q->head = q->tail = NULL;
pthread_mutex_init(&q->mutex, NULL);
pthread_cond_init(&q->cond, NULL);
q->total_size = 0;
q->finished = 0;
q->stop_requested = 0;
}
// 向队列添加数据
static void queue_push(struct data_queue *q, unsigned char *data, size_t size) {
if (!q || !data || size == 0) return;
struct data_chunk *chunk = malloc(sizeof(struct data_chunk));
if (!chunk) return;
chunk->data = malloc(size);
if (!chunk->data) {
free(chunk);
return;
}
memcpy(chunk->data, data, size);
chunk->size = size;
chunk->next = NULL;
pthread_mutex_lock(&q->mutex);
if (q->tail) {
q->tail->next = chunk;
} else {
q->head = chunk;
}
q->tail = chunk;
q->total_size += size;
pthread_cond_signal(&q->cond);
pthread_mutex_unlock(&q->mutex);
}
// 标记队列完成
static void queue_finish(struct data_queue *q) {
if (!q) return;
pthread_mutex_lock(&q->mutex);
q->finished = 1;
pthread_cond_signal(&q->cond);
pthread_mutex_unlock(&q->mutex);
}
// 从队列获取数据
static struct data_chunk *queue_pop(struct data_queue *q) {
pthread_mutex_lock(&q->mutex);
while (!q->head && !q->finished && !q->stop_requested) {
pthread_cond_wait(&q->cond, &q->mutex);
}
if (q->stop_requested) {
pthread_mutex_unlock(&q->mutex);
return NULL;
}
if (!q->head) {
pthread_mutex_unlock(&q->mutex);
return NULL;
}
struct data_chunk *chunk = q->head;
q->head = chunk->next;
if (!q->head) q->tail = NULL;
q->total_size -= chunk->size;
pthread_mutex_unlock(&q->mutex);
return chunk;
}
// 清理队列
static void queue_cleanup(struct data_queue *q) {
if (!q) return;
pthread_mutex_lock(&q->mutex);
struct data_chunk *chunk = q->head;
while (chunk) {
struct data_chunk *next = chunk->next;
free(chunk->data);
free(chunk);
chunk = next;
}
q->head = q->tail = NULL;
q->total_size = 0;
q->finished = 0;
q->stop_requested = 0;
pthread_mutex_unlock(&q->mutex);
}
// 头部回调函数 - 用于捕获HTTP响应头信息
static size_t header_callback(char *buffer, size_t size, size_t nitems, void *userdata) {
size_t realsize = size * nitems;
StreamDecoder *decoder = (StreamDecoder *)userdata;
// 解析头部行
char *colon = strchr(buffer, ':');
if (colon) {
*colon = '\0'; // 临时分割键值
char *key = buffer;
char *value = colon + 1;
// 去除前导空格
while (*value == ' ') value++;
// 去除尾部换行
char *end = value + strlen(value);
while (end > value && (end[-1] == '\r' || end[-1] == '\n')) {
*(--end) = '\0';
}
pthread_mutex_lock(&decoder->media_mutex);
// 检测关键头部
if (strcasecmp(key, "Content-Type") == 0) {
if (decoder->download_status.content_type) {
free(decoder->download_status.content_type);
}
decoder->download_status.content_type = strdup(value);
}
else if (strcasecmp(key, "Accept-Ranges") == 0) {
decoder->download_status.supports_range =
(strcasecmp(value, "bytes") == 0);
}
else if (strcasecmp(key, "Transfer-Encoding") == 0) {
decoder->download_status.is_chunked =
(strstr(value, "chunked") != NULL);
}
else if (strcasecmp(key, "Content-Length") == 0) {
decoder->download_status.content_length = atol(value);
}
else if (strcasecmp(key, "Content-Range") == 0) {
decoder->download_status.has_content_range = 1;
}
else if (strcasecmp(key, "Icy-MetaInt") == 0) {
decoder->download_status.is_icy_stream = 1;
}
pthread_mutex_unlock(&decoder->media_mutex);
*colon = ':'; // 恢复原始格式
}
return realsize;
}
// CURL写入回调
static size_t write_callback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
struct data_queue *q = (struct data_queue *)userp;
// 检查停止请求
pthread_mutex_lock(&q->mutex);
if (q->stop_requested) {
pthread_mutex_unlock(&q->mutex);
return 0; // 返回0会中断CURL传输
}
pthread_mutex_unlock(&q->mutex);
queue_push(q, (unsigned char *)contents, realsize);
StreamDecoder *decoder = (StreamDecoder *)q->decoder_ref;
if (!decoder) return realsize;
pthread_mutex_lock(&decoder->media_mutex);
// 首次检测到数据时进行媒体类型判断
if (!decoder->download_status.type_detected) {
// 默认初始化为未知类型
decoder->download_status.detected_type = MEDIA_TYPE_UNKNOWN;
// 1. 根据Content-Type判断是否是MP3音频
if (decoder->download_status.content_type) {
if (strstr(decoder->download_status.content_type, "audio/mpeg") || strstr(decoder->download_status.content_type, "audio/mp3")) {
// 2. 对于MP3音频,进一步区分是完整文件还是实时流
if (decoder->download_status.supports_range || decoder->download_status.content_length > 0) {
// 支持范围请求或有明确长度 = 完整文件
decoder->download_status.detected_type = MEDIA_TYPE_FILE;
} else if (decoder->download_status.is_chunked ||
decoder->download_status.is_icy_stream || (decoder->download_status.content_length == -1)) {
//分块传输或ICY流或未知长度 = 实时流
decoder->download_status.detected_type = MEDIA_TYPE_STREAM;
}
} else {
// 非MP3内容视为流媒体
decoder->download_status.detected_type = MEDIA_TYPE_STREAM;
}
}
// 记录检测结果
if (decoder->download_status.detected_type != MEDIA_TYPE_UNKNOWN) {
const char *type_name = "未知";
switch (decoder->download_status.detected_type) {
case MEDIA_TYPE_FILE: type_name = "完整MP3文件"; break;
case MEDIA_TYPE_STREAM: type_name = "实时音频流"; break;
default: break;
}
decoder_log(decoder, LOG_LEVEL_INFO, "媒体类型检测结果: %s", type_name);
decoder_log(decoder, LOG_LEVEL_DEBUG, "详细信息: Content-Type=%s, Range=%s, Chunked=%s, Length=%ld",
decoder->download_status.content_type ? decoder->download_status.content_type : "NULL",
decoder->download_status.supports_range ? "支持" : "不支持",
decoder->download_status.is_chunked ? "是" : "否",
decoder->download_status.content_length);
// 标记类型已检测
decoder->download_status.type_detected = 1;
}
}
pthread_mutex_unlock(&decoder->media_mutex);
return realsize;
}
// 应用抖动处理
static void apply_dither(short *output, float *input, size_t samples) {
const float scale = 32767.0f;
for (size_t i = 0; i < samples; i++) {
float sample = input[i];
float dither_val = (rand() / (float)RAND_MAX) * 0.0001f;
sample += dither_val;
if (sample > 1.0f) sample = 1.0f;
if (sample < -1.0f) sample = -1.0f;
output[i] = (short)(sample * scale);
}
}
// 解码线程
static void* decode_thread(void *arg) {
StreamDecoder *decoder = (StreamDecoder *)arg;
if (!decoder) return NULL;
struct data_queue *q = &decoder->queue;
float *buffer = NULL;
size_t buffer_size = 8192 * sizeof(float);
size_t done;
int status;
// 分配音频缓冲区
if (posix_memalign((void**)&buffer, 16, buffer_size)) {
decoder_log(decoder, LOG_LEVEL_ERROR, "音频缓冲区分配失败");
return NULL;
}
// 分配PCM输出缓冲区
size_t max_pcm_size = 8192 * sizeof(short) * 2; // 立体声
short *pcm_buffer = malloc(max_pcm_size);
if (!pcm_buffer) {
decoder_log(decoder, LOG_LEVEL_ERROR, "PCM缓冲区分配失败");
free(buffer);
return NULL;
}
srand(time(NULL));
// 等待媒体类型检测完成
time_t start_time = time(NULL);
while (!decoder->download_status.type_detected &&
!decoder->stop_requested) {
if (time(NULL) - start_time >= 5)
break;
usleep(100000); // 100ms
}
// 根据媒体类型设置初始缓冲大小
size_t initial_buffer = 0;
pthread_mutex_lock(&decoder->media_mutex);
switch (decoder->download_status.detected_type) {
case MEDIA_TYPE_FILE:
initial_buffer = 1024 * 256; // 256KB缓冲 (完整文件)
break;
case MEDIA_TYPE_STREAM:
initial_buffer = 1024 * 1024 * 2; // 2MB缓冲 (流媒体)
break;
default:
initial_buffer = 1024 * 512; // 默认512KB
}
const char *type_name = "未知";
switch (decoder->download_status.detected_type) {
case MEDIA_TYPE_FILE: type_name = "文件"; break;
case MEDIA_TYPE_STREAM: type_name = "流媒体"; break;
default: break;
}
pthread_mutex_unlock(&decoder->media_mutex);
decoder_log(decoder, LOG_LEVEL_INFO, "等待初始缓冲: %zu KB (%s)",
initial_buffer / 1024, type_name);
time_t start_wait = time(NULL);
while (q->total_size < initial_buffer &&
!decoder->stop_requested){
if (time(NULL) - start_wait >= 2)
break;
usleep(100000); // 100ms休眠
}
if (q->total_size >= initial_buffer) {
decoder_log(decoder, LOG_LEVEL_INFO, "缓冲完成,开始解码");
} else if (decoder->stop_requested) {
decoder_log(decoder, LOG_LEVEL_WARNING, "解码被中断");
free(buffer);
free(pcm_buffer);
return NULL;
} else {
decoder_log(decoder, LOG_LEVEL_WARNING, "缓冲不足,继续解码");
}
while (1) {
// 检查停止标志
pthread_mutex_lock(&decoder->mutex);
if (decoder->stop_requested) {
pthread_mutex_unlock(&decoder->mutex);
break;
}
pthread_mutex_unlock(&decoder->mutex);
struct data_chunk *chunk = queue_pop(q);
if (chunk == NULL) {
// 没有更多数据
break;
}
if (mpg123_feed(decoder->mh, chunk->data, chunk->size) != MPG123_OK) {
decoder_log(decoder, LOG_LEVEL_WARNING, "数据供给失败");
free(chunk->data);
free(chunk);
// 尝试重置解码器
mpg123_close(decoder->mh);
if (mpg123_open_feed(decoder->mh) != MPG123_OK) {
decoder_log(decoder, LOG_LEVEL_ERROR, "无法重置解码器");
break;
}
continue;
}
free(chunk->data);
free(chunk);
while (1) {
// 检查停止标志
pthread_mutex_lock(&decoder->mutex);
if (decoder->stop_requested) {
pthread_mutex_unlock(&decoder->mutex);
break;
}
pthread_mutex_unlock(&decoder->mutex);
status = mpg123_read(decoder->mh, (unsigned char*)buffer, buffer_size, &done);
// 处理格式变化
if (status == MPG123_NEW_FORMAT) {
long rate;
int channels, encoding;
if (mpg123_getformat(decoder->mh, &rate, &channels, &encoding) == MPG123_OK) {
decoder->channels = channels;
decoder->rate = rate;
decoder_log(decoder, LOG_LEVEL_INFO, "音频格式: %d 声道, %ld Hz", channels, rate);
}
continue;
}
// 需要更多数据或错误
if (status == MPG123_NEED_MORE || status != MPG123_OK) {
break;
}
// 处理解码后的PCM数据
if (done > 0) {
size_t frames = done / (sizeof(float) * decoder->channels);
size_t pcm_size = frames * sizeof(short) * decoder->channels;
apply_dither(pcm_buffer, buffer, frames * decoder->channels);
if (decoder->pcm_callback) {
decoder->pcm_callback(pcm_buffer, pcm_size,
decoder->channels, decoder->rate,
decoder->callback_userdata);
}
}
}
}
free(buffer);
free(pcm_buffer);
decoder_log(decoder, LOG_LEVEL_INFO, "解码线程退出");
return NULL;
}
// 下载线程
static void* download_thread(void *arg) {
StreamDecoder *decoder = (StreamDecoder *)arg;
if (!decoder || !decoder->curl) return NULL;
decoder_log(decoder, LOG_LEVEL_INFO, "开始下载音频流");
// 初始化下载状态
decoder->download_status.detected_type = MEDIA_TYPE_UNKNOWN;
decoder->download_status.content_type = NULL;
decoder->download_status.type_detected = 0;
decoder->download_status.supports_range = 0;
decoder->download_status.is_chunked = 0;
decoder->download_status.has_content_range = 0;
decoder->download_status.is_icy_stream = 0;
decoder->download_status.content_length = -1;
CURLcode res = curl_easy_perform(decoder->curl);
if (res == CURLE_OPERATION_TIMEDOUT) {
decoder_log(decoder, LOG_LEVEL_WARNING, "下载超时");
} else if (res == CURLE_SEND_ERROR || res == CURLE_RECV_ERROR) {
decoder_log(decoder, LOG_LEVEL_WARNING, "网络连接中断");
} else if (res != CURLE_OK && res != CURLE_ABORTED_BY_CALLBACK) {
decoder_log(decoder, LOG_LEVEL_ERROR, "下载失败: %s", curl_easy_strerror(res));
} else {
decoder_log(decoder, LOG_LEVEL_INFO, "下载完成");
}
queue_finish(&decoder->queue);
decoder_log(decoder, LOG_LEVEL_INFO, "下载线程退出");
return NULL;
}
// ================== 公共接口实现 ==================
StreamDecoder* stream_decoder_create() {
StreamDecoder* decoder = calloc(1, sizeof(StreamDecoder));
if (!decoder) return NULL;
// 初始化队列
queue_init(&decoder->queue);
decoder->queue.decoder_ref = decoder; // 设置反向引用
// 初始化下载状态
decoder->download_status.content_type = NULL;
decoder->download_status.detected_type = MEDIA_TYPE_UNKNOWN;
decoder->download_status.type_detected = 0;
decoder->download_status.supports_range = 0;
decoder->download_status.is_chunked = 0;
decoder->download_status.has_content_range = 0;
decoder->download_status.is_icy_stream = 0;
decoder->download_status.content_length = -1; // -1表示未知
// 初始化mpg123
if (mpg123_init() != MPG123_OK) {
free(decoder);
return NULL;
}
decoder->mh = mpg123_new(NULL, NULL);
if (!decoder->mh) {
mpg123_exit();
free(decoder);
return NULL;
}
if (mpg123_format_none(decoder->mh) != MPG123_OK ||
mpg123_format(decoder->mh, 44100, MPG123_STEREO, MPG123_ENC_FLOAT_32) != MPG123_OK) {
mpg123_delete(decoder->mh);
mpg123_exit();
free(decoder);
return NULL;
}
if (mpg123_open_feed(decoder->mh) != MPG123_OK) {
mpg123_delete(decoder->mh);
mpg123_exit();
free(decoder);
return NULL;
}
// 初始化互斥锁
pthread_mutex_init(&decoder->mutex, NULL);
pthread_mutex_init(&decoder->media_mutex, NULL);
// 初始化解码器状态
decoder->stop_requested = 0;
decoder->channels = 0;
decoder->rate = 0;
decoder->pcm_callback = NULL;
decoder->callback_userdata = NULL;
decoder->log_level = LOG_LEVEL_ERROR;
decoder->curl = NULL;
decoder->headers = NULL;
return decoder;
}
void stream_decoder_destroy(StreamDecoder* decoder) {
if (!decoder) return;
// 停止解码
stream_decoder_stop(decoder);
// 清理HTTP头部
if (decoder->headers) {
curl_slist_free_all(decoder->headers);
decoder->headers = NULL;
}
// 清理下载状态
if (decoder->download_status.content_type) {
free(decoder->download_status.content_type);
decoder->download_status.content_type = NULL;
}
// 清理队列
queue_cleanup(&decoder->queue);
pthread_mutex_destroy(&decoder->queue.mutex);
pthread_cond_destroy(&decoder->queue.cond);
// 清理mpg123
if (decoder->mh) {
mpg123_close(decoder->mh);
mpg123_delete(decoder->mh);
}
mpg123_exit();
// 销毁互斥锁
pthread_mutex_destroy(&decoder->mutex);
pthread_mutex_destroy(&decoder->media_mutex);
free(decoder);
}
void stream_decoder_set_callback(StreamDecoder* decoder, PCMCallback callback, void* userdata) {
if (!decoder) return;
decoder->pcm_callback = callback;
decoder->callback_userdata = userdata;
}
void stream_decoder_set_log_level(StreamDecoder* decoder, LogLevel level) {
if (!decoder) return;
decoder->log_level = level;
}
int stream_decoder_start(StreamDecoder* decoder, const char* url) {
if (!decoder || !url) return 0;
decoder_log(decoder, LOG_LEVEL_INFO, "开始解码: %s", url);
// 重置状态
pthread_mutex_lock(&decoder->mutex);
decoder->stop_requested = 0;
decoder->channels = 0;
decoder->rate = 0;
pthread_mutex_unlock(&decoder->mutex);
// 清理队列
queue_cleanup(&decoder->queue);
decoder->queue.decoder_ref = decoder; // 重置反向引用
// 重置下载状态
pthread_mutex_lock(&decoder->media_mutex);
if (decoder->download_status.content_type) {
free(decoder->download_status.content_type);
decoder->download_status.content_type = NULL;
}
decoder->download_status.detected_type = MEDIA_TYPE_UNKNOWN;
decoder->download_status.type_detected = 0;
decoder->download_status.supports_range = 0;
decoder->download_status.is_chunked = 0;
decoder->download_status.has_content_range = 0;
decoder->download_status.is_icy_stream = 0;
decoder->download_status.content_length = -1;
pthread_mutex_unlock(&decoder->media_mutex);
// 初始化curl
curl_global_init(CURL_GLOBAL_DEFAULT);
decoder->curl = curl_easy_init();
if (!decoder->curl) {
decoder_log(decoder, LOG_LEVEL_ERROR, "无法初始化CURL");
return 0;
}
// 设置CURL选项
curl_easy_setopt(decoder->curl, CURLOPT_URL, url);
curl_easy_setopt(decoder->curl, CURLOPT_WRITEFUNCTION, write_callback);
curl_easy_setopt(decoder->curl, CURLOPT_WRITEDATA, &decoder->queue);
// 添加头部回调
curl_easy_setopt(decoder->curl, CURLOPT_HEADERFUNCTION, header_callback);
curl_easy_setopt(decoder->curl, CURLOPT_HEADERDATA, decoder);
// 设置HTTP头部
if (decoder->headers) {
curl_slist_free_all(decoder->headers);
decoder->headers = NULL;
}
decoder->headers = curl_slist_append(decoder->headers, "User-Agent: StreamDecoder/1.0");
decoder->headers = curl_slist_append(decoder->headers, "Connection: keep-alive");
// 仅对可能支持范围请求的URL添加Range头
if (strstr(url, ".mp3") || strstr(url, ".mp4")) {
decoder->headers = curl_slist_append(decoder->headers, "Range: bytes=0-");
}
curl_easy_setopt(decoder->curl, CURLOPT_HTTPHEADER, decoder->headers);
// 设置SSL选项(忽略证书验证)
curl_easy_setopt(decoder->curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(decoder->curl, CURLOPT_SSL_VERIFYHOST, 0L);
// 设置网络选项
curl_easy_setopt(decoder->curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(decoder->curl, CURLOPT_NOSIGNAL, 1L);
curl_easy_setopt(decoder->curl, CURLOPT_CONNECTTIMEOUT, 10L);
curl_easy_setopt(decoder->curl, CURLOPT_TIMEOUT, 0L); // 无限超时
curl_easy_setopt(decoder->curl, CURLOPT_BUFFERSIZE, 65536L);
curl_easy_setopt(decoder->curl, CURLOPT_TCP_KEEPALIVE, 1L);
curl_easy_setopt(decoder->curl, CURLOPT_TCP_KEEPIDLE, 30L);
curl_easy_setopt(decoder->curl, CURLOPT_TCP_KEEPINTVL, 15L);
// 防止连接成功但传输极慢
curl_easy_setopt(decoder->curl, CURLOPT_LOW_SPEED_LIMIT, 1024); // 1KB/s
curl_easy_setopt(decoder->curl, CURLOPT_LOW_SPEED_TIME, 10L); // 持续10秒
// 创建下载线程
if (pthread_create(&decoder->download_tid, NULL, download_thread, decoder) != 0) {
decoder_log(decoder, LOG_LEVEL_ERROR, "无法创建下载线程");
curl_easy_cleanup(decoder->curl);
curl_global_cleanup();
return 0;
}
// 创建解码线程
if (pthread_create(&decoder->decode_tid, NULL, decode_thread, decoder) != 0) {
decoder_log(decoder, LOG_LEVEL_ERROR, "无法创建解码线程");
pthread_mutex_lock(&decoder->mutex);
decoder->stop_requested = 1;
pthread_mutex_unlock(&decoder->mutex);
pthread_join(decoder->download_tid, NULL);
curl_easy_cleanup(decoder->curl);
curl_global_cleanup();
return 0;
}
return 1;
}
void stream_decoder_stop(StreamDecoder* decoder) {
if (!decoder) return;
decoder_log(decoder, LOG_LEVEL_INFO, "停止解码");
// 设置停止标志
pthread_mutex_lock(&decoder->mutex);
if (decoder->stop_requested) {
pthread_mutex_unlock(&decoder->mutex);
return;
}
decoder->stop_requested = 1;
pthread_mutex_unlock(&decoder->mutex);
// 设置队列的停止标志
pthread_mutex_lock(&decoder->queue.mutex);
decoder->queue.stop_requested = 1;
pthread_cond_broadcast(&decoder->queue.cond);
pthread_mutex_unlock(&decoder->queue.mutex);
// 中断CURL下载
if (decoder->curl) {
curl_easy_setopt(decoder->curl, CURLOPT_TIMEOUT, 1L); // 设置超时以中断下载
}
// 唤醒可能等待的线程
pthread_cond_broadcast(&decoder->queue.cond);
// 等待线程结束
if (pthread_self() != decoder->download_tid) {
pthread_join(decoder->download_tid, NULL);
}
if (pthread_self() != decoder->decode_tid) {
pthread_join(decoder->decode_tid, NULL);
}
// 清理curl
if (decoder->curl) {
curl_easy_cleanup(decoder->curl);
decoder->curl = NULL;
}
curl_global_cleanup();
// 重置队列
queue_cleanup(&decoder->queue);
}
输出的PCM的采样率是多少