av_recorder.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. #include "av_recorder.h"
  2. #include <QDateTime>
  3. #include <QStatusBar>
  4. #include <capturer/finder.h>
  5. #include "avrecorder/capturer/video/VideoCaptureManager.h"
  6. using namespace avrecorder::video;
  7. AvRecorder::AvRecorder(QWidget* parent)
  8. : QWidget(parent)
  9. {
  10. setWindowTitle("Recorder");
  11. m_settingsParam.audioParam.bitRate = 160'000;
  12. m_settingsParam.videoParam.bitRate = 8'000'000;
  13. m_settingsParam.videoParam.fps = 30;
  14. m_settingsParam.videoParam.name = Encoder<MediaType::VIDEO>::GetUsableEncoders().front();
  15. m_settingsParam.outputDir = ".";
  16. m_settingsParam.liveUrl = "rtmp://192.168.3.76:1935/stream/V1";
  17. m_settingsParam.liveName = "stream";
  18. // 1. 视频预览区
  19. m_glWidget = new OpenGLVideoWidget(this);
  20. // 2. 音频区
  21. m_microphoneWidget = new AudioWidget;
  22. m_speakerWidget = new AudioWidget;
  23. m_microphoneWidget->SetName("麦克风");
  24. m_speakerWidget->SetName("扬声器");
  25. // 3. 捕获区
  26. m_captureComboBox = new QComboBox;
  27. m_updateListBtn = new QPushButton("刷新窗口列表");
  28. QGroupBox* captureGroup = new QGroupBox("捕获源");
  29. QHBoxLayout* captureRow = new QHBoxLayout;
  30. captureRow->addWidget(m_captureComboBox);
  31. captureRow->addWidget(m_updateListBtn);
  32. captureGroup->setLayout(captureRow);
  33. // m_captureComboBox->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
  34. m_captureComboBox->setMinimumWidth(20);
  35. // 4. 音频区分组
  36. QGroupBox* audioGroup = new QGroupBox("音频");
  37. QVBoxLayout* audioLayout = new QVBoxLayout;
  38. audioLayout->addWidget(m_microphoneWidget);
  39. audioLayout->addWidget(m_speakerWidget);
  40. audioGroup->setLayout(audioLayout);
  41. //audioGroup->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum);
  42. // 5. 操作区
  43. m_isDrawCursorBox = new QCheckBox("绘制鼠标指针");
  44. m_isDrawCursorBox->setChecked(true);
  45. m_isDrawCursorBox->setEnabled(false);
  46. m_syncRecordBox = new QCheckBox("直播时同步录像");
  47. m_syncRecordBox->setChecked(false);
  48. m_recordBtn = new QPushButton("开始录制");
  49. m_recordBtn->setEnabled(false);
  50. m_liveBtn = new QPushButton("开始直播");
  51. m_liveBtn->setEnabled(false);
  52. m_settingsBtn = new QPushButton("设置");
  53. QGroupBox* actionGroup = new QGroupBox("操作");
  54. QVBoxLayout* actionLayout = new QVBoxLayout;
  55. QHBoxLayout* checkBoxRow = new QHBoxLayout;
  56. checkBoxRow->setContentsMargins(0, 0, 0, 0);
  57. checkBoxRow->setSpacing(8);
  58. checkBoxRow->addWidget(m_syncRecordBox);
  59. checkBoxRow->addWidget(m_isDrawCursorBox);
  60. actionLayout->addLayout(checkBoxRow);
  61. actionLayout->addWidget(m_recordBtn);
  62. actionLayout->addWidget(m_liveBtn);
  63. actionGroup->setLayout(actionLayout);
  64. //actionGroup->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Maximum);
  65. // 6. 设置区
  66. QHBoxLayout* utilLayout = new QHBoxLayout;
  67. utilLayout->addWidget(m_settingsBtn);
  68. // 7. 左侧功能区(捕获区在上,音频区在下)
  69. QVBoxLayout* leftLayout = new QVBoxLayout;
  70. leftLayout->addWidget(captureGroup);
  71. leftLayout->addWidget(audioGroup);
  72. leftLayout->addStretch();
  73. // 8. 右侧功能区
  74. QVBoxLayout* rightLayout = new QVBoxLayout;
  75. rightLayout->addWidget(actionGroup);
  76. rightLayout->addLayout(utilLayout);
  77. rightLayout->addStretch();
  78. // 9. 中部主布局
  79. QHBoxLayout* centerLayout = new QHBoxLayout;
  80. centerLayout->addLayout(leftLayout, 2);
  81. centerLayout->addLayout(rightLayout, 3);
  82. // 10. 状态栏
  83. initStatusBarUi();
  84. // 让视频区尽量大
  85. // m_glWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
  86. // 11. 总体布局
  87. QVBoxLayout* mainLayout = new QVBoxLayout(this);
  88. mainLayout->addWidget(m_glWidget, 100);
  89. mainLayout->addLayout(centerLayout, 0);
  90. mainLayout->addWidget(m_statusBar, 0);
  91. setLayout(mainLayout);
  92. // 12. 连接信号槽、初始化数据
  93. initConnect();
  94. updateCaptureList();
  95. }
  96. void AvRecorder::setSettings(const SettingsPage::Param& param)
  97. {
  98. m_settingsParam.audioParam.bitRate = 160'000;
  99. m_settingsParam.videoParam.bitRate = 8'000'000;
  100. m_settingsParam.videoParam.fps = 30;
  101. m_settingsParam.videoParam.name = Encoder<MediaType::VIDEO>::GetUsableEncoders().front();
  102. m_settingsParam.outputDir = ".";
  103. m_settingsParam.liveUrl = param.liveUrl; // "rtmp://192.168.3.76:1935/stream/V1";
  104. m_settingsParam.liveName = param.liveName; // "stream";
  105. }
  106. void AvRecorder::initConnect()
  107. {
  108. connect(m_recordBtn, &QPushButton::released, this, [this] {
  109. if (!m_isRecord) {
  110. auto fileName = m_settingsParam.outputDir;
  111. if (fileName.back() != '\\') {
  112. fileName.push_back('\\');
  113. }
  114. auto format = "mp4";
  115. fileName += QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss").toStdString()
  116. + "." + format;
  117. // fileName += std::string("test.") + format;
  118. __CheckNo(startStream(fileName, format));
  119. m_liveBtn->setEnabled(false);
  120. m_recordBtn->setText("停止录制");
  121. } else {
  122. stopStream();
  123. m_liveBtn->setEnabled(true);
  124. m_recordBtn->setText("开始录制");
  125. }
  126. m_isRecord = !m_isRecord;
  127. });
  128. connect(m_liveBtn, &QPushButton::released, this, [this] {
  129. if (!m_isLive) {
  130. auto fileName = m_settingsParam.liveUrl + "/" + m_settingsParam.liveName;
  131. bool isRtsp = m_settingsParam.liveUrl.find("rtsp") != std::string::npos;
  132. qDebug() << "直播地址:" << QString::fromStdString(fileName);
  133. __CheckNo(startStream(fileName, isRtsp ? "rtsp" : "flv"));
  134. // 如果勾选了同步录像,则开始录像
  135. if (m_syncRecordBox->isChecked()) {
  136. __CheckNo(startSyncRecord());
  137. }
  138. m_recordBtn->setEnabled(false);
  139. m_liveBtn->setText("停止直播");
  140. } else {
  141. // 先停止同步录像
  142. stopSyncRecord();
  143. // 再停止直播
  144. stopStream();
  145. m_recordBtn->setEnabled(true);
  146. m_liveBtn->setText("开始直播");
  147. }
  148. m_isLive = !m_isLive;
  149. });
  150. connect(m_microphoneWidget, &AudioWidget::SetVolumeScale, this, [this](float scale) {
  151. m_audioRecorder.SetVolumeScale(scale, MICROPHONE_INDEX);
  152. });
  153. connect(m_speakerWidget, &AudioWidget::SetVolumeScale, this, [this](float scale) {
  154. m_audioRecorder.SetVolumeScale(scale, SPEAKER_INDEX);
  155. });
  156. connect(m_updateListBtn, &QPushButton::released, this, [this] { updateCaptureList(); });
  157. connect(m_captureComboBox, &QComboBox::currentTextChanged, this, [this](const QString& text) {
  158. if (text.isEmpty() || m_isLocked) {
  159. return;
  160. }
  161. m_isLocked = true;
  162. stopPreview();
  163. stopCapture();
  164. startCapture(CaptureMethod::WGC);
  165. startPreview();
  166. m_isLocked = false;
  167. });
  168. connect(m_captureComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &AvRecorder::onCaptureSourceChanged);
  169. connect(m_isDrawCursorBox, &QCheckBox::stateChanged, this, [this] {
  170. m_videoRecorder.SetIsDrawCursor(m_isDrawCursorBox->isChecked());
  171. });
  172. connect(m_captureMethodBox, &QComboBox::currentTextChanged, this, [this](const QString& text) {
  173. if (m_isLocked || text.isEmpty()) {
  174. return;
  175. }
  176. stopPreview();
  177. stopCapture();
  178. if (text == "WGC") {
  179. startCapture(CaptureMethod::WGC);
  180. } else if (text == "DXGI") {
  181. startCapture(CaptureMethod::DXGI);
  182. } else {
  183. startCapture(CaptureMethod::GDI);
  184. }
  185. startPreview();
  186. });
  187. connect(m_settingsBtn, &QPushButton::released, this, [this] {
  188. auto settingsPage = std::make_unique<SettingsPage>(&m_settingsParam, this);
  189. settingsPage->exec();
  190. m_isLocked = true;
  191. stopPreview();
  192. stopCapture();
  193. startCapture(CaptureMethod::WGC);
  194. startPreview();
  195. m_isLocked = false;
  196. });
  197. m_otherTimer.callOnTimeout([this] {
  198. if (windowState() == Qt::WindowMinimized) {
  199. return;
  200. }
  201. // 音频
  202. auto info = m_audioRecorder.GetCaptureInfo(MICROPHONE_INDEX);
  203. m_microphoneWidget->ShowVolume(info == nullptr ? 0 : info->volume);
  204. info = m_audioRecorder.GetCaptureInfo(SPEAKER_INDEX);
  205. m_speakerWidget->ShowVolume(info == nullptr ? 0 : info->volume);
  206. // 状态栏
  207. if (m_isRecord || m_isLive) {
  208. int interval = m_recordTime.secsTo(QTime::currentTime());
  209. int sec = interval % 60;
  210. interval /= 60;
  211. int minute = interval % 60;
  212. int hour = interval / 60;
  213. m_captureTimeLabel->setText(QString("%1:%2:%3")
  214. .arg(hour, 2, 10, QChar('0'))
  215. .arg(minute, 2, 10, QChar('0'))
  216. .arg(sec, 2, 10, QChar('0')));
  217. auto lossRate = m_videoRecorder.GetLossRate();
  218. if (lossRate < 0) {
  219. m_videolossRate->setText("丢帧率: 统计中");
  220. } else {
  221. int num = lossRate * 10000;
  222. m_videolossRate->setText(QString("丢帧率: %1.%2%")
  223. .arg(num / 100, 2, 10, QChar('0'))
  224. .arg(num % 100, 2, 10, QChar('0')));
  225. }
  226. } else if (m_captureTimeLabel->text() != "00:00:00") {
  227. m_captureTimeLabel->setText("00:00:00");
  228. }
  229. });
  230. }
  231. AvRecorder::~AvRecorder()
  232. {
  233. stopSyncRecord();
  234. stopStream();
  235. stopPreview();
  236. stopCapture();
  237. }
  238. bool AvRecorder::start()
  239. {
  240. auto timer = new QTimer(this);
  241. connect(timer, &QTimer::timeout, this, [this, timer] {
  242. m_isLocked = true;
  243. stopPreview();
  244. stopCapture();
  245. startCapture(CaptureMethod::WGC);
  246. startPreview();
  247. m_isLocked = false;
  248. timer->stop();
  249. });
  250. timer->start(100);
  251. return true;
  252. }
  253. void AvRecorder::startCapture(CaptureMethod method)
  254. {
  255. int idx = m_captureComboBox->currentIndex();
  256. if (idx < 0) return;
  257. int monitorCnt = (int)MonitorFinder::GetList().size();
  258. QString type = (idx < monitorCnt) ? "monitor" : "window";
  259. qintptr ptrHwnd = m_captureComboBox->currentData().value<qintptr>();
  260. bool ok = false;
  261. if (idx < monitorCnt) { // 捕获屏幕
  262. ok = m_videoRecorder.Open(idx, m_settingsParam.videoParam, method);
  263. } else if (type == "window" && ::IsWindow((HWND)ptrHwnd)) {
  264. ok = m_videoRecorder.Open((HWND)ptrHwnd, m_settingsParam.videoParam, method);
  265. }
  266. if (!ok) {
  267. // 可选:弹窗或日志提示
  268. return;
  269. }
  270. dealCapture();
  271. m_isDrawCursorBox->setEnabled(true);
  272. m_recordBtn->setEnabled(true);
  273. m_liveBtn->setEnabled(true);
  274. m_videoRecorder.SetIsDrawCursor(m_isDrawCursorBox->isChecked());
  275. m_audioRecorder.SetVolumeScale(m_microphoneWidget->GetVolume(), MICROPHONE_INDEX);
  276. m_audioRecorder.SetVolumeScale(m_speakerWidget->GetVolume(), SPEAKER_INDEX);
  277. }
  278. void AvRecorder::dealCapture()
  279. {
  280. __CheckNo(m_audioRecorder.Open({AudioCapturer::Microphone, AudioCapturer::Speaker},
  281. m_settingsParam.audioParam));
  282. m_microphoneWidget->setEnabled(m_audioRecorder.GetCaptureInfo(MICROPHONE_INDEX) != nullptr);
  283. m_speakerWidget->setEnabled(m_audioRecorder.GetCaptureInfo(SPEAKER_INDEX) != nullptr);
  284. m_fpsLabel->setText(QString("FPS: %1").arg(m_settingsParam.videoParam.fps));
  285. m_videoEncodeLabel->setText(("编码器: " + m_settingsParam.videoParam.name).c_str());
  286. }
  287. void AvRecorder::stopCapture()
  288. {
  289. m_videoRecorder.Close();
  290. m_audioRecorder.Close();
  291. }
  292. void AvRecorder::renderFrame()
  293. {
  294. auto frame = m_videoRecorder.GetRenderFrame();
  295. m_glWidget->Render(frame);
  296. }
  297. void AvRecorder::startPreview()
  298. {
  299. m_glWidget->Open(m_settingsParam.videoParam.width, m_settingsParam.videoParam.height);
  300. // 视频需要做到和帧率一样的渲染速度,QTimer 达不到要求
  301. // 需要自己封装一个计时器
  302. // m_videoRenderTimer.Start(m_settingsParam.videoParam.fps, [this] {
  303. // if (windowState() == Qt::WindowMinimized) {
  304. // return;
  305. // }
  306. // QMetaObject::invokeMethod(this, "renderFrame", Qt::QueuedConnection);
  307. // // // 视频
  308. // // auto frame = m_videoRecorder.GetRenderFrame();
  309. // // m_glWidget->Render(frame);
  310. // });
  311. if (!m_videoRenderTimer) {
  312. m_videoRenderTimer = new QTimer(this);
  313. connect(m_videoRenderTimer, &QTimer::timeout, this, [this] {
  314. if (windowState() == Qt::WindowMinimized)
  315. return;
  316. renderFrame();
  317. });
  318. }
  319. m_videoRenderTimer->start(1000 / m_settingsParam.videoParam.fps);
  320. // 刷新率设置为 25
  321. m_otherTimer.start(40);
  322. }
  323. void AvRecorder::stopPreview()
  324. {
  325. if (m_videoRenderTimer) {
  326. m_videoRenderTimer->stop();
  327. }
  328. m_otherTimer.stop();
  329. }
  330. bool AvRecorder::startStream(std::string_view path, std::string_view format)
  331. {
  332. __CheckBool(m_avMuxer.Open(path, format));
  333. __CheckBool(m_audioRecorder.LoadMuxer(m_avMuxer));
  334. __CheckBool(m_videoRecorder.LoadMuxer(m_avMuxer));
  335. __CheckBool(m_avMuxer.WriteHeader());
  336. __CheckBool(m_audioRecorder.StartRecord());
  337. __CheckBool(m_videoRecorder.StartRecord());
  338. m_recordTime = QTime::currentTime();
  339. m_captureStatusLabel->setText("状态: 正在工作");
  340. m_settingsBtn->setEnabled(false);
  341. m_captureComboBox->setEnabled(false);
  342. m_updateListBtn->setEnabled(false);
  343. m_captureMethodBox->setEnabled(false);
  344. return true;
  345. }
  346. void AvRecorder::stopStream()
  347. {
  348. m_audioRecorder.StopRecord();
  349. m_videoRecorder.StopRecord();
  350. m_avMuxer.Close();
  351. // 如果有同步录像,也需要关闭
  352. if (m_isSyncRecord) {
  353. m_recordMuxer.Close();
  354. m_isSyncRecord = false;
  355. }
  356. m_captureStatusLabel->setText("状态: 正常");
  357. m_settingsBtn->setEnabled(true);
  358. m_captureComboBox->setEnabled(true);
  359. m_updateListBtn->setEnabled(true);
  360. m_captureMethodBox->setEnabled(true);
  361. }
  362. bool AvRecorder::startSyncRecord()
  363. {
  364. auto fileName = m_settingsParam.outputDir;
  365. if (fileName.back() != '\\') {
  366. fileName.push_back('\\');
  367. }
  368. auto format = "mp4";
  369. fileName += QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss").toStdString()
  370. + "_sync." + format;
  371. __CheckBool(m_recordMuxer.Open(fileName, format));
  372. __CheckBool(m_audioRecorder.LoadMuxer(m_recordMuxer));
  373. __CheckBool(m_videoRecorder.LoadMuxer(m_recordMuxer));
  374. __CheckBool(m_recordMuxer.WriteHeader());
  375. m_isSyncRecord = true;
  376. return true;
  377. }
  378. void AvRecorder::stopSyncRecord()
  379. {
  380. if (m_isSyncRecord) {
  381. m_recordMuxer.Close();
  382. m_isSyncRecord = false;
  383. }
  384. }
  385. void AvRecorder::updateCaptureList()
  386. {
  387. m_captureComboBox->clear();
  388. auto&& monitorList = MonitorFinder::GetList(true);
  389. for (auto&& monitor : monitorList) {
  390. QString text = "屏幕: " + QString::fromStdWString(monitor.title);
  391. m_captureComboBox->addItem(text, QVariant::fromValue(qintptr(monitor.monitor)));
  392. }
  393. auto&& windowList = WindowFinder::GetList(true);
  394. for (auto&& window : windowList) {
  395. QString text = "窗口: " + QString::fromStdWString(window.title);
  396. m_captureComboBox->addItem(text, QVariant::fromValue(qintptr(window.hwnd)));
  397. }
  398. }
  399. void AvRecorder::initStatusBarUi()
  400. {
  401. m_videoEncodeLabel = new QLabel;
  402. auto hLayout = new QHBoxLayout;
  403. hLayout->setContentsMargins(0, 0, 0, 0);
  404. hLayout->addWidget(new QLabel("捕获方式:"));
  405. m_captureMethodBox = new QComboBox;
  406. hLayout->addWidget(m_captureMethodBox);
  407. m_captureStatusLabel = new QLabel("状态: 正常");
  408. m_captureTimeLabel = new QLabel("00:00:00");
  409. m_videolossRate = new QLabel("丢帧率: 00.00%");
  410. m_fpsLabel = new QLabel("FPS: 30");
  411. // 创建状态栏并添加到布局中
  412. m_statusBar = new QStatusBar(this);
  413. m_statusBar->setSizeGripEnabled(false);
  414. // 添加各个状态信息到状态栏
  415. m_statusBar->addWidget(m_videoEncodeLabel);
  416. auto widget = new QWidget;
  417. widget->setLayout(hLayout);
  418. m_statusBar->addWidget(widget);
  419. m_statusBar->addWidget(m_videolossRate);
  420. m_statusBar->addWidget(m_captureStatusLabel);
  421. m_statusBar->addWidget(m_captureTimeLabel);
  422. m_statusBar->addWidget(m_fpsLabel);
  423. }
  424. void AvRecorder::updateCaptureMethodBox(bool isMonitor) {
  425. m_captureMethodBox->clear();
  426. m_captureMethodBox->addItem("WGC");
  427. if (isMonitor) {
  428. m_captureMethodBox->addItem("DXGI");
  429. } else {
  430. m_captureMethodBox->addItem("GDI");
  431. }
  432. }
  433. // 捕获源切换时调用
  434. void AvRecorder::onCaptureSourceChanged() {
  435. int idx = m_captureComboBox->currentIndex();
  436. int monitorCnt = (int)MonitorFinder::GetList().size();
  437. bool isMonitor = (idx >= 0 && idx < monitorCnt);
  438. updateCaptureMethodBox(isMonitor);
  439. }