Previous topic

Widget Classes

This Page

Misc. Classes

class libavg.avg.Bitmap

Bases: Boost.Python.instance

Class representing a rectangular set of pixels in CPU memory. Bitmaps can be obtained from any RasterNode or loaded from disk. For nodes of type ImageNode, the current bitmap can be set as well. In general, huge Bitmaps (e.g. width>65536) are supported as long as they fit into memory.

The layout of the pixels in the bitmap is described by its pixel format. The names for pixel format constants are confusing. They try to follow logic, but it’s a bit elusive: In many cases, each component is described by a single letter indicating the component’s role in the pixel and a number indicating the number of bits used for this component. Components are named in the order they appear in memory. In the cases where the name doesn’t follow this logic, reasons for the name are usually historical or by convention. You can receive a complete list of all supported pixel formats by calling avg.getSupportedPixelFormats(). The pixel formats are:

  • B5G6R5: 16 bits per pixel blue, green, red components.
  • B8G8R8: 24 bits per pixel blue, green, red components.
  • B8G8R8A8: 32 bits per pixel: blue, green, red and an alpha (opacity) component.
  • B8G8R8X8: 32 bits per pixel, with the last byte unused.
  • A8B8G8R8
  • X8B8G8R8
  • R5G6B5
  • R8G8B8
  • R8G8B8A8
  • R8G8B8X8
  • A8R8G8B8
  • X8R8G8B8
  • I8: 8 bits of greyscale intensity.
  • I16: 16 bits of greyscale intensity.
  • A8: 8 bits of transparency information.
  • YCbCr411: Interleaved YCbCr: Y Y Cb Y Y Cr. Effectively 12 bits per pixel. Output format of some cameras.
  • YCbCr422: Interleaved YCbCr: Cb Y Cr Y. Effectively 16 bits per pixel. Output format of some cameras.
  • YUYV422: Like YCbCr422, but grey values come first, so the order is Y Cb Y Cr.
  • YCbCr420p: Not a valid pixel format for a single bitmap, but still a description of planar bitmap coding. Signifies separate bitmaps for Y, Cb and Cr components, with Cb and Cr half as big in both x and y dimensions. This is mpeg YCbCr, where the color components have values from 16...235. Used by many video formats, including mpeg.
  • YCbCrJ420p: Same as YCbCr420p, but this is the jpeg version with component values in the range 0...255. Used in video as well, for instance in motion jpeg encoding.
  • YCbCrA420p: YCbCr420p with an additional alpha (transparency) bitmap at full resolution. Used in flash video with transparency.
  • BAYER8: Bayer pattern. This is raw camera sensor data with an unspecified pixel order. The other BAYER_XXX constants specify differing camera sensor arrangements.
  • R32G32B32A32F: 32 bits per channel float RGBA.
  • I32F: 32 bits per channel greyscale intensity.
__init__(size, pixelFormat, name)

Creates an uninitialized bitmap of the given size and pixel format. name is a name to be used in debug output.


Creates a copy of an already existing bitmap.

__init__(bitmap, tlPos, brPos)

Returns a rectangle inside an existing bitmap as a new bitmap. Note that the pixels are not copied and write operations will therefore effect the original bitmap as well.


Loads an image file from disk and returns it as bitmap object.

blt(srcBmp, pos)

Copies the pixels of srcBmp into the current bitmap at pos.

getAvg() → float

Returns the average of all bitmap pixels.

getChannelAvg(channel) → float

Returns the average of one of the bitmap color channels (red, green or blue). Used for automatic tests.


Returns the bitmap’s pixel format.

getName() → string
getPixel(pos) -> (r, g, b, a)

Returns one image pixel as a color tuple. This should only be used for single pixels, as it is very slow.

getPixels() → string

Returns the raw pixel data in the bitmap as a python string. This method can be used to interface to the python imaging library PIL (

getResized(newSize) → Bitmap

Returns a new bitmap that is a resized version of the original.

getSize() → Point2D

Returns the size of the image in pixels.

getStdDev() → float

Returns the standard deviation of all bitmap pixels.


Writes the image to a file. File format is determined using the extension. Supported file types are those supported by gdk-pixbuf. This includes at least png, jpeg, gif, tiff and xpixmaps.


Changes the raw pixel data in the bitmap. Doesn’t change dimensions or pixel format. Can be used to interface to the python imaging library PIL (

Parameters:pixels (string) – Image data.
subtract(otherbitmap) → bmp

Subtracts two bitmaps and returns the result. Used mainly to compare test images with the intended results (along with getAvg() and getStdDev()).

class libavg.avg.BitmapManager

Bases: Boost.Python.instance

(EXPERIMENTAL) Singleton class that allow an asynchronous load of bitmaps. The instance is accessed by get().

loadBitmap(fileName, callback, pixelformat=NO_PIXELFORMAT)

Asynchronously loads a file into a Bitmap. The provided callback is invoked with a Bitmap instance as argument in case of a successful load or with a RuntimeError exception instance in case of failure. The optional parameter pixelformat can be used to convert the bitmap to a specific format asynchronously as well.

classmethod get() → BitmapManager

This method gives access to the BitmapManager instance.


Sets the number of threads used to load bitmaps. The default is a single thread. This should generally be less than the number of logical cores available.

class libavg.avg.CubicSpline(controlpoints)

Bases: Boost.Python.instance

Class that generates a smooth curve between control points using cubic spline-based interpolation. The utility can be used to edit a spline and generate control points. For an introduction on spline interpolation, see


A list of 2D coordinates. The x coordinates must be in increasing order.

interpolate(x) → y

Takes an x coordinate and delivers a corresponding y coordinate.

class libavg.avg.FontStyle(font="sans", variant="", color="FFFFFF", fontsize=15, indent=0, linespacing=-1, alignment="left", wrapmode="word", justify=False, letterspacing=0, aagamma=1, hint=True)

Bases: libavg.avg.ExportedObject

A FontStyle object encapsulates all configurable font attributes in a WordsNode. It provides a way to set all relevant attributes (font, fontsize, etc.) in one line of code. The attributes correspond to the WordsNode attributes; refer to the WordsNode reference for descriptions.

class libavg.avg.Logger

Bases: Boost.Python.instance

An python interface to libavg’s logger. It can be accessed as follows:

import libavg


log(message, category, severity)

Logs a message if category is active or severity is at least ERROR.

  • category – One of the categories listed or a custom category. Defaults to Logger.Category.APP.
  • severity – One of the severities listed. Defaults to Logger.Severity.INFO.
  • message – The log message string.
critical(msg, category)

Shortcut to log() with severity= Logger.Severity.CRIT.

error(msg, category)

Shortcut to log() with severity= Logger.Severity.ERR.

warning(msg, category)

Shortcut to log() with severity= Logger.Severity.WARN.

info(msg, category)

Shortcut to log() with severity= Logger.Severity.INFO.

debug(msg, category)

Shortcut to log() with severity= Logger.Severity.DBG.



Add a python logger object to libavg’s logging handlers. The python logger gets the key category as an “extra” kwarg, useful for formatting the output.


Remove a previously added logger. It will not receive any messages dispatched by the logger annymore. It’s safe to call the function even if the logger is not present.


Remove libavg console printing sink.

Setting AVG_LOG_OMIT_STDERR as EnvironmentVar has the same effect.

configureCategory(category, severity)

Assign a severity to a given category. category is either a custom string or a Logger.Category severity has to be one of Logger.Severity, or it will default to Logger.Severity.None


Returns a dict with category as key and severity as value

The Logger can also be configured using AVG_LOG_CATEGORIES with the format:


Thus it is possible to set a severity level for every category. If no severity is given, the default severity is used. (refer to: setDefaultSeverity()) If the category does not exist, it will be created.


Default categories are NONE, APP and DEPREC. They are set to the defaultSeverity.


Reserved for application-level messages issued by python code.
Outputs configuration data.
Deprecation Messages that warn of functionality that will be removed from libavg in the future.
Outputs basic event data.
Outputs open/close information whenever a media file is accessed.
Outputs everything that has not been categorized.
Outputs performance statistics on player termination.
Outputs performance statistics for video decoding.
Messages generated by loading plugins.
General libavg playback messages.
Shader compiler messages.


CRIT Critical

ERR Error

WARN Warning


DBG Debug


class libavg.avg.Point2D([x, y=(0, 0)])

Bases: Boost.Python.instance

A point in 2D space. Supports most arithmetic operations on vectors. The operators +, -, == and != are defined for two Point2D parameters. Unary - (negation) is defined as well. Point2D objects can also be multiplied and divided by a scalar.

Point2D implicitly converts from and to 2-element float tuples and lists, so in most cases you can use one of these types whenever a point is needed.

getAngle() → float

Returns the direction of the vector as an angle between pi and -pi, with 0 being the positive x axis. Angles run clockwise.

getNorm() → float

Returns the euclidian norm of the point, that is sqrt(x*x+y*y).

getNormalized() → Point2D

Returns a normalized version of the point with the same angle but a norm of one. Throws an exception if called on Point2D(0,0).

getRotated(angle) → Point2D

Return the position of point rotated around the origin.

getRotated(angle, pivot) → Point2D

Return the position of point rotated around pivot.

classmethod fromPolar(angle, radius) → Point2D

Converts polar to cartesian coordinates. angle is in radians with 0 being the positive x axis. Angle is clockwise (assuming that y points downward).

class libavg.avg.SVG(filename[, unescapeIllustratorIDs=False])

Bases: Boost.Python.instance

SVG objects load and parse an svg file and render images from it. svg (Scalable Vector Graphics, see files are xml-based and contain two-dimensional vector graphics. They can be created with editors such as Adobe Illustrator and Inkscape. SVG objects can render elements in the file to bitmaps and create image nodes from elements in the file. Since the files contain vector graphics, the elements can be scaled to any size when rendering without loss of resolution.

  • filename – The name of the file to load.
  • unescapeIllustratorIDs – If this is True, the file is assumed to be generated by Adobe Illustrator. Illustrator mangles element names to create IDs in the svg file. Setting this parameter to True allows these element names to be passed as IDs.
renderElement(elementID[, size | scale=1]) → Bitmap

Renders an element to a Bitmap. Either scale or size may be given. size is the size of the bitmap. scale is a factor to scale the native bitmap size with.

createImageNode(elementID, nodeAttrs[, size | scale=1]) → Node

Convenience method that calls renderElement() to render a bitmap and then creates an image node that displays that bitmap. nodeAttrs is a dictionary containing constructor parameters for the node.

getElementPos(elementID) → Point2D

Returns the position of an element.

getElementSize(elementID) → Point2D

Returns the original size of an element.

class libavg.avg.TestHelper

Bases: Boost.Python.instance

Miscellaneous routines used by tests. Not intended for normal application usage.

class libavg.avg.VersionInfo

Bases: Boost.Python.instance

Exposes version data, including the specs of the builder.


Full string containing a compact form of branch and revision number (if the build doesn’t come from an exported tree)


String representation in the form major.minor.micro


Integer component of the release version (major)


Integer component of the release version (minor)


Integer component of the release version (micro)


Revision number, if applicable, or 0


Full URL path that represents the branch root, if applicable, or empty string


String representation in the form of user@hostname machinespecs


ISO timestamp representation of the build

class libavg.avg.VideoWriter(canvas, filename[, framerate=30, qmin=3, qmax=5, synctoplayback=True])

Bases: Boost.Python.instance

Class that writes the contents of a canvas to disk as a video file. The videos are written as motion jpeg-encoded mov files. Writing commences immediately upon object construction and continues until stop() is called. pause() and play() can be used to pause and resume writing.

The VideoWriter is built for high performance: Opening, writing and closing the video file is asynchronous to normal playback. Writing full HD videos of offscreen canvasses to disk should cost virtually no time on the main thread of execution for an Intel Core-class processor with a graphics card that supports shaders.

Parameters:canvas – A libavg canvas used as source of the video.

The name of the file to write to. Read-only.


The speed of the encoded video in frames per second. This is used for two purposes. First, it determines the nominal playback speed of the video that is encoded in the file. Second, if synctoplayback is False, the VideoWriter will also use the framerate value as the actual number of frames per second to write. Read-only.


qmin and qmax specify the minimum and maximum encoding quality to use. qmin = qmax = 1 give maximum quality at maximum file size. qmin=3 and qmax=5 (the default) give a good quality and a smaller file. Read-only.


If synctoplayback is True (the default), each frame played back in the canvas will be written to disk. This makes a lot of sense in combination with Canvas.registerCameraNode(). If not, framerate is used to determine which frames to write to disk. For instance, if synctoplayback is False, framerate is 25 and the player is running at 60 fps, one movie frame will be written for each 2.5 frames of playback. The actual, not the nominal playback speed is used in this case. Read-only.


Temporarily stops recording.


Resumes recording after a call to pause(). play() doesn’t need to be called after construction of the VideoWriter - writing commences immediately.


Ends the recording and writes the rest of the file to disk. Note that this is asynchronous to normal playback. If you need to immediately re-open the video file (e.g. for playback in a video node), destroy the python object first. This waits for sync.

libavg.avg.getMemoryUsage() → int

Returns the amount of memory used by the application in bytes. More precisely, this function returns the resident set size of the process in bytes. This does not include shared libraries or memory paged out to disk.

libavg.avg.pointInPolygon(point, poly) → bool

Checks if a point is inside a polygon.

  • point (Point2D) – Point to check.
  • poly – List of points which constitute a polygon to check against.

True if point is inside, False otherwise.

libavg.avg.validateXml(xmlString, schemaString, xmlName, schemaName)

Validates an xml string using a schema. Throws an exception if the xml doesn’t conform to the schema.

class libavg.statemachine.StateMachine(name, startState)

Bases: object

A generic state machine, useful for user interface and other states. Consists of a set of states (represented by strings) and possible transitions between the states. The StateMachine can be configured to invoke callbacks at specific transitions and when entering or leaving a state. All callbacks are optional. State changes can be logged for debugging purposes.

State machines are initialized by calling addState() for each possible state after constructing it.

  • name (String) – A name for the state machine to be used in debugging output.
  • startState (String) –

The current state the StateMachine is in. States are strings.

addState(state, transitions[, enterFunc=None, leaveFunc=None])

Adds a state to the StateMachine. Must be called before the first changeState.

  • state (String) – The name of the state to add.
  • transitions – This parameter can be either a list of destination states or a dict of destinationState: callable pairs. The callables are invoked whenever the corresponding state change happens. If transitions() is a list, no state change callbacks are registered.
  • enterFunc – A callable to invoke whenever the state is entered.
  • leaveFunc – A callable to invoke whenever the state is left.

Changes the state. This includes calling the leave callback for the current state, actually changing the state, calling the transition callback and calling the enter callback for the new state.

Raises a RuntimeError if newState is not a valid state or if there is no transition defined from the current state to newState.


Prints all states and transitions to the console.

makeDiagram(imageFName[, showMethods=False])

Dumps a graph of the state machine to an image file using dot. graphviz must be installed and in the path for this to work. Very useful for debugging. If showMethods is true, names of enter, leave and transition methods are included in the diagram.


If trace is set to True, all state changes are dumped to the console.

class libavg.persist.Persist(storeFile, initialData[, validator=lambda v: True, autoCommit=False])

Bases: object

A general purpose persistent object. Its state is defined in the data attribute and pickled from/to a store file.

  • storeFile (string) – Full path of the store file that is used to store and retrieve a serialized version of the data.
  • initialData – A pickle-able object that is assigned to the data attribute when no file store exists or when the store file is corrupted.
  • validator (callable) – An optional callable that receives the object state as soon it’s de-pickled from the store file. If the validator call doesn’t return True, the object state is restored to the provided initialData.
  • autoCommit (bool) – If True, the commit method is registered as an atexit function.

State of the persistent object.


Returns the full path of the store file.


Dumps the contents of the data attribute to the store file.

class libavg.persist.UserPersistentData(appName, fileName, initialData[, validator=lambda v: True, autoCommit=False])

Bases: libavg.persist.Persist

A Persist subclass that sets up an OS-independent path for the store file. Under posix-compliant OSes is $HOME/.avg/<appName>/<fileName>.pkl Under Windows is %APPDATA%Avg<appName>/<fileName>.pkl

  • appName (string) – Name of the application. This string is used to compose the full path to the file store and it creates a namespace (directory) for multiple files for the same application.
  • fileName (string) – Name of the file store file. .pkl will be added as extension.