Previous topic

User Interface 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.

The layout of the pixels in the bitmap is described by it’s 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 it’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 historical or by convention or something, and anyway, most pixel formats are only used internally and users usually won’t come into contact with them. 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.
  • BAYER8_RGGB
  • BAYER8_GBRG
  • BAYER8_GRBG
  • BAYER8_BGGR
  • 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.

__init__(bitmap)

Creates a copy of an already existing bitmap.

__init__(fileName)

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

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.

getFormat()

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 (http://www.pythonware.com/products/pil/).

getSize() → Point2D

Returns the size of the image in pixels.

getStdDev() → float

Returns the standard deviation of all bitmap pixels.

save(filename)

Writes the image to a file. File format is determined using the extension. Any file format supported by ImageMagick (http://www.imagemagick.org/) can be used.

setPixels(pixels)

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 (http://www.pythonware.com/products/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)

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.

classmethod get() → BitmapManager

This method gives access to the BitmapManager instance.

class libavg.avg.ConradRelais(AVGPlayer, port)

Bases: Boost.Python.instance

Interface to one or more conrad relais cards connected to a serial port. Per card, up to eight 220V devices can be connected.

Deprecated since version 1.5.

Parameters:port – The port the device is connected to. The actual device file opened is /dev/ttyS<port>.
get(card, index) → value

Returns the state of one of the relais.

Parameters:
  • card – Zero-based index of the card to address.
  • index – Zero-based index of the relais on the card.
getNumCards() → int

Returns the number of cards connected to the serial port.

set(card, index, value)

Sets or resets one of the relais.

Parameters:
  • card – Zero-based index of the card to address.
  • index – Zero-based index of the relais on the card.
  • value – Whether to set (True) or reset (False) the relais.
class libavg.avg.Logger

Bases: Boost.Python.instance

Interface to the logger used by the avg player. Enables the setting of different logging categories. Categories can be set either by calling Logger.setCategories or by setting the AVG_LOG_CATEGORIES environment variable. When set through the environment, log categories are separated by colons. In bash syntax:

export AVG_LOG_CATEGORIES=ERROR:WARNING:CONFIG:PROFILE

Log categories are:

NONE
No logging except for errors.
BLTS
Display subsystem logging. Useful for timing/performance measurements.
PROFILE
Outputs performance statistics on player termination.
PROFILE_LATEFRAMES
Outputs performance statistics whenever a frame is displayed late.
PROFILE_VIDEO
Outputs performance statistics for video decoding.
EVENTS
Outputs basic event data.
EVENTS2
Outputs all event data available.
CONFIG
Outputs configuration data.
WARNING
Outputs warning messages.
ERROR
Outputs error messages. Can’t be turned off.
MEMORY
Outputs open/close information whenever a media file is accessed.
APP
Reserved for application-level messages issued by python code.
PLUGIN
Messages generated by loading plugins.
PLAYER
General libavg playback messages.

Default categories are ERROR, WARNING and APP.

Log output is sent to the console (stderr). Each log entry contains the time the message was written, the category of the entry and the message itself.

popCategories()

Pops the current set of categories from the internal stack, restoring the state when the corresponding push was called.

pushCategories()

Pushes the current set of categories on an internal stack. Useful for saving and restoring the logging state so it can be changed for a short amount of time.

setCategories(categories)

Sets the types of messages that should be logged. categories is an or’ed sequence of categories.

trace(category, message)

Logs message to the log if category is active.

Parameters:
  • category – One of the categories listed above. Should in be APP for messages logged from python.
  • message – The log message string.
classmethod get()

This method gives access to the logger. There is only one instance.

class libavg.avg.ParPort(devicename)

Bases: Boost.Python.instance

Used for low-level control of the parallel port’s data, status and control lines. Linux only. The parallel port device is opened on construction.

Deprecated since version 1.5.

Parameters:devicename – Device filename to use. If devicename is an empty string, /dev/parport0 is used as device name.
clearDataLines(lines)

Clears data lines.

Parameters:lines – The lines to clear. Constants to used for these lines are PARPORTDATA0 - PARPORTDATA7. Several of these constants can be or’ed together to set several lines. The lines not mentioned in the parameter are left unchanged.
Returns:True if the lines were cleared, False otherwise.
getStatusLine(line)

Returns the value of one of the parallel port status lines.

Parameters:line – Which status line to query. Possible values for line are STATUS_ERROR, STATUS_SELECT, STATUS_PAPEROUT, STATUS_ACK and STATUS_BUSY.
Returns:True if the line is set.
isAvailable()

Returns True if the parallel port has been opened successfully, False otherwise.

setAllDataLines(lines)

Changes the value of all data lines.

Parameters:lines – The lines to set. Constants to used for these lines are PARPORTDATA0 - PARPORTDATA7. Several of these constants can be or’ed together to set several lines. The lines not mentioned in the parameter are cleared.
Returns:True if the lines were set, False otherwise.
setControlLine(line, value) → bool

Sets or clears one of the control lines.

Parameters:
  • line – Which control line to modify. Possible values for line are CONTROL_STROBE, CONTROL_AUTOFD, CONTROL_INITu and CONTROL_SELECT.
  • value – Whether to set (True) or clear (False) the line.
Returns:

True if the value was set successfully, False otherwise.

setDataLines(lines)

Sets data lines.

Parameters:lines – The lines to set. Constants to used for these lines are PARPORTDATA0 - PARPORTDATA7. Several of these constants can be or’ed together to set several lines. The lines not mentioned in the parameter are left unchanged.
Returns:True if the lines were set, False otherwise.
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.

x
y
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.

isInf() → bool

Returns True if one of the components is infinite.

isNaN() → bool

Returns True if one of the components is Not a Number.

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 http://en.wikipedia.org/wiki/Svg) 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.

Parameters:
  • 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.

class libavg.avg.TestHelper

Bases: Boost.Python.instance

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

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.
filename

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

framerate

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
qmax

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.

synctoplayback

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.

pause()

Temporarily stops recording.

play()

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

stop()

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.

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

True if point is inside, False otherwise.

class libavg.statemachine.StateMachine(name, startState)

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.

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

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.

Parameters:
  • 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.
changeState(newState)

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.

dump()

Prints all states and transitions to the console.

traceChanges(trace)

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