decoder.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. #include "decoder.h"
  2. #include "dma_util.h"
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <pthread.h>
  7. #include <unistd.h>
  8. #include <fcntl.h>
  9. #include <sys/ioctl.h>
  10. #include <sys/mman.h>
  11. #include <linux/dma-heap.h>
  12. #include <linux/dma-buf.h>
  13. #include <gst/gst.h>
  14. #include <gst/app/gstappsink.h>
  15. #include <gst/video/video.h>
  16. #include <gst/allocators/gstdmabuf.h>
  17. #define DEC_NUM_BUF 3
  18. struct Decoder {
  19. GstElement *pipeline;
  20. GstElement *appsink;
  21. /* Zero-copy mode: appsink negotiates video/x-raw(memory:DMABuf) and we
  22. * hand out dups of the decoder's own dmabuf fds. Pulled samples are kept
  23. * alive per slot until decoder_release_frame() unrefs them, so GStreamer
  24. * can never overwrite a buffer the composer is still using. */
  25. int use_dmabuf;
  26. GstSample *slot_sample[DEC_NUM_BUF];
  27. /* Fallback mode: CPU copies each frame into our own dma-heap buffers. */
  28. int buf_fd[DEC_NUM_BUF];
  29. void *buf_map[DEC_NUM_BUF];
  30. size_t buf_size;
  31. int buf_width;
  32. int buf_height;
  33. int buf_stride;
  34. int buf_stride_v;
  35. int buf_index;
  36. int buf_inuse[DEC_NUM_BUF];
  37. pthread_mutex_t buf_mutex;
  38. pthread_cond_t buf_cond;
  39. int codec_type;
  40. int width;
  41. int height;
  42. int stride;
  43. };
  44. static GstElement *build_pipeline(const char *url, int want_dmabuf) {
  45. char pipeline_str[2048];
  46. if (want_dmabuf) {
  47. snprintf(pipeline_str, sizeof(pipeline_str),
  48. "rtspsrc name=src location=%s protocols=tcp latency=0 ! "
  49. "application/x-rtp,media=video ! parsebin name=pb ! mppvideodec ! "
  50. "video/x-raw(memory:DMABuf),format=NV12 ! appsink name=sink "
  51. "max-buffers=%d drop=true sync=false ",
  52. url, DEC_NUM_BUF);
  53. } else {
  54. snprintf(pipeline_str, sizeof(pipeline_str),
  55. "rtspsrc name=src location=%s protocols=tcp latency=0 ! "
  56. "application/x-rtp,media=video ! parsebin name=pb ! mppvideodec ! "
  57. "video/x-raw,format=NV12 ! appsink name=sink "
  58. "max-buffers=1 drop=true sync=false ",
  59. url);
  60. }
  61. GError *err = NULL;
  62. GstElement *pipeline = gst_parse_launch(pipeline_str, &err);
  63. if (!pipeline || err) {
  64. fprintf(stderr, "GStreamer pipeline creation failed: %s\n",
  65. err ? err->message : "unknown");
  66. if (err) g_error_free(err);
  67. if (pipeline) { gst_object_unref(pipeline); pipeline = NULL; }
  68. return NULL;
  69. }
  70. GstElement *appsink = gst_bin_get_by_name(GST_BIN(pipeline), "sink");
  71. gst_app_sink_set_drop(GST_APP_SINK(appsink), TRUE);
  72. gst_app_sink_set_max_buffers(GST_APP_SINK(appsink),
  73. want_dmabuf ? DEC_NUM_BUF : 1);
  74. gst_app_sink_set_emit_signals(GST_APP_SINK(appsink), FALSE);
  75. /* Set rtspsrc low-latency options */
  76. GstElement *src = gst_bin_get_by_name(GST_BIN(pipeline), "src");
  77. if (src) {
  78. g_object_set(src, "latency", 0, NULL);
  79. g_object_set(src, "buffer-mode", 0, NULL);
  80. g_object_set(src, "do-rtcp", FALSE, NULL);
  81. gst_object_unref(src);
  82. }
  83. gst_object_unref(appsink);
  84. return pipeline;
  85. }
  86. static void destroy_pipeline(Decoder *dec) {
  87. if (dec->pipeline) {
  88. gst_element_set_state(dec->pipeline, GST_STATE_NULL);
  89. gst_object_unref(dec->pipeline);
  90. dec->pipeline = NULL;
  91. }
  92. if (dec->appsink) { gst_object_unref(dec->appsink); dec->appsink = NULL; }
  93. }
  94. /* Fill dec dims from the caps of `sample`; returns ver_stride (UV plane row
  95. * offset in rows) or -1 on bad caps. */
  96. static int probe_dims(Decoder *dec, GstSample *sample) {
  97. GstCaps *caps = gst_sample_get_caps(sample);
  98. GstVideoInfo vinfo;
  99. if (!caps || !gst_video_info_from_caps(&vinfo, caps)) return -1;
  100. dec->width = GST_VIDEO_INFO_WIDTH(&vinfo);
  101. dec->height = GST_VIDEO_INFO_HEIGHT(&vinfo);
  102. dec->stride = GST_VIDEO_INFO_PLANE_STRIDE(&vinfo, 0);
  103. int stride_v = GST_VIDEO_INFO_PLANE_STRIDE(&vinfo, 1);
  104. gsize uv_off = GST_VIDEO_INFO_COMP_OFFSET(&vinfo, 1);
  105. /* UV plane starts after ver_stride aligned rows of Y */
  106. if (dec->stride > 0 && uv_off % (gsize)dec->stride == 0)
  107. return (int)(uv_off / (gsize)dec->stride);
  108. (void)stride_v;
  109. return dec->height;
  110. }
  111. Decoder *decoder_create(const char *url, int timeout_sec) {
  112. static int gst_inited = 0;
  113. if (!gst_inited) { gst_init(NULL, NULL); gst_inited = 1; }
  114. Decoder *dec = calloc(1, sizeof(Decoder));
  115. if (!dec) return NULL;
  116. for (int i = 0; i < DEC_NUM_BUF; i++) dec->buf_fd[i] = -1;
  117. pthread_mutex_init(&dec->buf_mutex, NULL);
  118. pthread_cond_init(&dec->buf_cond, NULL);
  119. for (int i = 0; i < DEC_NUM_BUF; i++) dec->buf_inuse[i] = 0;
  120. /* parsebin auto-detects whether the RTP stream is H.264, H.265, etc. from
  121. * the SDP encoding-name, so cameras need not advertise their codec via the
  122. * URL (a `.264`-less URL used to be forced to H.265, breaking H.264 cams
  123. * such as 192.168.1.120). mppvideodec does the hardware decode. */
  124. dec->codec_type = 1;
  125. /* --- Preferred path: copy into our own dma-heap buffers. The zero-copy
  126. * mppvideodec DMABuf path is skipped: on this board RGA cannot import the
  127. * MPP decoder's own dmabufs (importbuffer_fd fails -> tiles never appear).
  128. * Our dma-heap (system-uncached) buffers import cleanly into RGA. --- */
  129. copy_path:
  130. /* --- Fallback: system-memory output + CPU copy into our own heap --- */
  131. dec->pipeline = build_pipeline(url, 0);
  132. if (!dec->pipeline) {
  133. pthread_mutex_destroy(&dec->buf_mutex);
  134. pthread_cond_destroy(&dec->buf_cond);
  135. free(dec);
  136. return NULL;
  137. }
  138. dec->appsink = gst_bin_get_by_name(GST_BIN(dec->pipeline), "sink");
  139. gst_element_set_state(dec->pipeline, GST_STATE_PLAYING);
  140. /* Wait for first frame with timeout */
  141. GstSample *sample = gst_app_sink_try_pull_sample(GST_APP_SINK(dec->appsink),
  142. timeout_sec * GST_SECOND);
  143. if (!sample) {
  144. fprintf(stderr, "Timeout waiting for first frame from %s\n", url);
  145. destroy_pipeline(dec);
  146. pthread_mutex_destroy(&dec->buf_mutex);
  147. pthread_cond_destroy(&dec->buf_cond);
  148. free(dec);
  149. return NULL;
  150. }
  151. /* Get video info */
  152. if (probe_dims(dec, sample) < 0) {
  153. gst_sample_unref(sample);
  154. fprintf(stderr, "Failed to get video info\n");
  155. destroy_pipeline(dec);
  156. pthread_mutex_destroy(&dec->buf_mutex);
  157. pthread_cond_destroy(&dec->buf_cond);
  158. free(dec);
  159. return NULL;
  160. }
  161. /* Decode first frame to allocate buffer */
  162. GstBuffer *out_buf = gst_sample_get_buffer(sample);
  163. if (out_buf) {
  164. GstCaps *caps = gst_sample_get_caps(sample);
  165. GstVideoInfo vinfo;
  166. int stride_v = dec->height;
  167. if (caps && gst_video_info_from_caps(&vinfo, caps))
  168. stride_v = GST_VIDEO_INFO_PLANE_STRIDE(&vinfo, 1);
  169. size_t needed = dec->stride * dec->height + stride_v * dec->height / 2;
  170. for (int i = 0; i < DEC_NUM_BUF; i++) {
  171. if (dma_heap_alloc("cma", needed, &dec->buf_fd[i]) < 0) {
  172. if (dma_heap_alloc("system-uncached", needed, &dec->buf_fd[i]) < 0) {
  173. dec->buf_fd[i] = -1;
  174. }
  175. }
  176. if (dec->buf_fd[i] >= 0) {
  177. dec->buf_map[i] = mmap(NULL, needed, PROT_READ | PROT_WRITE,
  178. MAP_SHARED, dec->buf_fd[i], 0);
  179. if (dec->buf_map[i] != MAP_FAILED) {
  180. if (i == 0) {
  181. dec->buf_size = needed;
  182. dec->buf_width = dec->width;
  183. dec->buf_height = dec->height;
  184. dec->buf_stride = dec->stride;
  185. dec->buf_stride_v = stride_v;
  186. fprintf(stderr, "DBG: decoder buffer %dx%d stride=%d/%d size=%zu\n",
  187. dec->width, dec->height, dec->stride, stride_v, needed);
  188. }
  189. } else {
  190. close(dec->buf_fd[i]);
  191. dec->buf_fd[i] = -1;
  192. }
  193. }
  194. }
  195. }
  196. gst_sample_unref(sample);
  197. if (dec->buf_fd[0] < 0) {
  198. fprintf(stderr, "Failed to allocate decoder buffer\n");
  199. destroy_pipeline(dec);
  200. pthread_mutex_destroy(&dec->buf_mutex);
  201. pthread_cond_destroy(&dec->buf_cond);
  202. free(dec);
  203. return NULL;
  204. }
  205. return dec;
  206. }
  207. void decoder_destroy(Decoder *dec) {
  208. if (!dec) return;
  209. destroy_pipeline(dec);
  210. for (int i = 0; i < DEC_NUM_BUF; i++) {
  211. if (dec->slot_sample[i]) {
  212. gst_sample_unref(dec->slot_sample[i]);
  213. dec->slot_sample[i] = NULL;
  214. }
  215. }
  216. for (int i = 0; i < DEC_NUM_BUF; i++) {
  217. if (dec->buf_fd[i] >= 0) {
  218. if (dec->buf_map[i]) munmap(dec->buf_map[i], dec->buf_size);
  219. close(dec->buf_fd[i]);
  220. }
  221. }
  222. pthread_mutex_destroy(&dec->buf_mutex);
  223. pthread_cond_destroy(&dec->buf_cond);
  224. free(dec);
  225. }
  226. int decoder_get_codec(Decoder *dec) { return dec->codec_type; }
  227. int decoder_get_width(Decoder *dec) { return dec->width; }
  228. int decoder_get_height(Decoder *dec) { return dec->height; }
  229. int decoder_get_stride(Decoder *dec) { return dec->stride; }
  230. int decoder_get_frame(Decoder *dec, DecodedFrame *frame) {
  231. if (!dec || !dec->pipeline) return -1;
  232. /* --- zero-copy dmabuf path --- */
  233. if (dec->use_dmabuf) {
  234. GstSample *sample = gst_app_sink_try_pull_sample(GST_APP_SINK(dec->appsink), 0);
  235. if (!sample) return -3;
  236. GstBuffer *buf = gst_sample_get_buffer(sample);
  237. GstMemory *mem = buf ? gst_buffer_peek_memory(buf, 0) : NULL;
  238. if (!mem || !gst_is_dmabuf_memory(mem)) {
  239. gst_sample_unref(sample);
  240. return -1;
  241. }
  242. pthread_mutex_lock(&dec->buf_mutex);
  243. int idx = -1;
  244. for (int i = 0; i < DEC_NUM_BUF; i++) {
  245. if (!dec->slot_sample[i]) { idx = i; break; }
  246. }
  247. if (idx < 0) {
  248. /* all slots pinned (ring + held + in-flight): drop the new
  249. * frame, main catches up next iteration */
  250. pthread_mutex_unlock(&dec->buf_mutex);
  251. gst_sample_unref(sample);
  252. return -3;
  253. }
  254. dec->slot_sample[idx] = sample; /* keep alive until release */
  255. pthread_mutex_unlock(&dec->buf_mutex);
  256. int fd = gst_dmabuf_memory_get_fd(mem);
  257. if (fd < 0) {
  258. pthread_mutex_lock(&dec->buf_mutex);
  259. dec->slot_sample[idx] = NULL;
  260. pthread_mutex_unlock(&dec->buf_mutex);
  261. gst_sample_unref(sample);
  262. return -1;
  263. }
  264. int ver = probe_dims(dec, sample);
  265. if (ver <= 0) ver = dec->height;
  266. frame->fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
  267. frame->width = dec->width;
  268. frame->height = dec->height;
  269. frame->hor_stride = dec->stride;
  270. frame->ver_stride = ver;
  271. frame->idx = idx;
  272. frame->pts = 0;
  273. if (frame->fd < 0) {
  274. pthread_mutex_lock(&dec->buf_mutex);
  275. dec->slot_sample[idx] = NULL;
  276. pthread_mutex_unlock(&dec->buf_mutex);
  277. gst_sample_unref(sample);
  278. return -1;
  279. }
  280. return 0;
  281. }
  282. /* --- fallback: system memory + CPU copy into our own heap --- */
  283. GstSample *sample = gst_app_sink_try_pull_sample(GST_APP_SINK(dec->appsink), 0);
  284. if (!sample) return -3;
  285. GstBuffer *out_buf = gst_sample_get_buffer(sample);
  286. GstCaps *caps = gst_sample_get_caps(sample);
  287. if (!caps || !out_buf) { gst_sample_unref(sample); return -1; }
  288. GstVideoInfo vinfo;
  289. if (!gst_video_info_from_caps(&vinfo, caps)) { gst_sample_unref(sample); return -1; }
  290. int w = GST_VIDEO_INFO_WIDTH(&vinfo);
  291. int h = GST_VIDEO_INFO_HEIGHT(&vinfo);
  292. int stride = GST_VIDEO_INFO_PLANE_STRIDE(&vinfo, 0);
  293. int stride_v = GST_VIDEO_INFO_PLANE_STRIDE(&vinfo, 1);
  294. size_t needed = stride * h + stride_v * h / 2;
  295. /* Reallocate if dimensions changed */
  296. if (w != dec->buf_width || h != dec->buf_height ||
  297. stride != dec->buf_stride || needed > dec->buf_size) {
  298. for (int i = 0; i < DEC_NUM_BUF; i++) {
  299. if (dec->buf_map[i]) munmap(dec->buf_map[i], dec->buf_size);
  300. if (dec->buf_fd[i] >= 0) close(dec->buf_fd[i]);
  301. dec->buf_fd[i] = -1;
  302. dec->buf_map[i] = NULL;
  303. if (dma_heap_alloc("cma", needed, &dec->buf_fd[i]) < 0) {
  304. if (dma_heap_alloc("system-uncached", needed, &dec->buf_fd[i]) < 0) {
  305. dec->buf_fd[i] = -1;
  306. }
  307. }
  308. if (dec->buf_fd[i] < 0) { gst_sample_unref(sample); return -1; }
  309. dec->buf_map[i] = mmap(NULL, needed, PROT_READ | PROT_WRITE,
  310. MAP_SHARED, dec->buf_fd[i], 0);
  311. if (dec->buf_map[i] == MAP_FAILED) {
  312. close(dec->buf_fd[i]);
  313. dec->buf_fd[i] = -1;
  314. gst_sample_unref(sample);
  315. return -1;
  316. }
  317. }
  318. dec->buf_size = needed;
  319. dec->buf_width = w;
  320. dec->buf_height = h;
  321. dec->buf_stride = stride;
  322. dec->buf_stride_v = stride_v;
  323. }
  324. pthread_mutex_lock(&dec->buf_mutex);
  325. while (dec->buf_inuse[dec->buf_index]) {
  326. struct timespec ts;
  327. clock_gettime(CLOCK_REALTIME, &ts);
  328. ts.tv_nsec += 200000000;
  329. if (ts.tv_nsec >= 1000000000) { ts.tv_sec++; ts.tv_nsec -= 1000000000; }
  330. pthread_cond_timedwait(&dec->buf_cond, &dec->buf_mutex, &ts);
  331. }
  332. int idx = dec->buf_index;
  333. dec->buf_inuse[idx] = 1;
  334. dec->buf_index = (idx + 1) % DEC_NUM_BUF;
  335. pthread_mutex_unlock(&dec->buf_mutex);
  336. GstVideoFrame vframe;
  337. if (!gst_video_frame_map(&vframe, &vinfo, out_buf, GST_MAP_READ)) {
  338. gst_sample_unref(sample);
  339. return -1;
  340. }
  341. uint8_t *src_y = GST_VIDEO_FRAME_PLANE_DATA(&vframe, 0);
  342. uint8_t *src_uv = GST_VIDEO_FRAME_PLANE_DATA(&vframe, 1);
  343. int src_stride = GST_VIDEO_FRAME_PLANE_STRIDE(&vframe, 0);
  344. int src_stride_uv = GST_VIDEO_FRAME_PLANE_STRIDE(&vframe, 1);
  345. uint8_t *dst = (uint8_t *)dec->buf_map[idx];
  346. /* CPU write start: invalidate/clean so cached dma-heap memory stays coherent */
  347. {
  348. struct dma_buf_sync sync = { .flags = DMA_BUF_SYNC_START | DMA_BUF_SYNC_WRITE };
  349. ioctl(dec->buf_fd[idx], DMA_BUF_IOCTL_SYNC, &sync);
  350. }
  351. if (src_stride == stride) {
  352. memcpy(dst, src_y, stride * h);
  353. } else {
  354. for (int y = 0; y < h; y++)
  355. memcpy(dst + y * stride, src_y + y * src_stride, stride < src_stride ? stride : src_stride);
  356. }
  357. dst += stride * h;
  358. int uv_h = h / 2;
  359. if (src_stride_uv == stride_v) {
  360. memcpy(dst, src_uv, stride_v * uv_h);
  361. } else {
  362. for (int y = 0; y < uv_h; y++)
  363. memcpy(dst + y * stride_v, src_uv + y * src_stride_uv, stride_v < src_stride_uv ? stride_v : src_stride_uv);
  364. }
  365. gst_video_frame_unmap(&vframe);
  366. gst_sample_unref(sample);
  367. /* CPU write done: flush cache so RGA DMA reads the latest frame data.
  368. Without this, fast motion shows a mix of old/new rows (tearing). */
  369. {
  370. struct dma_buf_sync sync = { .flags = DMA_BUF_SYNC_END | DMA_BUF_SYNC_WRITE };
  371. ioctl(dec->buf_fd[idx], DMA_BUF_IOCTL_SYNC, &sync);
  372. }
  373. frame->fd = fcntl(dec->buf_fd[idx], F_DUPFD_CLOEXEC, 3);
  374. frame->width = w;
  375. frame->height = h;
  376. frame->hor_stride = stride;
  377. frame->ver_stride = h;
  378. frame->idx = idx;
  379. frame->pts = 0;
  380. return 0;
  381. }
  382. int decoder_flush(Decoder *dec) {
  383. (void)dec;
  384. return 0;
  385. }
  386. int decoder_release_frame(Decoder *dec, int idx) {
  387. if (!dec || idx < 0 || idx >= DEC_NUM_BUF) return -1;
  388. pthread_mutex_lock(&dec->buf_mutex);
  389. if (dec->slot_sample[idx]) {
  390. gst_sample_unref(dec->slot_sample[idx]);
  391. dec->slot_sample[idx] = NULL;
  392. pthread_cond_signal(&dec->buf_cond);
  393. } else if (dec->buf_inuse[idx]) {
  394. dec->buf_inuse[idx] = 0;
  395. pthread_cond_signal(&dec->buf_cond);
  396. }
  397. pthread_mutex_unlock(&dec->buf_mutex);
  398. return 0;
  399. }