android_camera.c 29 KB

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