android_camera.c 29 KB

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