Ocean
Loading...
Searching...
No Matches
ALiveVideo.h
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8#ifndef META_OCEAN_MEDIA_ANDROID_A_LIVE_VIDEO_H
9#define META_OCEAN_MEDIA_ANDROID_A_LIVE_VIDEO_H
10
15
16#include "ocean/base/Value.h"
17
19
21
22#include <jni.h>
23
24namespace Ocean
25{
26
27namespace Media
28{
29
30namespace Android
31{
32
33#ifdef OCEAN_MEDIA_ANDROID_NATIVECAMERALIBRARY_AVAILABLE
34
35/**
36 * This class implements an live video class for Android.
37 * @ingroup mediaandroid
38 */
39class OCEAN_MEDIA_A_EXPORT ALiveVideo final :
40 virtual public AMedium,
41 virtual public LiveVideo
42{
43 friend class ALibrary;
44 friend class ALiveVideoManager;
45
46 public:
47
48 /**
49 * This class holds the relevant information of a selectable live video device.
50 */
51 class Device
52 {
53 friend class ALiveVideo;
54
55 public:
56
57 /// Definition of an unordered map mapping metadata tags to their values.
58 using MetadataMap = std::unordered_map<uint32_t, Value>;
59
60 public:
61
62 /**
63 * Default constructor.
64 */
65 Device() = default;
66
67 /**
68 * Returns the device's id.
69 * @return The id of the device
70 */
71 inline const std::string& id() const;
72
73 /**
74 * Returns the device's name.
75 * @return The name of the device
76 */
77 inline const std::string& name() const;
78
79 /**
80 * Returns the device's direction.
81 * @return The direction of the device
82 */
83 inline acamera_metadata_enum_android_lens_facing_t lensFacing() const;
84
85 /**
86 * Returns the optional metadata map of the device.
87 * @return The optional metadata map of the device
88 */
89 inline const MetadataMap& metadataMap() const;
90
91 /**
92 * Returns whether this object is valid.
93 * @return True, if so
94 */
95 inline bool isValid() const;
96
97 /**
98 * Returns the readable string for a lens facing type.
99 * @param lensFacing The lens facing type to return the readable string for
100 * @return The readable string for the given lens facing type
101 */
102 static std::string readableLensFacing(const acamera_metadata_enum_android_lens_facing_t lensFacing);
103
104 protected:
105
106 /**
107 * Creates a new device object.
108 * @param id The id of the device, must be valid
109 * @param name The human redable name of the device, must be valid
110 * @param lensFacing The direction of the device
111 * @param metadataMap The optional metadata map of the device
112 */
113 inline Device(const std::string& id, const std::string& name_, const acamera_metadata_enum_android_lens_facing_t lensFacing, MetadataMap&& metadataMap = MetadataMap());
114
115 protected:
116
117 /// The device's id.
118 std::string id_;
119
120 /// The device's human readable name.
121 std::string name_;
122
123 /// The device's direction.
124 acamera_metadata_enum_android_lens_facing_t lensFacing_ = acamera_metadata_enum_acamera_lens_facing(-1);
125
126 /// The optional metadata map of the device.
128 };
129
130 using Devices = std::vector<Device>;
131
132 private:
133
134 /**
135 * Definition of Android image formats that are missing from the NDK
136 * These values are used but they are missing from the NDK header, media/NdkImage.h.
137 * @see https://developer.android.com/reference/kotlin/android/graphics/ImageFormat
138 */
140 {
141 // Android YUV P010 format.
142 AIMAGE_FORMAT_YCBCR_P010 = 54,
143 };
144
145 public:
146
147 /**
148 * Returns whether the medium is started currently.
149 * @see Medium::isStarted().
150 */
151 bool isStarted() const override;
152
153 /**
154 * Returns the start timestamp.
155 * @see FiniteMedium::startTimestamp().
156 */
157 Timestamp startTimestamp() const override;
158
159 /**
160 * Returns the pause timestamp.
161 * @see FiniteMedium::pauseTimestamp().
162 */
163 Timestamp pauseTimestamp() const override;
164
165 /**
166 * Returns the stop timestamp.
167 * @see FiniteMedium::stopTimestamp().
168 */
169 Timestamp stopTimestamp() const override;
170
171 /**
172 * Returns the transformation between the camera and device.
173 * @see FrameMedium::device_T_camera().
174 */
176
177 /**
178 * Returns the supported stream types.
179 * @see LiveVideo::supportedStreamTypes().
180 */
182
183 /**
184 * Returns the supported stream configurations for a given stream type.
185 * @see LiveVideo::supportedStreamConfigurations().
186 */
187 StreamConfigurations supportedStreamConfigurations(const StreamType streamType = ST_INVALID) const override;
188
189 /**
190 * Returns the current exposure duration of this device.
191 * @see exposureDuration().
192 */
193 double exposureDuration(double* minDuration = nullptr, double* maxDuration = nullptr, ControlMode* exposureMode = nullptr) const override;
194
195 /**
196 * Returns the current ISO of this device.
197 * @see iso().
198 */
199 float iso(float* minISO = nullptr, float* maxISO = nullptr, ControlMode* isoMode = nullptr) const override;
200
201 /**
202 * Returns the current focus of this device.
203 * @see LiveVideo::focus().
204 */
205 float focus(ControlMode* focusMode = nullptr) const override;
206
207 /**
208 * Sets the preferred stream type.
209 * @see LiveVideo::setPreferredStreamConfiguration().
210 */
211 bool setPreferredStreamType(const StreamType streamType) override;
212
213 /**
214 * Sets the preferred stream configuration.
215 * @see LiveVideo::setPreferredStreamConfiguration().
216 */
217 bool setPreferredStreamConfiguration(const StreamConfiguration& streamConfiguration) override;
218
219 /**
220 * Sets the exposure duration of this device.
221 * Note: 'allowShorterExposure' is ignored
222 * @see setExposureDuration().
223 */
224 bool setExposureDuration(const double duration, const bool allowShorterExposure = false) override;
225
226 /**
227 * Sets the ISO of this device.
228 * @see setISO().
229 */
230 bool setISO(const float iso) override;
231
232 /**
233 * Sets the focus of this device.
234 * @see setFocus().
235 */
236 bool setFocus(const float position) override;
237
238 /**
239 * Explicitly feeds a new external frame this live video.
240 * This function is intended for situations in which this live video does not receive the frame anymore from the system (e.g., when ARCore is accessing the video stream).<br>
241 * Do not call this function in case the live video is still receiving pixel buffers from the Android media system.
242 * @param frame The frame to be fed, must be valid
243 * @param anyCamera The camera profile defining the projection, must be valid
244 * @param exposureMode The exposure mode of the camera, CM_INVALID if unknown
245 * @param exposureDuration The exposure duration of the camera, in seconds, -1 if unknown
246 * @param isoMode The ISO mode of the camera, CM_INVALID if unknown
247 * @param iso The ISO of the camera, -1 if unknown
248 * @param focusMode The focus mode of the camera, CM_INVALID if unknown
249 * @param focusValue The focus value of the camera, in the same domain as ACAMERA_LENS_INFO_MINIMUM_FOCUS_DISTANCE, -1 if unknown
250 */
251 void feedNewFrame(Frame&& frame, SharedAnyCamera&& anyCamera, const ControlMode exposureMode, const double exposureDuration, const ControlMode isoMode, const float iso, const ControlMode focusMode, const float focusValue);
252
253 /**
254 * Forces a restart of the live video for situations in which the camera was used by an external resource.
255 * This function is intended for situations in which e.g., ARCore has used the borrowed the camera resource but does not use it anymore.
256 * Do not call this function in case the live video is still receiving pixel buffers from the Android media system.
257 * @return True, if succeeded
258 */
260
261 /**
262 * Returns the list of currently selectable devices.
263 * @return The list of currently selectable devices
264 */
266
267 protected:
268
269 /**
270 * Creates a new medium by a given url.
271 * @param url Url of the medium
272 * @param id Optional unique id of the medium
273 */
274 explicit ALiveVideo(const std::string& url, const std::string& id);
275
276 /**
277 * Destructs the live video object.
278 */
279 ~ALiveVideo() override;
280
281 /**
282 * Starts the medium.
283 * @see Medium::start().
284 */
285 bool start() override;
286
287 /**
288 * Pauses the medium.
289 * @see Medium::pause():
290 */
291 bool pause() override;
292
293 /**
294 * Stops the medium.
295 * @see Medium::stop().
296 */
297 bool stop() override;
298
299 /**
300 * Initializes the camera and all corresponding resources.
301 * @return True, if succeeded
302 */
304
305 /**
306 * Releases the camera and all corresponding resources.
307 * @return True, if succeeded
308 */
309 bool release();
310
311 /**
312 * Creates an Android camera for the URL of this medium.
313 * @param frameType The resulting frame type matching with the Android camera
314 * @return True, if succeeded
315 */
316 bool createCamera(FrameType& frameType);
317
318 /**
319 * Releases the Android camera.
320 * @return True, if succeeded
321 */
323
324 /**
325 * Creates a new image reader based on a given frame type, needs a valid camera.
326 * @param frameType The frame type of the image reader, must be valid
327 * @return True, if succeeded
328 */
329 bool createImageReader(const FrameType& frameType);
330
331 /**
332 * Releases the image reader.
333 */
335
336 /**
337 * Creates a new capture session, needs a valid camera and image reader.
338 * @return True, if succeeded
339 */
341
342 /**
343 * Releases the capture session.
344 */
346
347 /**
348 * The callback function for camera images.
349 * @param imageReader The image reader of the event, must be valid
350 * @see onCameraImageCallbackStatic().
351 */
352 void onCameraImageCallback(AImageReader* imageReader);
353
354 /**
355 * The callback function for a disconnected camera.
356 * @param cameraDevice The camera device of the event, must be valid
357 * @see onCameraDisconnectedStatic().
358 */
359 void onCameraDisconnected(ACameraDevice* cameraDevice);
360
361 /**
362 * The callback function for errors.
363 * @param cameraDevice The camera device of the event, must be valid
364 * @param error The error value of the event
365 * @see onCameraErrorStatic().
366 */
367 void onCameraError(ACameraDevice* cameraDevice, int error);
368
369 /**
370 * The callback function for an active session.
371 * @param session The session, must be valid
372 */
373 void onSessionActive(ACameraCaptureSession* session);
374
375 /**
376 * The callback function for a closed session.
377 * @param session The session, must be valid
378 */
379 void onSessionClosed(ACameraCaptureSession* session);
380
381 /**
382 * The callback function for a started capture.
383 * @param session The session, must be valid
384 * @param request The capture request, must be valid
385 * @param timestamp The capture results, must be valid
386 */
387 void onCaptureStarted(ACameraCaptureSession* session, const ACaptureRequest* request, int64_t timestamp);
388
389 /**
390 * The callback function for a completed capture.
391 * @param session The session, must be valid
392 * @param request The capture request, must be valid
393 * @param result The capture results, must be valid
394 */
395 void onCaptureCompleted(ACameraCaptureSession* session, ACaptureRequest* request, const ACameraMetadata* result);
396
397 /**
398 * Event function for new camera frames.
399 * @param frame The new camera frame, must be valid
400 * @param anyCamera The camera profile defining the projection, invalid if unknown
401 * @return True, if succeeded
402 */
403 bool onNewFrame(Frame&& frame, SharedAnyCamera&& anyCamera);
404
405 /**
406 * Determines the camera id and associated frame type for a given URL.
407 * @param cameraManager The camera manager from which the camera id will be determined, must be valid
408 * @param url The URL for which the camera id will be determined
409 * @param id Optional known id of the camera, if provided the camera id will be verified again
410 * @param preferredFrameType The preferred frame type (may contain a valid image dimension, or just a pixel format), can be invalid
411 * @param frameType The resulting frame type matching with the resulting id
412 * @param streamConfigurations Optional resulting stream configurations
413 * @param device_T_camera Optional resulting transformation between camera and device
414 * @return The resulting id of the camera
415 */
416 static std::string cameraIdForMedium(ACameraManager* cameraManager, const std::string& url, const std::string& id, const FrameType& preferredFrameType, FrameType& frameType, StreamConfigurations* streamConfigurations = nullptr, HomogenousMatrixD4* device_T_camera = nullptr);
417
418 /**
419 * Determines the camera id and associated frame type for a given URL or/and id.
420 * @param cameraIdList The camera id list from which the camera id will be determined, must be valid
421 * @param url The URL for which the camera id will be determined
422 * @param id Optional known id of the camera, if provided the camera id will be verified again
423 * @return The resulting id of the camera, empty if no camera could be found
424 */
425 static std::string cameraIdForMedium(ACameraIdList* cameraIdList, const std::string& url, const std::string& id);
426
427 /**
428 * Determines the range of the exposure duration of the camera sensor.
429 * @param cameraManager The camera manager, must be valid
430 * @param cameraId The id of the camera, must be valid
431 * @param minExposureDuration The minimal exposure duration, in seconds
432 * @param maxExposureDuration The maximal exposure duration, in seconds
433 * @return True, if succeeded
434 */
435 static bool cameraExposureDurationRange(ACameraManager* cameraManager, const std::string& cameraId, double& minExposureDuration, double& maxExposureDuration);
436
437 /**
438 * Determines the range of the ISO of the camera sensor.
439 * @param cameraManager The camera manager, must be valid
440 * @param cameraId The id of the camera, must be valid
441 * @param minISO The minimal ISO
442 * @param maxISO The maximal ISO
443 * @return True, if succeeded
444 */
445 static bool cameraISORange(ACameraManager* cameraManager, const std::string& cameraId, float& minISO, float& maxISO);
446
447 /**
448 * Determines the minimal focus distance of the camera sensor.
449 * @param cameraManager The camera manager, must be valid
450 * @param cameraId The id of the camera, must be valid
451 * @param minFocusPosition The minimal focus distance, which is the reciprocal of the focus distance in meters
452 * @return True, if succeeded
453 */
454 static bool cameraMinFocus(ACameraManager* cameraManager, const std::string& cameraId, float& minFocusPosition);
455
456 /**
457 * Determines the physical size of the camera sensor.
458 * @param cameraManager The camera manager, must be valid
459 * @param cameraId The id of the camera, must be valid
460 * @param cameraSensorPhysicalSizeX Resulting horizontal physical size of the sensor
461 * @return True, if succeeded
462 */
463 static bool cameraSensorPysicalSize(ACameraManager* cameraManager, const std::string& cameraId, float& cameraSensorPhysicalSizeX);
464
465 /**
466 * Determines the horizontal field of view from the camera's metadata based on `ACAMERA_LENS_FOCAL_LENGTH`.
467 * @param cameraSensorPhysicalSizeX The horizontal physical size of camera sensor, as provided by `ACAMERA_SENSOR_INFO_PHYSICAL_SIZE`.
468 * @param cameraMetadata The camera's metadata for a recent frame, must be valid
469 * @param fovX The resulting horizontal field of view of the camera, in radian
470 * @return True, if succeeded
471 */
472 static bool horizontalFieldOfView(const float cameraSensorPhysicalSizeX, const ACameraMetadata* cameraMetadata, float& fovX);
473
474 /**
475 * Extracts the next frame from an Android image object.
476 * @param image The Android image object from which the next frame will be extracted
477 * @param frame The resulting frame containing the extracted image
478 * @return True, if succeeded
479 */
480 static bool frameFromImage(AImage* image, Frame& frame);
481
482 /**
483 * Returns the transformation between camera and device (device_T_camera).
484 * @param cameraMetadata The camera metadata from which the transformation will be determined, must be valid
485 * @return The camera transformation with default camera pointing towards the negative z-space with y-axis upwards; invalid if the transformation could not be determined
486 */
487 static HomogenousMatrixD4 determineCameraTransformation(ACameraMetadata* cameraMetadata);
488
489 /**
490 * Translates an Android pixel format to an Ocean pixel format.
491 * @param androidFormat The Android pixel format to translate
492 * @return The corresponding Ocean pixel format, FORMAT_UNDEFINED if no corresponding Ocean pixel format exists
493 */
494 static FrameType::PixelFormat androidFormatToPixelFormat(const int32_t androidFormat);
495
496 /**
497 * Translates Android formats to readable strings.
498 * @param androidFormat The Android pixel format to translate
499 * @return The corresponding readable string of the Android format
500 */
501 static std::string androidFormatToString(const int32_t androidFormat);
502
503 /**
504 * Translates an Ocean pixel format to an Android pixel format.
505 * @param pixelFormat The Ocean pixel format to translate
506 * @return The corresponding Android pixel format, 0 if no corresponding Android pixel format exists
507 */
508 static int32_t pixelFormatToAndroidFormat(const FrameType::PixelFormat pixelFormat);
509
510 /**
511 * Determines the available stream configurations for the camera metadata from a camera.
512 * @param cameraMetadata The camera metadata from which the stream configurations will be determined, must be valid
513 * @return The resulting stream configurations
514 */
515 static StreamConfigurations determineAvailableStreamConfigurations(const ACameraMetadata* cameraMetadata);
516
517 /**
518 * The static callback function for camera images.
519 * @param context The event's context, must be valid
520 * @param imageReader The image reader of the event, must be valid
521 * @see onCameraImageCallback().
522 */
523 static void onCameraImageCallbackStatic(void* context, AImageReader* imageReader);
524
525 /**
526 * The static callback function for a disconnected camera.
527 * @param context The event's context, must be valid
528 * @param cameraDevice The camera device of the event, must be valid
529 * @see onCameraDisconnected().
530 */
531 static void onCameraDisconnectedStatic(void* context, ACameraDevice* cameraDevice);
532
533 /**
534 * The static callback function for errors.
535 * @param context The event's context, must be valid
536 * @param cameraDevice The camera device of the event, must be valid
537 * @param error The error value of the event
538 * @see onCameraError().
539 */
540 static void onCameraErrorStatic(void* context, ACameraDevice* cameraDevice, int error);
541
542 /**
543 * The static callback function for an active session.
544 * @param context The event's context, must be valid
545 * @param session The session, must be valid
546 */
547 static void onSessionActiveStatic(void* context, ACameraCaptureSession* session);
548
549 /**
550 * The static callback function for a ready session.
551 * @param context The event's context, must be valid
552 * @param session The session, must be valid
553 */
554 static void onSessionReadyStatic(void* context, ACameraCaptureSession* session);
555
556 /**
557 * The static callback function for a closed session.
558 * @param context The event's context, must be valid
559 * @param session The session, must be valid
560 */
561 static void onSessionClosedStatic(void* context, ACameraCaptureSession* session);
562
563 /**
564 * The static callback function for a failed capture.
565 * @param context The event's context, must be valid
566 * @param session The session, must be valid
567 * @param request The capture request, must be valid
568 * @param failure The failure, must be valid
569 */
570 static void onCaptureFailedStatic(void* context, ACameraCaptureSession* session, ACaptureRequest* request, ACameraCaptureFailure* failure);
571
572 /**
573 * The static callback function for a completed capture sequence.
574 * @param context The event's context, must be valid
575 * @param session The session, must be valid
576 * @param sequenceId The sequence id
577 * @param frameNumber The number of frames
578 */
579 static void onCaptureSequenceCompletedStatic(void* context, ACameraCaptureSession* session, int sequenceId, int64_t frameNumber);
580
581 /**
582 * The static callback function for an aborted sequence.
583 * @param context The event's context, must be valid
584 * @param session The session, must be valid
585 * @param sequenceId The sequence id
586 */
587 static void onCaptureSequenceAbortedStatic(void* context, ACameraCaptureSession* session, int sequenceId);
588
589 /**
590 * The static callback function for a started capture.
591 * @param context The event's context, must be valid
592 * @param session The session, must be valid
593 * @param request The capture request, must be valid
594 * @param timestamp The capture timestamp
595 */
596 static void onCaptureStartedStatic(void *context, ACameraCaptureSession *session, const ACaptureRequest *request, int64_t timestamp);
597
598 /**
599 * The static callback function for a completed capture.
600 * @param context The event's context, must be valid
601 * @param session The session, must be valid
602 * @param request The capture request, must be valid
603 * @param result The capture results, must be valid
604 */
605 static void onCaptureCompletedStatic(void* context, ACameraCaptureSession* session, ACaptureRequest* request, const ACameraMetadata* result);
606
607 /**
608 * Translates a camera status to a readable strings.
609 * @param cameraStatus The camera status
610 * @return The readable camera status.
611 */
612 static std::string translateCameraStatus(const camera_status_t cameraStatus);
613
614 protected:
615
616 /// Unique camera id defined by Android, may be valid even if 'cameraDevice_' is not yet valid.
617 std::string cameraId_;
618
619 /// The camera device.
620 ACameraDevice* cameraDevice_ = nullptr;
621
622 /// The image reader.
623 AImageReader* imageReader_ = nullptr;
624
625 /// The native Android window associated with the video.
626 ANativeWindow* nativeWindow_ = nullptr;
627
628 /// The session output.
630
631 /// The session output container.
633
634 /// The capture session.
635 ACameraCaptureSession* captureSession_ = nullptr;
636
637 /// The capture request.
638 ACaptureRequest* captureRequest_ = nullptr;
639
640 /// The output target.
641 ACameraOutputTarget* outputTarget_ = nullptr;
642
643 /// The horizontal size of the physical camera sensor, if known; -1 if unknown.
644 float cameraSensorPhysicalSizeX_ = -1.0f;
645
646 /// The transformation between camera and device, with default camera pointing towards the negative z-space with y-axis up.
647 HomogenousMatrixD4 device_T_camera_ = HomogenousMatrixD4(false);
648
649 /// The current exposure mode of this device.
650 ControlMode exposureMode_ = CM_INVALID;
651
652 /// The current exposure duration of this device.
653 double exposureDuration_ = -1.0;
654
655 /// Minimal duration to set, in seconds, with range (0, infinity), -1 if unknown.
656 double exposureDurationMin_ = -1.0;
657
658 /// Maximal duration to set, in seconds, with range [exposureDurationMin_, infinity), -1 if unknown
659 double exposureDurationMax_ = -1.0;
660
661 /// The current ISO mode of this device.
662 ControlMode isoMode_ = CM_INVALID;
663
664 /// The current ISO, with range [isoMin_, isoMax_], 0 for auto IOS, -1 if unknown.
665 float iso_ = -1.0f;
666
667 /// Minimal ISO to set, with range (0, infinity), -1 if unknown.
668 float isoMin_ = -1.0f;
669
670 /// Maximal ISO to set, with range (isoMin_, infinity), -1 if unknown.
671 float isoMax_ = -1.0f;
672
673 /// The current focus mode of this device.
674 ControlMode focusMode_ = CM_INVALID;
675
676 /// The focus position to be set, with range [0, 1] with 0 shortest distance and 1 furthest distance, -1 if unknown.
677 float focusPosition_ = -1.0f;
678
679 /// The minimal focus distance (reciprocal of the focus distance in meters), -1 if unknown.
680 float focusPositionMin_ = -1.0f;
681
682 /// The stream configurations available for this camera.
684
685 /// Start timestamp.
687
688 /// Pause timestamp.
690
691 /// Stop timestamp.
693};
694
695inline ALiveVideo::Device::Device(const std::string& id, const std::string& name, const acamera_metadata_enum_android_lens_facing_t lensFacing, MetadataMap&& metadataMap) :
696 id_(id),
697 name_(name),
698 lensFacing_(lensFacing),
699 metadataMap_(std::move(metadataMap))
700{
701 ocean_assert(!id_.empty());
702 ocean_assert(!name_.empty());
703}
704
705inline const std::string& ALiveVideo::Device::id() const
706{
707 return id_;
708}
709
710inline const std::string& ALiveVideo::Device::name() const
711{
712 return name_;
713}
714
715inline acamera_metadata_enum_android_lens_facing_t ALiveVideo::Device::lensFacing() const
716{
717 return lensFacing_;
718}
719
721{
722 return metadataMap_;
723}
724
726{
727 return !id_.empty();
728}
729
730#else // OCEAN_MEDIA_ANDROID_NATIVECAMERALIBRARY_AVAILABLE
731
732/**
733 * Java native interface function for new camera framebuffer events.
734 * @param env JNI environment object
735 * @param javaThis JNI caller object
736 * @param objectId Id of the camera object
737 * @param imageBuffer New camera image buffer
738 * @param width The width of the new camera image buffer in pixel
739 * @param height The height of the new camera image buffer in pixel
740 * @param format The format of the camera image buffer
741 * @param fovX Horizontal field of view in radian
742 * @param bufferSize The size of the given image buffer in bytes
743 * @param timestamp Unix timestamp of the frame in seconds (time since 1970)
744 * @return True, if succeeded
745 * @ingroup mediaandroid
746 */
747extern "C" jboolean Java_com_meta_ocean_media_android_MediaAndroidJni_onNewCameraFrame(JNIEnv* env, jobject javaThis, jint objectId, jbyteArray imageBuffer, jint width, jint height, jint format, jfloat fovX, jint bufferSize, jdouble timestamp);
748
749/**
750 * This class implements an live video class for Android.
751 * @ingroup mediaandroid
752 */
753class OCEAN_MEDIA_A_EXPORT ALiveVideo final :
754 virtual public AMedium,
755 virtual public LiveVideo
756{
757 friend class ALibrary;
758 friend class ALiveVideoManager;
759
760 public:
761
762 /**
763 * This class implements a camera manager.
764 */
765 class ALiveVideoManager : public Singleton<ALiveVideoManager>
766 {
767 friend class Singleton<ALiveVideoManager>;
768 friend class ALiveVideo;
769
770 private:
771
772 /**
773 * Definition of a map mapping camera id to ocean camera objects.
774 */
775 typedef std::map<int, ALiveVideo*> ObjectMap;
776
777 public:
778
779 /**
780 * Event function for a new camera frame.
781 * @param cameraId Id of the camera the new frame belongs to
782 * @param frame The new camera frame, must be valid
783 * @param anyCamera The camera profile defining the projection, can be invalid
784 * @return True, if succeeded
785 */
786 bool onNewFrame(const int cameraId, Frame&& frame, SharedAnyCamera&& anyCamera);
787
788 private:
789
790 /**
791 * Creates a new camera manager.
792 */
794
795 /**
796 * Destructs a camera manager.
797 */
799
800 /**
801 * Creates a new camera object.
802 * @param object Ocean video object to connect with the android camera object
803 * @param url The camera url to create the object for
804 * @param preferredWidth Preferred frame width in pixel
805 * @param preferredHeight Preferred frame height in pixel
806 * @param preferredFrequency Preferred frame frequency in Hz
807 * @return Unique camera id if succeeded, -1 otherwise
808 */
809 int createCamera(ALiveVideo* object, const std::string& url, const unsigned int preferredWidth, const unsigned int preferredHeight, const float preferredFrequency);
810
811 /**
812 * Releases a camera object.
813 * @param cameraId Unique camera id of the camera to be released
814 */
815 void releaseCamera(const int cameraId);
816
817 /**
818 * Starts a specified camera object.
819 * @param cameraId Id of the camera to be started
820 * @return True, if succeeded
821 */
822 bool startCamera(const int cameraId);
823
824 /**
825 * Pauses a specified camera object.
826 * @param cameraId Id of the camera to be paused
827 * @return True, if succeeded
828 */
829 bool pauseCamera(const int cameraId);
830
831 /**
832 * Stops a specified camera object.
833 * @param cameraId Id of the camera to be stopped
834 * @return True, if succeeded
835 */
836 bool stopCamera(const int cameraId);
837
838 private:
839
840 /// The camera object map.
842
843 /// Manager lock.
845 };
846
847 /**
848 * Returns whether the medium is started currently.
849 * @see Medium::isStarted().
850 */
851 bool isStarted() const override;
852
853 /**
854 * Returns the start timestamp.
855 * @see FiniteMedium::startTimestamp().
856 */
857 Timestamp startTimestamp() const override;
858
859 /**
860 * Returns the pause timestamp.
861 * @see FiniteMedium::pauseTimestamp().
862 */
863 Timestamp pauseTimestamp() const override;
864
865 /**
866 * Returns the stop timestamp.
867 * @see FiniteMedium::stopTimestamp().
868 */
869 Timestamp stopTimestamp() const override;
870
871 /**
872 * Returns the transformation between the camera and device.
873 * @see FrameMedium::device_T_camera().
874 */
876
877 /**
878 * Explicitly feeds a new external frame this live video.
879 * This function is intended for situations in which this live video does not receive the frame anymore from the system (e.g., when ARCore is accessing the video stream).<br>
880 * Do not call this function in case the live video is still receiving pixel buffers from the Android media system.
881 * @param frame The frame to be fed, must be valid
882 * @param anyCamera The camera profile defining the projection, must be valid
883 * @param exposureMode The exposure mode of the camera, CM_INVALID if unknown
884 * @param exposureDuration The exposure duration of the camera, in seconds, -1 if unknown
885 * @param isoMode The ISO mode of the camera, CM_INVALID if unknown
886 * @param iso The ISO of the camera, -1 if unknown
887 * @param focusMode The focus mode of the camera, CM_INVALID if unknown
888 * @param focusValue The focus value of the camera, in the same domain as ACAMERA_LENS_INFO_MINIMUM_FOCUS_DISTANCE, -1 if unknown
889 */
890 void feedNewFrame(Frame&& frame, SharedAnyCamera&& anyCamera, const ControlMode exposureMode, const double exposureDuration, const ControlMode isoMode, const float iso, const ControlMode focusMode, const float focusValue);
891
892
893 /**
894 * Forces a restart of the live video for situations in which the camera was used by an external resource.
895 * This function is intended for situations in which e.g., ARCore has used the borrowed the camera resource but does not use it anymore.
896 * Do not call this function in case the live video is still receiving pixel buffers from the Android media system.
897 * @return True, if succeeded
898 */
900
901 protected:
902
903 /**
904 * Creates a new medium by a given url.
905 * @param url Url of the medium
906 */
907 explicit ALiveVideo(const std::string& url);
908
909 /**
910 * Destructs the live video object.
911 */
912 ~ALiveVideo() override;
913
914 /**
915 * Starts the medium.
916 * @see Medium::start().
917 */
918 bool start() override;
919
920 /**
921 * Pauses the medium.
922 * @see Medium::pause():
923 */
924 bool pause() override;
925
926 /**
927 * Stops the medium.
928 * @see Medium::stop().
929 */
930 bool stop() override;
931
932 /**
933 * Event function for new camera frames.
934 * @param frame The new camera frame, must be valid
935 * @param anyCamera The camera profile defining the projection, invalid if unknown
936 * @return True, if succeeded
937 */
938 bool onNewFrame(Frame&& frame, SharedAnyCamera&& anyCamera);
939
940 protected:
941
942 /// Unique camera id received by the android system.
943 int mediumCameraId = -1;
944
945 /// Recent frame type.
947
948 /// State determining whether the camera is currently started.
949 bool mediumIsStarted = false;
950
951 /// Start timestamp.
953
954 /// Pause timestamp.
956
957 /// Stop timestamp.
959};
960
961#endif // OCEAN_MEDIA_ANDROID_NATIVECAMERALIBRARY_AVAILABLE
962
963}
964
965}
966
967}
968
969#endif // META_OCEAN_MEDIA_ANDROID_A_LIVE_VIDEO_H
This class implements Ocean's image class.
Definition Frame.h:1808
Definition of a frame type composed by the frame dimension, pixel format and pixel origin.
Definition Frame.h:30
PixelFormat
Definition of all pixel formats available in the Ocean framework.
Definition Frame.h:183
This class implements a recursive lock object.
Definition Lock.h:31
This class implements the android library.
Definition ALibrary.h:37
This class implements a camera manager.
Definition ALiveVideo.h:766
Lock managerLock
Manager lock.
Definition ALiveVideo.h:844
virtual ~ALiveVideoManager()
Destructs a camera manager.
std::map< int, ALiveVideo * > ObjectMap
Definition of a map mapping camera id to ocean camera objects.
Definition ALiveVideo.h:775
bool onNewFrame(const int cameraId, Frame &&frame, SharedAnyCamera &&anyCamera)
Event function for a new camera frame.
ALiveVideoManager()
Creates a new camera manager.
bool stopCamera(const int cameraId)
Stops a specified camera object.
ObjectMap managerObjectMap
The camera object map.
Definition ALiveVideo.h:841
bool startCamera(const int cameraId)
Starts a specified camera object.
bool pauseCamera(const int cameraId)
Pauses a specified camera object.
int createCamera(ALiveVideo *object, const std::string &url, const unsigned int preferredWidth, const unsigned int preferredHeight, const float preferredFrequency)
Creates a new camera object.
void releaseCamera(const int cameraId)
Releases a camera object.
This class holds the relevant information of a selectable live video device.
Definition ALiveVideo.h:52
const MetadataMap & metadataMap() const
Returns the optional metadata map of the device.
Definition ALiveVideo.h:720
MetadataMap metadataMap_
The optional metadata map of the device.
Definition ALiveVideo.h:127
std::unordered_map< uint32_t, Value > MetadataMap
Definition of an unordered map mapping metadata tags to their values.
Definition ALiveVideo.h:58
static std::string readableLensFacing(const acamera_metadata_enum_android_lens_facing_t lensFacing)
Returns the readable string for a lens facing type.
Device()=default
Default constructor.
const std::string & id() const
Returns the device's id.
Definition ALiveVideo.h:705
bool isValid() const
Returns whether this object is valid.
Definition ALiveVideo.h:725
const std::string & name() const
Returns the device's name.
Definition ALiveVideo.h:710
acamera_metadata_enum_android_lens_facing_t lensFacing() const
Returns the device's direction.
Definition ALiveVideo.h:715
std::string id_
The device's id.
Definition ALiveVideo.h:118
std::string name_
The device's human readable name.
Definition ALiveVideo.h:121
This class implements an live video class for Android.
Definition ALiveVideo.h:42
Timestamp mediumStartTimestamp
Start timestamp.
Definition ALiveVideo.h:952
StreamConfigurations availableStreamConfigurations_
The stream configurations available for this camera.
Definition ALiveVideo.h:683
Timestamp mediumPauseTimestamp
Pause timestamp.
Definition ALiveVideo.h:955
bool onNewFrame(Frame &&frame, SharedAnyCamera &&anyCamera)
Event function for new camera frames.
static std::string cameraIdForMedium(ACameraIdList *cameraIdList, const std::string &url, const std::string &id)
Determines the camera id and associated frame type for a given URL or/and id.
static HomogenousMatrixD4 determineCameraTransformation(ACameraMetadata *cameraMetadata)
Returns the transformation between camera and device (device_T_camera).
bool start() override
Starts the medium.
float focus(ControlMode *focusMode=nullptr) const override
Returns the current focus of this device.
StreamTypes supportedStreamTypes() const override
Returns the supported stream types.
static bool cameraISORange(ACameraManager *cameraManager, const std::string &cameraId, float &minISO, float &maxISO)
Determines the range of the ISO of the camera sensor.
static void onCameraImageCallbackStatic(void *context, AImageReader *imageReader)
The static callback function for camera images.
bool stop() override
Stops the medium.
static bool cameraSensorPysicalSize(ACameraManager *cameraManager, const std::string &cameraId, float &cameraSensorPhysicalSizeX)
Determines the physical size of the camera sensor.
bool releaseCamera()
Releases the Android camera.
void onCameraError(ACameraDevice *cameraDevice, int error)
The callback function for errors.
static bool cameraMinFocus(ACameraManager *cameraManager, const std::string &cameraId, float &minFocusPosition)
Determines the minimal focus distance of the camera sensor.
void onCaptureStarted(ACameraCaptureSession *session, const ACaptureRequest *request, int64_t timestamp)
The callback function for a started capture.
bool setFocus(const float position) override
Sets the focus of this device.
static void onSessionClosedStatic(void *context, ACameraCaptureSession *session)
The static callback function for a closed session.
void releaseCaptureSession()
Releases the capture session.
static void onCaptureStartedStatic(void *context, ACameraCaptureSession *session, const ACaptureRequest *request, int64_t timestamp)
The static callback function for a started capture.
bool createCaptureSession()
Creates a new capture session, needs a valid camera and image reader.
HomogenousMatrixD4 device_T_camera() const override
Returns the transformation between the camera and device.
static StreamConfigurations determineAvailableStreamConfigurations(const ACameraMetadata *cameraMetadata)
Determines the available stream configurations for the camera metadata from a camera.
AIMAGE_FORMATS_MISSING_FROM_NDK
Definition of Android image formats that are missing from the NDK These values are used but they are ...
Definition ALiveVideo.h:140
void releaseImageReader()
Releases the image reader.
void onCameraDisconnected(ACameraDevice *cameraDevice)
The callback function for a disconnected camera.
Timestamp pauseTimestamp() const override
Returns the pause timestamp.
bool setExposureDuration(const double duration, const bool allowShorterExposure=false) override
Sets the exposure duration of this device.
bool release()
Releases the camera and all corresponding resources.
static Devices selectableDevices()
Returns the list of currently selectable devices.
bool forceRestart()
Forces a restart of the live video for situations in which the camera was used by an external resourc...
FrameType imageRecentFrameType
Recent frame type.
Definition ALiveVideo.h:946
static void onCaptureSequenceAbortedStatic(void *context, ACameraCaptureSession *session, int sequenceId)
The static callback function for an aborted sequence.
bool initialize()
Initializes the camera and all corresponding resources.
static FrameType::PixelFormat androidFormatToPixelFormat(const int32_t androidFormat)
Translates an Android pixel format to an Ocean pixel format.
ALiveVideo(const std::string &url, const std::string &id)
Creates a new medium by a given url.
static void onCaptureCompletedStatic(void *context, ACameraCaptureSession *session, ACaptureRequest *request, const ACameraMetadata *result)
The static callback function for a completed capture.
bool setPreferredStreamType(const StreamType streamType) override
Sets the preferred stream type.
Timestamp startTimestamp() const override
Returns the start timestamp.
static void onCameraErrorStatic(void *context, ACameraDevice *cameraDevice, int error)
The static callback function for errors.
Timestamp mediumStopTimestamp
Stop timestamp.
Definition ALiveVideo.h:958
bool setPreferredStreamConfiguration(const StreamConfiguration &streamConfiguration) override
Sets the preferred stream configuration.
static bool horizontalFieldOfView(const float cameraSensorPhysicalSizeX, const ACameraMetadata *cameraMetadata, float &fovX)
Determines the horizontal field of view from the camera's metadata based on ACAMERA_LENS_FOCAL_LENGTH...
static std::string translateCameraStatus(const camera_status_t cameraStatus)
Translates a camera status to a readable strings.
void onCameraImageCallback(AImageReader *imageReader)
The callback function for camera images.
Timestamp stopTimestamp_
Stop timestamp.
Definition ALiveVideo.h:692
NativeCameraLibrary::ScopedACaptureSessionOutput sessionOutput_
The session output.
Definition ALiveVideo.h:629
Timestamp stopTimestamp() const override
Returns the stop timestamp.
bool createCamera(FrameType &frameType)
Creates an Android camera for the URL of this medium.
static void onCaptureSequenceCompletedStatic(void *context, ACameraCaptureSession *session, int sequenceId, int64_t frameNumber)
The static callback function for a completed capture sequence.
static bool cameraExposureDurationRange(ACameraManager *cameraManager, const std::string &cameraId, double &minExposureDuration, double &maxExposureDuration)
Determines the range of the exposure duration of the camera sensor.
static void onSessionActiveStatic(void *context, ACameraCaptureSession *session)
The static callback function for an active session.
bool setISO(const float iso) override
Sets the ISO of this device.
static void onSessionReadyStatic(void *context, ACameraCaptureSession *session)
The static callback function for a ready session.
bool pause() override
Pauses the medium.
StreamConfigurations supportedStreamConfigurations(const StreamType streamType=ST_INVALID) const override
Returns the supported stream configurations for a given stream type.
static std::string cameraIdForMedium(ACameraManager *cameraManager, const std::string &url, const std::string &id, const FrameType &preferredFrameType, FrameType &frameType, StreamConfigurations *streamConfigurations=nullptr, HomogenousMatrixD4 *device_T_camera=nullptr)
Determines the camera id and associated frame type for a given URL.
NativeCameraLibrary::ScopedACaptureSessionOutputContainer sessionOutputContainer_
The session output container.
Definition ALiveVideo.h:632
void feedNewFrame(Frame &&frame, SharedAnyCamera &&anyCamera, const ControlMode exposureMode, const double exposureDuration, const ControlMode isoMode, const float iso, const ControlMode focusMode, const float focusValue)
Explicitly feeds a new external frame this live video.
bool isStarted() const override
Returns whether the medium is started currently.
void onSessionClosed(ACameraCaptureSession *session)
The callback function for a closed session.
bool createImageReader(const FrameType &frameType)
Creates a new image reader based on a given frame type, needs a valid camera.
static std::string androidFormatToString(const int32_t androidFormat)
Translates Android formats to readable strings.
float iso(float *minISO=nullptr, float *maxISO=nullptr, ControlMode *isoMode=nullptr) const override
Returns the current ISO of this device.
void onSessionActive(ACameraCaptureSession *session)
The callback function for an active session.
std::string cameraId_
Unique camera id defined by Android, may be valid even if 'cameraDevice_' is not yet valid.
Definition ALiveVideo.h:617
static int32_t pixelFormatToAndroidFormat(const FrameType::PixelFormat pixelFormat)
Translates an Ocean pixel format to an Android pixel format.
~ALiveVideo() override
Destructs the live video object.
ALiveVideo(const std::string &url)
Creates a new medium by a given url.
void onCaptureCompleted(ACameraCaptureSession *session, ACaptureRequest *request, const ACameraMetadata *result)
The callback function for a completed capture.
Timestamp startTimestamp_
Start timestamp.
Definition ALiveVideo.h:686
std::vector< Device > Devices
Definition ALiveVideo.h:130
Timestamp pauseTimestamp_
Pause timestamp.
Definition ALiveVideo.h:689
static void onCaptureFailedStatic(void *context, ACameraCaptureSession *session, ACaptureRequest *request, ACameraCaptureFailure *failure)
The static callback function for a failed capture.
double exposureDuration(double *minDuration=nullptr, double *maxDuration=nullptr, ControlMode *exposureMode=nullptr) const override
Returns the current exposure duration of this device.
static bool frameFromImage(AImage *image, Frame &frame)
Extracts the next frame from an Android image object.
static void onCameraDisconnectedStatic(void *context, ACameraDevice *cameraDevice)
The static callback function for a disconnected camera.
This class implements the base class for all Medium objects in the Android library.
Definition AMedium.h:35
Definition of a scoped object for ACaptureSessionOutputContainer objects.
Definition NativeCameraLibrary.h:95
Definition of a scoped object for ACaptureSessionOutput objects.
Definition NativeCameraLibrary.h:114
This class holds the relevant information describing a video stream configuration.
Definition LiveVideo.h:92
This class is the base class for all live videos.
Definition LiveVideo.h:38
StreamType
Definition of individual stream types.
Definition LiveVideo.h:59
ControlMode
Definition of individual control modes.
Definition LiveVideo.h:46
std::vector< StreamConfiguration > StreamConfigurations
Definition of a vector holding stream configurations.
Definition LiveVideo.h:148
std::vector< StreamType > StreamTypes
Definition of a vector holding stream types.
Definition LiveVideo.h:73
This template class is the base class for all singleton objects.
Definition Singleton.h:71
This class implements a timestamp.
Definition Timestamp.h:36
std::shared_ptr< AnyCamera > SharedAnyCamera
Definition of a shared pointer holding an AnyCamera object with Scalar precision.
Definition AnyCamera.h:60
jboolean Java_com_meta_ocean_media_android_MediaAndroidJni_onNewCameraFrame(JNIEnv *env, jobject javaThis, jint objectId, jbyteArray imageBuffer, jint width, jint height, jint format, jfloat fovX, jint bufferSize, jdouble timestamp)
Java native interface function for new camera framebuffer events.
The namespace covering the entire Ocean framework.
Definition Accessor.h:15