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.

857 lines
28KB

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