2 * Android camera input device
4 * Copyright (C) 2017 Felix Matouschek
6 * This file is part of FFmpeg.
8 * FFmpeg is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * FFmpeg is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with FFmpeg; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 #include <stdatomic.h>
29 #include <camera/NdkCameraDevice.h>
30 #include <camera/NdkCameraManager.h>
31 #include <media/NdkImage.h>
32 #include <media/NdkImageReader.h>
34 #include "libavformat/avformat.h"
35 #include "libavformat/internal.h"
36 #include "libavutil/avstring.h"
37 #include "libavutil/display.h"
38 #include "libavutil/imgutils.h"
39 #include "libavutil/log.h"
40 #include "libavutil/opt.h"
41 #include "libavutil/parseutils.h"
42 #include "libavutil/pixfmt.h"
43 #include "libavutil/threadmessage.h"
44 #include "libavutil/time.h"
48 /* This image format is available on all Android devices
49 * supporting the Camera2 API */
50 #define IMAGE_FORMAT_ANDROID AIMAGE_FORMAT_YUV_420_888
52 #define MAX_BUF_COUNT 2
53 #define VIDEO_STREAM_INDEX 0
54 #define VIDEO_TIMEBASE_ANDROID 1000000000
56 #define RETURN_CASE(x) case x: return AV_STRINGIFY(x);
57 #define RETURN_DEFAULT(x) default: return AV_STRINGIFY(x);
59 typedef struct AndroidCameraCtx {
69 int32_t sensor_orientation;
72 int32_t framerate_range[2];
75 ACameraManager *camera_mgr;
77 ACameraMetadata *camera_metadata;
78 ACameraDevice *camera_dev;
79 ACameraDevice_StateCallbacks camera_state_callbacks;
80 AImageReader *image_reader;
81 AImageReader_ImageListener image_listener;
82 ANativeWindow *image_reader_window;
83 ACaptureSessionOutputContainer *capture_session_output_container;
84 ACaptureSessionOutput *capture_session_output;
85 ACameraOutputTarget *camera_output_target;
86 ACaptureRequest *capture_request;
87 ACameraCaptureSession_stateCallbacks capture_session_state_callbacks;
88 ACameraCaptureSession *capture_session;
90 AVThreadMessageQueue *input_queue;
92 atomic_int got_image_format;
95 static const char *camera_status_string(camera_status_t val)
98 RETURN_CASE(ACAMERA_OK)
99 RETURN_CASE(ACAMERA_ERROR_UNKNOWN)
100 RETURN_CASE(ACAMERA_ERROR_INVALID_PARAMETER)
101 RETURN_CASE(ACAMERA_ERROR_CAMERA_DISCONNECTED)
102 RETURN_CASE(ACAMERA_ERROR_NOT_ENOUGH_MEMORY)
103 RETURN_CASE(ACAMERA_ERROR_METADATA_NOT_FOUND)
104 RETURN_CASE(ACAMERA_ERROR_CAMERA_DEVICE)
105 RETURN_CASE(ACAMERA_ERROR_CAMERA_SERVICE)
106 RETURN_CASE(ACAMERA_ERROR_SESSION_CLOSED)
107 RETURN_CASE(ACAMERA_ERROR_INVALID_OPERATION)
108 RETURN_CASE(ACAMERA_ERROR_STREAM_CONFIGURE_FAIL)
109 RETURN_CASE(ACAMERA_ERROR_CAMERA_IN_USE)
110 RETURN_CASE(ACAMERA_ERROR_MAX_CAMERA_IN_USE)
111 RETURN_CASE(ACAMERA_ERROR_CAMERA_DISABLED)
112 RETURN_CASE(ACAMERA_ERROR_PERMISSION_DENIED)
113 RETURN_DEFAULT(ACAMERA_ERROR_UNKNOWN)
117 static const char *media_status_string(media_status_t val)
120 RETURN_CASE(AMEDIA_OK)
121 RETURN_CASE(AMEDIA_ERROR_UNKNOWN)
122 RETURN_CASE(AMEDIA_ERROR_MALFORMED)
123 RETURN_CASE(AMEDIA_ERROR_UNSUPPORTED)
124 RETURN_CASE(AMEDIA_ERROR_INVALID_OBJECT)
125 RETURN_CASE(AMEDIA_ERROR_INVALID_PARAMETER)
126 RETURN_CASE(AMEDIA_ERROR_INVALID_OPERATION)
127 RETURN_CASE(AMEDIA_DRM_NOT_PROVISIONED)
128 RETURN_CASE(AMEDIA_DRM_RESOURCE_BUSY)
129 RETURN_CASE(AMEDIA_DRM_DEVICE_REVOKED)
130 RETURN_CASE(AMEDIA_DRM_SHORT_BUFFER)
131 RETURN_CASE(AMEDIA_DRM_SESSION_NOT_OPENED)
132 RETURN_CASE(AMEDIA_DRM_TAMPER_DETECTED)
133 RETURN_CASE(AMEDIA_DRM_VERIFY_FAILED)
134 RETURN_CASE(AMEDIA_DRM_NEED_KEY)
135 RETURN_CASE(AMEDIA_DRM_LICENSE_EXPIRED)
136 RETURN_CASE(AMEDIA_IMGREADER_NO_BUFFER_AVAILABLE)
137 RETURN_CASE(AMEDIA_IMGREADER_MAX_IMAGES_ACQUIRED)
138 RETURN_CASE(AMEDIA_IMGREADER_CANNOT_LOCK_IMAGE)
139 RETURN_CASE(AMEDIA_IMGREADER_CANNOT_UNLOCK_IMAGE)
140 RETURN_CASE(AMEDIA_IMGREADER_IMAGE_NOT_LOCKED)
141 RETURN_DEFAULT(AMEDIA_ERROR_UNKNOWN)
145 static const char *error_state_callback_string(int val)
148 RETURN_CASE(ERROR_CAMERA_IN_USE)
149 RETURN_CASE(ERROR_MAX_CAMERAS_IN_USE)
150 RETURN_CASE(ERROR_CAMERA_DISABLED)
151 RETURN_CASE(ERROR_CAMERA_DEVICE)
152 RETURN_CASE(ERROR_CAMERA_SERVICE)
154 return "ERROR_CAMERA_UNKNOWN";
158 static void camera_dev_disconnected(void *context, ACameraDevice *device)
160 AVFormatContext *avctx = context;
161 AndroidCameraCtx *ctx = avctx->priv_data;
162 atomic_store(&ctx->exit, 1);
163 av_log(avctx, AV_LOG_ERROR, "Camera with id %s disconnected.\n",
164 ACameraDevice_getId(device));
167 static void camera_dev_error(void *context, ACameraDevice *device, int error)
169 AVFormatContext *avctx = context;
170 AndroidCameraCtx *ctx = avctx->priv_data;
171 atomic_store(&ctx->exit, 1);
172 av_log(avctx, AV_LOG_ERROR, "Error %s on camera with id %s.\n",
173 error_state_callback_string(error), ACameraDevice_getId(device));
176 static int open_camera(AVFormatContext *avctx)
178 AndroidCameraCtx *ctx = avctx->priv_data;
180 ACameraIdList *camera_ids;
182 ret = ACameraManager_getCameraIdList(ctx->camera_mgr, &camera_ids);
183 if (ret != ACAMERA_OK) {
184 av_log(avctx, AV_LOG_ERROR, "Failed to get camera id list, error: %s.\n",
185 camera_status_string(ret));
186 return AVERROR_EXTERNAL;
189 if (ctx->camera_index < camera_ids->numCameras) {
190 ctx->camera_id = av_strdup(camera_ids->cameraIds[ctx->camera_index]);
191 if (!ctx->camera_id) {
192 av_log(avctx, AV_LOG_ERROR, "Failed to allocate memory for camera_id.\n");
193 return AVERROR(ENOMEM);
196 av_log(avctx, AV_LOG_ERROR, "No camera with index %d available.\n",
198 return AVERROR(ENXIO);
201 ACameraManager_deleteCameraIdList(camera_ids);
203 ret = ACameraManager_getCameraCharacteristics(ctx->camera_mgr,
204 ctx->camera_id, &ctx->camera_metadata);
205 if (ret != ACAMERA_OK) {
206 av_log(avctx, AV_LOG_ERROR, "Failed to get metadata for camera with id %s, error: %s.\n",
207 ctx->camera_id, camera_status_string(ret));
208 return AVERROR_EXTERNAL;
211 ctx->camera_state_callbacks.context = avctx;
212 ctx->camera_state_callbacks.onDisconnected = camera_dev_disconnected;
213 ctx->camera_state_callbacks.onError = camera_dev_error;
215 ret = ACameraManager_openCamera(ctx->camera_mgr, ctx->camera_id,
216 &ctx->camera_state_callbacks, &ctx->camera_dev);
217 if (ret != ACAMERA_OK) {
218 av_log(avctx, AV_LOG_ERROR, "Failed to open camera with id %s, error: %s.\n",
219 ctx->camera_id, camera_status_string(ret));
220 return AVERROR_EXTERNAL;
226 static void get_sensor_orientation(AVFormatContext *avctx)
228 AndroidCameraCtx *ctx = avctx->priv_data;
229 ACameraMetadata_const_entry lens_facing;
230 ACameraMetadata_const_entry sensor_orientation;
232 ACameraMetadata_getConstEntry(ctx->camera_metadata,
233 ACAMERA_LENS_FACING, &lens_facing);
234 ACameraMetadata_getConstEntry(ctx->camera_metadata,
235 ACAMERA_SENSOR_ORIENTATION, &sensor_orientation);
237 ctx->lens_facing = lens_facing.data.u8[0];
238 ctx->sensor_orientation = sensor_orientation.data.i32[0];
241 static void match_video_size(AVFormatContext *avctx)
243 AndroidCameraCtx *ctx = avctx->priv_data;
244 ACameraMetadata_const_entry available_configs;
247 ACameraMetadata_getConstEntry(ctx->camera_metadata,
248 ACAMERA_SCALER_AVAILABLE_STREAM_CONFIGURATIONS,
251 for (int i = 0; i < available_configs.count; i++) {
252 int32_t input = available_configs.data.i32[i * 4 + 3];
253 int32_t format = available_configs.data.i32[i * 4 + 0];
259 if (format == IMAGE_FORMAT_ANDROID) {
260 int32_t width = available_configs.data.i32[i * 4 + 1];
261 int32_t height = available_configs.data.i32[i * 4 + 2];
264 if ((ctx->requested_width == width && ctx->requested_height == height) ||
265 (ctx->requested_width == height && ctx->requested_height == width)) {
267 ctx->height = height;
274 if (!found || ctx->width == 0 || ctx->height == 0) {
275 ctx->width = available_configs.data.i32[1];
276 ctx->height = available_configs.data.i32[2];
278 av_log(avctx, AV_LOG_WARNING,
279 "Requested video_size %dx%d not available, falling back to %dx%d\n",
280 ctx->requested_width, ctx->requested_height, ctx->width, ctx->height);
286 static void match_framerate(AVFormatContext *avctx)
288 AndroidCameraCtx *ctx = avctx->priv_data;
289 ACameraMetadata_const_entry available_framerates;
291 int current_best_match = -1;
292 int requested_framerate = av_q2d(ctx->framerate);
294 ACameraMetadata_getConstEntry(ctx->camera_metadata,
295 ACAMERA_CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES,
296 &available_framerates);
298 for (int i = 0; i < available_framerates.count; i++) {
299 int32_t min = available_framerates.data.i32[i * 2 + 0];
300 int32_t max = available_framerates.data.i32[i * 2 + 1];
302 if (requested_framerate == max) {
304 ctx->framerate_range[0] = min;
305 ctx->framerate_range[1] = max;
308 } else if (current_best_match >= 0) {
309 int32_t current_best_match_min = available_framerates.data.i32[current_best_match * 2 + 0];
310 if (min > current_best_match_min) {
311 current_best_match = i;
314 current_best_match = i;
320 if (current_best_match >= 0) {
321 ctx->framerate_range[0] = available_framerates.data.i32[current_best_match * 2 + 0];
322 ctx->framerate_range[1] = available_framerates.data.i32[current_best_match * 2 + 1];
325 ctx->framerate_range[0] = available_framerates.data.i32[0];
326 ctx->framerate_range[1] = available_framerates.data.i32[1];
329 av_log(avctx, AV_LOG_WARNING,
330 "Requested framerate %d not available, falling back to min: %d and max: %d fps\n",
331 requested_framerate, ctx->framerate_range[0], ctx->framerate_range[1]);
337 static int get_image_format(AVFormatContext *avctx, AImage *image)
339 AndroidCameraCtx *ctx = avctx->priv_data;
340 int32_t image_pixelstrides[2];
341 uint8_t *image_plane_data[2];
342 int plane_data_length[2];
344 for (int i = 0; i < 2; i++) {
345 AImage_getPlanePixelStride(image, i + 1, &image_pixelstrides[i]);
346 AImage_getPlaneData(image, i + 1, &image_plane_data[i], &plane_data_length[i]);
349 if (image_pixelstrides[0] != image_pixelstrides[1]) {
350 av_log(avctx, AV_LOG_ERROR,
351 "Pixel strides of U and V plane should have been the same.\n");
352 return AVERROR_EXTERNAL;
355 switch (image_pixelstrides[0]) {
357 ctx->image_format = AV_PIX_FMT_YUV420P;
360 if (image_plane_data[0] < image_plane_data[1]) {
361 ctx->image_format = AV_PIX_FMT_NV12;
363 ctx->image_format = AV_PIX_FMT_NV21;
367 av_log(avctx, AV_LOG_ERROR,
368 "Unknown pixel stride %d of U and V plane, cannot determine camera image format.\n",
369 image_pixelstrides[0]);
370 return AVERROR(ENOSYS);
376 static void image_available(void *context, AImageReader *reader)
378 AVFormatContext *avctx = context;
379 AndroidCameraCtx *ctx = avctx->priv_data;
380 media_status_t media_status;
384 int64_t image_timestamp;
385 int32_t image_linestrides[4];
386 uint8_t *image_plane_data[4];
387 int plane_data_length[4];
390 int pkt_buffer_size = 0;
392 media_status = AImageReader_acquireLatestImage(reader, &image);
393 if (media_status != AMEDIA_OK) {
394 if (media_status == AMEDIA_IMGREADER_NO_BUFFER_AVAILABLE) {
395 av_log(avctx, AV_LOG_WARNING,
396 "An image reader frame was discarded");
398 av_log(avctx, AV_LOG_ERROR,
399 "Failed to acquire latest image from image reader, error: %s.\n",
400 media_status_string(media_status));
401 ret = AVERROR_EXTERNAL;
406 // Silently drop frames when exit is set
407 if (atomic_load(&ctx->exit)) {
411 // Determine actual image format
412 if (!atomic_load(&ctx->got_image_format)) {
413 ret = get_image_format(avctx, image);
415 av_log(avctx, AV_LOG_ERROR,
416 "Could not get image format of camera.\n");
419 atomic_store(&ctx->got_image_format, 1);
423 pkt_buffer_size = av_image_get_buffer_size(ctx->image_format, ctx->width, ctx->height, 32);
424 AImage_getTimestamp(image, &image_timestamp);
426 AImage_getPlaneRowStride(image, 0, &image_linestrides[0]);
427 AImage_getPlaneData(image, 0, &image_plane_data[0], &plane_data_length[0]);
429 switch (ctx->image_format) {
430 case AV_PIX_FMT_YUV420P:
431 AImage_getPlaneRowStride(image, 1, &image_linestrides[1]);
432 AImage_getPlaneData(image, 1, &image_plane_data[1], &plane_data_length[1]);
433 AImage_getPlaneRowStride(image, 2, &image_linestrides[2]);
434 AImage_getPlaneData(image, 2, &image_plane_data[2], &plane_data_length[2]);
436 case AV_PIX_FMT_NV12:
437 AImage_getPlaneRowStride(image, 1, &image_linestrides[1]);
438 AImage_getPlaneData(image, 1, &image_plane_data[1], &plane_data_length[1]);
440 case AV_PIX_FMT_NV21:
441 AImage_getPlaneRowStride(image, 2, &image_linestrides[1]);
442 AImage_getPlaneData(image, 2, &image_plane_data[1], &plane_data_length[1]);
445 av_log(avctx, AV_LOG_ERROR, "Unsupported camera image format.\n");
446 ret = AVERROR(ENOSYS);
450 ret = av_new_packet(&pkt, pkt_buffer_size);
452 av_log(avctx, AV_LOG_ERROR,
453 "Failed to create new av packet, error: %s.\n", av_err2str(ret));
457 pkt.stream_index = VIDEO_STREAM_INDEX;
458 pkt.pts = image_timestamp;
459 av_image_copy_to_buffer(pkt.data, pkt_buffer_size,
460 (const uint8_t * const *) image_plane_data,
461 image_linestrides, ctx->image_format,
462 ctx->width, ctx->height, 32);
464 ret = av_thread_message_queue_send(ctx->input_queue, &pkt, AV_THREAD_MESSAGE_NONBLOCK);
468 if (ret != AVERROR(EAGAIN)) {
469 av_log(avctx, AV_LOG_ERROR,
470 "Error while processing new image, error: %s.\n", av_err2str(ret));
471 av_thread_message_queue_set_err_recv(ctx->input_queue, ret);
472 atomic_store(&ctx->exit, 1);
474 av_log(avctx, AV_LOG_WARNING,
475 "Input queue was full, dropping frame, consider raising the input_queue_size option (current value: %d)\n",
476 ctx->input_queue_size);
478 if (pkt_buffer_size) {
479 av_packet_unref(&pkt);
483 AImage_delete(image);
488 static int create_image_reader(AVFormatContext *avctx)
490 AndroidCameraCtx *ctx = avctx->priv_data;
493 ret = AImageReader_new(ctx->width, ctx->height, IMAGE_FORMAT_ANDROID,
494 MAX_BUF_COUNT, &ctx->image_reader);
495 if (ret != AMEDIA_OK) {
496 av_log(avctx, AV_LOG_ERROR,
497 "Failed to create image reader, error: %s.\n", media_status_string(ret));
498 return AVERROR_EXTERNAL;
501 ctx->image_listener.context = avctx;
502 ctx->image_listener.onImageAvailable = image_available;
504 ret = AImageReader_setImageListener(ctx->image_reader, &ctx->image_listener);
505 if (ret != AMEDIA_OK) {
506 av_log(avctx, AV_LOG_ERROR,
507 "Failed to set image listener on image reader, error: %s.\n",
508 media_status_string(ret));
509 return AVERROR_EXTERNAL;
512 ret = AImageReader_getWindow(ctx->image_reader, &ctx->image_reader_window);
513 if (ret != AMEDIA_OK) {
514 av_log(avctx, AV_LOG_ERROR,
515 "Could not get image reader window, error: %s.\n",
516 media_status_string(ret));
517 return AVERROR_EXTERNAL;
523 static void capture_session_closed(void *context, ACameraCaptureSession *session)
525 av_log(context, AV_LOG_INFO, "Android camera capture session was closed.\n");
528 static void capture_session_ready(void *context, ACameraCaptureSession *session)
530 av_log(context, AV_LOG_INFO, "Android camera capture session is ready.\n");
533 static void capture_session_active(void *context, ACameraCaptureSession *session)
535 av_log(context, AV_LOG_INFO, "Android camera capture session is active.\n");
538 static int create_capture_session(AVFormatContext *avctx)
540 AndroidCameraCtx *ctx = avctx->priv_data;
543 ret = ACaptureSessionOutputContainer_create(&ctx->capture_session_output_container);
544 if (ret != ACAMERA_OK) {
545 av_log(avctx, AV_LOG_ERROR,
546 "Failed to create capture session output container, error: %s.\n",
547 camera_status_string(ret));
548 return AVERROR_EXTERNAL;
551 ANativeWindow_acquire(ctx->image_reader_window);
553 ret = ACaptureSessionOutput_create(ctx->image_reader_window, &ctx->capture_session_output);
554 if (ret != ACAMERA_OK) {
555 av_log(avctx, AV_LOG_ERROR,
556 "Failed to create capture session container, error: %s.\n",
557 camera_status_string(ret));
558 return AVERROR_EXTERNAL;
561 ret = ACaptureSessionOutputContainer_add(ctx->capture_session_output_container,
562 ctx->capture_session_output);
563 if (ret != ACAMERA_OK) {
564 av_log(avctx, AV_LOG_ERROR,
565 "Failed to add output to output container, error: %s.\n",
566 camera_status_string(ret));
567 return AVERROR_EXTERNAL;
570 ret = ACameraOutputTarget_create(ctx->image_reader_window, &ctx->camera_output_target);
571 if (ret != ACAMERA_OK) {
572 av_log(avctx, AV_LOG_ERROR,
573 "Failed to create camera output target, error: %s.\n",
574 camera_status_string(ret));
575 return AVERROR_EXTERNAL;
578 ret = ACameraDevice_createCaptureRequest(ctx->camera_dev, TEMPLATE_RECORD, &ctx->capture_request);
579 if (ret != ACAMERA_OK) {
580 av_log(avctx, AV_LOG_ERROR,
581 "Failed to create capture request, error: %s.\n",
582 camera_status_string(ret));
583 return AVERROR_EXTERNAL;
586 ret = ACaptureRequest_setEntry_i32(ctx->capture_request, ACAMERA_CONTROL_AE_TARGET_FPS_RANGE,
587 2, ctx->framerate_range);
588 if (ret != ACAMERA_OK) {
589 av_log(avctx, AV_LOG_ERROR,
590 "Failed to set target fps range in capture request, error: %s.\n",
591 camera_status_string(ret));
592 return AVERROR_EXTERNAL;
595 ret = ACaptureRequest_addTarget(ctx->capture_request, ctx->camera_output_target);
596 if (ret != ACAMERA_OK) {
597 av_log(avctx, AV_LOG_ERROR,
598 "Failed to add capture request capture request, error: %s.\n",
599 camera_status_string(ret));
600 return AVERROR_EXTERNAL;
603 ctx->capture_session_state_callbacks.context = avctx;
604 ctx->capture_session_state_callbacks.onClosed = capture_session_closed;
605 ctx->capture_session_state_callbacks.onReady = capture_session_ready;
606 ctx->capture_session_state_callbacks.onActive = capture_session_active;
608 ret = ACameraDevice_createCaptureSession(ctx->camera_dev, ctx->capture_session_output_container,
609 &ctx->capture_session_state_callbacks, &ctx->capture_session);
610 if (ret != ACAMERA_OK) {
611 av_log(avctx, AV_LOG_ERROR,
612 "Failed to create capture session, error: %s.\n",
613 camera_status_string(ret));
614 return AVERROR_EXTERNAL;
617 ret = ACameraCaptureSession_setRepeatingRequest(ctx->capture_session, NULL, 1, &ctx->capture_request, NULL);
618 if (ret != ACAMERA_OK) {
619 av_log(avctx, AV_LOG_ERROR,
620 "Failed to set repeating request on capture session, error: %s.\n",
621 camera_status_string(ret));
622 return AVERROR_EXTERNAL;
628 static int wait_for_image_format(AVFormatContext *avctx)
630 AndroidCameraCtx *ctx = avctx->priv_data;
632 while (!atomic_load(&ctx->got_image_format) && !atomic_load(&ctx->exit)) {
633 //Wait until first frame arrived and actual image format was determined
637 return atomic_load(&ctx->got_image_format);
640 static int add_display_matrix(AVFormatContext *avctx, AVStream *st)
642 AndroidCameraCtx *ctx = avctx->priv_data;
644 int32_t display_matrix[9];
646 av_display_rotation_set(display_matrix, ctx->sensor_orientation);
648 if (ctx->lens_facing == ACAMERA_LENS_FACING_FRONT) {
649 av_display_matrix_flip(display_matrix, 1, 0);
652 side_data = av_stream_new_side_data(st,
653 AV_PKT_DATA_DISPLAYMATRIX, sizeof(display_matrix));
656 return AVERROR(ENOMEM);
659 memcpy(side_data, display_matrix, sizeof(display_matrix));
664 static int add_video_stream(AVFormatContext *avctx)
666 AndroidCameraCtx *ctx = avctx->priv_data;
668 AVCodecParameters *codecpar;
670 st = avformat_new_stream(avctx, NULL);
672 return AVERROR(ENOMEM);
675 st->id = VIDEO_STREAM_INDEX;
676 st->avg_frame_rate = (AVRational) { ctx->framerate_range[1], 1 };
677 st->r_frame_rate = (AVRational) { ctx->framerate_range[1], 1 };
679 if (!wait_for_image_format(avctx)) {
680 return AVERROR_EXTERNAL;
683 codecpar = st->codecpar;
684 codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
685 codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
686 codecpar->format = ctx->image_format;
687 codecpar->width = ctx->width;
688 codecpar->height = ctx->height;
690 avpriv_set_pts_info(st, 64, 1, VIDEO_TIMEBASE_ANDROID);
692 return add_display_matrix(avctx, st);
695 static int android_camera_read_close(AVFormatContext *avctx)
697 AndroidCameraCtx *ctx = avctx->priv_data;
699 atomic_store(&ctx->exit, 1);
701 if (ctx->capture_session) {
702 ACameraCaptureSession_stopRepeating(ctx->capture_session);
703 // Following warning is emitted, after capture session closed callback is received:
704 // ACameraCaptureSession: Device is closed but session 0 is not notified
705 // Seems to be a bug in Android, we can ignore this
706 ACameraCaptureSession_close(ctx->capture_session);
707 ctx->capture_session = NULL;
710 if (ctx->capture_request) {
711 ACaptureRequest_removeTarget(ctx->capture_request, ctx->camera_output_target);
712 ACaptureRequest_free(ctx->capture_request);
713 ctx->capture_request = NULL;
716 if (ctx->camera_output_target) {
717 ACameraOutputTarget_free(ctx->camera_output_target);
718 ctx->camera_output_target = NULL;
721 if (ctx->capture_session_output) {
722 ACaptureSessionOutputContainer_remove(ctx->capture_session_output_container,
723 ctx->capture_session_output);
724 ACaptureSessionOutput_free(ctx->capture_session_output);
725 ctx->capture_session_output = NULL;
728 if (ctx->image_reader_window) {
729 ANativeWindow_release(ctx->image_reader_window);
730 ctx->image_reader_window = NULL;
733 if (ctx->capture_session_output_container) {
734 ACaptureSessionOutputContainer_free(ctx->capture_session_output_container);
735 ctx->capture_session_output_container = NULL;
738 if (ctx->camera_dev) {
739 ACameraDevice_close(ctx->camera_dev);
740 ctx->camera_dev = NULL;
743 if (ctx->image_reader) {
744 AImageReader_delete(ctx->image_reader);
745 ctx->image_reader = NULL;
748 if (ctx->camera_metadata) {
749 ACameraMetadata_free(ctx->camera_metadata);
750 ctx->camera_metadata = NULL;
753 av_freep(&ctx->camera_id);
755 if (ctx->camera_mgr) {
756 ACameraManager_delete(ctx->camera_mgr);
757 ctx->camera_mgr = NULL;
760 if (ctx->input_queue) {
762 av_thread_message_queue_set_err_send(ctx->input_queue, AVERROR_EOF);
763 while (av_thread_message_queue_recv(ctx->input_queue, &pkt, AV_THREAD_MESSAGE_NONBLOCK) >= 0) {
764 av_packet_unref(&pkt);
766 av_thread_message_queue_free(&ctx->input_queue);
772 static int android_camera_read_header(AVFormatContext *avctx)
774 AndroidCameraCtx *ctx = avctx->priv_data;
777 atomic_init(&ctx->got_image_format, 0);
778 atomic_init(&ctx->exit, 0);
780 ret = av_thread_message_queue_alloc(&ctx->input_queue, ctx->input_queue_size, sizeof(AVPacket));
782 av_log(avctx, AV_LOG_ERROR,
783 "Failed to allocate input queue, error: %s.\n", av_err2str(ret));
787 ctx->camera_mgr = ACameraManager_create();
788 if (!ctx->camera_mgr) {
789 av_log(avctx, AV_LOG_ERROR, "Failed to create Android camera manager.\n");
790 ret = AVERROR_EXTERNAL;
794 ret = open_camera(avctx);
796 av_log(avctx, AV_LOG_ERROR, "Failed to open camera.\n");
800 get_sensor_orientation(avctx);
801 match_video_size(avctx);
802 match_framerate(avctx);
804 ret = create_image_reader(avctx);
809 ret = create_capture_session(avctx);
814 ret = add_video_stream(avctx);
818 android_camera_read_close(avctx);
819 av_log(avctx, AV_LOG_ERROR, "Failed to open android_camera.\n");
825 static int android_camera_read_packet(AVFormatContext *avctx, AVPacket *pkt)
827 AndroidCameraCtx *ctx = avctx->priv_data;
830 if (!atomic_load(&ctx->exit)) {
831 ret = av_thread_message_queue_recv(ctx->input_queue, pkt,
832 avctx->flags & AVFMT_FLAG_NONBLOCK ? AV_THREAD_MESSAGE_NONBLOCK : 0);
844 #define OFFSET(x) offsetof(AndroidCameraCtx, x)
845 #define DEC AV_OPT_FLAG_DECODING_PARAM
846 static const AVOption options[] = {
847 { "video_size", "set video size given as a string such as 640x480 or hd720", OFFSET(requested_width), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, DEC },
848 { "framerate", "set video frame rate", OFFSET(framerate), AV_OPT_TYPE_VIDEO_RATE, {.str = "30"}, 0, INT_MAX, DEC },
849 { "camera_index", "set index of camera to use", OFFSET(camera_index), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, DEC },
850 { "input_queue_size", "set maximum number of frames to buffer", OFFSET(input_queue_size), AV_OPT_TYPE_INT, {.i64 = 5}, 0, INT_MAX, DEC },
854 static const AVClass android_camera_class = {
855 .class_name = "android_camera indev",
856 .item_name = av_default_item_name,
858 .version = LIBAVUTIL_VERSION_INT,
859 .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
862 AVInputFormat ff_android_camera_demuxer = {
863 .name = "android_camera",
864 .long_name = NULL_IF_CONFIG_SMALL("Android camera input device"),
865 .priv_data_size = sizeof(AndroidCameraCtx),
866 .read_header = android_camera_read_header,
867 .read_packet = android_camera_read_packet,
868 .read_close = android_camera_read_close,
869 .flags = AVFMT_NOFILE,
870 .priv_class = &android_camera_class,