gsml_capturer_ori.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. #include "pch.h"
  2. #include "../common/comm.h"
  3. #include "./include/api.h"
  4. #include "lock.h"
  5. #include <iostream>
  6. #include <linux/videodev2.h>
  7. #include <poll.h>
  8. #include <sys/ioctl.h>
  9. #include <sys/stat.h>
  10. #include <sys/mman.h>
  11. #include <fcntl.h>
  12. #include <errno.h>
  13. #include <string>
  14. #include "capture_op.h"
  15. #include "gsml_capturer.h"
  16. rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> OpenGSMLCapture(CaptureOp* op)
  17. {
  18. auto video_capture=std::make_unique<GSMLCapturer>(op);
  19. video_capture->Start();
  20. rtc::scoped_refptr<GSMLTrackSource> video_source = GSMLTrackSource::Create(std::move(video_capture));
  21. return video_source;
  22. }
  23. GSMLCapturer::GSMLCapturer(CaptureOp* lhs):_op(lhs)
  24. {
  25. }
  26. void GSMLCapturer::Start()
  27. {
  28. _thread = std::thread(std::bind(&GSMLCapturer::Run, this));
  29. }
  30. //视频的捕获
  31. bool GSMLCapturer::open_cam()
  32. {
  33. // int32_t count=_op->GetType()==RenderPosition::FRONT_BACK?2:1;
  34. _op->_ctx0=(context_t *)malloc(sizeof(context_t));
  35. //for(int i=0;i<count;i++)
  36. {
  37. context_t * p=_op->_ctx0;
  38. p->cam_fd=-1;
  39. p->cam_pixfmt = V4L2_PIX_FMT_YUYV;
  40. p->cam_w = 1280;
  41. p->cam_h = 720;
  42. // p->frame = 0;
  43. p->g_buff = NULL;
  44. p->capture_dmabuf = false; // opencv display v4l2 can't be true
  45. p->fps = 30;
  46. p->enable_verbose = false;
  47. std::string devname="/dev/video" + std::to_string(_op->GetIndex());
  48. // std::cout<<"设备:"<<devname<<std::endl;
  49. //ctx.cam_devname=devname+std::to_string();
  50. p->cam_fd = open(devname.c_str(), O_RDWR); //打开视频设备
  51. if( p->cam_fd==-1)
  52. {
  53. ERROR_RETURN("Failed to open camera device %s: %s (%d)",
  54. devname.c_str(), strerror(errno), errno);
  55. }
  56. struct v4l2_format fmt;
  57. fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  58. fmt.fmt.pix.width = p->cam_w;
  59. fmt.fmt.pix.height = p->cam_h;
  60. fmt.fmt.pix.pixelformat = p->cam_pixfmt;
  61. fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
  62. if (ioctl( p->cam_fd, VIDIOC_S_FMT, &fmt) < 0)
  63. ERROR_RETURN("Failed to set camera output format: %s (%d)",
  64. strerror(errno), errno);
  65. /* Get the real format in case the desired is not supported */
  66. memset(&fmt, 0, sizeof fmt);
  67. fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  68. if (ioctl( p->cam_fd, VIDIOC_G_FMT, &fmt) < 0)
  69. ERROR_RETURN("Failed to get camera output format: %s (%d)",
  70. strerror(errno), errno);
  71. if (fmt.fmt.pix.width != p->cam_w ||
  72. fmt.fmt.pix.height != p->cam_h ||
  73. fmt.fmt.pix.pixelformat != p->cam_pixfmt)
  74. {
  75. WARN("The desired format is not supported");
  76. p->cam_w = fmt.fmt.pix.width;
  77. p->cam_h = fmt.fmt.pix.height;
  78. p->cam_pixfmt =fmt.fmt.pix.pixelformat;
  79. }
  80. struct v4l2_streamparm streamparm;
  81. memset (&streamparm, 0x00, sizeof (struct v4l2_streamparm));
  82. streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  83. /*
  84. streamparm.parm.capture.timeperframe.numerator = 1;
  85. streamparm.parm.capture.timeperframe.denominator = 3;
  86. streamparm.parm.output.timeperframe.numerator = 1;
  87. streamparm.parm.output.timeperframe.denominator = 3;
  88. */
  89. ioctl ( p->cam_fd, VIDIOC_G_PARM, &streamparm);
  90. printf(">>: Frame rate: %u/%u\n",streamparm.parm.capture.timeperframe.numerator,streamparm.parm.capture.timeperframe.denominator);
  91. INFO("Camera ouput format: (%d x %d) stride: %d, imagesize: %d, frate: %u / %u",
  92. fmt.fmt.pix.width,
  93. fmt.fmt.pix.height,
  94. fmt.fmt.pix.bytesperline,
  95. fmt.fmt.pix.sizeimage,
  96. streamparm.parm.capture.timeperframe.denominator,
  97. streamparm.parm.capture.timeperframe.numerator);
  98. }
  99. return true;
  100. }
  101. void GSMLCapturer::Run()
  102. {
  103. if(!open_cam()) return;
  104. prepare_buffer();
  105. start_streams();
  106. _run=true;
  107. struct pollfd fds[1];
  108. struct v4l2_buffer v4l2_buf;
  109. long long _source = 0,_dst = 0;
  110. while(_run)
  111. {
  112. int cam_fd=-1;
  113. context_t * p=nullptr;
  114. //if((_op->GetType()!=RenderPosition::FRONT&&_op->GetType()!=RenderPosition::BACK)||_op->IsForward())
  115. if(_op->IsForward())
  116. //if(_op->GetType()!=RenderPosition::ALL)
  117. {
  118. cam_fd=_op->_ctx0->cam_fd;
  119. p=_op->_ctx0;
  120. }
  121. else{
  122. cam_fd=_op->_ctx1->cam_fd;
  123. p=_op->_ctx1;
  124. }
  125. //assert(p!=nullptr);
  126. /*
  127. else
  128. {
  129. if(_op->IsForward())
  130. {
  131. cam_fd=_ctx[0].cam_fd;
  132. p=&_ctx[0];
  133. }
  134. else
  135. {
  136. cam_fd=_ctx[1].cam_fd;
  137. p=&_ctx[1];
  138. }
  139. }
  140. */
  141. fds[0].fd = cam_fd;
  142. fds[0].events = POLLIN;
  143. if(poll(fds, 1, 5000) > 0)
  144. {
  145. if (fds[0].revents & POLLIN)
  146. {
  147. /* Dequeue a camera buff */
  148. memset(&v4l2_buf, 0, sizeof(v4l2_buf));
  149. v4l2_buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  150. if (p->capture_dmabuf)
  151. v4l2_buf.memory = V4L2_MEMORY_DMABUF;
  152. else
  153. v4l2_buf.memory = V4L2_MEMORY_MMAP;
  154. if (ioctl(cam_fd, VIDIOC_DQBUF, &v4l2_buf) < 0)
  155. printf("Failed to dequeue camera buff: %s (%d)",
  156. strerror(errno), errno);
  157. if(_op->GetType()==RenderPosition::FRONT)
  158. {
  159. _source = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
  160. //printf("encode delay:%lld----frame:%ld\r\n", _source);
  161. }
  162. //_ctx.frame++;
  163. rtc::scoped_refptr<webrtc::I420Buffer> buffer=webrtc::I420Buffer::Create(p->cam_w,p->cam_h);
  164. // rtc::scoped_refptr<webrtc::I420Buffer> buffer=webrtc::I420Buffer::Create(800,600);
  165. // std::cout << v4l2_buf.index << std::endl;
  166. const int conversionResult = libyuv::ConvertToI420((uint8_t*)p->g_buff[v4l2_buf.index].start, 0,
  167. buffer->MutableDataY(), buffer->StrideY(),
  168. buffer->MutableDataU(), buffer->StrideU(),
  169. buffer->MutableDataV(), buffer->StrideV(),
  170. 0, 0,
  171. p->cam_w,p->cam_h,
  172. buffer->width(), buffer->height(),
  173. libyuv::kRotate0, libyuv::FOURCC_YUYV);
  174. // // 假设 p->g_buff[v4l2_buf.index].start 是 YUYV 格式的源数据
  175. // unsigned char* src = static_cast<unsigned char*>(p->g_buff[v4l2_buf.index].start);
  176. // int width = p->cam_w;
  177. // int height = p->cam_h;
  178. // // 创建 I420Buffer
  179. // rtc::scoped_refptr<webrtc::I420Buffer> buffer = webrtc::I420Buffer::Create(
  180. // width, height,
  181. // buffer->StrideY(), // Y plane stride
  182. // buffer->StrideU(), // U plane stride
  183. // buffer->StrideV() // V plane stride
  184. // );
  185. // // 使用 CUDA 进行 YUYV 到 I420 的转换
  186. // gpuConvertYUYVtoI420(
  187. // src,
  188. // buffer->MutableDataY(), buffer->MutableDataU(), buffer->MutableDataV(),
  189. // width, height,
  190. // buffer->StrideY(), buffer->StrideU()
  191. // );
  192. // // 创建 VideoFrame 并传递给 _broadcaster
  193. // webrtc::VideoFrame frame(buffer, webrtc::kVideoRotation_0, rtc::TimeNanos());
  194. // _broadcaster.OnFrame(frame);
  195. int width = p->cam_w;
  196. int height = p->cam_h;
  197. if (conversionResult >= 0)
  198. {
  199. webrtc::VideoFrame videoFrame(buffer, webrtc::VideoRotation::kVideoRotation_0, rtc::TimeNanos());
  200. if ((p->cam_w == 0) && (p->cam_h == 0)) {
  201. _broadcaster.OnFrame(videoFrame);
  202. }
  203. else
  204. {
  205. if (height == 0) {
  206. height = (videoFrame.height() * width) / videoFrame.width();
  207. }
  208. else if (width == 0) {
  209. width = (videoFrame.width() * height) / videoFrame.height();
  210. }
  211. int stride_y = width;
  212. int stride_uv = (width + 1) / 2;
  213. rtc::scoped_refptr<webrtc::I420Buffer> scaled_buffer = webrtc::I420Buffer::Create(width, height, stride_y, stride_uv, stride_uv);
  214. scaled_buffer->ScaleFrom(*videoFrame.video_frame_buffer()->ToI420());
  215. webrtc::VideoFrame frame = webrtc::VideoFrame(scaled_buffer, webrtc::kVideoRotation_0, rtc::TimeNanos());
  216. _broadcaster.OnFrame(frame);
  217. }
  218. }
  219. if(_op->GetType()==RenderPosition::FRONT)
  220. {
  221. _dst = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
  222. //printf("encode delay:%lld\r\n",_dst - _source);
  223. }
  224. if (ioctl(p->cam_fd, VIDIOC_QBUF, &v4l2_buf))
  225. printf("Failed to queue camera buffers: %s (%d)",
  226. strerror(errno), errno);
  227. }
  228. }
  229. //std::this_thread::sleep_for(std::chrono::milliseconds(30));
  230. }
  231. stop_streams();
  232. close_cam();
  233. }
  234. void GSMLCapturer::Destroy() {
  235. Stop();
  236. }
  237. void GSMLCapturer::AddOrUpdateSink(
  238. rtc::VideoSinkInterface<webrtc::VideoFrame>* sink,
  239. const rtc::VideoSinkWants& wants) {
  240. _broadcaster.AddOrUpdateSink(sink, wants);
  241. }
  242. void GSMLCapturer::RemoveSink(rtc::VideoSinkInterface<webrtc::VideoFrame>* sink)
  243. {
  244. _broadcaster.RemoveSink(sink);
  245. }
  246. bool GSMLCapturer::prepare_buffer()
  247. {
  248. //int32_t count=_op->GetType()==RenderPosition::FRONT_BACK?2:1;
  249. //for(int32_t i=0;i<count;i++)
  250. {
  251. context_t * p=_op->_ctx0;
  252. p->g_buff = (nv_buffer *)malloc(V4L2_BUFFERS_NUM * sizeof(nv_buffer));
  253. if ( p->g_buff == NULL)
  254. ERROR_RETURN("Failed to allocate global buffer context");
  255. if ( p->capture_dmabuf) {
  256. if (!request_camera_buff(p))
  257. ERROR_RETURN("Failed to set up camera buff");
  258. } else {
  259. if (!request_camera_buff_mmap(p))
  260. ERROR_RETURN("Failed to set up camera buff");
  261. }
  262. INFO("Succeed in preparing stream buffers");
  263. }
  264. return true;
  265. }
  266. bool GSMLCapturer::request_camera_buff( context_t * p)
  267. {
  268. // for(int32_t i=0;i<count;i++)
  269. {
  270. // context_t * p=&_ctx[i];
  271. struct v4l2_requestbuffers rb;
  272. memset(&rb, 0, sizeof(rb));
  273. rb.count = V4L2_BUFFERS_NUM;
  274. rb.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  275. rb.memory = V4L2_MEMORY_DMABUF;
  276. if (ioctl( p->cam_fd, VIDIOC_REQBUFS, &rb) < 0)
  277. ERROR_RETURN("Failed to request v4l2 buffers: %s (%d)",
  278. strerror(errno), errno);
  279. if (rb.count != V4L2_BUFFERS_NUM)
  280. ERROR_RETURN("V4l2 buffer number is not as desired");
  281. for (unsigned int index = 0; index < V4L2_BUFFERS_NUM; index++)
  282. {
  283. struct v4l2_buffer buf;
  284. /* Query camera v4l2 buf length */
  285. memset(&buf, 0, sizeof buf);
  286. buf.index = index;
  287. buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  288. buf.memory = V4L2_MEMORY_DMABUF;
  289. if (ioctl( p->cam_fd, VIDIOC_QUERYBUF, &buf) < 0)
  290. ERROR_RETURN("Failed to query buff: %s (%d)",
  291. strerror(errno), errno);
  292. /* TODO: add support for multi-planer
  293. Enqueue empty v4l2 buff into camera capture plane */
  294. buf.m.fd = (unsigned long) p->g_buff[index].dmabuff_fd;
  295. if (buf.length != p->g_buff[index].size)
  296. {
  297. WARN("Camera v4l2 buf length is not expected");
  298. p->g_buff[index].size = buf.length;
  299. }
  300. if (ioctl( p->cam_fd, VIDIOC_QBUF, &buf) < 0)
  301. ERROR_RETURN("Failed to enqueue buffers: %s (%d)",
  302. strerror(errno), errno);
  303. }
  304. }
  305. return true;
  306. }
  307. bool GSMLCapturer::stop_streams()
  308. {
  309. enum v4l2_buf_type type;
  310. //int32_t count=_op->GetType()==RenderPosition::FRONT_BACK?2:1;
  311. //for(int32_t i=0;i<count;i++)
  312. {
  313. context_t * p=_op->_ctx0;
  314. for (unsigned int index = 0; index < V4L2_BUFFERS_NUM; index++)
  315. {
  316. if(munmap(p->g_buff[index].start,p->g_buff[index].size)==-1)
  317. {
  318. ERROR_RETURN("munmap failed: %s (%d)", strerror(errno), errno);
  319. }
  320. }
  321. /* Stop v4l2 streaming */
  322. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  323. if (ioctl( p->cam_fd, VIDIOC_STREAMOFF, &type))
  324. ERROR_RETURN("Failed to stop streaming: %s (%d)",
  325. strerror(errno), errno);
  326. INFO("Camera video streaming off ...");
  327. }
  328. return true;
  329. }
  330. bool GSMLCapturer::start_streams()
  331. {
  332. enum v4l2_buf_type type; //是否可以注释??
  333. // int32_t count=_op->GetType()==RenderPosition::FRONT_BACK?2:1;
  334. // for(int32_t i=0;i<count;i++)
  335. {
  336. context_t * p=_op->_ctx0;
  337. /* Start v4l2 streaming */
  338. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  339. if (ioctl( p->cam_fd, VIDIOC_STREAMON, &type) < 0)
  340. ERROR_RETURN("Failed to start streaming: %s (%d)",
  341. strerror(errno), errno);
  342. usleep(200);
  343. INFO("Camera video streaming on ...");
  344. }
  345. return true;
  346. }
  347. bool GSMLCapturer::request_camera_buff_mmap(context_t * p)
  348. {
  349. struct v4l2_requestbuffers rb;
  350. // int32_t count=_op->GetType()==RenderPosition::FRONT_BACK?2:1;
  351. // for(int32_t i=0;i<count;i++)
  352. {
  353. memset(&rb, 0, sizeof(rb));
  354. rb.count = V4L2_BUFFERS_NUM;
  355. rb.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  356. rb.memory = V4L2_MEMORY_MMAP;
  357. if (ioctl( p->cam_fd, VIDIOC_REQBUFS, &rb) < 0)
  358. ERROR_RETURN("Failed to request v4l2 buffers: %s (%d)",
  359. strerror(errno), errno);
  360. if (rb.count != V4L2_BUFFERS_NUM)
  361. ERROR_RETURN("V4l2 buffer number is not as desired");
  362. for (unsigned int index = 0; index < V4L2_BUFFERS_NUM; index++)
  363. {
  364. struct v4l2_buffer buf;
  365. /* Query camera v4l2 buf length */
  366. memset(&buf, 0, sizeof buf);
  367. buf.index = index;
  368. buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  369. buf.memory = V4L2_MEMORY_MMAP;
  370. if (ioctl(p->cam_fd, VIDIOC_QUERYBUF, &buf) < 0)
  371. ERROR_RETURN("Failed to query buff: %s (%d)",
  372. strerror(errno), errno);
  373. p->g_buff[index].size = buf.length;
  374. p->g_buff[index].start = (unsigned char *)
  375. mmap (NULL /* start anywhere */,
  376. buf.length,
  377. PROT_READ | PROT_WRITE /* required */,
  378. MAP_SHARED /* recommended */,
  379. p->cam_fd, buf.m.offset);
  380. if (MAP_FAILED == p->g_buff[index].start)
  381. ERROR_RETURN("Failed to map buffers");
  382. if (ioctl( p->cam_fd, VIDIOC_QBUF, &buf) < 0)
  383. ERROR_RETURN("Failed to enqueue buffers: %s (%d)",
  384. strerror(errno), errno);
  385. }
  386. }
  387. return true;
  388. }
  389. void GSMLCapturer::close_cam()
  390. {
  391. // int32_t count=_op->GetType()==RenderPosition::FRONT_BACK?2:1;
  392. //for(int32_t i=0;i<count;i++)
  393. {
  394. context_t * p=_op->_ctx0;
  395. if(p->g_buff!=nullptr)
  396. {
  397. free(p->g_buff);
  398. p->g_buff = nullptr;
  399. }
  400. if(p->cam_fd>0)
  401. close(p->cam_fd);
  402. }
  403. free(_op->_ctx0);
  404. }
  405. void GSMLCapturer::Stop()
  406. {
  407. _run=false;
  408. //if(_thread.joinable())
  409. _thread.join();
  410. }