av_recorder.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. #include "av_recorder.h"
  2. #include <QDateTime>
  3. #include <QStatusBar>
  4. #include <QMessageBox>
  5. #include "avrecorder/capturer/video/VideoCaptureManager.h"
  6. #include "qglobal.h"
  7. #include <capturer/finder.h>
  8. using namespace avrecorder::video;
  9. AvRecorder::AvRecorder(QWidget* parent)
  10. : QWidget(parent)
  11. {
  12. m_settingsParam.audioParam.bitRate = 160'000;
  13. m_settingsParam.videoParam.bitRate = 8'000'000;
  14. m_settingsParam.videoParam.fps = 30;
  15. {
  16. const auto& encs = Encoder<MediaType::VIDEO>::GetUsableEncoders();
  17. m_settingsParam.videoParam.name = encs.empty() ? std::string("libx264") : encs.front();
  18. }
  19. {
  20. const auto& aencs = Encoder<MediaType::AUDIO>::GetUsableEncoders();
  21. m_settingsParam.audioParam.name = aencs.empty() ? std::string("aac") : aencs.front();
  22. }
  23. // 设置安全的默认分辨率,避免在捕获首帧前width/height为0
  24. m_settingsParam.videoParam.width = 1920;
  25. m_settingsParam.videoParam.height = 1080;
  26. m_settingsParam.outputDir = ".";
  27. m_settingsParam.liveUrl = "rtmp://127.0.0.1:1935/stream/V1";
  28. m_settingsParam.liveName = "stream";
  29. // 1. 视频预览区
  30. m_glWidget = new OpenGLVideoWidget(this);
  31. // 2. 音频区
  32. m_microphoneWidget = new AudioWidget;
  33. m_speakerWidget = new AudioWidget;
  34. m_microphoneWidget->SetName("麦克风");
  35. m_speakerWidget->SetName("扬声器");
  36. // 3. 捕获区
  37. m_captureComboBox = new QComboBox;
  38. m_updateListBtn = new QPushButton("刷新窗口列表");
  39. QGroupBox* captureGroup = new QGroupBox("捕获源");
  40. QHBoxLayout* captureRow = new QHBoxLayout;
  41. captureRow->addWidget(m_captureComboBox);
  42. captureRow->addWidget(m_updateListBtn);
  43. captureGroup->setLayout(captureRow);
  44. // m_captureComboBox->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
  45. m_captureComboBox->setMinimumWidth(20);
  46. // 4. 音频区分组
  47. QGroupBox* audioGroup = new QGroupBox("音频");
  48. QVBoxLayout* audioLayout = new QVBoxLayout;
  49. audioLayout->addWidget(m_microphoneWidget);
  50. audioLayout->addWidget(m_speakerWidget);
  51. audioGroup->setLayout(audioLayout);
  52. //audioGroup->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum);
  53. // 5. 操作区
  54. m_isDrawCursorBox = new QCheckBox("绘制鼠标指针");
  55. m_isDrawCursorBox->setChecked(true);
  56. m_isDrawCursorBox->setEnabled(false);
  57. m_syncRecordBox = new QCheckBox("直播时同步录像");
  58. m_syncRecordBox->setChecked(false);
  59. m_recordBtn = new QPushButton("开始录制");
  60. m_recordBtn->setEnabled(false);
  61. m_liveBtn = new QPushButton("开始直播");
  62. m_liveBtn->setEnabled(false);
  63. m_settingsBtn = new QPushButton("设置");
  64. QGroupBox* actionGroup = new QGroupBox("操作");
  65. QVBoxLayout* actionLayout = new QVBoxLayout;
  66. QHBoxLayout* checkBoxRow = new QHBoxLayout;
  67. checkBoxRow->setContentsMargins(0, 0, 0, 0);
  68. checkBoxRow->setSpacing(8);
  69. checkBoxRow->addWidget(m_syncRecordBox);
  70. checkBoxRow->addWidget(m_isDrawCursorBox);
  71. actionLayout->addLayout(checkBoxRow);
  72. actionLayout->addWidget(m_recordBtn);
  73. actionLayout->addWidget(m_liveBtn);
  74. actionGroup->setLayout(actionLayout);
  75. //actionGroup->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum);
  76. // 6. 设置区
  77. QHBoxLayout* utilLayout = new QHBoxLayout;
  78. utilLayout->addWidget(m_settingsBtn);
  79. // 7. 左侧功能区(捕获区在上,音频区在下)
  80. QVBoxLayout* leftLayout = new QVBoxLayout;
  81. leftLayout->addWidget(captureGroup);
  82. leftLayout->addWidget(audioGroup);
  83. leftLayout->addStretch();
  84. // 8. 右侧功能区
  85. QVBoxLayout* rightLayout = new QVBoxLayout;
  86. rightLayout->addWidget(actionGroup);
  87. rightLayout->addLayout(utilLayout);
  88. rightLayout->addStretch();
  89. // 9. 中部主布局
  90. QHBoxLayout* centerLayout = new QHBoxLayout;
  91. centerLayout->addLayout(leftLayout, 2);
  92. centerLayout->addLayout(rightLayout, 3);
  93. // 10. 状态栏
  94. initStatusBarUi();
  95. // 让视频区尽量大
  96. // m_glWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
  97. // 11. 总体布局
  98. QVBoxLayout* mainLayout = new QVBoxLayout(this);
  99. mainLayout->addWidget(m_glWidget, 100);
  100. mainLayout->addLayout(centerLayout, 0);
  101. mainLayout->addWidget(m_statusBar, 0);
  102. setLayout(mainLayout);
  103. // 12. 连接信号槽、初始化数据
  104. initConnect();
  105. updateCaptureList();
  106. }
  107. void AvRecorder::setSettings(const SettingsPage::Param& param)
  108. {
  109. m_settingsParam.audioParam.bitRate = 160'000;
  110. m_settingsParam.videoParam.bitRate = 8'000'000;
  111. m_settingsParam.videoParam.fps = 30;
  112. {
  113. const auto& encs = Encoder<MediaType::VIDEO>::GetUsableEncoders();
  114. m_settingsParam.videoParam.name = encs.empty() ? std::string("libx264") : encs.front();
  115. }
  116. {
  117. const auto& aencs = Encoder<MediaType::AUDIO>::GetUsableEncoders();
  118. m_settingsParam.audioParam.name = aencs.empty() ? std::string("aac") : aencs.front();
  119. }
  120. // 重置时也保持安全默认分辨率,实际分辨率会在捕获后更新
  121. m_settingsParam.videoParam.width = 1920;
  122. m_settingsParam.videoParam.height = 1080;
  123. m_settingsParam.outputDir = ".";
  124. m_settingsParam.liveUrl = param.liveUrl; // "rtmp://192.168.3.76:1935/stream/V1";
  125. m_settingsParam.liveName = param.liveName; // "stream";
  126. }
  127. void AvRecorder::initConnect()
  128. {
  129. connect(m_recordBtn, &QPushButton::released, this, [this] {
  130. if (!m_isRecord) {
  131. auto fileName = m_settingsParam.outputDir;
  132. if (fileName.back() != '\\') {
  133. fileName.push_back('\\');
  134. }
  135. auto format = "mp4";
  136. fileName += QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss").toStdString()
  137. + "." + format;
  138. // fileName += std::string("test.") + format;
  139. if (!startStream(fileName, format)) {
  140. qDebug() << "startStream failed for recording";
  141. return;
  142. }
  143. m_liveBtn->setEnabled(false);
  144. m_recordBtn->setText("停止录制");
  145. } else {
  146. stopStream();
  147. m_liveBtn->setEnabled(true);
  148. m_recordBtn->setText("开始录制");
  149. }
  150. m_isRecord = !m_isRecord;
  151. });
  152. connect(m_liveBtn, &QPushButton::released, this, [this] {
  153. if (!m_isLive) {
  154. auto fileName = m_settingsParam.liveUrl + "/" + m_settingsParam.liveName;
  155. bool isRtsp = m_settingsParam.liveUrl.find("rtsp") != std::string::npos;
  156. qDebug() << "直播地址:" << QString::fromStdString(fileName);
  157. if (!startStream(fileName, isRtsp ? "rtsp" : "flv")) {
  158. qDebug() << "startStream failed for live";
  159. return;
  160. }
  161. // 如果勾选了同步录像,则开始录像
  162. if (m_syncRecordBox->isChecked()) {
  163. if (!startSyncRecord()) {
  164. qDebug() << "startSyncRecord failed";
  165. // 不阻断直播,仅提示
  166. }
  167. }
  168. m_recordBtn->setEnabled(false);
  169. m_liveBtn->setText("停止直播");
  170. // 显式设置直播状态
  171. m_isLive = true;
  172. } else {
  173. // 先停止同步录像
  174. stopSyncRecord();
  175. // 再停止直播
  176. stopStream();
  177. m_recordBtn->setEnabled(true);
  178. m_liveBtn->setText("开始直播");
  179. // 显式清除直播状态
  180. m_isLive = false;
  181. }
  182. });
  183. connect(m_microphoneWidget, &AudioWidget::SetVolumeScale, this, [this](float scale) {
  184. m_audioRecorder.SetVolumeScale(scale, MICROPHONE_INDEX);
  185. });
  186. connect(m_speakerWidget, &AudioWidget::SetVolumeScale, this, [this](float scale) {
  187. m_audioRecorder.SetVolumeScale(scale, SPEAKER_INDEX);
  188. });
  189. connect(m_updateListBtn, &QPushButton::released, this, [this] { updateCaptureList(); });
  190. connect(m_captureComboBox, &QComboBox::currentTextChanged, this, [this](const QString& text) {
  191. if (text.isEmpty() || m_isLocked) {
  192. return;
  193. }
  194. m_isLocked = true;
  195. if (!(m_isRecord || m_isLive)) {
  196. stopPreview();
  197. stopCapture();
  198. startCapture(CaptureMethod::WGC);
  199. startPreview();
  200. }
  201. m_isLocked = false;
  202. });
  203. connect(m_captureComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &AvRecorder::onCaptureSourceChanged);
  204. connect(m_isDrawCursorBox, &QCheckBox::stateChanged, this, [this] {
  205. m_videoRecorder.SetIsDrawCursor(m_isDrawCursorBox->isChecked());
  206. });
  207. connect(m_captureMethodBox, &QComboBox::currentTextChanged, this, [this](const QString& text) {
  208. if (m_isLocked || text.isEmpty()) {
  209. return;
  210. }
  211. stopPreview();
  212. stopCapture();
  213. if (text == "WGC") {
  214. startCapture(CaptureMethod::WGC);
  215. } else if (text == "DXGI") {
  216. startCapture(CaptureMethod::DXGI);
  217. } else {
  218. startCapture(CaptureMethod::GDI);
  219. }
  220. startPreview();
  221. });
  222. connect(m_settingsBtn, &QPushButton::released, this, [this] {
  223. // 运行中禁止打开设置以切换编码器,避免异常
  224. if (m_isRecord || m_isLive || m_isSyncRecord) {
  225. QMessageBox::warning(this, "提示", "正在直播/录制,无法修改编码器设置。请先停止后再修改。");
  226. return;
  227. }
  228. auto settingsPage = std::make_unique<SettingsPage>(&m_settingsParam, this);
  229. settingsPage->exec();
  230. m_isLocked = true;
  231. stopPreview();
  232. stopCapture();
  233. startCapture(CaptureMethod::WGC);
  234. startPreview();
  235. m_isLocked = false;
  236. });
  237. m_otherTimer.callOnTimeout([this] {
  238. if (windowState() == Qt::WindowMinimized) {
  239. return;
  240. }
  241. // 音频
  242. auto info = m_audioRecorder.GetCaptureInfo(MICROPHONE_INDEX);
  243. m_microphoneWidget->ShowVolume(info == nullptr ? 0 : info->volume);
  244. info = m_audioRecorder.GetCaptureInfo(SPEAKER_INDEX);
  245. m_speakerWidget->ShowVolume(info == nullptr ? 0 : info->volume);
  246. // 状态栏
  247. if (m_isRecord || m_isLive) {
  248. int interval = m_recordTime.secsTo(QTime::currentTime());
  249. int sec = interval % 60;
  250. interval /= 60;
  251. int minute = interval % 60;
  252. int hour = interval / 60;
  253. m_captureTimeLabel->setText(QString("%1:%2:%3")
  254. .arg(hour, 2, 10, QChar('0'))
  255. .arg(minute, 2, 10, QChar('0'))
  256. .arg(sec, 2, 10, QChar('0')));
  257. auto lossRate = m_videoRecorder.GetLossRate();
  258. if (lossRate < 0) {
  259. m_videolossRate->setText("丢帧率: 统计中");
  260. } else {
  261. int num = lossRate * 10000;
  262. m_videolossRate->setText(QString("丢帧率: %1.%2%")
  263. .arg(num / 100, 2, 10, QChar('0'))
  264. .arg(num % 100, 2, 10, QChar('0')));
  265. }
  266. } else if (m_captureTimeLabel->text() != "00:00:00") {
  267. m_captureTimeLabel->setText("00:00:00");
  268. }
  269. });
  270. }
  271. AvRecorder::~AvRecorder()
  272. {
  273. stopSyncRecord();
  274. stopStream();
  275. stopPreview();
  276. stopCapture();
  277. }
  278. bool AvRecorder::start()
  279. {
  280. auto timer = new QTimer(this);
  281. connect(timer, &QTimer::timeout, this, [this, timer] {
  282. m_isLocked = true;
  283. stopPreview();
  284. stopCapture();
  285. startCapture(CaptureMethod::WGC);
  286. startPreview();
  287. m_isLocked = false;
  288. timer->stop();
  289. });
  290. timer->start(100);
  291. return true;
  292. }
  293. void AvRecorder::startCapture(CaptureMethod method)
  294. {
  295. int idx = m_captureComboBox->currentIndex();
  296. if (idx < 0) return;
  297. int monitorCnt = (int)MonitorFinder::GetList().size();
  298. QString type = (idx < monitorCnt) ? "monitor" : "window";
  299. qintptr ptrHwnd = m_captureComboBox->currentData().value<qintptr>();
  300. bool ok = false;
  301. if (m_isRecord || m_isLive) {
  302. // 推流/录制时,安全切换采集源
  303. if (idx < monitorCnt) {
  304. m_videoRecorder.SetCaptureSource(idx, method);
  305. ok = true;
  306. } else if (type == "window" && ::IsWindow((HWND)ptrHwnd)) {
  307. m_videoRecorder.SetCaptureSource((HWND)ptrHwnd, method);
  308. ok = true;
  309. }
  310. } else {
  311. // 未推流/录制时,正常 open
  312. if (idx < monitorCnt) { // 捕获屏幕
  313. ok = m_videoRecorder.Open(idx, m_settingsParam.videoParam, method);
  314. } else if (type == "window" && ::IsWindow((HWND)ptrHwnd)) {
  315. ok = m_videoRecorder.Open((HWND)ptrHwnd, m_settingsParam.videoParam, method);
  316. }
  317. }
  318. if (!ok) {
  319. // 可选:弹窗或日志提示
  320. return;
  321. }
  322. dealCapture();
  323. m_isDrawCursorBox->setEnabled(true);
  324. m_recordBtn->setEnabled(true);
  325. m_liveBtn->setEnabled(true);
  326. m_videoRecorder.SetIsDrawCursor(m_isDrawCursorBox->isChecked());
  327. m_audioRecorder.SetVolumeScale(m_microphoneWidget->GetVolume(), MICROPHONE_INDEX);
  328. m_audioRecorder.SetVolumeScale(m_speakerWidget->GetVolume(), SPEAKER_INDEX);
  329. }
  330. void AvRecorder::dealCapture()
  331. {
  332. if (!m_audioRecorder.Open({AudioCapturer::Microphone, AudioCapturer::Speaker},
  333. m_settingsParam.audioParam)) {
  334. qDebug() << "AudioRecorder::Open failed";
  335. return;
  336. }
  337. m_microphoneWidget->setEnabled(m_audioRecorder.GetCaptureInfo(MICROPHONE_INDEX) != nullptr);
  338. m_speakerWidget->setEnabled(m_audioRecorder.GetCaptureInfo(SPEAKER_INDEX) != nullptr);
  339. m_fpsLabel->setText(QString("FPS: %1").arg(m_settingsParam.videoParam.fps));
  340. m_videoEncodeLabel->setText(("编码器: " + m_settingsParam.videoParam.name).c_str());
  341. if (m_audioEncodeLabel) {
  342. m_audioEncodeLabel->setText(("音频编码器: " + m_settingsParam.audioParam.name).c_str());
  343. }
  344. }
  345. void AvRecorder::stopCapture()
  346. {
  347. m_videoRecorder.Close();
  348. m_audioRecorder.Close();
  349. }
  350. void AvRecorder::renderFrame()
  351. {
  352. auto frame = m_videoRecorder.GetRenderFrame();
  353. if (!frame) {
  354. qDebug() << "renderFrame error";
  355. return;
  356. }
  357. AVFrame* copiedFrame = av_frame_clone(frame);
  358. // m_glWidget->Render(copiedFrame);
  359. QMetaObject::invokeMethod(m_glWidget,
  360. "Render",
  361. Qt::QueuedConnection,
  362. Q_ARG(AVFrame*, copiedFrame));
  363. }
  364. void AvRecorder::startPreview()
  365. {
  366. m_glWidget->Open(m_settingsParam.videoParam.width, m_settingsParam.videoParam.height);
  367. // 视频需要做到和帧率一样的渲染速度,QTimer 达不到要求
  368. // 需要自己封装一个计时器
  369. // m_videoRenderTimer.Start(m_settingsParam.videoParam.fps, [this] {
  370. // if (windowState() == Qt::WindowMinimized) {
  371. // return;
  372. // }
  373. // QMetaObject::invokeMethod(this, "renderFrame", Qt::QueuedConnection);
  374. // // // 视频
  375. // // auto frame = m_videoRecorder.GetRenderFrame();
  376. // // m_glWidget->Render(frame);
  377. // });
  378. if (!m_videoRenderTimer) {
  379. m_videoRenderTimer = new QTimer(this);
  380. connect(m_videoRenderTimer, &QTimer::timeout, this, [this] {
  381. if (windowState() == Qt::WindowMinimized)
  382. return;
  383. renderFrame();
  384. });
  385. }
  386. m_videoRenderTimer->start(1000 / m_settingsParam.videoParam.fps);
  387. // 刷新率设置为 25
  388. m_otherTimer.start(40);
  389. }
  390. void AvRecorder::stopPreview()
  391. {
  392. if (m_videoRenderTimer) {
  393. m_videoRenderTimer->stop();
  394. }
  395. m_otherTimer.stop();
  396. }
  397. bool AvRecorder::startStream(std::string_view path, std::string_view format)
  398. {
  399. if (!m_avMuxer.Open(path, format)) {
  400. qDebug() << "Failed to open muxer with path:" << QString::fromStdString(std::string(path)) << "format:" << QString::fromStdString(std::string(format));
  401. return false;
  402. }
  403. if (!m_audioRecorder.LoadMuxer(m_avMuxer)) {
  404. qDebug() << "Failed to load muxer for audio recorder";
  405. return false;
  406. }
  407. if (!m_videoRecorder.LoadMuxer(m_avMuxer)) {
  408. qDebug() << "Failed to load muxer for video recorder";
  409. return false;
  410. }
  411. if (!m_avMuxer.WriteHeader()) {
  412. qDebug() << "Failed to write muxer header";
  413. return false;
  414. }
  415. if (!m_audioRecorder.StartRecord()) {
  416. qDebug() << "Failed to start audio recording";
  417. return false;
  418. }
  419. if (!m_videoRecorder.StartRecord()) {
  420. qDebug() << "Failed to start video recording";
  421. return false;
  422. }
  423. // 同步:展示实际使用的编码器名称(考虑自动回退后的结果)
  424. {
  425. std::string used = m_videoRecorder.GetEncoderNameForMuxer(m_avMuxer);
  426. if (!used.empty()) {
  427. m_videoEncodeLabel->setText((std::string("编码器: ") + used).c_str());
  428. }
  429. std::string aused = m_audioRecorder.GetEncoderNameForMuxer(m_avMuxer);
  430. if (!aused.empty()) {
  431. m_audioEncodeLabel->setText((std::string("音频编码器: ") + aused).c_str());
  432. }
  433. }
  434. m_recordTime = QTime::currentTime();
  435. m_captureStatusLabel->setText("状态: 正在工作");
  436. m_settingsBtn->setEnabled(false);
  437. m_captureComboBox->setEnabled(false); // 禁用采集源切换
  438. m_syncRecordBox->setEnabled(false);
  439. m_updateListBtn->setEnabled(false);
  440. m_captureMethodBox->setEnabled(false); // 禁用采集方式切换
  441. // 注意:不要在这里修改 m_isLive,由调用方(按钮逻辑)根据场景设置
  442. return true;
  443. }
  444. void AvRecorder::stopStream()
  445. {
  446. m_audioRecorder.StopRecord();
  447. m_videoRecorder.StopRecord();
  448. // 从录制器中卸载直播muxer
  449. m_audioRecorder.UnloadMuxer(m_avMuxer);
  450. m_videoRecorder.UnloadMuxer(m_avMuxer);
  451. m_avMuxer.Close();
  452. // 如果有同步录像,也需要关闭
  453. if (m_isSyncRecord) {
  454. // 先从录制器中卸载同步录像muxer
  455. m_audioRecorder.UnloadMuxer(m_recordMuxer);
  456. m_videoRecorder.UnloadMuxer(m_recordMuxer);
  457. m_recordMuxer.Close();
  458. m_isSyncRecord = false;
  459. }
  460. m_captureStatusLabel->setText("状态: 正常");
  461. m_settingsBtn->setEnabled(true);
  462. m_captureComboBox->setEnabled(true); // 恢复采集源切换
  463. m_syncRecordBox->setEnabled(true);
  464. m_updateListBtn->setEnabled(true);
  465. m_captureMethodBox->setEnabled(true); // 恢复采集方式切换
  466. }
  467. bool AvRecorder::startSyncRecord()
  468. {
  469. // 检查是否已经在同步录像
  470. if (m_isSyncRecord) {
  471. qDebug() << "Sync recording is already active";
  472. return true;
  473. }
  474. // 检查是否正在直播(必须在直播状态下才能启动同步录像)
  475. if (!m_isLive) {
  476. qDebug() << "Cannot start sync recording: not in live streaming mode";
  477. return false;
  478. }
  479. auto fileName = m_settingsParam.outputDir;
  480. if (fileName.back() != '\\') {
  481. fileName.push_back('\\');
  482. }
  483. auto format = "mp4";
  484. fileName += QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss").toStdString()
  485. + "_sync." + format;
  486. // 打开同步录像的muxer
  487. if (!m_recordMuxer.Open(fileName, format)) {
  488. qDebug() << "Failed to open sync record muxer";
  489. return false;
  490. }
  491. // 加载muxer到录制器
  492. if (!m_audioRecorder.LoadMuxer(m_recordMuxer)) {
  493. qDebug() << "Failed to load sync muxer for audio recorder";
  494. m_recordMuxer.Close();
  495. return false;
  496. }
  497. if (!m_videoRecorder.LoadMuxer(m_recordMuxer)) {
  498. qDebug() << "Failed to load sync muxer for video recorder";
  499. m_audioRecorder.UnloadMuxer(m_recordMuxer);
  500. m_recordMuxer.Close();
  501. return false;
  502. }
  503. // 写入头部
  504. if (!m_recordMuxer.WriteHeader()) {
  505. qDebug() << "Failed to write sync muxer header";
  506. m_audioRecorder.UnloadMuxer(m_recordMuxer);
  507. m_videoRecorder.UnloadMuxer(m_recordMuxer);
  508. m_recordMuxer.Close();
  509. return false;
  510. }
  511. m_isSyncRecord = true;
  512. qDebug() << "Sync recording started successfully: " << QString::fromStdString(fileName);
  513. return true;
  514. }
  515. void AvRecorder::stopSyncRecord()
  516. {
  517. if (m_isSyncRecord) {
  518. // 先从录制器中卸载muxer
  519. m_audioRecorder.UnloadMuxer(m_recordMuxer);
  520. m_videoRecorder.UnloadMuxer(m_recordMuxer);
  521. // 然后关闭muxer
  522. m_recordMuxer.Close();
  523. m_isSyncRecord = false;
  524. }
  525. }
  526. void AvRecorder::updateCaptureList()
  527. {
  528. m_captureComboBox->clear();
  529. auto&& monitorList = MonitorFinder::GetList(true);
  530. for (auto&& monitor : monitorList) {
  531. QString text = "屏幕: " + QString::fromStdWString(monitor.title);
  532. m_captureComboBox->addItem(text, QVariant::fromValue(qintptr(monitor.monitor)));
  533. }
  534. auto&& windowList = WindowFinder::GetList(true);
  535. for (auto&& window : windowList) {
  536. QString text = "窗口: " + QString::fromStdWString(window.title);
  537. m_captureComboBox->addItem(text, QVariant::fromValue(qintptr(window.hwnd)));
  538. }
  539. }
  540. void AvRecorder::initStatusBarUi()
  541. {
  542. m_videoEncodeLabel = new QLabel;
  543. m_audioEncodeLabel = new QLabel;
  544. auto hLayout = new QHBoxLayout;
  545. hLayout->setContentsMargins(0, 0, 0, 0);
  546. hLayout->addWidget(new QLabel("捕获方式:"));
  547. m_captureMethodBox = new QComboBox;
  548. hLayout->addWidget(m_captureMethodBox);
  549. m_captureStatusLabel = new QLabel("状态: 正常");
  550. m_captureTimeLabel = new QLabel("00:00:00");
  551. m_videolossRate = new QLabel("丢帧率: 00.00%");
  552. m_fpsLabel = new QLabel("FPS: 30");
  553. // 创建状态栏并添加到布局中
  554. m_statusBar = new QStatusBar(this);
  555. m_statusBar->setSizeGripEnabled(false);
  556. // 添加各个状态信息到状态栏
  557. m_statusBar->addWidget(m_videoEncodeLabel);
  558. m_statusBar->addWidget(m_audioEncodeLabel);
  559. auto widget = new QWidget;
  560. widget->setLayout(hLayout);
  561. m_statusBar->addWidget(widget);
  562. m_statusBar->addWidget(m_videolossRate);
  563. m_statusBar->addWidget(m_captureStatusLabel);
  564. m_statusBar->addWidget(m_captureTimeLabel);
  565. m_statusBar->addWidget(m_fpsLabel);
  566. }
  567. void AvRecorder::updateCaptureMethodBox(bool isMonitor) {
  568. m_captureMethodBox->clear();
  569. m_captureMethodBox->addItem("WGC");
  570. if (isMonitor) {
  571. m_captureMethodBox->addItem("DXGI");
  572. } else {
  573. m_captureMethodBox->addItem("GDI");
  574. }
  575. }
  576. // 捕获源切换时调用
  577. void AvRecorder::onCaptureSourceChanged() {
  578. int idx = m_captureComboBox->currentIndex();
  579. int monitorCnt = (int)MonitorFinder::GetList().size();
  580. bool isMonitor = (idx >= 0 && idx < monitorCnt);
  581. updateCaptureMethodBox(isMonitor);
  582. // 新增:推流/录制时切换采集源不中断
  583. if (m_isRecord || m_isLive) {
  584. CaptureMethod method = CaptureMethod::WGC;
  585. QString methodText = m_captureMethodBox->currentText();
  586. if (methodText == "DXGI") method = CaptureMethod::DXGI;
  587. else if (methodText == "GDI") method = CaptureMethod::GDI;
  588. if (isMonitor) {
  589. m_videoRecorder.SetCaptureSource(idx, method);
  590. } else {
  591. qintptr ptrHwnd = m_captureComboBox->currentData().value<qintptr>();
  592. m_videoRecorder.SetCaptureSource((HWND)ptrHwnd, method);
  593. }
  594. }
  595. }