muxer_file_muxer.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. #include "muxer_file_muxer.h"
  2. #include "../base/logger.h"
  3. #include "../base/media_common.h"
  4. #include <filesystem>
  5. #include <sstream>
  6. #include <iomanip>
  7. #include <algorithm>
  8. extern "C" {
  9. #include <libavformat/avformat.h>
  10. #include <libavutil/opt.h>
  11. #include <libavutil/time.h>
  12. #include <libavutil/mathematics.h>
  13. }
  14. namespace av {
  15. namespace muxer {
  16. FileMuxer::FileMuxer() {
  17. AV_LOGGER_DEBUG("创建文件复用器");
  18. lastFlushTime_ = std::chrono::steady_clock::now();
  19. }
  20. FileMuxer::~FileMuxer() {
  21. close();
  22. AV_LOGGER_DEBUG("文件复用器已销毁");
  23. }
  24. ErrorCode FileMuxer::initialize(const MuxerParams& params) {
  25. if (params.type != MuxerType::FILE_MUXER) {
  26. AV_LOGGER_ERROR("参数类型不是文件复用器");
  27. return ErrorCode::INVALID_PARAMS;
  28. }
  29. fileMuxerParams_ = static_cast<const FileMuxerParams&>(params);
  30. if (!validateParams(fileMuxerParams_)) {
  31. return ErrorCode::INVALID_PARAMS;
  32. }
  33. // 调用父类的initialize方法来处理streams
  34. ErrorCode result = AbstractMuxer::initialize(params);
  35. if (result != ErrorCode::SUCCESS) {
  36. return result;
  37. }
  38. // 设置输出文件
  39. if (!fileMuxerParams_.outputFile.empty()) {
  40. currentOutputFile_ = fileMuxerParams_.outputFile;
  41. } else {
  42. currentOutputFile_ = fileMuxerParams_.outputPath;
  43. }
  44. ErrorCode validateResult = validateFilePath(currentOutputFile_);
  45. if (validateResult != ErrorCode::SUCCESS) {
  46. return validateResult;
  47. }
  48. // 设置分段
  49. if (fileMuxerParams_.enableSegmentation) {
  50. segmentationEnabled_ = true;
  51. if (fileMuxerParams_.segmentPattern.empty()) {
  52. // 生成默认分段模式
  53. std::filesystem::path path(currentOutputFile_);
  54. std::string stem = path.stem().string();
  55. std::string ext = path.extension().string();
  56. fileMuxerParams_.segmentPattern = stem + "_%03d" + ext;
  57. }
  58. }
  59. AV_LOGGER_INFOF("文件复用器初始化成功: {}", currentOutputFile_);
  60. return ErrorCode::SUCCESS;
  61. }
  62. ErrorCode FileMuxer::start() {
  63. if (getState() != MuxerState::INITIALIZED) {
  64. AV_LOGGER_ERROR("复用器状态无效,无法启动");
  65. return ErrorCode::INVALID_STATE;
  66. }
  67. ErrorCode result = setupOutput();
  68. if (result != ErrorCode::SUCCESS) {
  69. return result;
  70. }
  71. result = writeHeader();
  72. if (result != ErrorCode::SUCCESS) {
  73. return result;
  74. }
  75. // 启动写入线程
  76. shouldStopWriting_ = false;
  77. try {
  78. writeThread_ = std::thread(&FileMuxer::writeThreadFunc, this);
  79. setState(MuxerState::STARTED);
  80. fileStartTime_ = std::chrono::steady_clock::now();
  81. AV_LOGGER_INFO("文件复用器已启动");
  82. return ErrorCode::SUCCESS;
  83. } catch (const std::exception& e) {
  84. AV_LOGGER_ERRORF("启动写入线程失败: {}", e.what());
  85. return ErrorCode::THREAD_ERROR;
  86. }
  87. }
  88. ErrorCode FileMuxer::stop() {
  89. if (getState() != MuxerState::STARTED && getState() != MuxerState::PAUSED) {
  90. return ErrorCode::SUCCESS;
  91. }
  92. // 停止写入线程
  93. shouldStopWriting_ = true;
  94. queueCondition_.notify_all();
  95. if (writeThread_.joinable()) {
  96. writeThread_.join();
  97. }
  98. // 刷新剩余数据
  99. flush();
  100. // 写入文件尾
  101. ErrorCode result = writeTrailer();
  102. if (result != ErrorCode::SUCCESS) {
  103. AV_LOGGER_ERRORF("写入文件尾失败: {}", static_cast<int>(result));
  104. }
  105. setState(MuxerState::STOPPED);
  106. AV_LOGGER_INFO("文件复用器已停止");
  107. return ErrorCode::SUCCESS;
  108. }
  109. ErrorCode FileMuxer::close() {
  110. stop();
  111. ErrorCode result = closeOutputFile();
  112. // 清空队列
  113. {
  114. std::lock_guard<std::mutex> lock(queueMutex_);
  115. while (!packetQueue_.empty()) {
  116. packetQueue_.pop();
  117. }
  118. }
  119. setState(MuxerState::IDLE);
  120. AV_LOGGER_INFO("文件复用器已关闭");
  121. return result;
  122. }
  123. ErrorCode FileMuxer::writePacket(AVPacket* packet) {
  124. if (!packet) {
  125. AV_LOGGER_ERROR("包指针为空");
  126. return ErrorCode::INVALID_PARAMS;
  127. }
  128. if (getState() != MuxerState::STARTED) {
  129. AV_LOGGER_ERROR("复用器未启动,无法写入包");
  130. return ErrorCode::INVALID_STATE;
  131. }
  132. // 检查队列大小
  133. {
  134. std::lock_guard<std::mutex> lock(queueMutex_);
  135. if (packetQueue_.size() >= MAX_QUEUE_SIZE) {
  136. AV_LOGGER_WARNING("包队列已满,丢弃包");
  137. {
  138. std::lock_guard<std::mutex> statsLock(statsMutex_);
  139. stats_.droppedPackets++;
  140. }
  141. return ErrorCode::QUEUE_FULL;
  142. }
  143. }
  144. // 复制包
  145. AVPacket* packetCopy = av_packet_alloc();
  146. if (!packetCopy) {
  147. AV_LOGGER_ERROR("分配包内存失败");
  148. return ErrorCode::MEMORY_ALLOC_FAILED;
  149. }
  150. int ret = av_packet_ref(packetCopy, packet);
  151. if (ret < 0) {
  152. av_packet_free(&packetCopy);
  153. AV_LOGGER_ERRORF("复制包失败: {}", ffmpeg_utils::errorToString(ret));
  154. return static_cast<ErrorCode>(ret);
  155. }
  156. // 添加到队列
  157. auto queueItem = std::make_unique<PacketQueueItem>(packetCopy, packet->stream_index);
  158. {
  159. std::lock_guard<std::mutex> lock(queueMutex_);
  160. packetQueue_.push(std::move(queueItem));
  161. queuedPackets_++;
  162. }
  163. queueCondition_.notify_one();
  164. return ErrorCode::SUCCESS;
  165. }
  166. ErrorCode FileMuxer::writeFrame(AVFrame* frame, int streamIndex) {
  167. if (!frame) {
  168. AV_LOGGER_ERROR("帧指针为空");
  169. return ErrorCode::INVALID_PARAMS;
  170. }
  171. // 这里需要编码器将帧编码为包,然后调用writePacket
  172. // 由于这是复用器,通常接收已编码的包
  173. AV_LOGGER_WARNING("文件复用器不直接支持写入原始帧,请先编码为包");
  174. return ErrorCode::NOT_SUPPORTED;
  175. }
  176. ErrorCode FileMuxer::flush() {
  177. if (!formatCtx_) {
  178. return ErrorCode::SUCCESS;
  179. }
  180. std::lock_guard<std::mutex> lock(fileMutex_);
  181. return flushInternal();
  182. }
  183. ErrorCode FileMuxer::flushInternal() {
  184. if (!formatCtx_) {
  185. return ErrorCode::SUCCESS;
  186. }
  187. // 注意:此方法假设调用者已经持有fileMutex_锁
  188. int ret = av_write_frame(formatCtx_, nullptr); // 刷新
  189. if (ret < 0) {
  190. AV_LOGGER_ERRORF("刷新复用器失败: {}", ffmpeg_utils::errorToString(ret));
  191. return static_cast<ErrorCode>(ret);
  192. }
  193. if (formatCtx_->pb) {
  194. avio_flush(formatCtx_->pb);
  195. }
  196. lastFlushTime_ = std::chrono::steady_clock::now();
  197. AV_LOGGER_DEBUG("复用器已刷新");
  198. return ErrorCode::SUCCESS;
  199. }
  200. ErrorCode FileMuxer::addStream(const StreamInfo& streamInfo) {
  201. if (getState() != MuxerState::INITIALIZED) {
  202. AV_LOGGER_ERROR("只能在初始化状态下添加流");
  203. return ErrorCode::INVALID_STATE;
  204. }
  205. std::lock_guard<std::mutex> lock(streamsMutex_);
  206. // 检查流索引是否已存在
  207. auto it = std::find_if(streams_.begin(), streams_.end(),
  208. [&streamInfo](const StreamInfo& info) {
  209. return info.index == streamInfo.index;
  210. });
  211. if (it != streams_.end()) {
  212. AV_LOGGER_ERRORF("流索引 {} 已存在", streamInfo.index);
  213. return ErrorCode::STREAM_EXISTS;
  214. }
  215. streams_.push_back(streamInfo);
  216. AV_LOGGER_INFOF("已添加流: 索引={}, 类型={}, 编解码器={}",
  217. streamInfo.index, static_cast<int>(streamInfo.type),
  218. streamInfo.codecName);
  219. return ErrorCode::SUCCESS;
  220. }
  221. ErrorCode FileMuxer::setOutputFile(const std::string& filename) {
  222. if (getState() != MuxerState::IDLE && getState() != MuxerState::INITIALIZED) {
  223. AV_LOGGER_ERROR("无法在运行时更改输出文件");
  224. return ErrorCode::INVALID_STATE;
  225. }
  226. ErrorCode result = validateFilePath(filename);
  227. if (result != ErrorCode::SUCCESS) {
  228. return result;
  229. }
  230. currentOutputFile_ = filename;
  231. fileMuxerParams_.outputFile = filename;
  232. AV_LOGGER_INFOF("输出文件已设置为: {}", filename);
  233. return ErrorCode::SUCCESS;
  234. }
  235. std::string FileMuxer::getOutputFile() const {
  236. return currentOutputFile_;
  237. }
  238. int64_t FileMuxer::getCurrentFileSize() const {
  239. return currentFileSize_;
  240. }
  241. double FileMuxer::getCurrentDuration() const {
  242. auto now = std::chrono::steady_clock::now();
  243. return std::chrono::duration<double>(now - fileStartTime_).count();
  244. }
  245. ErrorCode FileMuxer::enableSegmentation(bool enable, int duration) {
  246. if (getState() == MuxerState::STARTED) {
  247. AV_LOGGER_ERROR("无法在运行时更改分段设置");
  248. return ErrorCode::INVALID_STATE;
  249. }
  250. segmentationEnabled_ = enable;
  251. fileMuxerParams_.enableSegmentation = enable;
  252. fileMuxerParams_.segmentDuration = duration;
  253. AV_LOGGER_INFOF("Segmentation {}: duration={}s", enable ? "enabled" : "disabled", duration);
  254. return ErrorCode::SUCCESS;
  255. }
  256. ErrorCode FileMuxer::forceNewSegment() {
  257. if (!segmentationEnabled_) {
  258. AV_LOGGER_ERROR("分段功能未启用");
  259. return ErrorCode::INVALID_STATE;
  260. }
  261. if (getState() != MuxerState::STARTED) {
  262. AV_LOGGER_ERROR("复用器未启动");
  263. return ErrorCode::INVALID_STATE;
  264. }
  265. return createNewSegment();
  266. }
  267. std::vector<std::string> FileMuxer::getSegmentFiles() const {
  268. return segmentFiles_;
  269. }
  270. ErrorCode FileMuxer::setFastStart(bool enable) {
  271. fileMuxerParams_.enableFastStart = enable;
  272. if (enable) {
  273. fileMuxerParams_.movFlags |= 0x01; // AVFMT_FLAG_FASTSTART
  274. } else {
  275. fileMuxerParams_.movFlags &= ~0x01;
  276. }
  277. AV_LOGGER_INFOF("Fast start {}", enable ? "enabled" : "disabled");
  278. return ErrorCode::SUCCESS;
  279. }
  280. ErrorCode FileMuxer::setMovFlags(int flags) {
  281. fileMuxerParams_.movFlags = flags;
  282. AV_LOGGER_INFOF("MOV标志已设置为: 0x{:X}", flags);
  283. return ErrorCode::SUCCESS;
  284. }
  285. ErrorCode FileMuxer::setupOutput() {
  286. // 分配格式上下文
  287. const char* formatName = fileMuxerParams_.format.empty() ? nullptr : fileMuxerParams_.format.c_str();
  288. const char* filename = currentOutputFile_.c_str();
  289. int ret = avformat_alloc_output_context2(&formatCtx_, nullptr, formatName, filename);
  290. if (ret < 0) {
  291. AV_LOGGER_ERRORF("分配输出格式上下文失败: {}", ffmpeg_utils::errorToString(ret));
  292. return static_cast<ErrorCode>(ret);
  293. }
  294. if (!formatCtx_->oformat) {
  295. AV_LOGGER_ERROR("无法确定输出格式");
  296. return ErrorCode::FORMAT_NOT_SUPPORTED;
  297. }
  298. AV_LOGGER_INFOF("输出格式: {} ({})", formatCtx_->oformat->name, formatCtx_->oformat->long_name);
  299. // 设置流
  300. ErrorCode result = setupStreams();
  301. if (result != ErrorCode::SUCCESS) {
  302. return result;
  303. }
  304. // 设置元数据
  305. for (const auto& meta : fileMuxerParams_.metadata) {
  306. av_dict_set(&formatCtx_->metadata, meta.first.c_str(), meta.second.c_str(), 0);
  307. }
  308. // 打开输出文件
  309. return openOutputFile();
  310. }
  311. ErrorCode FileMuxer::writeHeader() {
  312. if (!formatCtx_) {
  313. AV_LOGGER_ERROR("格式上下文未初始化");
  314. return ErrorCode::INVALID_STATE;
  315. }
  316. // 设置格式选项
  317. AVDictionary* options = nullptr;
  318. for (const auto& option : fileMuxerParams_.options) {
  319. av_dict_set(&options, option.first.c_str(), option.second.c_str(), 0);
  320. }
  321. // 设置MOV标志
  322. if (fileMuxerParams_.movFlags != 0) {
  323. av_dict_set_int(&options, "movflags", fileMuxerParams_.movFlags, 0);
  324. }
  325. // 写入文件头
  326. int ret = avformat_write_header(formatCtx_, &options);
  327. av_dict_free(&options);
  328. if (ret < 0) {
  329. AV_LOGGER_ERRORF("写入文件头失败: {}", ffmpeg_utils::errorToString(ret));
  330. return static_cast<ErrorCode>(ret);
  331. }
  332. AV_LOGGER_INFO("文件头已写入");
  333. return ErrorCode::SUCCESS;
  334. }
  335. ErrorCode FileMuxer::writeTrailer() {
  336. if (!formatCtx_) {
  337. return ErrorCode::SUCCESS;
  338. }
  339. std::lock_guard<std::mutex> lock(fileMutex_);
  340. int ret = av_write_trailer(formatCtx_);
  341. if (ret < 0) {
  342. AV_LOGGER_ERRORF("写入文件尾失败: {}", ffmpeg_utils::errorToString(ret));
  343. return static_cast<ErrorCode>(ret);
  344. }
  345. AV_LOGGER_INFO("文件尾已写入");
  346. return ErrorCode::SUCCESS;
  347. }
  348. ErrorCode FileMuxer::openOutputFile() {
  349. if (!formatCtx_) {
  350. return ErrorCode::INVALID_STATE;
  351. }
  352. // 检查是否需要覆盖文件
  353. if (!fileMuxerParams_.overwrite && std::filesystem::exists(currentOutputFile_)) {
  354. AV_LOGGER_ERRORF("文件已存在且不允许覆盖: {}", currentOutputFile_);
  355. return ErrorCode::FILE_EXISTS;
  356. }
  357. // 打开输出文件
  358. if (!(formatCtx_->oformat->flags & AVFMT_NOFILE)) {
  359. int ret = avio_open(&formatCtx_->pb, currentOutputFile_.c_str(), AVIO_FLAG_WRITE);
  360. if (ret < 0) {
  361. AV_LOGGER_ERRORF("打开输出文件失败: {} ({})",
  362. ffmpeg_utils::errorToString(ret), currentOutputFile_);
  363. return static_cast<ErrorCode>(ret);
  364. }
  365. }
  366. currentFileSize_ = 0;
  367. AV_LOGGER_INFOF("输出文件已打开: {}", currentOutputFile_);
  368. return ErrorCode::SUCCESS;
  369. }
  370. ErrorCode FileMuxer::closeOutputFile() {
  371. if (!formatCtx_) {
  372. return ErrorCode::SUCCESS;
  373. }
  374. std::lock_guard<std::mutex> lock(fileMutex_);
  375. // 关闭文件
  376. if (formatCtx_->pb && !(formatCtx_->oformat->flags & AVFMT_NOFILE)) {
  377. avio_closep(&formatCtx_->pb);
  378. }
  379. // 释放格式上下文
  380. avformat_free_context(formatCtx_);
  381. formatCtx_ = nullptr;
  382. // 清理流映射
  383. streamMap_.clear();
  384. AV_LOGGER_INFO("输出文件已关闭");
  385. return ErrorCode::SUCCESS;
  386. }
  387. ErrorCode FileMuxer::createNewSegment() {
  388. if (!segmentationEnabled_) {
  389. return ErrorCode::SUCCESS;
  390. }
  391. // 写入当前段的尾部
  392. ErrorCode result = writeTrailer();
  393. if (result != ErrorCode::SUCCESS) {
  394. return result;
  395. }
  396. // 关闭当前文件
  397. result = closeOutputFile();
  398. if (result != ErrorCode::SUCCESS) {
  399. return result;
  400. }
  401. // 添加到段文件列表
  402. segmentFiles_.push_back(currentOutputFile_);
  403. // 生成新的段文件名
  404. currentSegmentIndex_++;
  405. currentOutputFile_ = generateSegmentFilename(currentSegmentIndex_);
  406. // 重新设置输出
  407. result = setupOutput();
  408. if (result != ErrorCode::SUCCESS) {
  409. return result;
  410. }
  411. // 写入新段的头部
  412. result = writeHeader();
  413. if (result != ErrorCode::SUCCESS) {
  414. return result;
  415. }
  416. fileStartTime_ = std::chrono::steady_clock::now();
  417. AV_LOGGER_INFOF("创建新段: {}", currentOutputFile_);
  418. return ErrorCode::SUCCESS;
  419. }
  420. ErrorCode FileMuxer::setupStreams() {
  421. std::lock_guard<std::mutex> lock(streamsMutex_);
  422. for (const auto& streamInfo : streams_) {
  423. AVStream* stream = createAVStream(streamInfo);
  424. if (!stream) {
  425. AV_LOGGER_ERRORF("创建流失败: 索引={}", streamInfo.index);
  426. return ErrorCode::STREAM_CREATE_FAILED;
  427. }
  428. streamMap_[streamInfo.index] = stream;
  429. }
  430. AV_LOGGER_INFOF("已设置 {} 个流", streams_.size());
  431. return ErrorCode::SUCCESS;
  432. }
  433. AVStream* FileMuxer::createAVStream(const StreamInfo& streamInfo) {
  434. if (!formatCtx_) {
  435. return nullptr;
  436. }
  437. AVStream* stream = avformat_new_stream(formatCtx_, nullptr);
  438. if (!stream) {
  439. AV_LOGGER_ERROR("创建新流失败");
  440. return nullptr;
  441. }
  442. stream->id = streamInfo.index;
  443. stream->time_base = streamInfo.timeBase;
  444. // 设置编解码器参数
  445. AVCodecParameters* codecpar = stream->codecpar;
  446. codecpar->codec_id = streamInfo.codecId;
  447. codecpar->codec_type = (streamInfo.type == StreamType::VIDEO) ? AVMEDIA_TYPE_VIDEO : AVMEDIA_TYPE_AUDIO;
  448. if (streamInfo.type == StreamType::VIDEO) {
  449. codecpar->width = streamInfo.width;
  450. codecpar->height = streamInfo.height;
  451. codecpar->format = streamInfo.pixelFormat;
  452. codecpar->bit_rate = streamInfo.bitrate;
  453. // 设置帧率
  454. stream->avg_frame_rate = streamInfo.frameRate;
  455. stream->r_frame_rate = streamInfo.frameRate;
  456. } else if (streamInfo.type == StreamType::AUDIO) {
  457. codecpar->sample_rate = streamInfo.sampleRate;
  458. av_channel_layout_default(&codecpar->ch_layout, streamInfo.channels);
  459. codecpar->format = streamInfo.sampleFormat;
  460. codecpar->bit_rate = streamInfo.bitrate;
  461. }
  462. AV_LOGGER_INFOF("创建流成功: 索引={}, 类型={}", streamInfo.index, static_cast<int>(streamInfo.type));
  463. return stream;
  464. }
  465. ErrorCode FileMuxer::processPacket(AVPacket* packet) {
  466. if (!packet || !formatCtx_) {
  467. return ErrorCode::INVALID_PARAMS;
  468. }
  469. // 检查流索引
  470. auto it = streamMap_.find(packet->stream_index);
  471. if (it == streamMap_.end()) {
  472. AV_LOGGER_ERRORF("未找到流索引: {}", packet->stream_index);
  473. return ErrorCode::STREAM_NOT_FOUND;
  474. }
  475. // 检查是否需要创建新段
  476. if (shouldCreateNewSegment()) {
  477. ErrorCode result = createNewSegment();
  478. if (result != ErrorCode::SUCCESS) {
  479. return result;
  480. }
  481. }
  482. return writePacketInternal(packet);
  483. }
  484. ErrorCode FileMuxer::writePacketInternal(AVPacket* packet) {
  485. std::lock_guard<std::mutex> lock(fileMutex_);
  486. auto startTime = std::chrono::steady_clock::now();
  487. // 写入包
  488. int ret = av_interleaved_write_frame(formatCtx_, packet);
  489. if (ret < 0) {
  490. AV_LOGGER_ERRORF("写入包失败: {}", ffmpeg_utils::errorToString(ret));
  491. return static_cast<ErrorCode>(ret);
  492. }
  493. // 更新统计信息
  494. updateStats(packet);
  495. currentFileSize_ += packet->size;
  496. writtenPackets_++;
  497. // 更新平均写入时间
  498. auto endTime = std::chrono::steady_clock::now();
  499. double writeTime = std::chrono::duration<double, std::milli>(endTime - startTime).count();
  500. averageWriteTime_ = (averageWriteTime_ * 0.9) + (writeTime * 0.1);
  501. // 定期刷新 - 使用内部刷新方法避免死锁
  502. if (!fileMuxerParams_.syncMode) {
  503. auto now = std::chrono::steady_clock::now();
  504. auto elapsed = std::chrono::duration<double>(now - lastFlushTime_).count();
  505. if (elapsed >= fileMuxerParams_.flushInterval) {
  506. flushInternal();
  507. }
  508. }
  509. return ErrorCode::SUCCESS;
  510. }
  511. void FileMuxer::writeThreadFunc() {
  512. AV_LOGGER_INFO("写入线程已启动");
  513. while (!shouldStopWriting_) {
  514. std::unique_ptr<PacketQueueItem> item;
  515. // 从队列获取包
  516. {
  517. std::unique_lock<std::mutex> lock(queueMutex_);
  518. queueCondition_.wait(lock, [this] {
  519. return !packetQueue_.empty() || shouldStopWriting_;
  520. });
  521. if (shouldStopWriting_ && packetQueue_.empty()) {
  522. break;
  523. }
  524. if (!packetQueue_.empty()) {
  525. item = std::move(packetQueue_.front());
  526. packetQueue_.pop();
  527. }
  528. }
  529. if (item && item->packet) {
  530. ErrorCode result = processPacket(item->packet);
  531. if (result != ErrorCode::SUCCESS) {
  532. onError(result, "写入包失败");
  533. }
  534. }
  535. }
  536. // 处理剩余的包
  537. while (true) {
  538. std::unique_ptr<PacketQueueItem> item;
  539. {
  540. std::lock_guard<std::mutex> lock(queueMutex_);
  541. if (packetQueue_.empty()) {
  542. break;
  543. }
  544. item = std::move(packetQueue_.front());
  545. packetQueue_.pop();
  546. }
  547. if (item && item->packet) {
  548. processPacket(item->packet);
  549. }
  550. }
  551. AV_LOGGER_INFO("写入线程已退出");
  552. }
  553. std::string FileMuxer::generateSegmentFilename(int segmentIndex) {
  554. if (fileMuxerParams_.segmentPattern.empty()) {
  555. std::filesystem::path path(currentOutputFile_);
  556. std::string stem = path.stem().string();
  557. std::string ext = path.extension().string();
  558. std::ostringstream oss;
  559. oss << stem << "_" << std::setfill('0') << std::setw(3) << segmentIndex << ext;
  560. return oss.str();
  561. } else {
  562. char buffer[1024];
  563. snprintf(buffer, sizeof(buffer), fileMuxerParams_.segmentPattern.c_str(), segmentIndex);
  564. return std::string(buffer);
  565. }
  566. }
  567. bool FileMuxer::shouldCreateNewSegment() const {
  568. if (!segmentationEnabled_) {
  569. return false;
  570. }
  571. // 检查时长
  572. if (fileMuxerParams_.segmentDuration > 0) {
  573. double currentDuration = getCurrentDuration();
  574. if (currentDuration >= fileMuxerParams_.segmentDuration) {
  575. return true;
  576. }
  577. }
  578. // 检查文件大小
  579. if (fileMuxerParams_.maxFileSize > 0) {
  580. if (currentFileSize_ >= fileMuxerParams_.maxFileSize) {
  581. return true;
  582. }
  583. }
  584. return false;
  585. }
  586. ErrorCode FileMuxer::validateFilePath(const std::string& path) {
  587. if (path.empty()) {
  588. AV_LOGGER_ERROR("文件路径不能为空");
  589. return ErrorCode::INVALID_PARAMS;
  590. }
  591. try {
  592. std::filesystem::path filePath(path);
  593. // 检查父目录是否存在
  594. std::filesystem::path parentDir = filePath.parent_path();
  595. if (!parentDir.empty() && !std::filesystem::exists(parentDir)) {
  596. // 尝试创建目录
  597. std::filesystem::create_directories(parentDir);
  598. }
  599. // 检查文件扩展名
  600. std::string extension = filePath.extension().string();
  601. if (extension.empty()) {
  602. AV_LOGGER_WARNING("文件没有扩展名,可能导致格式检测问题");
  603. }
  604. } catch (const std::exception& e) {
  605. AV_LOGGER_ERRORF("文件路径验证失败: {}", e.what());
  606. return ErrorCode::INVALID_PATH;
  607. }
  608. return ErrorCode::SUCCESS;
  609. }
  610. bool FileMuxer::validateParams(const MuxerParams& params) {
  611. if (!AbstractMuxer::validateParams(params)) {
  612. return false;
  613. }
  614. const auto& fileParams = static_cast<const FileMuxerParams&>(params);
  615. if (fileParams.outputFile.empty() && fileParams.outputPath.empty()) {
  616. AV_LOGGER_ERROR("输出文件路径不能为空");
  617. return false;
  618. }
  619. if (fileParams.segmentDuration < 0) {
  620. AV_LOGGER_ERROR("分段时长不能为负数");
  621. return false;
  622. }
  623. if (fileParams.maxFileSize < 0) {
  624. AV_LOGGER_ERROR("最大文件大小不能为负数");
  625. return false;
  626. }
  627. if (fileParams.flushInterval <= 0) {
  628. AV_LOGGER_ERROR("刷新间隔必须大于0");
  629. return false;
  630. }
  631. return true;
  632. }
  633. // FileMuxerFactory 实现
  634. std::unique_ptr<AbstractMuxer> FileMuxer::FileMuxerFactory::createMuxer(MuxerType type) {
  635. if (type == MuxerType::FILE_MUXER) {
  636. return std::make_unique<FileMuxer>();
  637. }
  638. return nullptr;
  639. }
  640. bool FileMuxer::FileMuxerFactory::isTypeSupported(MuxerType type) const {
  641. return type == MuxerType::FILE_MUXER;
  642. }
  643. std::vector<MuxerType> FileMuxer::FileMuxerFactory::getSupportedTypes() const {
  644. return {MuxerType::FILE_MUXER};
  645. }
  646. std::unique_ptr<FileMuxer> FileMuxer::FileMuxerFactory::createFileMuxer(const std::string& filename) {
  647. auto muxer = std::make_unique<FileMuxer>();
  648. FileMuxerParams params;
  649. params.outputFile = filename;
  650. params.format = AbstractMuxer::getFormatFromExtension(filename);
  651. ErrorCode result = muxer->initialize(params);
  652. if (result != ErrorCode::SUCCESS) {
  653. AV_LOGGER_ERRORF("创建文件复用器失败: {}", static_cast<int>(result));
  654. return nullptr;
  655. }
  656. return muxer;
  657. }
  658. std::unique_ptr<FileMuxer> FileMuxer::FileMuxerFactory::createSegmentedMuxer(const std::string& pattern, int duration) {
  659. auto muxer = std::make_unique<FileMuxer>();
  660. FileMuxerParams params;
  661. params.outputFile = pattern;
  662. params.enableSegmentation = true;
  663. params.segmentDuration = duration;
  664. params.segmentPattern = pattern;
  665. // 从模式中推断格式
  666. std::string firstFile = pattern;
  667. size_t pos = firstFile.find("%");
  668. if (pos != std::string::npos) {
  669. firstFile.replace(pos, firstFile.find('d', pos) - pos + 1, "001");
  670. }
  671. params.format = AbstractMuxer::getFormatFromExtension(firstFile);
  672. ErrorCode result = muxer->initialize(params);
  673. if (result != ErrorCode::SUCCESS) {
  674. AV_LOGGER_ERRORF("创建分段复用器失败: {}", static_cast<int>(result));
  675. return nullptr;
  676. }
  677. return muxer;
  678. }
  679. } // namespace muxer
  680. } // namespace av