android_camera.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  1. /*
  2. * Android camera input device
  3. *
  4. * Copyright (C) 2017 Felix Matouschek
  5. *
  6. * This file is part of FFmpeg.
  7. *
  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.
  12. *
  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.
  17. *
  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
  21. */
  22. #include <errno.h>
  23. #include <pthread.h>
  24. #include <stdatomic.h>
  25. #include <stdbool.h>
  26. #include <stdint.h>
  27. #include <camera/NdkCameraDevice.h>
  28. #include <camera/NdkCameraManager.h>
  29. #include <media/NdkImage.h>
  30. #include <media/NdkImageReader.h>
  31. #include "libavformat/avformat.h"
  32. #include "libavformat/internal.h"
  33. #include "libavutil/avstring.h"
  34. #include "libavutil/display.h"
  35. #include "libavutil/imgutils.h"
  36. #include "libavutil/log.h"
  37. #include "libavutil/opt.h"
  38. #include "libavutil/parseutils.h"
  39. #include "libavutil/pixfmt.h"
  40. #include "libavutil/threadmessage.h"
  41. #include "libavutil/time.h"
  42. /* This image format is available on all Android devices
  43. * supporting the Camera2 API */
  44. #define IMAGE_FORMAT_ANDROID AIMAGE_FORMAT_YUV_420_888
  45. #define MAX_BUF_COUNT 2
  46. #define VIDEO_STREAM_INDEX 0
  47. #define VIDEO_TIMEBASE_ANDROID 1000000000
  48. #define RETURN_CASE(x) case x: return AV_STRINGIFY(x);
  49. #define RETURN_DEFAULT(x) default: return AV_STRINGIFY(x);
  50. typedef struct AndroidCameraCtx {
  51. const AVClass *class;
  52. int requested_width;
  53. int requested_height;
  54. AVRational framerate;
  55. int camera_index;
  56. int input_queue_size;
  57. uint8_t lens_facing;
  58. int32_t sensor_orientation;
  59. int width;
  60. int height;
  61. int32_t framerate_range[2];
  62. int image_format;
  63. ACameraManager *camera_mgr;
  64. char *camera_id;
  65. ACameraMetadata *camera_metadata;
  66. ACameraDevice *camera_dev;
  67. ACameraDevice_StateCallbacks camera_state_callbacks;
  68. AImageReader *image_reader;
  69. AImageReader_ImageListener image_listener;
  70. ANativeWindow *image_reader_window;
  71. ACaptureSessionOutputContainer *capture_session_output_container;
  72. ACaptureSessionOutput *capture_session_output;
  73. ACameraOutputTarget *camera_output_target;
  74. ACaptureRequest *capture_request;
  75. ACameraCaptureSession_stateCallbacks capture_session_state_callbacks;
  76. ACameraCaptureSession *capture_session;
  77. AVThreadMessageQueue *input_queue;
  78. atomic_int exit;
  79. atomic_int got_image_format;
  80. } AndroidCameraCtx;
  81. static const char *camera_status_string(camera_status_t val)
  82. {
  83. switch(val) {
  84. RETURN_CASE(ACAMERA_OK)
  85. RETURN_CASE(ACAMERA_ERROR_UNKNOWN)
  86. RETURN_CASE(ACAMERA_ERROR_INVALID_PARAMETER)
  87. RETURN_CASE(ACAMERA_ERROR_CAMERA_DISCONNECTED)
  88. RETURN_CASE(ACAMERA_ERROR_NOT_ENOUGH_MEMORY)
  89. RETURN_CASE(ACAMERA_ERROR_METADATA_NOT_FOUND)
  90. RETURN_CASE(ACAMERA_ERROR_CAMERA_DEVICE)
  91. RETURN_CASE(ACAMERA_ERROR_CAMERA_SERVICE)
  92. RETURN_CASE(ACAMERA_ERROR_SESSION_CLOSED)
  93. RETURN_CASE(ACAMERA_ERROR_INVALID_OPERATION)
  94. RETURN_CASE(ACAMERA_ERROR_STREAM_CONFIGURE_FAIL)
  95. RETURN_CASE(ACAMERA_ERROR_CAMERA_IN_USE)
  96. RETURN_CASE(ACAMERA_ERROR_MAX_CAMERA_IN_USE)
  97. RETURN_CASE(ACAMERA_ERROR_CAMERA_DISABLED)
  98. RETURN_CASE(ACAMERA_ERROR_PERMISSION_DENIED)
  99. RETURN_DEFAULT(ACAMERA_ERROR_UNKNOWN)
  100. }
  101. }
  102. static const char *media_status_string(media_status_t val)
  103. {
  104. switch(val) {
  105. RETURN_CASE(AMEDIA_OK)
  106. RETURN_CASE(AMEDIA_ERROR_UNKNOWN)
  107. RETURN_CASE(AMEDIA_ERROR_MALFORMED)
  108. RETURN_CASE(AMEDIA_ERROR_UNSUPPORTED)
  109. RETURN_CASE(AMEDIA_ERROR_INVALID_OBJECT)
  110. RETURN_CASE(AMEDIA_ERROR_INVALID_PARAMETER)
  111. RETURN_CASE(AMEDIA_ERROR_INVALID_OPERATION)
  112. RETURN_CASE(AMEDIA_DRM_NOT_PROVISIONED)
  113. RETURN_CASE(AMEDIA_DRM_RESOURCE_BUSY)
  114. RETURN_CASE(AMEDIA_DRM_DEVICE_REVOKED)
  115. RETURN_CASE(AMEDIA_DRM_SHORT_BUFFER)
  116. RETURN_CASE(AMEDIA_DRM_SESSION_NOT_OPENED)
  117. RETURN_CASE(AMEDIA_DRM_TAMPER_DETECTED)
  118. RETURN_CASE(AMEDIA_DRM_VERIFY_FAILED)
  119. RETURN_CASE(AMEDIA_DRM_NEED_KEY)
  120. RETURN_CASE(AMEDIA_DRM_LICENSE_EXPIRED)
  121. RETURN_CASE(AMEDIA_IMGREADER_NO_BUFFER_AVAILABLE)
  122. RETURN_CASE(AMEDIA_IMGREADER_MAX_IMAGES_ACQUIRED)
  123. RETURN_CASE(AMEDIA_IMGREADER_CANNOT_LOCK_IMAGE)
  124. RETURN_CASE(AMEDIA_IMGREADER_CANNOT_UNLOCK_IMAGE)
  125. RETURN_CASE(AMEDIA_IMGREADER_IMAGE_NOT_LOCKED)
  126. RETURN_DEFAULT(AMEDIA_ERROR_UNKNOWN)
  127. }
  128. }
  129. static const char *error_state_callback_string(int val)
  130. {
  131. switch(val) {
  132. RETURN_CASE(ERROR_CAMERA_IN_USE)
  133. RETURN_CASE(ERROR_MAX_CAMERAS_IN_USE)
  134. RETURN_CASE(ERROR_CAMERA_DISABLED)
  135. RETURN_CASE(ERROR_CAMERA_DEVICE)
  136. RETURN_CASE(ERROR_CAMERA_SERVICE)
  137. default:
  138. return "ERROR_CAMERA_UNKNOWN";
  139. }
  140. }
  141. static void camera_dev_disconnected(void *context, ACameraDevice *device)
  142. {
  143. AVFormatContext *avctx = context;
  144. AndroidCameraCtx *ctx = avctx->priv_data;
  145. atomic_store(&ctx->exit, 1);
  146. av_log(avctx, AV_LOG_ERROR, "Camera with id %s disconnected.\n",
  147. ACameraDevice_getId(device));
  148. }
  149. static void camera_dev_error(void *context, ACameraDevice *device, int error)
  150. {
  151. AVFormatContext *avctx = context;
  152. AndroidCameraCtx *ctx = avctx->priv_data;
  153. atomic_store(&ctx->exit, 1);
  154. av_log(avctx, AV_LOG_ERROR, "Error %s on camera with id %s.\n",
  155. error_state_callback_string(error), ACameraDevice_getId(device));
  156. }
  157. static int open_camera(AVFormatContext *avctx)
  158. {
  159. AndroidCameraCtx *ctx = avctx->priv_data;
  160. camera_status_t ret;
  161. ACameraIdList *camera_ids;
  162. ret = ACameraManager_getCameraIdList(ctx->camera_mgr, &camera_ids);
  163. if (ret != ACAMERA_OK) {
  164. av_log(avctx, AV_LOG_ERROR, "Failed to get camera id list, error: %s.\n",
  165. camera_status_string(ret));
  166. return AVERROR_EXTERNAL;
  167. }
  168. if (ctx->camera_index < camera_ids->numCameras) {
  169. ctx->camera_id = av_strdup(camera_ids->cameraIds[ctx->camera_index]);
  170. if (!ctx->camera_id) {
  171. av_log(avctx, AV_LOG_ERROR, "Failed to allocate memory for camera_id.\n");
  172. return AVERROR(ENOMEM);
  173. }
  174. } else {
  175. av_log(avctx, AV_LOG_ERROR, "No camera with index %d available.\n",
  176. ctx->camera_index);
  177. return AVERROR(ENXIO);
  178. }
  179. ACameraManager_deleteCameraIdList(camera_ids);
  180. ret = ACameraManager_getCameraCharacteristics(ctx->camera_mgr,
  181. ctx->camera_id, &ctx->camera_metadata);
  182. if (ret != ACAMERA_OK) {
  183. av_log(avctx, AV_LOG_ERROR, "Failed to get metadata for camera with id %s, error: %s.\n",
  184. ctx->camera_id, camera_status_string(ret));
  185. return AVERROR_EXTERNAL;
  186. }
  187. ctx->camera_state_callbacks.context = avctx;
  188. ctx->camera_state_callbacks.onDisconnected = camera_dev_disconnected;
  189. ctx->camera_state_callbacks.onError = camera_dev_error;
  190. ret = ACameraManager_openCamera(ctx->camera_mgr, ctx->camera_id,
  191. &ctx->camera_state_callbacks, &ctx->camera_dev);
  192. if (ret != ACAMERA_OK) {
  193. av_log(avctx, AV_LOG_ERROR, "Failed to open camera with id %s, error: %s.\n",
  194. ctx->camera_id, camera_status_string(ret));
  195. return AVERROR_EXTERNAL;
  196. }
  197. return 0;
  198. }
  199. static void get_sensor_orientation(AVFormatContext *avctx)
  200. {
  201. AndroidCameraCtx *ctx = avctx->priv_data;
  202. ACameraMetadata_const_entry lens_facing;
  203. ACameraMetadata_const_entry sensor_orientation;
  204. ACameraMetadata_getConstEntry(ctx->camera_metadata,
  205. ACAMERA_LENS_FACING, &lens_facing);
  206. ACameraMetadata_getConstEntry(ctx->camera_metadata,
  207. ACAMERA_SENSOR_ORIENTATION, &sensor_orientation);
  208. ctx->lens_facing = lens_facing.data.u8[0];
  209. ctx->sensor_orientation = sensor_orientation.data.i32[0];
  210. }
  211. static void match_video_size(AVFormatContext *avctx)
  212. {
  213. AndroidCameraCtx *ctx = avctx->priv_data;
  214. ACameraMetadata_const_entry available_configs;
  215. int found = 0;
  216. ACameraMetadata_getConstEntry(ctx->camera_metadata,
  217. ACAMERA_SCALER_AVAILABLE_STREAM_CONFIGURATIONS,
  218. &available_configs);
  219. for (int i = 0; i < available_configs.count; i++) {
  220. int32_t input = available_configs.data.i32[i * 4 + 3];
  221. int32_t format = available_configs.data.i32[i * 4 + 0];
  222. if (input) {
  223. continue;
  224. }
  225. if (format == IMAGE_FORMAT_ANDROID) {
  226. int32_t width = available_configs.data.i32[i * 4 + 1];
  227. int32_t height = available_configs.data.i32[i * 4 + 2];
  228. //Same ratio
  229. if ((ctx->requested_width == width && ctx->requested_height == height) ||
  230. (ctx->requested_width == height && ctx->requested_height == width)) {
  231. ctx->width = width;
  232. ctx->height = height;
  233. found = 1;
  234. break;
  235. }
  236. }
  237. }
  238. if (!found || ctx->width == 0 || ctx->height == 0) {
  239. ctx->width = available_configs.data.i32[1];
  240. ctx->height = available_configs.data.i32[2];
  241. av_log(avctx, AV_LOG_WARNING,
  242. "Requested video_size %dx%d not available, falling back to %dx%d\n",
  243. ctx->requested_width, ctx->requested_height, ctx->width, ctx->height);
  244. }
  245. return;
  246. }
  247. static void match_framerate(AVFormatContext *avctx)
  248. {
  249. AndroidCameraCtx *ctx = avctx->priv_data;
  250. ACameraMetadata_const_entry available_framerates;
  251. int found = 0;
  252. int current_best_match = -1;
  253. int requested_framerate = av_q2d(ctx->framerate);
  254. ACameraMetadata_getConstEntry(ctx->camera_metadata,
  255. ACAMERA_CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES,
  256. &available_framerates);
  257. for (int i = 0; i < available_framerates.count; i++) {
  258. int32_t min = available_framerates.data.i32[i * 2 + 0];
  259. int32_t max = available_framerates.data.i32[i * 2 + 1];
  260. if (requested_framerate == max) {
  261. if (min == max) {
  262. ctx->framerate_range[0] = min;
  263. ctx->framerate_range[1] = max;
  264. found = 1;
  265. break;
  266. } else if (current_best_match >= 0) {
  267. int32_t current_best_match_min = available_framerates.data.i32[current_best_match * 2 + 0];
  268. if (min > current_best_match_min) {
  269. current_best_match = i;
  270. }
  271. } else {
  272. current_best_match = i;
  273. }
  274. }
  275. }
  276. if (!found) {
  277. if (current_best_match >= 0) {
  278. ctx->framerate_range[0] = available_framerates.data.i32[current_best_match * 2 + 0];
  279. ctx->framerate_range[1] = available_framerates.data.i32[current_best_match * 2 + 1];
  280. } else {
  281. ctx->framerate_range[0] = available_framerates.data.i32[0];
  282. ctx->framerate_range[1] = available_framerates.data.i32[1];
  283. }
  284. av_log(avctx, AV_LOG_WARNING,
  285. "Requested framerate %d not available, falling back to min: %d and max: %d fps\n",
  286. requested_framerate, ctx->framerate_range[0], ctx->framerate_range[1]);
  287. }
  288. return;
  289. }
  290. static int get_image_format(AVFormatContext *avctx, AImage *image)
  291. {
  292. AndroidCameraCtx *ctx = avctx->priv_data;
  293. int32_t image_pixelstrides[2];
  294. uint8_t *image_plane_data[2];
  295. int plane_data_length[2];
  296. for (int i = 0; i < 2; i++) {
  297. AImage_getPlanePixelStride(image, i + 1, &image_pixelstrides[i]);
  298. AImage_getPlaneData(image, i + 1, &image_plane_data[i], &plane_data_length[i]);
  299. }
  300. if (image_pixelstrides[0] != image_pixelstrides[1]) {
  301. av_log(avctx, AV_LOG_ERROR,
  302. "Pixel strides of U and V plane should have been the same.\n");
  303. return AVERROR_EXTERNAL;
  304. }
  305. switch (image_pixelstrides[0]) {
  306. case 1:
  307. ctx->image_format = AV_PIX_FMT_YUV420P;
  308. break;
  309. case 2:
  310. if (image_plane_data[0] < image_plane_data[1]) {
  311. ctx->image_format = AV_PIX_FMT_NV12;
  312. } else {
  313. ctx->image_format = AV_PIX_FMT_NV21;
  314. }
  315. break;
  316. default:
  317. av_log(avctx, AV_LOG_ERROR,
  318. "Unknown pixel stride %d of U and V plane, cannot determine camera image format.\n",
  319. image_pixelstrides[0]);
  320. return AVERROR(ENOSYS);
  321. }
  322. return 0;
  323. }
  324. static void image_available(void *context, AImageReader *reader)
  325. {
  326. AVFormatContext *avctx = context;
  327. AndroidCameraCtx *ctx = avctx->priv_data;
  328. media_status_t media_status;
  329. int ret = 0;
  330. AImage *image;
  331. int64_t image_timestamp;
  332. int32_t image_linestrides[4];
  333. uint8_t *image_plane_data[4];
  334. int plane_data_length[4];
  335. AVPacket pkt;
  336. int pkt_buffer_size = 0;
  337. media_status = AImageReader_acquireLatestImage(reader, &image);
  338. if (media_status != AMEDIA_OK) {
  339. if (media_status == AMEDIA_IMGREADER_NO_BUFFER_AVAILABLE) {
  340. av_log(avctx, AV_LOG_WARNING,
  341. "An image reader frame was discarded");
  342. } else {
  343. av_log(avctx, AV_LOG_ERROR,
  344. "Failed to acquire latest image from image reader, error: %s.\n",
  345. media_status_string(media_status));
  346. ret = AVERROR_EXTERNAL;
  347. }
  348. goto error;
  349. }
  350. // Silently drop frames when exit is set
  351. if (atomic_load(&ctx->exit)) {
  352. goto error;
  353. }
  354. // Determine actual image format
  355. if (!atomic_load(&ctx->got_image_format)) {
  356. ret = get_image_format(avctx, image);
  357. if (ret < 0) {
  358. av_log(avctx, AV_LOG_ERROR,
  359. "Could not get image format of camera.\n");
  360. goto error;
  361. } else {
  362. atomic_store(&ctx->got_image_format, 1);
  363. }
  364. }
  365. pkt_buffer_size = av_image_get_buffer_size(ctx->image_format, ctx->width, ctx->height, 32);
  366. AImage_getTimestamp(image, &image_timestamp);
  367. AImage_getPlaneRowStride(image, 0, &image_linestrides[0]);
  368. AImage_getPlaneData(image, 0, &image_plane_data[0], &plane_data_length[0]);
  369. switch (ctx->image_format) {
  370. case AV_PIX_FMT_YUV420P:
  371. AImage_getPlaneRowStride(image, 1, &image_linestrides[1]);
  372. AImage_getPlaneData(image, 1, &image_plane_data[1], &plane_data_length[1]);
  373. AImage_getPlaneRowStride(image, 2, &image_linestrides[2]);
  374. AImage_getPlaneData(image, 2, &image_plane_data[2], &plane_data_length[2]);
  375. break;
  376. case AV_PIX_FMT_NV12:
  377. AImage_getPlaneRowStride(image, 1, &image_linestrides[1]);
  378. AImage_getPlaneData(image, 1, &image_plane_data[1], &plane_data_length[1]);
  379. break;
  380. case AV_PIX_FMT_NV21:
  381. AImage_getPlaneRowStride(image, 2, &image_linestrides[1]);
  382. AImage_getPlaneData(image, 2, &image_plane_data[1], &plane_data_length[1]);
  383. break;
  384. default:
  385. av_log(avctx, AV_LOG_ERROR, "Unsupported camera image format.\n");
  386. ret = AVERROR(ENOSYS);
  387. goto error;
  388. }
  389. ret = av_new_packet(&pkt, pkt_buffer_size);
  390. if (ret < 0) {
  391. av_log(avctx, AV_LOG_ERROR,
  392. "Failed to create new av packet, error: %s.\n", av_err2str(ret));
  393. goto error;
  394. }
  395. pkt.stream_index = VIDEO_STREAM_INDEX;
  396. pkt.pts = image_timestamp;
  397. av_image_copy_to_buffer(pkt.data, pkt_buffer_size,
  398. (const uint8_t * const *) image_plane_data,
  399. image_linestrides, ctx->image_format,
  400. ctx->width, ctx->height, 32);
  401. ret = av_thread_message_queue_send(ctx->input_queue, &pkt, AV_THREAD_MESSAGE_NONBLOCK);
  402. error:
  403. if (ret < 0) {
  404. if (ret != AVERROR(EAGAIN)) {
  405. av_log(avctx, AV_LOG_ERROR,
  406. "Error while processing new image, error: %s.\n", av_err2str(ret));
  407. av_thread_message_queue_set_err_recv(ctx->input_queue, ret);
  408. atomic_store(&ctx->exit, 1);
  409. } else {
  410. av_log(avctx, AV_LOG_WARNING,
  411. "Input queue was full, dropping frame, consider raising the input_queue_size option (current value: %d)\n",
  412. ctx->input_queue_size);
  413. }
  414. if (pkt_buffer_size) {
  415. av_packet_unref(&pkt);
  416. }
  417. }
  418. AImage_delete(image);
  419. return;
  420. }
  421. static int create_image_reader(AVFormatContext *avctx)
  422. {
  423. AndroidCameraCtx *ctx = avctx->priv_data;
  424. media_status_t ret;
  425. ret = AImageReader_new(ctx->width, ctx->height, IMAGE_FORMAT_ANDROID,
  426. MAX_BUF_COUNT, &ctx->image_reader);
  427. if (ret != AMEDIA_OK) {
  428. av_log(avctx, AV_LOG_ERROR,
  429. "Failed to create image reader, error: %s.\n", media_status_string(ret));
  430. return AVERROR_EXTERNAL;
  431. }
  432. ctx->image_listener.context = avctx;
  433. ctx->image_listener.onImageAvailable = image_available;
  434. ret = AImageReader_setImageListener(ctx->image_reader, &ctx->image_listener);
  435. if (ret != AMEDIA_OK) {
  436. av_log(avctx, AV_LOG_ERROR,
  437. "Failed to set image listener on image reader, error: %s.\n",
  438. media_status_string(ret));
  439. return AVERROR_EXTERNAL;
  440. }
  441. ret = AImageReader_getWindow(ctx->image_reader, &ctx->image_reader_window);
  442. if (ret != AMEDIA_OK) {
  443. av_log(avctx, AV_LOG_ERROR,
  444. "Could not get image reader window, error: %s.\n",
  445. media_status_string(ret));
  446. return AVERROR_EXTERNAL;
  447. }
  448. return 0;
  449. }
  450. static void capture_session_closed(void *context, ACameraCaptureSession *session)
  451. {
  452. av_log(context, AV_LOG_INFO, "Android camera capture session was closed.\n");
  453. }
  454. static void capture_session_ready(void *context, ACameraCaptureSession *session)
  455. {
  456. av_log(context, AV_LOG_INFO, "Android camera capture session is ready.\n");
  457. }
  458. static void capture_session_active(void *context, ACameraCaptureSession *session)
  459. {
  460. av_log(context, AV_LOG_INFO, "Android camera capture session is active.\n");
  461. }
  462. static int create_capture_session(AVFormatContext *avctx)
  463. {
  464. AndroidCameraCtx *ctx = avctx->priv_data;
  465. camera_status_t ret;
  466. ret = ACaptureSessionOutputContainer_create(&ctx->capture_session_output_container);
  467. if (ret != ACAMERA_OK) {
  468. av_log(avctx, AV_LOG_ERROR,
  469. "Failed to create capture session output container, error: %s.\n",
  470. camera_status_string(ret));
  471. return AVERROR_EXTERNAL;
  472. }
  473. ANativeWindow_acquire(ctx->image_reader_window);
  474. ret = ACaptureSessionOutput_create(ctx->image_reader_window, &ctx->capture_session_output);
  475. if (ret != ACAMERA_OK) {
  476. av_log(avctx, AV_LOG_ERROR,
  477. "Failed to create capture session container, error: %s.\n",
  478. camera_status_string(ret));
  479. return AVERROR_EXTERNAL;
  480. }
  481. ret = ACaptureSessionOutputContainer_add(ctx->capture_session_output_container,
  482. ctx->capture_session_output);
  483. if (ret != ACAMERA_OK) {
  484. av_log(avctx, AV_LOG_ERROR,
  485. "Failed to add output to output container, error: %s.\n",
  486. camera_status_string(ret));
  487. return AVERROR_EXTERNAL;
  488. }
  489. ret = ACameraOutputTarget_create(ctx->image_reader_window, &ctx->camera_output_target);
  490. if (ret != ACAMERA_OK) {
  491. av_log(avctx, AV_LOG_ERROR,
  492. "Failed to create camera output target, error: %s.\n",
  493. camera_status_string(ret));
  494. return AVERROR_EXTERNAL;
  495. }
  496. ret = ACameraDevice_createCaptureRequest(ctx->camera_dev, TEMPLATE_RECORD, &ctx->capture_request);
  497. if (ret != ACAMERA_OK) {
  498. av_log(avctx, AV_LOG_ERROR,
  499. "Failed to create capture request, error: %s.\n",
  500. camera_status_string(ret));
  501. return AVERROR_EXTERNAL;
  502. }
  503. ret = ACaptureRequest_setEntry_i32(ctx->capture_request, ACAMERA_CONTROL_AE_TARGET_FPS_RANGE,
  504. 2, ctx->framerate_range);
  505. if (ret != ACAMERA_OK) {
  506. av_log(avctx, AV_LOG_ERROR,
  507. "Failed to set target fps range in capture request, error: %s.\n",
  508. camera_status_string(ret));
  509. return AVERROR_EXTERNAL;
  510. }
  511. ret = ACaptureRequest_addTarget(ctx->capture_request, ctx->camera_output_target);
  512. if (ret != ACAMERA_OK) {
  513. av_log(avctx, AV_LOG_ERROR,
  514. "Failed to add capture request capture request, error: %s.\n",
  515. camera_status_string(ret));
  516. return AVERROR_EXTERNAL;
  517. }
  518. ctx->capture_session_state_callbacks.context = avctx;
  519. ctx->capture_session_state_callbacks.onClosed = capture_session_closed;
  520. ctx->capture_session_state_callbacks.onReady = capture_session_ready;
  521. ctx->capture_session_state_callbacks.onActive = capture_session_active;
  522. ret = ACameraDevice_createCaptureSession(ctx->camera_dev, ctx->capture_session_output_container,
  523. &ctx->capture_session_state_callbacks, &ctx->capture_session);
  524. if (ret != ACAMERA_OK) {
  525. av_log(avctx, AV_LOG_ERROR,
  526. "Failed to create capture session, error: %s.\n",
  527. camera_status_string(ret));
  528. return AVERROR_EXTERNAL;
  529. }
  530. ret = ACameraCaptureSession_setRepeatingRequest(ctx->capture_session, NULL, 1, &ctx->capture_request, NULL);
  531. if (ret != ACAMERA_OK) {
  532. av_log(avctx, AV_LOG_ERROR,
  533. "Failed to set repeating request on capture session, error: %s.\n",
  534. camera_status_string(ret));
  535. return AVERROR_EXTERNAL;
  536. }
  537. return 0;
  538. }
  539. static int wait_for_image_format(AVFormatContext *avctx)
  540. {
  541. AndroidCameraCtx *ctx = avctx->priv_data;
  542. while (!atomic_load(&ctx->got_image_format) && !atomic_load(&ctx->exit)) {
  543. //Wait until first frame arrived and actual image format was determined
  544. usleep(1000);
  545. }
  546. return atomic_load(&ctx->got_image_format);
  547. }
  548. static int add_display_matrix(AVFormatContext *avctx, AVStream *st)
  549. {
  550. AndroidCameraCtx *ctx = avctx->priv_data;
  551. uint8_t *side_data;
  552. int32_t display_matrix[9];
  553. av_display_rotation_set(display_matrix, ctx->sensor_orientation);
  554. if (ctx->lens_facing == ACAMERA_LENS_FACING_FRONT) {
  555. av_display_matrix_flip(display_matrix, 1, 0);
  556. }
  557. side_data = av_stream_new_side_data(st,
  558. AV_PKT_DATA_DISPLAYMATRIX, sizeof(display_matrix));
  559. if (!side_data) {
  560. return AVERROR(ENOMEM);
  561. }
  562. memcpy(side_data, display_matrix, sizeof(display_matrix));
  563. return 0;
  564. }
  565. static int add_video_stream(AVFormatContext *avctx)
  566. {
  567. AndroidCameraCtx *ctx = avctx->priv_data;
  568. AVStream *st;
  569. AVCodecParameters *codecpar;
  570. st = avformat_new_stream(avctx, NULL);
  571. if (!st) {
  572. return AVERROR(ENOMEM);
  573. }
  574. st->id = VIDEO_STREAM_INDEX;
  575. st->avg_frame_rate = (AVRational) { ctx->framerate_range[1], 1 };
  576. st->r_frame_rate = (AVRational) { ctx->framerate_range[1], 1 };
  577. if (!wait_for_image_format(avctx)) {
  578. return AVERROR_EXTERNAL;
  579. }
  580. codecpar = st->codecpar;
  581. codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
  582. codecpar->codec_id = AV_CODEC_ID_RAWVIDEO;
  583. codecpar->format = ctx->image_format;
  584. codecpar->width = ctx->width;
  585. codecpar->height = ctx->height;
  586. avpriv_set_pts_info(st, 64, 1, VIDEO_TIMEBASE_ANDROID);
  587. return add_display_matrix(avctx, st);
  588. }
  589. static int android_camera_read_close(AVFormatContext *avctx)
  590. {
  591. AndroidCameraCtx *ctx = avctx->priv_data;
  592. atomic_store(&ctx->exit, 1);
  593. if (ctx->capture_session) {
  594. ACameraCaptureSession_stopRepeating(ctx->capture_session);
  595. // Following warning is emitted, after capture session closed callback is received:
  596. // ACameraCaptureSession: Device is closed but session 0 is not notified
  597. // Seems to be a bug in Android, we can ignore this
  598. ACameraCaptureSession_close(ctx->capture_session);
  599. ctx->capture_session = NULL;
  600. }
  601. if (ctx->capture_request) {
  602. ACaptureRequest_removeTarget(ctx->capture_request, ctx->camera_output_target);
  603. ACaptureRequest_free(ctx->capture_request);
  604. ctx->capture_request = NULL;
  605. }
  606. if (ctx->camera_output_target) {
  607. ACameraOutputTarget_free(ctx->camera_output_target);
  608. ctx->camera_output_target = NULL;
  609. }
  610. if (ctx->capture_session_output) {
  611. ACaptureSessionOutputContainer_remove(ctx->capture_session_output_container,
  612. ctx->capture_session_output);
  613. ACaptureSessionOutput_free(ctx->capture_session_output);
  614. ctx->capture_session_output = NULL;
  615. }
  616. if (ctx->image_reader_window) {
  617. ANativeWindow_release(ctx->image_reader_window);
  618. ctx->image_reader_window = NULL;
  619. }
  620. if (ctx->capture_session_output_container) {
  621. ACaptureSessionOutputContainer_free(ctx->capture_session_output_container);
  622. ctx->capture_session_output_container = NULL;
  623. }
  624. if (ctx->camera_dev) {
  625. ACameraDevice_close(ctx->camera_dev);
  626. ctx->camera_dev = NULL;
  627. }
  628. if (ctx->image_reader) {
  629. AImageReader_delete(ctx->image_reader);
  630. ctx->image_reader = NULL;
  631. }
  632. if (ctx->camera_metadata) {
  633. ACameraMetadata_free(ctx->camera_metadata);
  634. ctx->camera_metadata = NULL;
  635. }
  636. av_freep(&ctx->camera_id);
  637. if (ctx->camera_mgr) {
  638. ACameraManager_delete(ctx->camera_mgr);
  639. ctx->camera_mgr = NULL;
  640. }
  641. if (ctx->input_queue) {
  642. AVPacket pkt;
  643. av_thread_message_queue_set_err_send(ctx->input_queue, AVERROR_EOF);
  644. while (av_thread_message_queue_recv(ctx->input_queue, &pkt, AV_THREAD_MESSAGE_NONBLOCK) >= 0) {
  645. av_packet_unref(&pkt);
  646. }
  647. av_thread_message_queue_free(&ctx->input_queue);
  648. }
  649. return 0;
  650. }
  651. static int android_camera_read_header(AVFormatContext *avctx)
  652. {
  653. AndroidCameraCtx *ctx = avctx->priv_data;
  654. int ret;
  655. atomic_init(&ctx->got_image_format, 0);
  656. atomic_init(&ctx->exit, 0);
  657. ret = av_thread_message_queue_alloc(&ctx->input_queue, ctx->input_queue_size, sizeof(AVPacket));
  658. if (ret < 0) {
  659. av_log(avctx, AV_LOG_ERROR,
  660. "Failed to allocate input queue, error: %s.\n", av_err2str(ret));
  661. goto error;
  662. }
  663. ctx->camera_mgr = ACameraManager_create();
  664. if (!ctx->camera_mgr) {
  665. av_log(avctx, AV_LOG_ERROR, "Failed to create Android camera manager.\n");
  666. ret = AVERROR_EXTERNAL;
  667. goto error;
  668. }
  669. ret = open_camera(avctx);
  670. if (ret < 0) {
  671. av_log(avctx, AV_LOG_ERROR, "Failed to open camera.\n");
  672. goto error;
  673. }
  674. get_sensor_orientation(avctx);
  675. match_video_size(avctx);
  676. match_framerate(avctx);
  677. ret = create_image_reader(avctx);
  678. if (ret < 0) {
  679. goto error;
  680. }
  681. ret = create_capture_session(avctx);
  682. if (ret < 0) {
  683. goto error;
  684. }
  685. ret = add_video_stream(avctx);
  686. error:
  687. if (ret < 0) {
  688. android_camera_read_close(avctx);
  689. av_log(avctx, AV_LOG_ERROR, "Failed to open android_camera.\n");
  690. }
  691. return ret;
  692. }
  693. static int android_camera_read_packet(AVFormatContext *avctx, AVPacket *pkt)
  694. {
  695. AndroidCameraCtx *ctx = avctx->priv_data;
  696. int ret;
  697. if (!atomic_load(&ctx->exit)) {
  698. ret = av_thread_message_queue_recv(ctx->input_queue, pkt,
  699. avctx->flags & AVFMT_FLAG_NONBLOCK ? AV_THREAD_MESSAGE_NONBLOCK : 0);
  700. } else {
  701. ret = AVERROR_EOF;
  702. }
  703. if (ret < 0) {
  704. return ret;
  705. } else {
  706. return pkt->size;
  707. }
  708. }
  709. #define OFFSET(x) offsetof(AndroidCameraCtx, x)
  710. #define DEC AV_OPT_FLAG_DECODING_PARAM
  711. static const AVOption options[] = {
  712. { "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 },
  713. { "framerate", "set video frame rate", OFFSET(framerate), AV_OPT_TYPE_VIDEO_RATE, {.str = "30"}, 0, INT_MAX, DEC },
  714. { "camera_index", "set index of camera to use", OFFSET(camera_index), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, DEC },
  715. { "input_queue_size", "set maximum number of frames to buffer", OFFSET(input_queue_size), AV_OPT_TYPE_INT, {.i64 = 5}, 0, INT_MAX, DEC },
  716. { NULL },
  717. };
  718. static const AVClass android_camera_class = {
  719. .class_name = "android_camera indev",
  720. .item_name = av_default_item_name,
  721. .option = options,
  722. .version = LIBAVUTIL_VERSION_INT,
  723. .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
  724. };
  725. const AVInputFormat ff_android_camera_demuxer = {
  726. .name = "android_camera",
  727. .long_name = NULL_IF_CONFIG_SMALL("Android camera input device"),
  728. .priv_data_size = sizeof(AndroidCameraCtx),
  729. .read_header = android_camera_read_header,
  730. .read_packet = android_camera_read_packet,
  731. .read_close = android_camera_read_close,
  732. .flags = AVFMT_NOFILE,
  733. .priv_class = &android_camera_class,
  734. };