av_recorder.cpp 26 KB

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