av_recorder.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  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,
  189. &CaptureSourceWidget::captureSourceTextChanged,
  190. this,
  191. [this](const QString& text) {
  192. if (text.isEmpty() || m_isLocked) {
  193. return;
  194. }
  195. m_isLocked = true;
  196. if (!(m_isRecord || m_isLive)) {
  197. stopPreview();
  198. stopCapture();
  199. startCapture(CaptureMethod::DXGI);
  200. startPreview();
  201. }
  202. m_isLocked = false;
  203. });
  204. connect(m_captureSourceWidget,
  205. &CaptureSourceWidget::captureSourceIndexChanged,
  206. this,
  207. &AvRecorder::onCaptureSourceChanged);
  208. connect(m_captureSourceWidget, &CaptureSourceWidget::refreshRequested, this, []() {
  209. // 刷新请求处理,可以在这里添加额外的逻辑
  210. qDebug() << "Capture source list refreshed";
  211. });
  212. connect(m_isDrawCursorBox, &QCheckBox::stateChanged, this, [this] {
  213. m_videoRecorder.SetIsDrawCursor(m_isDrawCursorBox->isChecked());
  214. });
  215. connect(m_captureMethodBox, &QComboBox::currentTextChanged, this, [this](const QString& text) {
  216. if (m_isLocked || text.isEmpty()) {
  217. return;
  218. }
  219. stopPreview();
  220. stopCapture();
  221. if (text == "WGC") {
  222. startCapture(CaptureMethod::WGC);
  223. } else if (text == "DXGI") {
  224. startCapture(CaptureMethod::DXGI);
  225. } else {
  226. startCapture(CaptureMethod::GDI);
  227. }
  228. startPreview();
  229. });
  230. connect(m_settingsBtn, &QPushButton::released, this, [this] {
  231. // 运行中禁止打开设置以切换编码器,避免异常
  232. if (m_isRecord || m_isLive || m_isSyncRecord) {
  233. QMessageBox::warning(this,
  234. "提示",
  235. "正在直播/录制,无法修改编码器设置。请先停止后再修改。");
  236. return;
  237. }
  238. auto settingsPage = std::make_unique<SettingsPage>(&m_settingsParam, this);
  239. settingsPage->exec();
  240. m_isLocked = true;
  241. stopPreview();
  242. stopCapture();
  243. startCapture(CaptureMethod::DXGI);
  244. startPreview();
  245. m_isLocked = false;
  246. });
  247. m_otherTimer.callOnTimeout([this] {
  248. if (windowState() == Qt::WindowMinimized) {
  249. return;
  250. }
  251. // 音频
  252. auto info = m_audioRecorder.GetCaptureInfo(MICROPHONE_INDEX);
  253. m_microphoneWidget->ShowVolume(info == nullptr ? 0 : info->volume);
  254. info = m_audioRecorder.GetCaptureInfo(SPEAKER_INDEX);
  255. m_speakerWidget->ShowVolume(info == nullptr ? 0 : info->volume);
  256. // 状态栏
  257. if (m_isRecord || m_isLive) {
  258. int interval = m_recordTime.secsTo(QTime::currentTime());
  259. int sec = interval % 60;
  260. interval /= 60;
  261. int minute = interval % 60;
  262. int hour = interval / 60;
  263. m_captureTimeLabel->setText(QString("%1:%2:%3")
  264. .arg(hour, 2, 10, QChar('0'))
  265. .arg(minute, 2, 10, QChar('0'))
  266. .arg(sec, 2, 10, QChar('0')));
  267. auto lossRate = m_videoRecorder.GetLossRate();
  268. if (lossRate < 0) {
  269. m_videolossRate->setText("丢帧率: 统计中");
  270. } else {
  271. int num = lossRate * 10000;
  272. m_videolossRate->setText(QString("丢帧率: %1.%2%")
  273. .arg(num / 100, 2, 10, QChar('0'))
  274. .arg(num % 100, 2, 10, QChar('0')));
  275. }
  276. } else if (m_captureTimeLabel->text() != "00:00:00") {
  277. m_captureTimeLabel->setText("00:00:00");
  278. }
  279. });
  280. }
  281. AvRecorder::~AvRecorder()
  282. {
  283. stopSyncRecord();
  284. stopStream();
  285. stopPreview();
  286. stopCapture();
  287. }
  288. bool AvRecorder::start()
  289. {
  290. auto timer = new QTimer(this);
  291. connect(timer, &QTimer::timeout, this, [this, timer] {
  292. m_isLocked = true;
  293. stopPreview();
  294. stopCapture();
  295. startCapture(CaptureMethod::DXGI);
  296. startPreview();
  297. m_isLocked = false;
  298. timer->stop();
  299. });
  300. timer->start(100);
  301. return true;
  302. }
  303. void AvRecorder::startCapture(CaptureMethod method)
  304. {
  305. int idx = m_captureSourceWidget->getCurrentIndex();
  306. if (idx < 0)
  307. return;
  308. int monitorCnt = (int) MonitorFinder::GetList().size();
  309. QString type = (idx < monitorCnt) ? "monitor" : "window";
  310. qintptr ptrHwnd = m_captureSourceWidget->getCurrentData().value<qintptr>();
  311. bool ok = false;
  312. if (m_isRecord || m_isLive) {
  313. // 推流/录制时,安全切换采集源
  314. if (idx < monitorCnt) {
  315. m_videoRecorder.SetCaptureSource(idx, method);
  316. ok = true;
  317. } else if (type == "window" && ::IsWindow((HWND) ptrHwnd)) {
  318. m_videoRecorder.SetCaptureSource((HWND) ptrHwnd, method);
  319. ok = true;
  320. }
  321. } else {
  322. // 未推流/录制时,正常 open
  323. if (idx < monitorCnt) { // 捕获屏幕
  324. ok = m_videoRecorder.Open(idx, m_settingsParam.videoParam, method);
  325. } else if (type == "window" && ::IsWindow((HWND) ptrHwnd)) {
  326. ok = m_videoRecorder.Open((HWND) ptrHwnd, m_settingsParam.videoParam, method);
  327. }
  328. }
  329. if (!ok) {
  330. // 可选:弹窗或日志提示
  331. return;
  332. }
  333. dealCapture();
  334. m_isDrawCursorBox->setEnabled(true);
  335. m_recordBtn->setEnabled(true);
  336. m_liveBtn->setEnabled(true);
  337. m_videoRecorder.SetIsDrawCursor(m_isDrawCursorBox->isChecked());
  338. m_audioRecorder.SetVolumeScale(m_microphoneWidget->GetVolume(), MICROPHONE_INDEX);
  339. m_audioRecorder.SetVolumeScale(m_speakerWidget->GetVolume(), SPEAKER_INDEX);
  340. }
  341. void AvRecorder::dealCapture()
  342. {
  343. if (!m_audioRecorder.Open({AudioCapturer::Microphone, AudioCapturer::Speaker},
  344. m_settingsParam.audioParam)) {
  345. qDebug() << "AudioRecorder::Open failed";
  346. return;
  347. }
  348. m_microphoneWidget->setEnabled(m_audioRecorder.GetCaptureInfo(MICROPHONE_INDEX) != nullptr);
  349. m_speakerWidget->setEnabled(m_audioRecorder.GetCaptureInfo(SPEAKER_INDEX) != nullptr);
  350. m_fpsLabel->setText(QString("FPS: %1").arg(m_settingsParam.videoParam.fps));
  351. m_videoEncodeLabel->setText(("编码器: " + m_settingsParam.videoParam.name).c_str());
  352. if (m_audioEncodeLabel) {
  353. m_audioEncodeLabel->setText(("音频编码器: " + m_settingsParam.audioParam.name).c_str());
  354. }
  355. }
  356. void AvRecorder::stopCapture()
  357. {
  358. m_videoRecorder.Close();
  359. m_audioRecorder.Close();
  360. }
  361. void AvRecorder::renderFrame()
  362. {
  363. auto frame = m_videoRecorder.GetRenderFrame();
  364. if (!frame) {
  365. qDebug() << "renderFrame error";
  366. return;
  367. }
  368. AVFrame* copiedFrame = av_frame_clone(frame);
  369. // m_glWidget->Render(copiedFrame);
  370. QMetaObject::invokeMethod(m_glWidget,
  371. "Render",
  372. Qt::QueuedConnection,
  373. Q_ARG(AVFrame*, copiedFrame));
  374. }
  375. void AvRecorder::startPreview()
  376. {
  377. m_glWidget->Open(m_settingsParam.videoParam.width, m_settingsParam.videoParam.height);
  378. // 视频需要做到和帧率一样的渲染速度,QTimer 达不到要求
  379. // 需要自己封装一个计时器
  380. // m_videoRenderTimer.Start(m_settingsParam.videoParam.fps, [this] {
  381. // if (windowState() == Qt::WindowMinimized) {
  382. // return;
  383. // }
  384. // QMetaObject::invokeMethod(this, "renderFrame", Qt::QueuedConnection);
  385. // // // 视频
  386. // // auto frame = m_videoRecorder.GetRenderFrame();
  387. // // m_glWidget->Render(frame);
  388. // });
  389. if (!m_videoRenderTimer) {
  390. m_videoRenderTimer = new QTimer(this);
  391. connect(m_videoRenderTimer, &QTimer::timeout, this, [this] {
  392. if (windowState() == Qt::WindowMinimized)
  393. return;
  394. renderFrame();
  395. });
  396. }
  397. m_videoRenderTimer->start(1000 / m_settingsParam.videoParam.fps);
  398. // 刷新率设置为 25
  399. m_otherTimer.start(40);
  400. }
  401. void AvRecorder::stopPreview()
  402. {
  403. if (m_videoRenderTimer) {
  404. m_videoRenderTimer->stop();
  405. }
  406. m_otherTimer.stop();
  407. }
  408. bool AvRecorder::startStream(std::string_view path, std::string_view format)
  409. {
  410. if (!m_avMuxer.Open(path, format)) {
  411. qDebug() << "Failed to open muxer with path:" << QString::fromStdString(std::string(path))
  412. << "format:" << QString::fromStdString(std::string(format));
  413. return false;
  414. }
  415. if (!m_audioRecorder.LoadMuxer(m_avMuxer)) {
  416. qDebug() << "Failed to load muxer for audio recorder";
  417. return false;
  418. }
  419. if (!m_videoRecorder.LoadMuxer(m_avMuxer)) {
  420. qDebug() << "Failed to load muxer for video recorder";
  421. return false;
  422. }
  423. if (!m_avMuxer.WriteHeader()) {
  424. qDebug() << "Failed to write muxer header";
  425. return false;
  426. }
  427. if (!m_audioRecorder.StartRecord()) {
  428. qDebug() << "Failed to start audio recording";
  429. return false;
  430. }
  431. if (!m_videoRecorder.StartRecord()) {
  432. qDebug() << "Failed to start video recording";
  433. return false;
  434. }
  435. // 同步:展示实际使用的编码器名称(考虑自动回退后的结果)
  436. {
  437. std::string used = m_videoRecorder.GetEncoderNameForMuxer(m_avMuxer);
  438. if (!used.empty()) {
  439. m_videoEncodeLabel->setText((std::string("编码器: ") + used).c_str());
  440. }
  441. std::string aused = m_audioRecorder.GetEncoderNameForMuxer(m_avMuxer);
  442. if (!aused.empty()) {
  443. m_audioEncodeLabel->setText((std::string("音频编码器: ") + aused).c_str());
  444. }
  445. }
  446. m_recordTime = QTime::currentTime();
  447. m_captureStatusLabel->setText("状态: 正在工作");
  448. m_settingsBtn->setEnabled(false);
  449. m_captureSourceWidget->setEnabled(false); // 禁用采集源切换
  450. m_syncRecordBox->setEnabled(false);
  451. m_captureMethodBox->setEnabled(false); // 禁用采集方式切换
  452. // 注意:不要在这里修改 m_isLive,由调用方(按钮逻辑)根据场景设置
  453. return true;
  454. }
  455. void AvRecorder::stopStream()
  456. {
  457. m_audioRecorder.StopRecord();
  458. m_videoRecorder.StopRecord();
  459. // 从录制器中卸载直播muxer
  460. m_audioRecorder.UnloadMuxer(m_avMuxer);
  461. m_videoRecorder.UnloadMuxer(m_avMuxer);
  462. m_avMuxer.Close();
  463. // 如果有同步录像,也需要关闭
  464. if (m_isSyncRecord) {
  465. // 先从录制器中卸载同步录像muxer
  466. m_audioRecorder.UnloadMuxer(m_recordMuxer);
  467. m_videoRecorder.UnloadMuxer(m_recordMuxer);
  468. m_recordMuxer.Close();
  469. m_isSyncRecord = false;
  470. }
  471. m_captureStatusLabel->setText("状态: 正常");
  472. m_settingsBtn->setEnabled(true);
  473. m_captureSourceWidget->setEnabled(true); // 恢复采集源切换
  474. m_syncRecordBox->setEnabled(true);
  475. m_captureMethodBox->setEnabled(true); // 恢复采集方式切换
  476. }
  477. bool AvRecorder::startSyncRecord()
  478. {
  479. // 检查是否已经在同步录像
  480. if (m_isSyncRecord) {
  481. qDebug() << "Sync recording is already active";
  482. return true;
  483. }
  484. // 检查是否正在直播(必须在直播状态下才能启动同步录像)
  485. if (!m_isLive) {
  486. qDebug() << "Cannot start sync recording: not in live streaming mode";
  487. return false;
  488. }
  489. auto fileName = m_settingsParam.outputDir;
  490. if (fileName.back() != '\\') {
  491. fileName.push_back('\\');
  492. }
  493. auto format = "mp4";
  494. fileName += QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss").toStdString()
  495. + "_sync." + format;
  496. // 打开同步录像的muxer
  497. if (!m_recordMuxer.Open(fileName, format)) {
  498. qDebug() << "Failed to open sync record muxer";
  499. return false;
  500. }
  501. // 加载muxer到录制器
  502. if (!m_audioRecorder.LoadMuxer(m_recordMuxer)) {
  503. qDebug() << "Failed to load sync muxer for audio recorder";
  504. m_recordMuxer.Close();
  505. return false;
  506. }
  507. if (!m_videoRecorder.LoadMuxer(m_recordMuxer)) {
  508. qDebug() << "Failed to load sync muxer for video recorder";
  509. m_audioRecorder.UnloadMuxer(m_recordMuxer);
  510. m_recordMuxer.Close();
  511. return false;
  512. }
  513. // 写入头部
  514. if (!m_recordMuxer.WriteHeader()) {
  515. qDebug() << "Failed to write sync muxer header";
  516. m_audioRecorder.UnloadMuxer(m_recordMuxer);
  517. m_videoRecorder.UnloadMuxer(m_recordMuxer);
  518. m_recordMuxer.Close();
  519. return false;
  520. }
  521. m_isSyncRecord = true;
  522. qDebug() << "Sync recording started successfully: " << QString::fromStdString(fileName);
  523. return true;
  524. }
  525. void AvRecorder::stopSyncRecord()
  526. {
  527. if (m_isSyncRecord) {
  528. // 先从录制器中卸载muxer
  529. m_audioRecorder.UnloadMuxer(m_recordMuxer);
  530. m_videoRecorder.UnloadMuxer(m_recordMuxer);
  531. // 然后关闭muxer
  532. m_recordMuxer.Close();
  533. m_isSyncRecord = false;
  534. }
  535. }
  536. void AvRecorder::initStatusBarUi()
  537. {
  538. m_videoEncodeLabel = new QLabel;
  539. m_audioEncodeLabel = new QLabel;
  540. auto hLayout = new QHBoxLayout;
  541. hLayout->setContentsMargins(0, 0, 0, 0);
  542. hLayout->addWidget(new QLabel("捕获方式:"));
  543. m_captureMethodBox = new QComboBox;
  544. hLayout->addWidget(m_captureMethodBox);
  545. m_captureStatusLabel = new QLabel("状态: 正常");
  546. m_captureTimeLabel = new QLabel("00:00:00");
  547. m_videolossRate = new QLabel("丢帧率: 00.00%");
  548. m_fpsLabel = new QLabel("FPS: 30");
  549. // 创建状态栏并添加到布局中
  550. m_statusBar = new QStatusBar(this);
  551. m_statusBar->setSizeGripEnabled(false);
  552. // 添加各个状态信息到状态栏
  553. m_statusBar->addWidget(m_videoEncodeLabel);
  554. m_statusBar->addWidget(m_audioEncodeLabel);
  555. auto widget = new QWidget;
  556. widget->setLayout(hLayout);
  557. m_statusBar->addWidget(widget);
  558. m_statusBar->addWidget(m_videolossRate);
  559. m_statusBar->addWidget(m_captureStatusLabel);
  560. m_statusBar->addWidget(m_captureTimeLabel);
  561. m_statusBar->addWidget(m_fpsLabel);
  562. }
  563. void AvRecorder::updateCaptureMethodBox(bool isMonitor)
  564. {
  565. m_captureMethodBox->clear();
  566. m_captureMethodBox->addItem("WGC");
  567. if (isMonitor) {
  568. m_captureMethodBox->addItem("DXGI");
  569. } else {
  570. m_captureMethodBox->addItem("GDI");
  571. }
  572. }
  573. // 捕获源切换时调用
  574. void AvRecorder::onCaptureSourceChanged()
  575. {
  576. int idx = m_captureSourceWidget->getCurrentIndex();
  577. int monitorCnt = (int) MonitorFinder::GetList().size();
  578. bool isMonitor = (idx >= 0 && idx < monitorCnt);
  579. updateCaptureMethodBox(isMonitor);
  580. // 新增:推流/录制时切换采集源不中断
  581. if (m_isRecord || m_isLive) {
  582. CaptureMethod method = CaptureMethod::DXGI;
  583. QString methodText = m_captureMethodBox->currentText();
  584. if (methodText == "DXGI")
  585. method = CaptureMethod::DXGI;
  586. else if (methodText == "GDI")
  587. method = CaptureMethod::GDI;
  588. else
  589. method = CaptureMethod::WGC;
  590. if (isMonitor) {
  591. m_videoRecorder.SetCaptureSource(idx, method);
  592. } else {
  593. qintptr ptrHwnd = m_captureSourceWidget->getCurrentData().value<qintptr>();
  594. m_videoRecorder.SetCaptureSource((HWND) ptrHwnd, method);
  595. }
  596. }
  597. }
  598. void AvRecorder::showAudioDeviceMenu()
  599. {
  600. QMenu* menu = new QMenu(this);
  601. // // 麦克风设备子菜单
  602. // QMenu *micMenu = menu->addMenu("麦克风设备");
  603. // const auto inputDevices = QMediaDevices::audioInputs();
  604. // for (const auto &device : inputDevices) {
  605. // QAction *action = micMenu->addAction(device.description());
  606. // action->setData(device.id());
  607. // action->setCheckable(true);
  608. // if (device == QMediaDevices::defaultAudioInput()) {
  609. // action->setChecked(true);
  610. // action->setText(device.description() + " (默认)");
  611. // }
  612. // connect(action, &QAction::triggered, this, [this, device]() {
  613. // qDebug() << "选择麦克风设备:" << device.description() << "ID:" << device.id();
  614. // // 这里可以添加实际的设备切换逻辑
  615. // if (m_microphoneWidget) {
  616. // // 更新麦克风组件显示
  617. // }
  618. // });
  619. // }
  620. // menu->addSeparator();
  621. // // 扬声器设备子菜单
  622. // QMenu *speakerMenu = menu->addMenu("扬声器设备");
  623. // const auto outputDevices = QMediaDevices::audioOutputs();
  624. // for (const auto &device : outputDevices) {
  625. // QAction *action = speakerMenu->addAction(device.description());
  626. // action->setData(device.id());
  627. // action->setCheckable(true);
  628. // if (device == QMediaDevices::defaultAudioOutput()) {
  629. // action->setChecked(true);
  630. // action->setText(device.description() + " (默认)");
  631. // }
  632. // connect(action, &QAction::triggered, this, [this, device]() {
  633. // qDebug() << "选择扬声器设备:" << device.description() << "ID:" << device.id();
  634. // // 这里可以添加实际的设备切换逻辑
  635. // if (m_speakerWidget) {
  636. // // 更新扬声器组件显示
  637. // }
  638. // });
  639. // }
  640. menu->addSeparator();
  641. // 刷新设备列表
  642. QAction* refreshAction = menu->addAction("刷新设备列表");
  643. connect(refreshAction, &QAction::triggered, this, [this]() {
  644. qDebug() << "刷新音频设备列表";
  645. // 重新显示菜单以刷新设备列表
  646. QTimer::singleShot(100, this, &AvRecorder::showAudioDeviceMenu);
  647. });
  648. // 在按钮下方显示菜单
  649. QPoint pos = m_audioDeviceBtn->mapToGlobal(QPoint(0, m_audioDeviceBtn->height()));
  650. menu->exec(pos);
  651. menu->deleteLater();
  652. }
  653. void AvRecorder::onMicrophoneDeviceSelected()
  654. {
  655. // 麦克风设备选择处理
  656. }
  657. void AvRecorder::onSpeakerDeviceSelected()
  658. {
  659. // 扬声器设备选择处理
  660. }