gsml_capturer.cpp 14 KB

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