Q&A----TCP TIME_WAIT状态

本文探讨了TCP协议中TIME_WAIT状态的原理及应用,包括SO_REUSEADDR选项的作用、TIME_WAIT状态的保持时间及其调整方法,以及如何避免因TIME_WAIT状态导致的服务重启问题。

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

TCP TIME_WAIT状态

关键词TIME_WAIT    SO_REUSEADDR                                          

Q: 我正在写一个unix server程序,不是daemon,经常需要在命令行上重启它,绝大
多数时候工作正常,但是某些时候会报告"bind: address in use",于是重启失
败。

A: Andrew Gierth
server程序总是应该在调用bind()之前设置SO_REUSEADDR套接字选项。至于
TIME_WAIT状态,你无法避免,那是TCP协议的一部分。

Q: 如何避免等待60秒之后才能重启服务

A: Erik Max Francis

使用setsockopt,比如

--------------------------------------------------------------------------
int option = 1;

if ( setsockopt ( masterSocket, SOL_SOCKET, SO_REUSEADDR, &option,
sizeof( option ) ) < 0 )
{
die( "setsockopt" );
}
--------------------------------------------------------------------------

Q: 编写 TCP/SOCK_STREAM 服务程序时,SO_REUSEADDR到底什么意思?

A: 这个套接字选项通知内核,如果端口忙,但TCP状态位于 TIME_WAIT ,可以重用
端口。如果端口忙,而TCP状态位于其他状态,重用端口时依旧得到一个错误信息,
指明"地址已经使用中"。如果你的服务程序停止后想立即重启,而新套接字依旧
使用同一端口,此时 SO_REUSEADDR 选项非常有用。必须意识到,此时任何非期
望数据到达,都可能导致服务程序反应混乱,不过这只是一种可能,事实上很不
可能。

一个套接字由相关五元组构成,协议、本地地址、本地端口、远程地址、远程端
口。SO_REUSEADDR 仅仅表示可以重用本地本地地址、本地端口,整个相关五元组
还是唯一确定的。所以,重启后的服务程序有可能收到非期望数据。必须慎重使
用 SO_REUSEADDR 选项。

Q: 在客户机/服务器编程中(TCP/SOCK_STREAM),如何理解TCP自动机 TIME_WAIT 状
态?

A: W. Richard Stevens <1999年逝世,享年49岁>

下面我来解释一下 TIME_WAIT 状态,这些在<>
中2.6节解释很清楚了。

MSL(最大分段生存期)指明TCP报文在Internet上最长生存时间,每个具体的TCP实现
都必须选择一个确定的MSL值。RFC 1122建议是2分钟,但BSD传统实现采用了30秒。

TIME_WAIT 状态最大保持时间是2 * MSL,也就是1-4分钟。

IP头部有一个TTL,最大值255。尽管TTL的单位不是秒(根本和时间无关),我们仍需
假设,TTL为255的TCP报文在Internet上生存时间不能超过MSL。

TCP报文在传送过程中可能因为路由故障被迫缓冲延迟、选择非最优路径等等,结果
发送方TCP机制开始超时重传。前一个TCP报文可以称为"漫游TCP重复报文",后一个
TCP报文可以称为"超时重传TCP重复报文",作为面向连接的可靠协议,TCP实现必须
正确处理这种重复报文,因为二者可能最终都到达。

一个通常的TCP连接终止可以用图描述如下:

client server
FIN M
close -----------------> (被动关闭)
ACK M+1
<-----------------
FIN N
<----------------- close
ACK N+1
----------------->

为什么需要 TIME_WAIT 状态?

假设最终的ACK丢失,server将重发FIN,client必须维护TCP状态信息以便可以重发
最终的ACK,否则会发送RST,结果server认为发生错误。TCP实现必须可靠地终止连
接的两个方向(全双工关闭),client必须进入 TIME_WAIT 状态,因为client可能面
临重发最终ACK的情形。

{
scz 2001-08-31 13:28

先调用close()的一方会进入TIME_WAIT状态
}

此外,考虑一种情况,TCP实现可能面临先后两个同样的相关五元组。如果前一个连
接处在 TIME_WAIT 状态,而允许另一个拥有相同相关五元组的连接出现,可能处理
TCP报文时,两个连接互相干扰。使用 SO_REUSEADDR 选项就需要考虑这种情况。

为什么 TIME_WAIT 状态需要保持 2MSL 这么长的时间?

如果 TIME_WAIT 状态保持时间不足够长(比如小于2MSL),第一个连接就正常终止了。
第二个拥有相同相关五元组的连接出现,而第一个连接的重复报文到达,干扰了第二
个连接。TCP实现必须防止某个连接的重复报文在连接终止后出现,所以让TIME_WAIT
状态保持时间足够长(2MSL),连接相应方向上的TCP报文要么完全响应完毕,要么被
丢弃。建立第二个连接的时候,不会混淆。

A: 小四

在Solaris 7下有内核参数对应 TIME_WAIT 状态保持时间

# ndd -get /dev/tcp tcp_time_wait_interval
240000
# ndd -set /dev/tcp tcp_time_wait_interval 1000

缺省设置是240000ms,也就是4分钟。如果用ndd修改这个值,最小只能设置到1000ms,
也就是1秒。显然内核做了限制,需要Kernel Hacking。

# echo "tcp_param_arr/W 0t0" | adb -kw /dev/ksyms /dev/mem
physmem 3b72
tcp_param_arr: 0x3e8 = 0x0
# ndd -set /dev/tcp tcp_time_wait_interval 0

我不知道这样做有什么灾难性后果,参看<>的声明。

Q: TIME_WAIT 状态保持时间为0会有什么灾难性后果?在普遍的现实应用中,好象也
就是服务器不稳定点,不见得有什么灾难性后果吧?

D: rain@bbs.whnet.edu.cn

Linux 内核源码 /usr/src/linux/include/net/tcp.h 中

#define TCP_TIMEWAIT_LEN (60*HZ) /* how long to wait to successfully
* close the socket, about 60 seconds */

最好不要改为0,改成1。端口分配是从上一次分配的端口号+1开始分配的,所以一般
不会有什么问题。端口分配算法在tcp_ipv4.c中tcp_v4_get_port中。

#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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值