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.

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