av_recorder.cpp 25 KB

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