You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

856 lines
28KB

  1. /*
  2. * MMAL Video Decoder
  3. * Copyright (c) 2015 Rodger Combs
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * MMAL Video Decoder
  24. */
  25. #include <bcm_host.h>
  26. #include <interface/mmal/mmal.h>
  27. #include <interface/mmal/mmal_parameters_video.h>
  28. #include <interface/mmal/util/mmal_util.h>
  29. #include <interface/mmal/util/mmal_util_params.h>
  30. #include <interface/mmal/util/mmal_default_components.h>
  31. #include <interface/mmal/vc/mmal_vc_api.h>
  32. #include <stdatomic.h>
  33. #include "avcodec.h"
  34. #include "hwaccel.h"
  35. #include "internal.h"
  36. #include "libavutil/avassert.h"
  37. #include "libavutil/buffer.h"
  38. #include "libavutil/common.h"
  39. #include "libavutil/imgutils.h"
  40. #include "libavutil/opt.h"
  41. #include "libavutil/log.h"
  42. typedef struct FFBufferEntry {
  43. AVBufferRef *ref;
  44. void *data;
  45. size_t length;
  46. int64_t pts, dts;
  47. int flags;
  48. struct FFBufferEntry *next;
  49. } FFBufferEntry;
  50. // MMAL_POOL_T destroys all of its MMAL_BUFFER_HEADER_Ts. If we want correct
  51. // refcounting for AVFrames, we can free the MMAL_POOL_T only after all AVFrames
  52. // have been unreferenced.
  53. typedef struct FFPoolRef {
  54. atomic_int refcount;
  55. MMAL_POOL_T *pool;
  56. } FFPoolRef;
  57. typedef struct FFBufferRef {
  58. MMAL_BUFFER_HEADER_T *buffer;
  59. FFPoolRef *pool;
  60. } FFBufferRef;
  61. typedef struct MMALDecodeContext {
  62. AVClass *av_class;
  63. int extra_buffers;
  64. int extra_decoder_buffers;
  65. MMAL_COMPONENT_T *decoder;
  66. MMAL_QUEUE_T *queue_decoded_frames;
  67. MMAL_POOL_T *pool_in;
  68. FFPoolRef *pool_out;
  69. // Waiting input packets. Because the libavcodec API requires decoding and
  70. // returning packets in lockstep, it can happen that queue_decoded_frames
  71. // contains almost all surfaces - then the decoder input queue can quickly
  72. // fill up and won't accept new input either. Without consuming input, the
  73. // libavcodec API can't return new frames, and we have a logical deadlock.
  74. // This is avoided by queuing such buffers here.
  75. FFBufferEntry *waiting_buffers, *waiting_buffers_tail;
  76. int64_t packets_sent;
  77. atomic_int packets_buffered;
  78. int64_t frames_output;
  79. int eos_received;
  80. int eos_sent;
  81. int extradata_sent;
  82. int interlaced_frame;
  83. int top_field_first;
  84. } MMALDecodeContext;
  85. // Assume decoder is guaranteed to produce output after at least this many
  86. // packets (where each packet contains 1 frame).
  87. #define MAX_DELAYED_FRAMES 16
  88. static void ffmmal_poolref_unref(FFPoolRef *ref)
  89. {
  90. if (ref &&
  91. atomic_fetch_add_explicit(&ref->refcount, -1, memory_order_acq_rel) == 1) {
  92. mmal_pool_destroy(ref->pool);
  93. av_free(ref);
  94. }
  95. }
  96. static void ffmmal_release_frame(void *opaque, uint8_t *data)
  97. {
  98. FFBufferRef *ref = (void *)data;
  99. mmal_buffer_header_release(ref->buffer);
  100. ffmmal_poolref_unref(ref->pool);
  101. av_free(ref);
  102. }
  103. // Setup frame with a new reference to buffer. The buffer must have been
  104. // allocated from the given pool.
  105. static int ffmmal_set_ref(AVFrame *frame, FFPoolRef *pool,
  106. MMAL_BUFFER_HEADER_T *buffer)
  107. {
  108. FFBufferRef *ref = av_mallocz(sizeof(*ref));
  109. if (!ref)
  110. return AVERROR(ENOMEM);
  111. ref->pool = pool;
  112. ref->buffer = buffer;
  113. frame->buf[0] = av_buffer_create((void *)ref, sizeof(*ref),
  114. ffmmal_release_frame, NULL,
  115. AV_BUFFER_FLAG_READONLY);
  116. if (!frame->buf[0]) {
  117. av_free(ref);
  118. return AVERROR(ENOMEM);
  119. }
  120. atomic_fetch_add_explicit(&ref->pool->refcount, 1, memory_order_relaxed);
  121. mmal_buffer_header_acquire(buffer);
  122. frame->format = AV_PIX_FMT_MMAL;
  123. frame->data[3] = (uint8_t *)ref->buffer;
  124. return 0;
  125. }
  126. static void ffmmal_stop_decoder(AVCodecContext *avctx)
  127. {
  128. MMALDecodeContext *ctx = avctx->priv_data;
  129. MMAL_COMPONENT_T *decoder = ctx->decoder;
  130. MMAL_BUFFER_HEADER_T *buffer;
  131. mmal_port_disable(decoder->input[0]);
  132. mmal_port_disable(decoder->output[0]);
  133. mmal_port_disable(decoder->control);
  134. mmal_port_flush(decoder->input[0]);
  135. mmal_port_flush(decoder->output[0]);
  136. mmal_port_flush(decoder->control);
  137. while ((buffer = mmal_queue_get(ctx->queue_decoded_frames)))
  138. mmal_buffer_header_release(buffer);
  139. while (ctx->waiting_buffers) {
  140. FFBufferEntry *buffer = ctx->waiting_buffers;
  141. ctx->waiting_buffers = buffer->next;
  142. if (buffer->flags & MMAL_BUFFER_HEADER_FLAG_FRAME_END)
  143. atomic_fetch_add(&ctx->packets_buffered, -1);
  144. av_buffer_unref(&buffer->ref);
  145. av_free(buffer);
  146. }
  147. ctx->waiting_buffers_tail = NULL;
  148. av_assert0(atomic_load(&ctx->packets_buffered) == 0);
  149. ctx->frames_output = ctx->eos_received = ctx->eos_sent = ctx->packets_sent = ctx->extradata_sent = 0;
  150. }
  151. static av_cold int ffmmal_close_decoder(AVCodecContext *avctx)
  152. {
  153. MMALDecodeContext *ctx = avctx->priv_data;
  154. if (ctx->decoder)
  155. ffmmal_stop_decoder(avctx);
  156. mmal_component_destroy(ctx->decoder);
  157. ctx->decoder = NULL;
  158. mmal_queue_destroy(ctx->queue_decoded_frames);
  159. mmal_pool_destroy(ctx->pool_in);
  160. ffmmal_poolref_unref(ctx->pool_out);
  161. mmal_vc_deinit();
  162. return 0;
  163. }
  164. static void input_callback(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer)
  165. {
  166. AVCodecContext *avctx = (AVCodecContext*)port->userdata;
  167. MMALDecodeContext *ctx = avctx->priv_data;
  168. if (!buffer->cmd) {
  169. FFBufferEntry *entry = buffer->user_data;
  170. av_buffer_unref(&entry->ref);
  171. if (entry->flags & MMAL_BUFFER_HEADER_FLAG_FRAME_END)
  172. atomic_fetch_add(&ctx->packets_buffered, -1);
  173. av_free(entry);
  174. }
  175. mmal_buffer_header_release(buffer);
  176. }
  177. static void output_callback(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer)
  178. {
  179. AVCodecContext *avctx = (AVCodecContext*)port->userdata;
  180. MMALDecodeContext *ctx = avctx->priv_data;
  181. mmal_queue_put(ctx->queue_decoded_frames, buffer);
  182. }
  183. static void control_port_cb(MMAL_PORT_T *port, MMAL_BUFFER_HEADER_T *buffer)
  184. {
  185. AVCodecContext *avctx = (AVCodecContext*)port->userdata;
  186. MMAL_STATUS_T status;
  187. if (buffer->cmd == MMAL_EVENT_ERROR) {
  188. status = *(uint32_t *)buffer->data;
  189. av_log(avctx, AV_LOG_ERROR, "MMAL error %d on control port\n", (int)status);
  190. } else {
  191. av_log(avctx, AV_LOG_WARNING, "Unknown MMAL event %s on control port\n",
  192. av_fourcc2str(buffer->cmd));
  193. }
  194. mmal_buffer_header_release(buffer);
  195. }
  196. // Feed free output buffers to the decoder.
  197. static int ffmmal_fill_output_port(AVCodecContext *avctx)
  198. {
  199. MMALDecodeContext *ctx = avctx->priv_data;
  200. MMAL_BUFFER_HEADER_T *buffer;
  201. MMAL_STATUS_T status;
  202. if (!ctx->pool_out)
  203. return AVERROR_UNKNOWN; // format change code failed with OOM previously
  204. while ((buffer = mmal_queue_get(ctx->pool_out->pool->queue))) {
  205. if ((status = mmal_port_send_buffer(ctx->decoder->output[0], buffer))) {
  206. mmal_buffer_header_release(buffer);
  207. av_log(avctx, AV_LOG_ERROR, "MMAL error %d when sending output buffer.\n", (int)status);
  208. return AVERROR_UNKNOWN;
  209. }
  210. }
  211. return 0;
  212. }
  213. static enum AVColorSpace ffmmal_csp_to_av_csp(MMAL_FOURCC_T fourcc)
  214. {
  215. switch (fourcc) {
  216. case MMAL_COLOR_SPACE_BT470_2_BG:
  217. case MMAL_COLOR_SPACE_BT470_2_M:
  218. case MMAL_COLOR_SPACE_ITUR_BT601: return AVCOL_SPC_BT470BG;
  219. case MMAL_COLOR_SPACE_ITUR_BT709: return AVCOL_SPC_BT709;
  220. case MMAL_COLOR_SPACE_FCC: return AVCOL_SPC_FCC;
  221. case MMAL_COLOR_SPACE_SMPTE240M: return AVCOL_SPC_SMPTE240M;
  222. default: return AVCOL_SPC_UNSPECIFIED;
  223. }
  224. }
  225. static int ffmal_update_format(AVCodecContext *avctx)
  226. {
  227. MMALDecodeContext *ctx = avctx->priv_data;
  228. MMAL_STATUS_T status;
  229. int ret = 0;
  230. MMAL_COMPONENT_T *decoder = ctx->decoder;
  231. MMAL_ES_FORMAT_T *format_out = decoder->output[0]->format;
  232. MMAL_PARAMETER_VIDEO_INTERLACE_TYPE_T interlace_type;
  233. ffmmal_poolref_unref(ctx->pool_out);
  234. if (!(ctx->pool_out = av_mallocz(sizeof(*ctx->pool_out)))) {
  235. ret = AVERROR(ENOMEM);
  236. goto fail;
  237. }
  238. atomic_init(&ctx->pool_out->refcount, 1);
  239. if (!format_out)
  240. goto fail;
  241. if ((status = mmal_port_parameter_set_uint32(decoder->output[0], MMAL_PARAMETER_EXTRA_BUFFERS, ctx->extra_buffers)))
  242. goto fail;
  243. if ((status = mmal_port_parameter_set_boolean(decoder->output[0], MMAL_PARAMETER_VIDEO_INTERPOLATE_TIMESTAMPS, 0)))
  244. goto fail;
  245. if (avctx->pix_fmt == AV_PIX_FMT_MMAL) {
  246. format_out->encoding = MMAL_ENCODING_OPAQUE;
  247. } else {
  248. format_out->encoding_variant = format_out->encoding = MMAL_ENCODING_I420;
  249. }
  250. if ((status = mmal_port_format_commit(decoder->output[0])))
  251. goto fail;
  252. interlace_type.hdr.id = MMAL_PARAMETER_VIDEO_INTERLACE_TYPE;
  253. interlace_type.hdr.size = sizeof(MMAL_PARAMETER_VIDEO_INTERLACE_TYPE_T);
  254. status = mmal_port_parameter_get(decoder->output[0], &interlace_type.hdr);
  255. if (status != MMAL_SUCCESS) {
  256. av_log(avctx, AV_LOG_ERROR, "Cannot read MMAL interlace information!\n");
  257. } else {
  258. ctx->interlaced_frame = (interlace_type.eMode != MMAL_InterlaceProgressive);
  259. ctx->top_field_first = (interlace_type.eMode == MMAL_InterlaceFieldsInterleavedUpperFirst);
  260. }
  261. if ((ret = ff_set_dimensions(avctx, format_out->es->video.crop.x + format_out->es->video.crop.width,
  262. format_out->es->video.crop.y + format_out->es->video.crop.height)) < 0)
  263. goto fail;
  264. if (format_out->es->video.par.num && format_out->es->video.par.den) {
  265. avctx->sample_aspect_ratio.num = format_out->es->video.par.num;
  266. avctx->sample_aspect_ratio.den = format_out->es->video.par.den;
  267. }
  268. if (format_out->es->video.frame_rate.num && format_out->es->video.frame_rate.den) {
  269. avctx->framerate.num = format_out->es->video.frame_rate.num;
  270. avctx->framerate.den = format_out->es->video.frame_rate.den;
  271. }
  272. avctx->colorspace = ffmmal_csp_to_av_csp(format_out->es->video.color_space);
  273. decoder->output[0]->buffer_size =
  274. FFMAX(decoder->output[0]->buffer_size_min, decoder->output[0]->buffer_size_recommended);
  275. decoder->output[0]->buffer_num =
  276. FFMAX(decoder->output[0]->buffer_num_min, decoder->output[0]->buffer_num_recommended) + ctx->extra_buffers;
  277. ctx->pool_out->pool = mmal_pool_create(decoder->output[0]->buffer_num,
  278. decoder->output[0]->buffer_size);
  279. if (!ctx->pool_out->pool) {
  280. ret = AVERROR(ENOMEM);
  281. goto fail;
  282. }
  283. return 0;
  284. fail:
  285. return ret < 0 ? ret : AVERROR_UNKNOWN;
  286. }
  287. static av_cold int ffmmal_init_decoder(AVCodecContext *avctx)
  288. {
  289. MMALDecodeContext *ctx = avctx->priv_data;
  290. MMAL_STATUS_T status;
  291. MMAL_ES_FORMAT_T *format_in;
  292. MMAL_COMPONENT_T *decoder;
  293. int ret = 0;
  294. bcm_host_init();
  295. if (mmal_vc_init()) {
  296. av_log(avctx, AV_LOG_ERROR, "Cannot initialize MMAL VC driver!\n");
  297. return AVERROR(ENOSYS);
  298. }
  299. if ((ret = ff_get_format(avctx, avctx->codec->pix_fmts)) < 0)
  300. return ret;
  301. avctx->pix_fmt = ret;
  302. if ((status = mmal_component_create(MMAL_COMPONENT_DEFAULT_VIDEO_DECODER, &ctx->decoder)))
  303. goto fail;
  304. decoder = ctx->decoder;
  305. format_in = decoder->input[0]->format;
  306. format_in->type = MMAL_ES_TYPE_VIDEO;
  307. switch (avctx->codec_id) {
  308. case AV_CODEC_ID_MPEG2VIDEO:
  309. format_in->encoding = MMAL_ENCODING_MP2V;
  310. break;
  311. case AV_CODEC_ID_MPEG4:
  312. format_in->encoding = MMAL_ENCODING_MP4V;
  313. break;
  314. case AV_CODEC_ID_VC1:
  315. format_in->encoding = MMAL_ENCODING_WVC1;
  316. break;
  317. case AV_CODEC_ID_H264:
  318. default:
  319. format_in->encoding = MMAL_ENCODING_H264;
  320. break;
  321. }
  322. format_in->es->video.width = FFALIGN(avctx->width, 32);
  323. format_in->es->video.height = FFALIGN(avctx->height, 16);
  324. format_in->es->video.crop.width = avctx->width;
  325. format_in->es->video.crop.height = avctx->height;
  326. format_in->es->video.frame_rate.num = 24000;
  327. format_in->es->video.frame_rate.den = 1001;
  328. format_in->es->video.par.num = avctx->sample_aspect_ratio.num;
  329. format_in->es->video.par.den = avctx->sample_aspect_ratio.den;
  330. format_in->flags = MMAL_ES_FORMAT_FLAG_FRAMED;
  331. av_log(avctx, AV_LOG_DEBUG, "Using MMAL %s encoding.\n",
  332. av_fourcc2str(format_in->encoding));
  333. #if HAVE_MMAL_PARAMETER_VIDEO_MAX_NUM_CALLBACKS
  334. if (mmal_port_parameter_set_uint32(decoder->input[0], MMAL_PARAMETER_VIDEO_MAX_NUM_CALLBACKS,
  335. -1 - ctx->extra_decoder_buffers)) {
  336. av_log(avctx, AV_LOG_WARNING, "Could not set input buffering limit.\n");
  337. }
  338. #endif
  339. if ((status = mmal_port_format_commit(decoder->input[0])))
  340. goto fail;
  341. decoder->input[0]->buffer_num =
  342. FFMAX(decoder->input[0]->buffer_num_min, 20);
  343. decoder->input[0]->buffer_size =
  344. FFMAX(decoder->input[0]->buffer_size_min, 512 * 1024);
  345. ctx->pool_in = mmal_pool_create(decoder->input[0]->buffer_num, 0);
  346. if (!ctx->pool_in) {
  347. ret = AVERROR(ENOMEM);
  348. goto fail;
  349. }
  350. if ((ret = ffmal_update_format(avctx)) < 0)
  351. goto fail;
  352. ctx->queue_decoded_frames = mmal_queue_create();
  353. if (!ctx->queue_decoded_frames)
  354. goto fail;
  355. decoder->input[0]->userdata = (void*)avctx;
  356. decoder->output[0]->userdata = (void*)avctx;
  357. decoder->control->userdata = (void*)avctx;
  358. if ((status = mmal_port_enable(decoder->control, control_port_cb)))
  359. goto fail;
  360. if ((status = mmal_port_enable(decoder->input[0], input_callback)))
  361. goto fail;
  362. if ((status = mmal_port_enable(decoder->output[0], output_callback)))
  363. goto fail;
  364. if ((status = mmal_component_enable(decoder)))
  365. goto fail;
  366. return 0;
  367. fail:
  368. ffmmal_close_decoder(avctx);
  369. return ret < 0 ? ret : AVERROR_UNKNOWN;
  370. }
  371. static void ffmmal_flush(AVCodecContext *avctx)
  372. {
  373. MMALDecodeContext *ctx = avctx->priv_data;
  374. MMAL_COMPONENT_T *decoder = ctx->decoder;
  375. MMAL_STATUS_T status;
  376. ffmmal_stop_decoder(avctx);
  377. if ((status = mmal_port_enable(decoder->control, control_port_cb)))
  378. goto fail;
  379. if ((status = mmal_port_enable(decoder->input[0], input_callback)))
  380. goto fail;
  381. if ((status = mmal_port_enable(decoder->output[0], output_callback)))
  382. goto fail;
  383. return;
  384. fail:
  385. av_log(avctx, AV_LOG_ERROR, "MMAL flush error: %i\n", (int)status);
  386. }
  387. // Split packets and add them to the waiting_buffers list. We don't queue them
  388. // immediately, because it can happen that the decoder is temporarily blocked
  389. // (due to us not reading/returning enough output buffers) and won't accept
  390. // new input. (This wouldn't be an issue if MMAL input buffers always were
  391. // complete frames - then the input buffer just would have to be big enough.)
  392. // If is_extradata is set, send it as MMAL_BUFFER_HEADER_FLAG_CONFIG.
  393. static int ffmmal_add_packet(AVCodecContext *avctx, AVPacket *avpkt,
  394. int is_extradata)
  395. {
  396. MMALDecodeContext *ctx = avctx->priv_data;
  397. AVBufferRef *buf = NULL;
  398. int size = 0;
  399. uint8_t *data = (uint8_t *)"";
  400. uint8_t *start;
  401. int ret = 0;
  402. if (avpkt->size) {
  403. if (avpkt->buf) {
  404. buf = av_buffer_ref(avpkt->buf);
  405. size = avpkt->size;
  406. data = avpkt->data;
  407. } else {
  408. buf = av_buffer_alloc(avpkt->size);
  409. if (buf) {
  410. memcpy(buf->data, avpkt->data, avpkt->size);
  411. size = buf->size;
  412. data = buf->data;
  413. }
  414. }
  415. if (!buf) {
  416. ret = AVERROR(ENOMEM);
  417. goto done;
  418. }
  419. if (!is_extradata)
  420. ctx->packets_sent++;
  421. } else {
  422. if (ctx->eos_sent)
  423. goto done;
  424. if (!ctx->packets_sent) {
  425. // Short-cut the flush logic to avoid upsetting MMAL.
  426. ctx->eos_sent = 1;
  427. ctx->eos_received = 1;
  428. goto done;
  429. }
  430. }
  431. start = data;
  432. do {
  433. FFBufferEntry *buffer = av_mallocz(sizeof(*buffer));
  434. if (!buffer) {
  435. ret = AVERROR(ENOMEM);
  436. goto done;
  437. }
  438. buffer->data = data;
  439. buffer->length = FFMIN(size, ctx->decoder->input[0]->buffer_size);
  440. if (is_extradata)
  441. buffer->flags |= MMAL_BUFFER_HEADER_FLAG_CONFIG;
  442. if (data == start)
  443. buffer->flags |= MMAL_BUFFER_HEADER_FLAG_FRAME_START;
  444. data += buffer->length;
  445. size -= buffer->length;
  446. buffer->pts = avpkt->pts == AV_NOPTS_VALUE ? MMAL_TIME_UNKNOWN : avpkt->pts;
  447. buffer->dts = avpkt->dts == AV_NOPTS_VALUE ? MMAL_TIME_UNKNOWN : avpkt->dts;
  448. if (!size) {
  449. buffer->flags |= MMAL_BUFFER_HEADER_FLAG_FRAME_END;
  450. atomic_fetch_add(&ctx->packets_buffered, 1);
  451. }
  452. if (!buffer->length) {
  453. buffer->flags |= MMAL_BUFFER_HEADER_FLAG_EOS;
  454. ctx->eos_sent = 1;
  455. }
  456. if (buf) {
  457. buffer->ref = av_buffer_ref(buf);
  458. if (!buffer->ref) {
  459. av_free(buffer);
  460. ret = AVERROR(ENOMEM);
  461. goto done;
  462. }
  463. }
  464. // Insert at end of the list
  465. if (!ctx->waiting_buffers)
  466. ctx->waiting_buffers = buffer;
  467. if (ctx->waiting_buffers_tail)
  468. ctx->waiting_buffers_tail->next = buffer;
  469. ctx->waiting_buffers_tail = buffer;
  470. } while (size);
  471. done:
  472. av_buffer_unref(&buf);
  473. return ret;
  474. }
  475. // Move prepared/split packets from waiting_buffers to the MMAL decoder.
  476. static int ffmmal_fill_input_port(AVCodecContext *avctx)
  477. {
  478. MMALDecodeContext *ctx = avctx->priv_data;
  479. while (ctx->waiting_buffers) {
  480. MMAL_BUFFER_HEADER_T *mbuffer;
  481. FFBufferEntry *buffer;
  482. MMAL_STATUS_T status;
  483. mbuffer = mmal_queue_get(ctx->pool_in->queue);
  484. if (!mbuffer)
  485. return 0;
  486. buffer = ctx->waiting_buffers;
  487. mmal_buffer_header_reset(mbuffer);
  488. mbuffer->cmd = 0;
  489. mbuffer->pts = buffer->pts;
  490. mbuffer->dts = buffer->dts;
  491. mbuffer->flags = buffer->flags;
  492. mbuffer->data = buffer->data;
  493. mbuffer->length = buffer->length;
  494. mbuffer->user_data = buffer;
  495. mbuffer->alloc_size = ctx->decoder->input[0]->buffer_size;
  496. // Remove from start of the list
  497. ctx->waiting_buffers = buffer->next;
  498. if (ctx->waiting_buffers_tail == buffer)
  499. ctx->waiting_buffers_tail = NULL;
  500. if ((status = mmal_port_send_buffer(ctx->decoder->input[0], mbuffer))) {
  501. mmal_buffer_header_release(mbuffer);
  502. av_buffer_unref(&buffer->ref);
  503. if (buffer->flags & MMAL_BUFFER_HEADER_FLAG_FRAME_END)
  504. atomic_fetch_add(&ctx->packets_buffered, -1);
  505. av_free(buffer);
  506. }
  507. if (status) {
  508. av_log(avctx, AV_LOG_ERROR, "MMAL error %d when sending input\n", (int)status);
  509. return AVERROR_UNKNOWN;
  510. }
  511. }
  512. return 0;
  513. }
  514. static int ffmal_copy_frame(AVCodecContext *avctx, AVFrame *frame,
  515. MMAL_BUFFER_HEADER_T *buffer)
  516. {
  517. MMALDecodeContext *ctx = avctx->priv_data;
  518. int ret = 0;
  519. frame->interlaced_frame = ctx->interlaced_frame;
  520. frame->top_field_first = ctx->top_field_first;
  521. if (avctx->pix_fmt == AV_PIX_FMT_MMAL) {
  522. if (!ctx->pool_out)
  523. return AVERROR_UNKNOWN; // format change code failed with OOM previously
  524. if ((ret = ff_decode_frame_props(avctx, frame)) < 0)
  525. goto done;
  526. if ((ret = ffmmal_set_ref(frame, ctx->pool_out, buffer)) < 0)
  527. goto done;
  528. } else {
  529. int w = FFALIGN(avctx->width, 32);
  530. int h = FFALIGN(avctx->height, 16);
  531. uint8_t *src[4];
  532. int linesize[4];
  533. if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
  534. goto done;
  535. av_image_fill_arrays(src, linesize,
  536. buffer->data + buffer->type->video.offset[0],
  537. avctx->pix_fmt, w, h, 1);
  538. av_image_copy(frame->data, frame->linesize, src, linesize,
  539. avctx->pix_fmt, avctx->width, avctx->height);
  540. }
  541. frame->pts = buffer->pts == MMAL_TIME_UNKNOWN ? AV_NOPTS_VALUE : buffer->pts;
  542. #if FF_API_PKT_PTS
  543. FF_DISABLE_DEPRECATION_WARNINGS
  544. frame->pkt_pts = frame->pts;
  545. FF_ENABLE_DEPRECATION_WARNINGS
  546. #endif
  547. frame->pkt_dts = AV_NOPTS_VALUE;
  548. done:
  549. return ret;
  550. }
  551. // Fetch a decoded buffer and place it into the frame parameter.
  552. static int ffmmal_read_frame(AVCodecContext *avctx, AVFrame *frame, int *got_frame)
  553. {
  554. MMALDecodeContext *ctx = avctx->priv_data;
  555. MMAL_BUFFER_HEADER_T *buffer = NULL;
  556. MMAL_STATUS_T status = 0;
  557. int ret = 0;
  558. if (ctx->eos_received)
  559. goto done;
  560. while (1) {
  561. // To ensure decoding in lockstep with a constant delay between fed packets
  562. // and output frames, we always wait until an output buffer is available.
  563. // Except during start we don't know after how many input packets the decoder
  564. // is going to return the first buffer, and we can't distinguish decoder
  565. // being busy from decoder waiting for input. So just poll at the start and
  566. // keep feeding new data to the buffer.
  567. // We are pretty sure the decoder will produce output if we sent more input
  568. // frames than what a H.264 decoder could logically delay. This avoids too
  569. // excessive buffering.
  570. // We also wait if we sent eos, but didn't receive it yet (think of decoding
  571. // stream with a very low number of frames).
  572. if (atomic_load(&ctx->packets_buffered) > MAX_DELAYED_FRAMES ||
  573. (ctx->packets_sent && ctx->eos_sent)) {
  574. // MMAL will ignore broken input packets, which means the frame we
  575. // expect here may never arrive. Dealing with this correctly is
  576. // complicated, so here's a hack to avoid that it freezes forever
  577. // in this unlikely situation.
  578. buffer = mmal_queue_timedwait(ctx->queue_decoded_frames, 100);
  579. if (!buffer) {
  580. av_log(avctx, AV_LOG_ERROR, "Did not get output frame from MMAL.\n");
  581. ret = AVERROR_UNKNOWN;
  582. goto done;
  583. }
  584. } else {
  585. buffer = mmal_queue_get(ctx->queue_decoded_frames);
  586. if (!buffer)
  587. goto done;
  588. }
  589. ctx->eos_received |= !!(buffer->flags & MMAL_BUFFER_HEADER_FLAG_EOS);
  590. if (ctx->eos_received)
  591. goto done;
  592. if (buffer->cmd == MMAL_EVENT_FORMAT_CHANGED) {
  593. MMAL_COMPONENT_T *decoder = ctx->decoder;
  594. MMAL_EVENT_FORMAT_CHANGED_T *ev = mmal_event_format_changed_get(buffer);
  595. MMAL_BUFFER_HEADER_T *stale_buffer;
  596. av_log(avctx, AV_LOG_INFO, "Changing output format.\n");
  597. if ((status = mmal_port_disable(decoder->output[0])))
  598. goto done;
  599. while ((stale_buffer = mmal_queue_get(ctx->queue_decoded_frames)))
  600. mmal_buffer_header_release(stale_buffer);
  601. mmal_format_copy(decoder->output[0]->format, ev->format);
  602. if ((ret = ffmal_update_format(avctx)) < 0)
  603. goto done;
  604. if ((status = mmal_port_enable(decoder->output[0], output_callback)))
  605. goto done;
  606. if ((ret = ffmmal_fill_output_port(avctx)) < 0)
  607. goto done;
  608. if ((ret = ffmmal_fill_input_port(avctx)) < 0)
  609. goto done;
  610. mmal_buffer_header_release(buffer);
  611. continue;
  612. } else if (buffer->cmd) {
  613. av_log(avctx, AV_LOG_WARNING, "Unknown MMAL event %s on output port\n",
  614. av_fourcc2str(buffer->cmd));
  615. goto done;
  616. } else if (buffer->length == 0) {
  617. // Unused output buffer that got drained after format change.
  618. mmal_buffer_header_release(buffer);
  619. continue;
  620. }
  621. ctx->frames_output++;
  622. if ((ret = ffmal_copy_frame(avctx, frame, buffer)) < 0)
  623. goto done;
  624. *got_frame = 1;
  625. break;
  626. }
  627. done:
  628. if (buffer)
  629. mmal_buffer_header_release(buffer);
  630. if (status && ret >= 0)
  631. ret = AVERROR_UNKNOWN;
  632. return ret;
  633. }
  634. static int ffmmal_decode(AVCodecContext *avctx, void *data, int *got_frame,
  635. AVPacket *avpkt)
  636. {
  637. MMALDecodeContext *ctx = avctx->priv_data;
  638. AVFrame *frame = data;
  639. int ret = 0;
  640. if (avctx->extradata_size && !ctx->extradata_sent) {
  641. AVPacket pkt = {0};
  642. av_init_packet(&pkt);
  643. pkt.data = avctx->extradata;
  644. pkt.size = avctx->extradata_size;
  645. ctx->extradata_sent = 1;
  646. if ((ret = ffmmal_add_packet(avctx, &pkt, 1)) < 0)
  647. return ret;
  648. }
  649. if ((ret = ffmmal_add_packet(avctx, avpkt, 0)) < 0)
  650. return ret;
  651. if ((ret = ffmmal_fill_input_port(avctx)) < 0)
  652. return ret;
  653. if ((ret = ffmmal_fill_output_port(avctx)) < 0)
  654. return ret;
  655. if ((ret = ffmmal_read_frame(avctx, frame, got_frame)) < 0)
  656. return ret;
  657. // ffmmal_read_frame() can block for a while. Since the decoder is
  658. // asynchronous, it's a good idea to fill the ports again.
  659. if ((ret = ffmmal_fill_output_port(avctx)) < 0)
  660. return ret;
  661. if ((ret = ffmmal_fill_input_port(avctx)) < 0)
  662. return ret;
  663. return ret;
  664. }
  665. static const AVCodecHWConfigInternal *mmal_hw_configs[] = {
  666. HW_CONFIG_INTERNAL(MMAL),
  667. NULL
  668. };
  669. static const AVOption options[]={
  670. {"extra_buffers", "extra buffers", offsetof(MMALDecodeContext, extra_buffers), AV_OPT_TYPE_INT, {.i64 = 10}, 0, 256, 0},
  671. {"extra_decoder_buffers", "extra MMAL internal buffered frames", offsetof(MMALDecodeContext, extra_decoder_buffers), AV_OPT_TYPE_INT, {.i64 = 10}, 0, 256, 0},
  672. {NULL}
  673. };
  674. #define FFMMAL_DEC_CLASS(NAME) \
  675. static const AVClass ffmmal_##NAME##_dec_class = { \
  676. .class_name = "mmal_" #NAME "_dec", \
  677. .item_name = av_default_item_name, \
  678. .option = options, \
  679. .version = LIBAVUTIL_VERSION_INT, \
  680. };
  681. #define FFMMAL_DEC(NAME, ID) \
  682. FFMMAL_DEC_CLASS(NAME) \
  683. AVCodec ff_##NAME##_mmal_decoder = { \
  684. .name = #NAME "_mmal", \
  685. .long_name = NULL_IF_CONFIG_SMALL(#NAME " (mmal)"), \
  686. .type = AVMEDIA_TYPE_VIDEO, \
  687. .id = ID, \
  688. .priv_data_size = sizeof(MMALDecodeContext), \
  689. .init = ffmmal_init_decoder, \
  690. .close = ffmmal_close_decoder, \
  691. .decode = ffmmal_decode, \
  692. .flush = ffmmal_flush, \
  693. .priv_class = &ffmmal_##NAME##_dec_class, \
  694. .capabilities = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_HARDWARE, \
  695. .caps_internal = FF_CODEC_CAP_SETS_PKT_DTS, \
  696. .pix_fmts = (const enum AVPixelFormat[]) { AV_PIX_FMT_MMAL, \
  697. AV_PIX_FMT_YUV420P, \
  698. AV_PIX_FMT_NONE}, \
  699. .hw_configs = mmal_hw_configs, \
  700. .wrapper_name = "mmal", \
  701. };
  702. FFMMAL_DEC(h264, AV_CODEC_ID_H264)
  703. FFMMAL_DEC(mpeg2, AV_CODEC_ID_MPEG2VIDEO)
  704. FFMMAL_DEC(mpeg4, AV_CODEC_ID_MPEG4)
  705. FFMMAL_DEC(vc1, AV_CODEC_ID_VC1)