PHP4用户手册:函数->CURL->curl_setopt

博客涉及PHP和服务器相关内容,包含如string操作、upload上传、header设置、delete删除等信息技术操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


curl_setopt

(PHP 4 >= 4.0.2)

curl_setopt -- 为CURL调用设置一个选项

描述

 

bool curl_setopt (int ch, string option, mixed value)

 

curl_setopt()函数将为一个CURL会话设置选项。option参数是你想要的设置,value是这个选项给定的值。

下列选项的值将被作为长整形使用(在option参数中指定):

 

  • CURLOPT_INFILESIZE: 当你上传一个文件到远程站点,这个选项告诉PHP你上传文件的大小。

  • CURLOPT_VERBOSE: 如果你想CURL报告每一件意外的事情,设置这个选项为一个非零值。

  • CURLOPT_HEADER: 如果你想把一个头包含在输出中,设置这个选项为一个非零值。

  • CURLOPT_NOPROGRESS: 如果你不会PHP为CURL传输显示一个进程条,设置这个选项为一个非零值。

    注意:PHP自动设置这个选项为非零值,你应该仅仅为了调试的目的来改变这个选项。

  • CURLOPT_NOBODY: 如果你不想在输出中包含body部分,设置这个选项为一个非零值。

  • CURLOPT_FAILONERROR: 如果你想让PHP在发生错误(HTTP代码返回大于等于300)时,不显示,设置这个选项为一人非零值。默认行为是返回一个正常页,忽略代码。

  • CURLOPT_UPLOAD: 如果你想让PHP为上传做准备,设置这个选项为一个非零值。

  • CURLOPT_POST: 如果你想PHP去做一个正规的HTTP POST,设置这个选项为一个非零值。这个POST是普通的 application/x-www-from-urlencoded 类型,多数被HTML表单使用。

  • CURLOPT_FTPLISTONLY: 设置这个选项为非零值,PHP将列出FTP的目录名列表。

  • CURLOPT_FTPAPPEND: 设置这个选项为一个非零值,PHP将应用远程文件代替覆盖它。

  • CURLOPT_NETRC: 设置这个选项为一个非零值,PHP将在你的 ~./netrc 文件中查找你要建立连接的远程站点的用户名及密码。

  • CURLOPT_FOLLOWLOCATION: 设置这个选项为一个非零值(象 "Location: ")的头,服务器会把它当做HTTP头的一部分发送(注意这是递归的,PHP将发送形如 "Location: "的头)。

  • CURLOPT_PUT: 设置这个选项为一个非零值去用HTTP上传一个文件。要上传这个文件必须设置CURLOPT_INFILE和CURLOPT_INFILESIZE选项.

  • CURLOPT_MUTE: 设置这个选项为一个非零值,PHP对于CURL函数将完全沉默。

  • CURLOPT_TIMEOUT: 设置一个长整形数,作为最大延续多少秒。

  • CURLOPT_LOW_SPEED_LIMIT: 设置一个长整形数,控制传送多少字节。

  • CURLOPT_LOW_SPEED_TIME: 设置一个长整形数,控制多少秒传送CURLOPT_LOW_SPEED_LIMIT规定的字节数。

  • CURLOPT_RESUME_FROM: 传递一个包含字节偏移地址的长整形参数,(你想转移到的开始表单)。

  • CURLOPT_SSLVERSION: 传递一个包含SSL版本的长参数。默认PHP将被它自己努力的确定,在更多的安全中你必须手工设置。

  • CURLOPT_TIMECONDITION: 传递一个长参数,指定怎么处理CURLOPT_TIMEVALUE参数。你可以设置这个参数为TIMECOND_IFMODSINCE 或 TIMECOND_ISUNMODSINCE。这仅用于HTTP。

  • CURLOPT_TIMEVALUE: 传递一个从1970-1-1开始到现在的秒数。这个时间将被CURLOPT_TIMEVALUE选项作为指定值使用,或被默认TIMECOND_IFMODSINCE使用。

下列选项的值将被作为字符串:

 

  • CURLOPT_URL: 这是你想用PHP取回的URL地址。你也可以在用curl_init()函数初始化时设置这个选项。

  • CURLOPT_USERPWD: 传递一个形如[username]:[password]风格的字符串,作用PHP去连接。

  • CURLOPT_PROXYUSERPWD: 传递一个形如[username]:[password] 格式的字符串去连接HTTP代理。

  • CURLOPT_RANGE: 传递一个你想指定的范围。它应该是"X-Y"格式,X或Y是被除外的。HTTP传送同样支持几个间隔,用逗句来分隔(X-Y,N-M)。

  • CURLOPT_POSTFIELDS: 传递一个作为HTTP “POST”操作的所有数据的字符串。

  • CURLOPT_REFERER: 在HTTP请求中包含一个"referer"头的字符串。

  • CURLOPT_USERAGENT: 在HTTP请求中包含一个"user-agent"头的字符串。

  • CURLOPT_FTPPORT: 传递一个包含被ftp "POST"指令使用的IP地址。这个POST指令告诉远程服务器去连接我们指定的IP地址。 这个字符串可以是一个IP地址,一个主机名,一个网络界面名(在UNIX下),或是‘-’(使用系统默认IP地址)。

  • CURLOPT_COOKIE: 传递一个包含HTTP cookie的头连接。

  • CURLOPT_SSLCERT: 传递一个包含PEM格式证书的字符串。

  • CURLOPT_SSLCERTPASSWD: 传递一个包含使用CURLOPT_SSLCERT证书必需的密码。

  • CURLOPT_COOKIEFILE: 传递一个包含cookie数据的文件的名字的字符串。这个cookie文件可以是Netscape格式,或是堆存在文件中的HTTP风格的头。

  • CURLOPT_CUSTOMREQUEST: 当进行HTTP请求时,传递一个字符被GET或HEAD使用。为进行DELETE或其它操作是有益的,更Pass a string to be used instead of GET or HEAD when doing an HTTP request. This is useful for doing  or another, more obscure, HTTP request.

    注意: 在确认你的服务器支持命令先不要去这样做。

下列的选项要求一个文件描述(通过使用fopen()函数获得):

 

  • CURLOPT_FILE: 这个文件将是你放置传送的输出文件,默认是STDOUT.

  • CURLOPT_INFILE: 这个文件是你传送过来的输入文件。

  • CURLOPT_WRITEHEADER: 这个文件写有你输出的头部分。

  • CURLOPT_STDERR: 这个文件写有错误而不是stderr。

#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的采样率是多少
07-10
#include "stream_decoder.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <curl/curl.h> #include <mpg123.h> #include <stdarg.h> #include <time.h> #include <stdint.h> #include <unistd.h> #include <signal.h> // 数据块结构 struct data_chunk { unsigned char *data; size_t size; struct data_chunk *next; }; // 数据队列 struct data_queue { struct data_chunk *head; struct data_chunk *tail; pthread_mutex_t mutex; pthread_cond_t cond; size_t total_size; int finished; }; // 解码器状态 struct StreamDecoder { mpg123_handle *mh; pthread_mutex_t mutex; int stop_requested; // 停止请求标志 int channels; long rate; PCMCallback pcm_callback; void* callback_userdata; LogLevel log_level; pthread_t download_tid; pthread_t decode_tid; struct data_queue queue; CURL *curl; }; // 内部日志函数 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; } // 向队列添加数据 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) { if (!q) return NULL; pthread_mutex_lock(&q->mutex); while (!q->head && !q->finished && !q->stop_requested) { pthread_cond_wait(&q->cond, &q->mutex); } 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; pthread_mutex_unlock(&q->mutex); } // 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; queue_push(q, (unsigned char *)contents, realsize); 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)); 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); 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, "开始下载音频流"); CURLcode res = curl_easy_perform(decoder->curl); if (res != CURLE_OK) { 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); // 初始化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); // 初始化解码器状态 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; return decoder; } void stream_decoder_destroy(StreamDecoder* decoder) { if (!decoder) return; // 停止解码 stream_decoder_stop(decoder); // 清理队列 queue_cleanup(&decoder->queue); // 清理mpg123 if (decoder->mh) { mpg123_close(decoder->mh); mpg123_delete(decoder->mh); } mpg123_exit(); // 销毁互斥锁 pthread_mutex_destroy(&decoder->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); queue_init(&decoder->queue); // 初始化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_USERAGENT, "AudioStreamDecoder/1.0"); 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); // 无限超时 // 创建下载线程 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); decoder->stop_requested = 1; pthread_mutex_unlock(&decoder->mutex); // 中断CURL下载 if (decoder->curl) { curl_easy_setopt(decoder->curl, CURLOPT_TIMEOUT, 1L); // 设置超时以中断下载 } // 唤醒可能等待的线程 pthread_cond_broadcast(&decoder->queue.cond); // 等待线程结束 pthread_join(decoder->download_tid, NULL); pthread_join(decoder->decode_tid, NULL); // 清理curl if (decoder->curl) { curl_easy_cleanup(decoder->curl); curl_global_cleanup(); decoder->curl = NULL; } // 重置队列 queue_cleanup(&decoder->queue); } gcc -c stream_decoder.c -o stream_decoder.o -I. -lcurl -lmpg123 -lpthread stream_decoder.c: In function ‘queue_pop’: stream_decoder.c:121:42: error: ‘struct data_queue’ has no member named ‘stop_requested’ 121 | while (!q->head && !q->finished && !q->stop_requested) {
07-09
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值