C++ API Reference

The native interface and the SDK’s canonical, most complete surface. All public types live in the affdex::vision namespace (pipeline types in affdex::vision::event; shared basics in affdex).

HeaderProvides
<Frame.h>Frame, ColorFormat, Rotation
<Detector.h>Detector base class, BaselineMode
<FrameDetector.h> / <SyncFrameDetector.h>the two concrete detectors
<Face.h>Face and the metric enums
<Feature.h>Feature enum + string conversions
<FaceListener.h> / <ProcessStatusListener.h> / <ImageListener.h>callback interfaces
<Sensors.h> / <FaceConnector.h> / <MetricsConnector.h> / <Events.h>the sensor/connector pipeline
<Core.h> / <Exception.h> / <BoundingBox.h>core types, Exception, Point / BoundingBox

Core types

TypeDefinitionNotes
affdex::Timestampint64_ta point in time, in milliseconds
affdex::Durationint64_telapsed time in milliseconds
affdex::vision::Idintgeneric identifier type
affdex::vision::FaceIdIdper-face tracking identifier, stable while a face remains tracked
affdex::Byteunsigned charpixel data element
affdex::Str / affdex::Pathstd::wstring on Windows, else std::stringuse the STR("...") macro for portable literals

Point

A 2-D coordinate in image pixels.

struct Point { float x; float y; };

Constructors Point() and Point(float x, float y); also operator== and bool isZero().

BoundingBox

An axis-aligned rectangle defined by top-left and bottom-right points. The constructor throws affdex::Exception if br is above or left of tl. Note that Face::getBoundingBox() returns a std::vector<Point> (the two corners), not a BoundingBox.

MethodDescription
BoundingBox(Point tl, Point br)constructor
Point getTopLeft() const / Point getBottomRight() constcorner accessors
float area() constrectangle area in pxΒ²
bool isEmpty() consttrue if width or height is zero
bool contains(const BoundingBox&) constfull containment test
bool overlaps(const BoundingBox&) constintersection test
float overlappingArea(const BoundingBox&) constarea of the intersection in pxΒ²

affdex::Exception

Derived from std::runtime_error; every SDK error throws this type. Errors raised on background processing threads are delivered through a ProcessStatusListener instead of being thrown.

Frame

Wraps one image and its timestamp. Frames are cheap value objects β€” construct one per captured image and pass it to process(). The pixel buffer is consumed and converted during construction, so it only needs to remain valid for the constructor call.

Frame(Timestamp timestamp_ms, int width, int height, void* pixels, ColorFormat color_format, Rotation rotation = Rotation::UPRIGHT)

Preferred constructor. width/height must be > 0; timestamp_ms identifies the frame and must strictly increase across successive process() calls. Legacy timestamp-last constructors are deprecated.

MethodDescription
Timestamp getTimestamp() consttimestamp in ms
int getWidth() const / int getHeight() constdimensions in px
ColorFormat getColorFormat() conststored format β€” may differ from the constructor argument after internal conversion
std::shared_ptr<affdex::Byte> getBGRByteArray() constpixel data as BGR bytes
int getBGRByteArrayLength() constlength of that byte array
static std::string colorFormatToString(ColorFormat)
static std::string rotationToString(Rotation)
debug string helpers

Frame::ColorFormat

ValueLayout
RGB24-bit, R-G-B channel order
BGR24-bit, B-G-R channel order (OpenCV default)
RGBA32-bit, R-G-B-A channel order
BGRA32-bit, B-G-R-A channel order
YUV_NV2112-bit YUV, NV21 encoding (Android camera)
YUV_I42012-bit YUV, I420 encoding
YUV_YUY216-bit YUV, YUY2 encoding
GRAY8-bit grayscale (e.g. near-IR sensors)

Frame::Rotation

Declares how the image is rotated relative to an upright face, so you never rotate pixel buffers yourself: UPRIGHT, CW_90, CW_180, CW_270 (clockwise).

Detectors

Detector (base class)

Common behavior shared by both concrete detectors; never instantiated directly.

Lifecycle

MethodDescription
void start(const std::string& license = "")validates the license and initializes processing. An empty string falls back to the AFFECTIVA_LICENSE_KEY environment variable; throws affdex::Exception if no valid license is found.
void stop()stops processing and deallocates resources
void reset()re-initializes for a new session (new video/camera) without stop/start; frame timestamps may restart at 0 afterwards
bool isRunning()true after start() and before stop()

Feature control

Features select which metric families are computed. Face detection/tracking metrics (bounding box, face points, measurements, qualities, confidence) are always delivered for tracked faces; expressions and emotions are computed only when enabled. Enabling fewer features reduces CPU load.

MethodDescription
void enable(Feature) / void enable(const std::set<Feature>&)adds to the enabled set
void disable(Feature) / void disable(const std::set<Feature>&)removes from the enabled set
bool isEnabled(Feature) consttrue if the feature is enabled
bool isEnabled(const std::set<Feature>&) consttrue only if all given features are enabled
std::set<Feature> getEnabledFeatures() constthe currently enabled set

Listener registration

MethodDescription
void setFaceListener(FaceListener*)register the results callback; the SDK does not take ownership β€” the listener must outlive its registration
void setProcessStatusListener(ProcessStatusListener*)register the background-error callback
void setImageListener(ImageListener*) Deprecateduse setFaceListener instead

Connector pipeline

MethodDescription
void connect(event::FaceConnector&)
void connect(std::shared_ptr<event::FaceConnector>)
attaches a connector; automatically enables the features it declares. With the reference overload, the caller must keep the connector alive while connected.
template<typename T, typename... Args> void connectChain(T& first, Args&&... args)connects a series of source/sink stages in one call (overloads for references, shared_ptr, and unique_ptr)
void disconnect(...)detaches a connector (same overloads as connect)
void disconnectAllMetricsConnectors()detaches everything

Detector::BaselineMode

  • OFF β€” metrics are calculated statically (default).
  • ON β€” metrics are calculated against a rolling-average “baseline”, adapting to the individual’s neutral expression over time.

Selected via the detector constructors that take a BaselineMode first argument.

FrameDetector β€” asynchronous

Queues pushed frames and processes them on a background thread with real-time semantics: frames that arrive closer together than 1 / processFrameRate are discarded so processing never falls behind. Callbacks are invoked on the background thread β€” synchronize shared state.

FrameDetector(float processFrameRate = DEFAULT_PROCESSING_FRAMERATE, unsigned int maxNumFaces = DEFAULT_MAX_NUM_FACES, unsigned int maxThreads = DEFAULT_MAX_THREAD_POOL_SIZE)

Also available with a leading Detector::BaselineMode parameter.

void process(const Frame& frame) const

Submits a frame and returns immediately. Timestamps of successive frames must have increasing values, otherwise it throws. Frames may be dropped to honor processFrameRate.

SyncFrameDetector β€” synchronous

Processes every pushed frame (never drops) and invokes callbacks on the thread that called process(), which blocks until the frame’s callbacks complete. Best for offline video analysis and deterministic tests.

SyncFrameDetector(unsigned int maxNumFaces = DEFAULT_MAX_NUM_FACES, unsigned int maxThreads = DEFAULT_MAX_THREAD_POOL_SIZE)

Also available with a leading Detector::BaselineMode parameter.

Face

One tracked face in a processed frame, delivered through your listener as std::map<FaceId, Face>. All getters return copies; the object is safe to store.

MethodReturns
FaceId getId() consttracking identifier, stable while the face stays in view
float getConfidence() constconfidence in the presence of the face, 0–100
std::map<Expression, float> getExpressions() constone value per enabled expression
std::map<Emotion, float> getEmotions() constone value per enabled emotion
std::map<Measurement, float> getMeasurements() consthead pose and measurements
std::map<Quality, float> getQualities() constimage quality metrics
std::vector<Point> getBoundingBox() consttwo points: top-left, then bottom-right
std::map<FacePoint, Point> getFacePoints() constlandmark positions in px

Listeners

FaceListener

The primary callback interface. Subclass it, override all three methods, and register with setFaceListener() before start().

CallbackCalled when
void onFaceFound(Timestamp timestamp, FaceId faceId)the tracker starts tracking a new face
void onFaceLost(Timestamp timestamp, FaceId faceId)a tracked face is no longer found
void onFaceResults(std::map<FaceId, Face> faces, const Frame& frame)a frame has been processed; delivers all tracked faces with their metrics

ProcessStatusListener

void onProcessingException(affdex::Exception& ex)

Delivers exceptions raised on background processing threads, where they cannot be thrown into your code. Always register one when using FrameDetector.

ImageListener Deprecated

Superseded by FaceListener. Callbacks: onImageResults(std::map<FaceId, Face>, Frame) and onImageCapture(Frame) (fires for every input frame, including frames the asynchronous detector chose not to process).

Sensors & connectors

A composable way to consume metrics: instead of reading whole Face objects in a listener, connect small “sensor” objects to a detector, each of which re-emits one metric (or one metric family) to downstream sinks β€” including plain lambdas. Connecting a sensor automatically enables the features it needs.

example β€” stream just the smile value

#include <Sensors.h>

using namespace affdex::vision;

event::ExpressionSensor smileSensor(Expression::SMILE);
detector.connect(smileSensor);                    // auto-enables Feature::EXPRESSIONS

smileSensor.connect(
    [](const std::map<Id, float>& valuesByFace, affdex::Timestamp ts)
    {
      for (const auto& [faceId, smile] : valuesByFace)
        std::cout << ts << " ms  face " << faceId << "  smile=" << smile << "n";
    });

Available sensors

SensorConstructor argumentEmits (per face)Auto-enables
event::AllExpressionsSensorβ€”std::map<Expression, float>EXPRESSIONS
event::ExpressionSensorExpressionfloatEXPRESSIONS
event::AllEmotionsSensorβ€”std::map<Emotion, float>EMOTIONS
event::EmotionSensorEmotionfloatEMOTIONS
event::AllMeasurementsSensorβ€”std::map<Measurement, float>β€”
event::MeasurementSensorMeasurementfloatβ€”
event::AllFacePointsSensorβ€”std::map<FacePoint, Point>β€”
event::FacePointSensorFacePointPointβ€”
event::QualitySensorQualityfloatβ€”
event::ConfidenceSensorβ€”floatβ€”

Underlying interfaces

  • event::MetricsConnector<T> β€” base interface for anything a detector can feed: override void onResults(const std::map<Id, T>& metrics, Timestamp timestamp_ms); declare required features via the constructor so the detector enables them on connect().
  • event::FaceConnector β€” MetricsConnector<Face>; the type Detector::connect() accepts.
  • affdex::event::Source<O> / Sink<I> β€” the generic dataflow primitives behind sensors. Source::connect() accepts a Sink, a shared_ptr<Sink>, or a lambda of type std::function<void(const std::map<Id, O>&, Timestamp)>.

Enumerations

The tables below give concise definitions. For a full explanation of each metric β€” the facial actions behind it, value semantics, and interpretation guidance β€” see the Metrics guide.

Feature

Metric families that can be enabled per detector. Helpers in <Feature.h>: featureToString(), stringToFeature(), and the set ALL_FEATURES.

ValueEnables
Feature::FACESface detection/tracking metrics
Feature::EXPRESSIONSthe Expression family
Feature::EMOTIONSthe Emotion family

Expression

Facial-action metrics. Continuous metrics range 0 (absent) to 100 (fully present); event metrics report 0 or 100. The vector ALL_EXPRESSIONS contains every value.

ValueDescriptionRange
SMILEupward pull of the lip corners0–100
INNER_BROW_RAISEraising of the inner brow corners0–100
BROW_RAISEraising of both brows0–100
BROW_FURROWlowering/drawing together of the brows0–100
NOSE_WRINKLEwrinkling of the nose0–100
UPPER_LIP_RAISEraising of the upper lip0–100
LIP_CORNER_DEPRESSORdownward pull of the lip corners0–100
CHIN_RAISEupward push of the chin boss0–100
LIP_PUCKERpuckering of the lips0–100
LIP_PRESSpressing the lips together0–100
LIP_SUCKpulling the lips inward0–100
MOUTH_OPENparting of the lips0–100
SMIRKasymmetric lip corner pull0–100
EYE_CLOSUREboth eyelids closed0–100
SPEAKINGthe person is speaking0–100
ATTENTIONvisual attention toward the camera (head orientation)0–100
EYE_WIDENwidening of the eyes0–100
CHEEK_RAISEraising of the cheeks0–100
LID_TIGHTENtightening of the eyelids0–100
DIMPLERtightening of the lip corners (dimpling)0–100
LIP_STRETCHhorizontal stretching of the lips0–100
JAW_DROPlowering of the jaw0–100
BLINKa blink occurred0 / 100
BLINK_RATEblinks per minute; NaN during the first 10Β s after a face is detectedblinks/min
YAWNa yawn occurred0 / 100
PAINcontinuous estimate that the person is expressing pain; 50 is the model’s decision threshold, so values above 50 mean pain is more likely present than not0–100

Emotion

Emotion estimates, 0–100 except the valence metrics (βˆ’100 to +100). The vector ALL_EMOTIONS contains every value.

ValueDescriptionRange
JOYdegree of expressed joy0–100
FEARdegree of expressed fear0–100
DISGUSTdegree of expressed disgust0–100
SADNESSdegree of expressed sadness0–100
ANGERdegree of expressed anger0–100
SURPRISEdegree of expressed surprise0–100
CONTEMPTdegree of expressed contempt0–100
NEUTRALdegree to which the face shows no emotion0–100
SENTIMENTALITYdegree of expressed sentimentality0–100
CONFUSIONdegree of expressed confusion0–100
VALENCEoverall positivity (+) or negativity (βˆ’) of the expressionβˆ’100–100
ENGAGEMENToverall facial expressiveness0–100
CONVERSATIONAL_VALENCEvalence variant tuned for conversational settingsβˆ’100–100
CONVERSATIONAL_ENGAGEMENTengagement variant tuned for conversational settings0–100
ADAPTIVE_VALENCEvalence variant that adapts to the individual’s baselineβˆ’100–100
ADAPTIVE_ENGAGEMENTengagement variant that adapts to the individual’s baseline0–100

Measurement

Head-pose angles are in degrees, relative to a reference position of the face looking straight at the camera (0/0/0). The vector ALL_MEASUREMENTS contains every value.

ValueDescriptionUnit
PITCHpositive = head tilted up, negative = tilted downdegrees
YAWpositive = head turned to the person’s right, negative = to their leftdegrees
ROLLpositive = head tilted to the person’s left, negative = to their rightdegrees
INTEROCULAR_DISTANCEdistance between the two outer eye corner landmarkspixels

FacePoint

Landmark identifiers for getFacePoints(); each maps to a Point in image pixels: OUTER_RIGHT_EYE, OUTER_LEFT_EYE, NOSE_TIP, CHIN_TIP. The vector ALL_FACE_POINTS contains every value.

Quality

Image-quality metrics for getQualities(): BRIGHTNESS (0–100) β€” useful for detecting under- or over-exposed capture conditions. The vector ALL_QUALITIES contains every value.

Constants & defaults

ConstantValueMeaning
Detector::DEFAULT_PROCESSING_FRAMERATE30default target processing rate (fps)
Detector::DEFAULT_MAX_NUM_FACES1default maximum tracked faces
Detector::DEFAULT_MAX_THREAD_POOL_SIZE00 = “use number of CPU cores βˆ’ 1” analysis threads
ALL_EXPRESSIONS, ALL_EMOTIONS, ALL_MEASUREMENTS, ALL_FACE_POINTS, ALL_QUALITIES, ALL_FEATURESβ€”collections of every value of each enum

Deprecated APIs

These remain functional in 5.4 but will be removed in a future release; new code should not use them.

DeprecatedUse instead
ImageListener and Detector::setImageListener()FaceListener / setFaceListener()
Frame(width, height, pixels, color_format[, rotation], timestamp_ms) β€” timestamp-last constructorsthe timestamp-first constructor: Frame(timestamp_ms, width, height, pixels, color_format[, rotation])