Skip to content

Commit c10af8e

Browse files
committed
camera: Report rotation needed to account for device orientation.
Fixes #11476.
1 parent 12e3162 commit c10af8e

File tree

12 files changed

+132
-15
lines changed

12 files changed

+132
-15
lines changed

include/SDL3/SDL_surface.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,12 @@ extern SDL_DECLSPEC void SDLCALL SDL_DestroySurface(SDL_Surface *surface);
241241
* left edge of the image, if this surface is being used as a cursor.
242242
* - `SDL_PROP_SURFACE_HOTSPOT_Y_NUMBER`: the hotspot pixel offset from the
243243
* top edge of the image, if this surface is being used as a cursor.
244+
* - `SDL_PROP_SURFACE_ROTATION_NUMBER`: the number of degrees a surface's
245+
* data is meant to be rotated clockwise to make the image
246+
* right-side up. Default 0. This is used by the camera API, if a mobile
247+
* device is oriented differently than what its camera provides (i.e. -
248+
* the camera always provides portrait images but the phone is being held
249+
* in landscape orientation). Since SDL 3.4.0.
244250
*
245251
* \param surface the SDL_Surface structure to query.
246252
* \returns a valid property ID on success or 0 on failure; call
@@ -257,6 +263,7 @@ extern SDL_DECLSPEC SDL_PropertiesID SDLCALL SDL_GetSurfaceProperties(SDL_Surfac
257263
#define SDL_PROP_SURFACE_TONEMAP_OPERATOR_STRING "SDL.surface.tonemap"
258264
#define SDL_PROP_SURFACE_HOTSPOT_X_NUMBER "SDL.surface.hotspot.x"
259265
#define SDL_PROP_SURFACE_HOTSPOT_Y_NUMBER "SDL.surface.hotspot.y"
266+
#define SDL_PROP_SURFACE_ROTATION_NUMBER "SDL.surface.rotation"
260267

261268
/**
262269
* Set the colorspace used by a surface.

src/camera/SDL_camera.c

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ static size_t GetFrameBufLen(const SDL_CameraSpec *spec)
150150
return wxh * SDL_BYTESPERPIXEL(fmt);
151151
}
152152

153-
static SDL_CameraFrameResult ZombieAcquireFrame(SDL_Camera *device, SDL_Surface *frame, Uint64 *timestampNS)
153+
static SDL_CameraFrameResult ZombieAcquireFrame(SDL_Camera *device, SDL_Surface *frame, Uint64 *timestampNS, int *rotation)
154154
{
155155
const SDL_CameraSpec *spec = &device->actual_spec;
156156

@@ -832,9 +832,10 @@ bool SDL_CameraThreadIterate(SDL_Camera *device)
832832
SDL_Surface *output_surface = NULL;
833833
SurfaceList *slist = NULL;
834834
Uint64 timestampNS = 0;
835+
int rotation = 0;
835836

836837
// AcquireFrame SHOULD NOT BLOCK, as we are holding a lock right now. Block in WaitDevice instead!
837-
const SDL_CameraFrameResult rc = device->AcquireFrame(device, device->acquire_surface, &timestampNS);
838+
const SDL_CameraFrameResult rc = device->AcquireFrame(device, device->acquire_surface, &timestampNS, &rotation);
838839

839840
if (rc == SDL_CAMERA_FRAME_READY) { // new frame acquired!
840841
#if DEBUG_CAMERA
@@ -928,6 +929,8 @@ bool SDL_CameraThreadIterate(SDL_Camera *device)
928929
acquired->pixels = NULL;
929930
acquired->pitch = 0;
930931

932+
SDL_SetNumberProperty(SDL_GetSurfaceProperties(output_surface), SDL_PROP_SURFACE_ROTATION_NUMBER, rotation);
933+
931934
// make the filled output surface available to the app.
932935
SDL_LockMutex(device->lock);
933936
slist->next = device->filled_output_surfaces.next;

src/camera/SDL_syscamera.h

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ struct SDL_Camera
9999

100100
// These are, initially, set from camera_driver, but we might swap them out with Zombie versions on disconnect/failure.
101101
bool (*WaitDevice)(SDL_Camera *device);
102-
SDL_CameraFrameResult (*AcquireFrame)(SDL_Camera *device, SDL_Surface *frame, Uint64 *timestampNS);
102+
SDL_CameraFrameResult (*AcquireFrame)(SDL_Camera *device, SDL_Surface *frame, Uint64 *timestampNS, int *rotation);
103103
void (*ReleaseFrame)(SDL_Camera *device, SDL_Surface *frame);
104104

105105
// All supported formats/dimensions for this device.
@@ -167,13 +167,18 @@ struct SDL_Camera
167167
struct SDL_PrivateCameraData *hidden;
168168
};
169169

170+
171+
// Note that for AcquireFrame, `rotation` is degrees, with positive values rotating clockwise. This is the amount to rotate an image so it would be right-side up.
172+
// Rotations should be in 90 degree increments at this time (landscape to portrait, or upside down to right side up, etc).
173+
// Most platforms won't care about this, but mobile devices might need to deal with the device itself being physically rotated, causing the fixed-orientation camera to be presenting sideways images.
174+
170175
typedef struct SDL_CameraDriverImpl
171176
{
172177
void (*DetectDevices)(void);
173178
bool (*OpenDevice)(SDL_Camera *device, const SDL_CameraSpec *spec);
174179
void (*CloseDevice)(SDL_Camera *device);
175180
bool (*WaitDevice)(SDL_Camera *device);
176-
SDL_CameraFrameResult (*AcquireFrame)(SDL_Camera *device, SDL_Surface *frame, Uint64 *timestampNS); // set frame->pixels, frame->pitch, and *timestampNS!
181+
SDL_CameraFrameResult (*AcquireFrame)(SDL_Camera *device, SDL_Surface *frame, Uint64 *timestampNS, int *rotation); // set frame->pixels, frame->pitch, *timestampNS, and *rotation!
177182
void (*ReleaseFrame)(SDL_Camera *device, SDL_Surface *frame); // Reclaim frame->pixels and frame->pitch!
178183
void (*FreeDeviceHandle)(SDL_Camera *device); // SDL is done with this device; free the handle from SDL_AddCamera()
179184
void (*Deinitialize)(void);

src/camera/android/SDL_camera_android.c

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,7 @@ struct SDL_PrivateCameraData
149149
ACaptureRequest *request;
150150
ACameraCaptureSession *session;
151151
SDL_CameraSpec requested_spec;
152+
int rotation; // degrees to rotate clockwise to get from camera's static orientation to device's native orientation. Apply this plus current phone rotation to get upright image!
152153
};
153154

154155
static bool SetErrorStr(const char *what, const char *errstr, const int rc)
@@ -295,7 +296,7 @@ static bool ANDROIDCAMERA_WaitDevice(SDL_Camera *device)
295296
return true; // this isn't used atm, since we run our own thread via onImageAvailable callbacks.
296297
}
297298

298-
static SDL_CameraFrameResult ANDROIDCAMERA_AcquireFrame(SDL_Camera *device, SDL_Surface *frame, Uint64 *timestampNS)
299+
static SDL_CameraFrameResult ANDROIDCAMERA_AcquireFrame(SDL_Camera *device, SDL_Surface *frame, Uint64 *timestampNS, int *rotation)
299300
{
300301
SDL_CameraFrameResult result = SDL_CAMERA_FRAME_READY;
301302
media_status_t res;
@@ -366,6 +367,21 @@ static SDL_CameraFrameResult ANDROIDCAMERA_AcquireFrame(SDL_Camera *device, SDL_
366367

367368
pAImage_delete(image);
368369

370+
int dev_rotation = 0;
371+
switch (Android_JNI_GetDisplayCurrentOrientation()) {
372+
case SDL_ORIENTATION_PORTRAIT: dev_rotation = 0; break;
373+
case SDL_ORIENTATION_LANDSCAPE: dev_rotation = 90; break;
374+
case SDL_ORIENTATION_PORTRAIT_FLIPPED: dev_rotation = 180; break;
375+
case SDL_ORIENTATION_LANDSCAPE_FLIPPED: dev_rotation = 270; break;
376+
default: SDL_assert(!"Unexpected device rotation!"); dev_rotation = 0; break;
377+
}
378+
379+
if (device->position == SDL_CAMERA_POSITION_BACK_FACING) {
380+
dev_rotation = -dev_rotation; // we want to subtract this value, instead of add, if back-facing.
381+
}
382+
383+
*rotation = dev_rotation + device->hidden->rotation; // current phone orientation, static camera orientation in relation to phone.
384+
369385
return result;
370386
}
371387

@@ -494,10 +510,23 @@ static bool PrepareCamera(SDL_Camera *device)
494510
imglistener.context = device;
495511
imglistener.onImageAvailable = onImageAvailable;
496512

513+
514+
const char *devid = (const char *) device->handle;
515+
516+
device->hidden->rotation = 0;
517+
ACameraMetadata *metadata = NULL;
518+
ACameraMetadata_const_entry orientationentry;
519+
if (pACameraManager_getCameraCharacteristics(cameraMgr, devid, &metadata) == ACAMERA_OK) {
520+
if (pACameraMetadata_getConstEntry(metadata, ACAMERA_SENSOR_ORIENTATION, &orientationentry) == ACAMERA_OK) {
521+
device->hidden->rotation = (int) (*orientationentry.data.i32 % 360);
522+
}
523+
pACameraMetadata_free(metadata);
524+
}
525+
497526
// just in case SDL_OpenCamera is overwriting device->spec as CameraPermissionCallback runs, we work from a different copy.
498527
const SDL_CameraSpec *spec = &device->hidden->requested_spec;
499528

500-
if ((res = pACameraManager_openCamera(cameraMgr, (const char *) device->handle, &dev_callbacks, &device->hidden->device)) != ACAMERA_OK) {
529+
if ((res = pACameraManager_openCamera(cameraMgr, devid, &dev_callbacks, &device->hidden->device)) != ACAMERA_OK) {
501530
return SetCameraError("Failed to open camera", res);
502531
} else if ((res2 = pAImageReader_new(spec->width, spec->height, format_sdl_to_android(spec->format), 10 /* nb buffers */, &device->hidden->reader)) != AMEDIA_OK) {
503532
return SetMediaError("Error AImageReader_new", res2);

src/camera/coremedia/SDL_camera_coremedia.m

Lines changed: 69 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,14 @@
2929
#import <AVFoundation/AVFoundation.h>
3030
#import <CoreMedia/CoreMedia.h>
3131

32+
#if defined(SDL_PLATFORM_IOS) && !defined(SDL_PLATFORM_TVOS)
33+
#define USE_UIKIT_DEVICE_ROTATION
34+
#endif
35+
36+
#ifdef USE_UIKIT_DEVICE_ROTATION
37+
#import <UIKit/UIKit.h>
38+
#endif
39+
3240
/*
3341
* Need to link with:: CoreMedia CoreVideo
3442
*
@@ -77,6 +85,9 @@ @interface SDLPrivateCameraData : NSObject
7785
@property(nonatomic, retain) AVCaptureSession *session;
7886
@property(nonatomic, retain) SDLCaptureVideoDataOutputSampleBufferDelegate *delegate;
7987
@property(nonatomic, assign) CMSampleBufferRef current_sample;
88+
#ifdef USE_UIKIT_DEVICE_ROTATION
89+
@property(nonatomic, assign) UIDeviceOrientation last_device_orientation;
90+
#endif
8091
@end
8192

8293
@implementation SDLPrivateCameraData
@@ -146,7 +157,7 @@ static bool COREMEDIA_WaitDevice(SDL_Camera *device)
146157
return true; // this isn't used atm, since we run our own thread out of Grand Central Dispatch.
147158
}
148159

149-
static SDL_CameraFrameResult COREMEDIA_AcquireFrame(SDL_Camera *device, SDL_Surface *frame, Uint64 *timestampNS)
160+
static SDL_CameraFrameResult COREMEDIA_AcquireFrame(SDL_Camera *device, SDL_Surface *frame, Uint64 *timestampNS, int *rotation)
150161
{
151162
SDL_CameraFrameResult result = SDL_CAMERA_FRAME_READY;
152163
SDLPrivateCameraData *hidden = (__bridge SDLPrivateCameraData *) device->hidden;
@@ -219,6 +230,37 @@ static SDL_CameraFrameResult COREMEDIA_AcquireFrame(SDL_Camera *device, SDL_Surf
219230

220231
CVPixelBufferUnlockBaseAddress(image, 0);
221232

233+
#ifdef USE_UIKIT_DEVICE_ROTATION
234+
UIDeviceOrientation device_orientation = [[UIDevice currentDevice] orientation];
235+
if (!UIDeviceOrientationIsValidInterfaceOrientation(device_orientation)) {
236+
device_orientation = hidden.last_device_orientation; // possible the phone is laying flat or something went wrong, just stay with the last known-good orientation.
237+
} else {
238+
hidden.last_device_orientation = device_orientation; // update the last known-good orientation for later.
239+
}
240+
241+
const UIInterfaceOrientation ui_orientation = [UIApplication sharedApplication].statusBarOrientation;
242+
243+
// there is probably math for this, but this is easy to slap into a table.
244+
// rotation = rotations[uiorientation-1][devorientation-1];
245+
if (device->position == SDL_CAMERA_POSITION_BACK_FACING) {
246+
static const int back_rotations[4][4] = {
247+
{ 90, 90, 90, 90 }, // ui portrait
248+
{ 270, 270, 270, 270 }, // ui portait upside down
249+
{ 0, 0, 0, 0 }, // ui landscape left
250+
{ 180, 180, 180, 180 } // ui landscape right
251+
};
252+
*rotation = back_rotations[ui_orientation - 1][device_orientation - 1];
253+
} else {
254+
static const int front_rotations[4][4] = {
255+
{ 90, 90, 270, 270 }, // ui portrait
256+
{ 270, 270, 90, 90 }, // ui portait upside down
257+
{ 0, 0, 180, 180 }, // ui landscape left
258+
{ 180, 180, 0, 0 } // ui landscape right
259+
};
260+
*rotation = front_rotations[ui_orientation - 1][device_orientation - 1];
261+
}
262+
#endif
263+
222264
return result;
223265
}
224266

@@ -231,6 +273,10 @@ static void COREMEDIA_ReleaseFrame(SDL_Camera *device, SDL_Surface *frame)
231273
static void COREMEDIA_CloseDevice(SDL_Camera *device)
232274
{
233275
if (device && device->hidden) {
276+
#ifdef USE_UIKIT_DEVICE_ROTATION
277+
[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
278+
#endif
279+
234280
SDLPrivateCameraData *hidden = (SDLPrivateCameraData *) CFBridgingRelease(device->hidden);
235281
device->hidden = NULL;
236282

@@ -358,6 +404,28 @@ static bool COREMEDIA_OpenDevice(SDL_Camera *device, const SDL_CameraSpec *spec)
358404
hidden.session = session;
359405
hidden.delegate = delegate;
360406
hidden.current_sample = NULL;
407+
408+
#ifdef USE_UIKIT_DEVICE_ROTATION
409+
// When using a camera, we turn on device orientation tracking. The docs note that this turns on
410+
// the device's accelerometer, so I assume this burns power, so we don't leave this running all
411+
// the time. These calls nest, so we just need to call the matching `end` message when we close.
412+
// You _can_ get an actual events through this mechanism, but we just want to be able to call
413+
// -[UIDevice orientation], which will update with real info while notificatons are enabled.
414+
UIDevice *uidevice = [UIDevice currentDevice];
415+
[uidevice beginGeneratingDeviceOrientationNotifications];
416+
hidden.last_device_orientation = uidevice.orientation;
417+
if (!UIDeviceOrientationIsValidInterfaceOrientation(hidden.last_device_orientation)) {
418+
// accelerometer isn't ready yet or the phone is laying flat or something. Just try to guess from how the UI is oriented at the moment.
419+
switch ([UIApplication sharedApplication].statusBarOrientation) {
420+
case UIInterfaceOrientationPortrait: hidden.last_device_orientation = UIDeviceOrientationPortrait; break;
421+
case UIInterfaceOrientationPortraitUpsideDown: hidden.last_device_orientation = UIDeviceOrientationPortraitUpsideDown; break;
422+
case UIInterfaceOrientationLandscapeLeft: hidden.last_device_orientation = UIDeviceOrientationLandscapeRight; break; // Apple docs say UI and device orientations are reversed in landscape.
423+
case UIInterfaceOrientationLandscapeRight: hidden.last_device_orientation = UIDeviceOrientationLandscapeLeft; break;
424+
default: hidden.last_device_orientation = UIDeviceOrientationPortrait; break; // oh well.
425+
}
426+
}
427+
#endif
428+
361429
device->hidden = (struct SDL_PrivateCameraData *)CFBridgingRetain(hidden);
362430

363431
[session startRunning]; // !!! FIXME: docs say this can block while camera warms up and shouldn't be done on main thread. Maybe push through `queue`?

src/camera/dummy/SDL_camera_dummy.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ static bool DUMMYCAMERA_WaitDevice(SDL_Camera *device)
3838
return SDL_Unsupported();
3939
}
4040

41-
static SDL_CameraFrameResult DUMMYCAMERA_AcquireFrame(SDL_Camera *device, SDL_Surface *frame, Uint64 *timestampNS)
41+
static SDL_CameraFrameResult DUMMYCAMERA_AcquireFrame(SDL_Camera *device, SDL_Surface *frame, Uint64 *timestampNS, int *rotation)
4242
{
4343
SDL_Unsupported();
4444
return SDL_CAMERA_FRAME_ERROR;

src/camera/emscripten/SDL_camera_emscripten.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ static bool EMSCRIPTENCAMERA_WaitDevice(SDL_Camera *device)
3939
return false;
4040
}
4141

42-
static SDL_CameraFrameResult EMSCRIPTENCAMERA_AcquireFrame(SDL_Camera *device, SDL_Surface *frame, Uint64 *timestampNS)
42+
static SDL_CameraFrameResult EMSCRIPTENCAMERA_AcquireFrame(SDL_Camera *device, SDL_Surface *frame, Uint64 *timestampNS, int *rotation)
4343
{
4444
void *rgba = SDL_malloc(device->actual_spec.width * device->actual_spec.height * 4);
4545
if (!rgba) {

src/camera/mediafoundation/SDL_camera_mediafoundation.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -430,7 +430,7 @@ static void SDLCALL CleanupIMFMediaBuffer(void *userdata, void *value)
430430
SDL_free(objs);
431431
}
432432

433-
static SDL_CameraFrameResult MEDIAFOUNDATION_AcquireFrame(SDL_Camera *device, SDL_Surface *frame, Uint64 *timestampNS)
433+
static SDL_CameraFrameResult MEDIAFOUNDATION_AcquireFrame(SDL_Camera *device, SDL_Surface *frame, Uint64 *timestampNS, int *rotation)
434434
{
435435
SDL_assert(device->hidden->current_sample != NULL);
436436

@@ -562,7 +562,7 @@ static SDL_CameraFrameResult MEDIAFOUNDATION_CopyFrame(SDL_Surface *frame, const
562562
return SDL_CAMERA_FRAME_READY;
563563
}
564564

565-
static SDL_CameraFrameResult MEDIAFOUNDATION_AcquireFrame(SDL_Camera *device, SDL_Surface *frame, Uint64 *timestampNS)
565+
static SDL_CameraFrameResult MEDIAFOUNDATION_AcquireFrame(SDL_Camera *device, SDL_Surface *frame, Uint64 *timestampNS, int *rotation)
566566
{
567567
SDL_assert(device->hidden->current_sample != NULL);
568568

src/camera/pipewire/SDL_camera_pipewire.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -577,7 +577,7 @@ static bool PIPEWIRECAMERA_WaitDevice(SDL_Camera *device)
577577
return true;
578578
}
579579

580-
static SDL_CameraFrameResult PIPEWIRECAMERA_AcquireFrame(SDL_Camera *device, SDL_Surface *frame, Uint64 *timestampNS)
580+
static SDL_CameraFrameResult PIPEWIRECAMERA_AcquireFrame(SDL_Camera *device, SDL_Surface *frame, Uint64 *timestampNS, int *rotation)
581581
{
582582
struct pw_buffer *b;
583583

src/camera/v4l2/SDL_camera_v4l2.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ static bool V4L2_WaitDevice(SDL_Camera *device)
125125
return false;
126126
}
127127

128-
static SDL_CameraFrameResult V4L2_AcquireFrame(SDL_Camera *device, SDL_Surface *frame, Uint64 *timestampNS)
128+
static SDL_CameraFrameResult V4L2_AcquireFrame(SDL_Camera *device, SDL_Surface *frame, Uint64 *timestampNS, int *rotation)
129129
{
130130
const int fd = device->hidden->fd;
131131
const io_method io = device->hidden->io;

0 commit comments

Comments
 (0)