android_camera.c 29 KB

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