VlcMovieStim

A stimulus class for playing movies (mpeg, avi, etc…) in PsychoPy® using a local installation of VLC media player (https://www.videolan.org/).

Requires version 3.0.11115 of python-vlc on Windows. Other platforms (MacOS and Linux) may use a newer version.

Attributes

VlcMovieStim(win[, filename, units, size, ...])

A stimulus class for playing movies in various formats (mpeg, avi, etc...) in PsychoPy using the VLC media player as a decoder.

VlcMovieStim.win

The Window object in which the stimulus will be rendered by default.

VlcMovieStim.units

VlcMovieStim.pos

The position of the center of the stimulus in the stimulus units

VlcMovieStim.ori

The orientation of the stimulus (in degrees).

VlcMovieStim.size

The size (width, height) of the stimulus in the stimulus units

VlcMovieStim.opacity

Determines how visible the stimulus is relative to background.

VlcMovieStim.name

The name (str) of the object to be using during logged messages about this stim.

VlcMovieStim.autoLog

Whether every change in this stimulus should be auto logged.

VlcMovieStim.draw([win])

Draw the current frame to a particular Window (or to the default win for this object if not specified).

VlcMovieStim.autoDraw

Determines whether the stimulus should be automatically drawn on every frame flip.

VlcMovieStim.setMovie(filename[, log])

See ~MovieStim.loadMovie (the functions are identical).

VlcMovieStim.loadMovie(filename[, log])

Load a movie from file

VlcMovieStim.isPlaying

True if the video is presently playing (bool).

VlcMovieStim.isNotStarted

True if the video has not be started yet (bool).

VlcMovieStim.isStopped

True if the video is stopped (bool).

VlcMovieStim.isPaused

True if the video is presently paused (bool).

VlcMovieStim.isFinished

True if the video is finished (bool).

VlcMovieStim.play([log])

Start or continue a paused movie from current position.

VlcMovieStim.pause([log])

Pause the current point in the movie.

VlcMovieStim.stop([log])

Stop the current point in the movie (sound will stop, current frame will not advance).

VlcMovieStim.seek(timestamp[, log])

Seek to a particular timestamp in the movie.

VlcMovieStim.rewind([seconds])

Rewind the video.

VlcMovieStim.fastForward([seconds])

Fast-forward the video.

VlcMovieStim.replay([autoPlay])

Replay the movie from the beginning.

VlcMovieStim.volume

Audio track volume (int or float).

VlcMovieStim.setVolume(volume)

Set the audio track volume.

VlcMovieStim.getVolume()

Returns the current movie audio volume.

VlcMovieStim.increaseVolume([amount])

Increase the volume.

VlcMovieStim.decreaseVolume([amount])

Decrease the volume.

VlcMovieStim.frameIndex

Current frame index being displayed (int).

VlcMovieStim.getCurrentFrameNumber()

Get the current movie frame number (int), same as frameIndex.

VlcMovieStim.duration

Duration of the loaded video in seconds (float).

VlcMovieStim.loopCount

Number of loops completed since playback started (int).

VlcMovieStim.fps

Movie frames per second (float).

VlcMovieStim.getFPS()

Movie frames per second.

VlcMovieStim.frameTime

Current frame time in seconds (float).

VlcMovieStim.getCurrentFrameTime()

Get the time that the movie file specified the current video frame as having.

VlcMovieStim.percentageComplete

Percentage of the video completed (float).

VlcMovieStim.getPercentageComplete()

Provides a value between 0.0 and 100.0, indicating the amount of the movie that has been already played.

VlcMovieStim.videoSize

Size of the video (w, h) in pixels (tuple).

VlcMovieStim.interpolate

Enable linear interpolation (`bool').

VlcMovieStim.setFlipHoriz([newVal, log])

If set to True then the movie will be flipped horizontally (left-to-right).

VlcMovieStim.setFlipVert([newVal, log])

If set to True then the movie will be flipped vertically (top-to-bottom).

VlcMovieStim.filename

File name for the loaded video (str).

VlcMovieStim.autoStart

Start playback when .draw() is called (bool).

Details

class psychopy.visual.VlcMovieStim(win, filename='', units='pix', size=None, pos=(0.0, 0.0), ori=0.0, flipVert=False, flipHoriz=False, color=(1.0, 1.0, 1.0), colorSpace='rgb', opacity=1.0, volume=1.0, name='', loop=False, autoLog=True, depth=0.0, noAudio=False, interpolate=True, autoStart=True)[source]

A stimulus class for playing movies in various formats (mpeg, avi, etc…) in PsychoPy using the VLC media player as a decoder. This is a lazy-imported class, therefore import using full path from psychopy.visual.vlcmoviestim import VlcMovieStim when inheriting from it.

This movie class is very efficient and better suited for playing high-resolution videos (720p+) than the other movie classes. However, audio is only played using the default output device. This may be adequate for most applications where the user is not concerned about precision audio onset times.

The VLC media player (https://www.videolan.org/) must be installed on the machine running PsychoPy to use this class. Make certain that the version of VLC installed matches the architecture of the Python interpreter hosting PsychoPy.

Parameters:
  • win (Window) – Window the video is being drawn to.

  • filename (str) – Name of the file or stream URL to play. If an empty string, no file will be loaded on initialization but can be set later.

  • units (str) – Units to use when sizing the video frame on the window, affects how size is interpreted.

  • size (ArrayLike or None) – Size of the video frame on the window in units. If None, the native size of the video will be used.

  • flipVert (bool) – If True then the movie will be top-bottom flipped.

  • flipHoriz (bool) – If True then the movie will be right-left flipped.

  • volume (int or float) – If specifying an int the nominal level is 100, and 0 is silence. If a float, values between 0 and 1 may be used.

  • loop (bool) – Whether to start the movie over from the beginning if draw is called and the movie is done. Default is `False.

  • autoStart (bool) – Automatically begin playback of the video when flip() is called.

Notes

  • You may see error messages in your log output from VLC (e.g., get_buffer() failed, no frame!, etc.) after shutting down. These errors originate from the decoder and can be safely ignored.

_calcPosRendered()

DEPRECATED in 1.80.00. This functionality is now handled by _updateVertices() and verticesPix.

_calcSizeRendered()

DEPRECATED in 1.80.00. This functionality is now handled by _updateVertices() and verticesPix

_closeMedia()[source]

Internal method to release the presently loaded stream (if any).

_createVLCInstance()[source]

Internal method to create a new VLC instance.

Raises an error if an instance is already spawned and hasn’t been released.

_drawRectangle()[source]

Draw the frame to the window. This is called by the draw() method.

_freeBuffers()[source]

Free texture and pixel buffers. Call this when tearing down this class or if a movie is stopped.

_getPolyAsRendered()

DEPRECATED. Return a list of vertices as rendered.

_onEos()[source]

Internal method called when the decoder encounters the end of the stream.

_openMedia(uri=None)[source]

Internal method that opens a new stream using filename. This will close the previous stream. Raises an error if a VLC instance is not available.

_pixelTransfer()[source]

Internal method which maps the pixel buffer for the video texture to client memory, allowing for VLC to directly draw a video frame to it.

This method is not thread-safe and should never be called without the pixel lock semaphore being first set by VLC.

_releaseVLCInstance()[source]

Internal method to release a VLC instance. Calling this implicitly stops and releases any stream presently loaded and playing.

_selectWindow(win)

Switch drawing to the specified window. Calls the window’s _setCurrent() method which handles the switch.

_set(attrib, val, op='', log=None)

DEPRECATED since 1.80.04 + 1. Use setAttribute() and val2array() instead.

_setupTextureBuffers()[source]

Setup texture buffers which hold frame data. This creates a 2D RGB texture and pixel buffer. The pixel buffer serves as the store for texture color data. Each frame, the pixel buffer memory is mapped and frame data is copied over to the GPU from the decoder.

This is called every time a video file is loaded. The _freeBuffers method is called in this routine prior to creating new buffers, so it’s safe to call this right after loading a new movie without having to _freeBuffers first.

_updateList()

The user shouldn’t need this method since it gets called after every call to .set() Chooses between using and not using shaders each call.

_updateVertices()

Sets Stim.verticesPix and ._borderPix from pos, size, ori, flipVert, flipHoriz

property anchor
autoDraw

Determines whether the stimulus should be automatically drawn on every frame flip.

Value should be: True or False. You do NOT need to set this on every frame flip!

autoLog

Whether every change in this stimulus should be auto logged.

Value should be: True or False. Set to False if your stimulus is updating frequently (e.g. updating its position every frame) and you want to avoid swamping the log file with messages that aren’t likely to be useful.

property autoStart

Start playback when .draw() is called (bool).

contains(x, y=None, units=None)

Returns True if a point x,y is inside the stimulus’ border.

Can accept variety of input options:
  • two separate args, x and y

  • one arg (list, tuple or array) containing two vals (x,y)

  • an object with a getPos() method that returns x,y, such

    as a Mouse.

Returns True if the point is within the area defined either by its border attribute (if one defined), or its vertices attribute if there is no .border. This method handles complex shapes, including concavities and self-crossings.

Note that, if your stimulus uses a mask (such as a Gaussian) then this is not accounted for by the contains method; the extent of the stimulus is determined purely by the size, position (pos), and orientation (ori) settings (and by the vertices for shape stimuli).

See Coder demos: shapeContains.py See Coder demos: shapeContains.py

decreaseVolume(amount=10)[source]

Decrease the volume.

Parameters:

amount (int) – Decrease the volume by this amount (percent). This gets subtracted from the present volume level. If the value of amount and the current volume is outside the valid range of 0 to 100, the value will be clipped. The default value is 10 (or 10% decrease).

Returns:

Volume after changed.

Return type:

int

Examples

Adjust the volume of the current video using key presses:

# assume `mov` is an instance of this class defined previously
for key in event.getKeys():
    if key == 'minus':
        mov.decreaseVolume()
    elif key == 'equals':
        mov.increaseVolume()
depth

DEPRECATED, depth is now controlled simply by drawing order.

draw(win=None)[source]

Draw the current frame to a particular Window (or to the default win for this object if not specified).

The current position in the movie will be determined automatically. This method should be called on every frame that the movie is meant to appear.

Parameters:

win (Window or None) – Window the video is being drawn to. If None, the window specified at initialization will be used instead.

Returns:

True if the frame was updated this draw call.

Return type:

bool

property duration

Duration of the loaded video in seconds (float). Not valid unless the video has been started.

fastForward(seconds=5)[source]

Fast-forward the video.

Parameters:

seconds (float) – Time in seconds to fast forward from the current position. Default is 5 seconds.

Returns:

Timestamp at new position after fast forwarding the video.

Return type:

float

property filename

File name for the loaded video (str).

property flip

1x2 array for flipping vertices along each axis; set as True to flip or False to not flip. If set as a single value, will duplicate across both axes. Accessing the protected attribute (._flip) will give an array of 1s and -1s with which to multiply vertices.

property flipHoriz
property flipVert
property fps

Movie frames per second (float).

property frameIndex

Current frame index being displayed (int).

property frameTexture

Texture ID for the current video frame (GLuint). You can use this as a video texture. However, you must periodically call updateTexture to keep this up to date.

property frameTime

Current frame time in seconds (float).

getAnchor()
getAutoDraw()
getAutoLog()
getAutoStart()
getCurrentFrameNumber()[source]

Get the current movie frame number (int), same as frameIndex.

getCurrentFrameTime()[source]

Get the time that the movie file specified the current video frame as having.

Returns:

Current video time in seconds.

Return type:

float

getDepth()
getDuration()
getFPS()[source]

Movie frames per second.

Returns:

Nominal number of frames to be displayed per second.

Return type:

float

getFilename()
getFlip()
getFlipHoriz()
getFlipVert()
getFps()
getFrameIndex()
getFrameTexture()
getFrameTime()
getHeight()
getInterpolate()
getIsFinished()
getIsNotStarted()
getIsPaused()
getIsPlaying()
getIsStopped()
getLoopCount()
getName()
getOpacity()
getOri()
getPercentageComplete()[source]

Provides a value between 0.0 and 100.0, indicating the amount of the movie that has been already played.

getPos()
getSize()
getUnits()
getVertices()
getVerticesPix()
getVideoSize()
getVolume()[source]

Returns the current movie audio volume.

Returns:

Volume level, 0 is no audio, 100 is max audio volume.

Return type:

int

getWidth()
getWin()
get_borderPix()
property height
increaseVolume(amount=10)[source]

Increase the volume.

Parameters:

amount (int) – Increase the volume by this amount (percent). This gets added to the present volume level. If the value of amount and the current volume is outside the valid range of 0 to 100, the value will be clipped. The default value is 10 (or 10% increase).

Returns:

Volume after changed.

Return type:

int

Examples

Adjust the volume of the current video using key presses:

# assume `mov` is an instance of this class defined previously
for key in event.getKeys():
    if key == 'minus':
        mov.decreaseVolume()
    elif key == 'equals':
        mov.increaseVolume()
property interpolate

Enable linear interpolation (`bool’).

If True linear filtering will be applied to the video making the image less pixelated if scaled. You may leave this off if the native size of the video is used.

property isFinished

True if the video is finished (bool).

property isNotStarted

True if the video has not be started yet (bool). This status is given after a video is loaded and play has yet to be called.

property isPaused

True if the video is presently paused (bool).

property isPlaying

True if the video is presently playing (bool).

property isStopped

True if the video is stopped (bool).

loadMovie(filename, log=True)[source]

Load a movie from file

Parameters:
  • filename (str) – The name of the file or URL, including path if necessary.

  • log (bool) – Log this event.

Notes

  • Due to VLC oddness, .duration is not correct until the movie starts playing.

property loopCount

Number of loops completed since playback started (int). This value is reset when either stop or loadMovie is called.

name

The name (str) of the object to be using during logged messages about this stim. If you have multiple stimuli in your experiment this really helps to make sense of log files!

If name = None your stimulus will be called “unnamed <type>”, e.g. visual.TextStim(win) will be called “unnamed TextStim” in the logs.

property opacity

Determines how visible the stimulus is relative to background.

The value should be a single float ranging 1.0 (opaque) to 0.0 (transparent). Operations are supported. Precisely how this is used depends on the Blend Mode.

ori

The orientation of the stimulus (in degrees).

Should be a single value (scalar). Operations are supported.

Orientation convention is like a clock: 0 is vertical, and positive values rotate clockwise. Beyond 360 and below zero values wrap appropriately.

overlaps(polygon)

Returns True if this stimulus intersects another one.

If polygon is another stimulus instance, then the vertices and location of that stimulus will be used as the polygon. Overlap detection is typically very good, but it can fail with very pointy shapes in a crossed-swords configuration.

Note that, if your stimulus uses a mask (such as a Gaussian blob) then this is not accounted for by the overlaps method; the extent of the stimulus is determined purely by the size, pos, and orientation settings (and by the vertices for shape stimuli).

See coder demo, shapeContains.py

pause(log=True)[source]

Pause the current point in the movie.

Parameters:

log (bool) – Log the pause event.

property percentageComplete

Percentage of the video completed (float).

play(log=True)[source]

Start or continue a paused movie from current position.

Parameters:

log (bool) – Log the play event.

Returns:

Frame index playback started at. Should always be 0 if starting at the beginning of the video. Returns None if the player has not been initialized.

Return type:

int or None

property pos

The position of the center of the stimulus in the stimulus units

value should be an x,y-pair. Operations are also supported.

Example:

stim.pos = (0.5, 0)  # Set slightly to the right of center
stim.pos += (0.5, -1)  # Increment pos rightwards and upwards.
    Is now (1.0, -1.0)
stim.pos *= 0.2  # Move stim towards the center.
    Is now (0.2, -0.2)

Tip: If you need the position of stim in pixels, you can obtain it like this:

from psychopy.tools.monitorunittools import posToPix
posPix = posToPix(stim)
replay(autoPlay=True)[source]

Replay the movie from the beginning.

Parameters:

autoPlay (bool) – Start playback immediately. If False, you must call play() afterwards to initiate playback.

Notes

  • This tears down the current VLC instance and creates a new one. Similar to calling stop() and loadMovie(). Use seek(0.0) if you would like to restart the movie without reloading.

rewind(seconds=5)[source]

Rewind the video.

Parameters:

seconds (float) – Time in seconds to rewind from the current position. Default is 5 seconds.

Returns:

Timestamp after rewinding the video.

Return type:

float

seek(timestamp, log=True)[source]

Seek to a particular timestamp in the movie.

Parameters:
  • timestamp (float) – Time in seconds.

  • log (bool) – Log the seek event.

setAnchor(value, log=None)
setAutoDraw(val, log=None)[source]

Add or remove a stimulus from the list of stimuli that will be automatically drawn on each flip

Parameters:
  • val: True/False

    True to add the stimulus to the draw list, False to remove it

setAutoLog(value=True, log=None)

Usually you can use ‘stim.attribute = value’ syntax instead, but use this method if you need to suppress the log message.

setAutoStart(value, log=None, operation=False, stealth=False)
setDepth(newDepth, operation='', log=None)

Usually you can use ‘stim.attribute = value’ syntax instead, but use this method if you need to suppress the log message

setFilename(value, log=None, operation=False, stealth=False)
setFlip(value, log=None, operation=False, stealth=False)
setFlipHoriz(newVal=True, log=True)[source]

If set to True then the movie will be flipped horizontally (left-to-right). Note that this is relative to the original, not relative to the current state.

setFlipVert(newVal=True, log=True)[source]

If set to True then the movie will be flipped vertically (top-to-bottom). Note that this is relative to the original, not relative to the current state.

setHeight(value, log=None, operation=False, stealth=False)
setInterpolate(value, log=None, operation=False, stealth=False)
setMovie(filename, log=True)[source]

See ~MovieStim.loadMovie (the functions are identical).

This form is provided for syntactic consistency with other visual stimuli.

setName(value, log=None, operation=False, stealth=False)
setOpacity(newOpacity, operation='', log=None)

Hard setter for opacity, allows the suppression of log messages and calls the update method

setOri(newOri, operation='', log=None)

Usually you can use ‘stim.attribute = value’ syntax instead, but use this method if you need to suppress the log message

setPos(newPos, operation='', log=None)

Usually you can use ‘stim.attribute = value’ syntax instead, but use this method if you need to suppress the log message.

setSize(newSize, operation='', units=None, log=None)

Usually you can use ‘stim.attribute = value’ syntax instead, but use this method if you need to suppress the log message

setUnits(value, log=None, operation=False, stealth=False)
setVertices(value, log=None, operation=False, stealth=False)
setVolume(volume)[source]

Set the audio track volume.

Parameters:

volume (int or float) – Volume level to set. 0 = mute, 100 = 0 dB. float values between 0.0 and 1.0 are also accepted, and scaled to an int between 0 and 100.

setWidth(value, log=None, operation=False, stealth=False)
setWin(value, log=None, operation=False, stealth=False)
property size

The size (width, height) of the stimulus in the stimulus units

Value should be x,y-pair, scalar (applies to both dimensions) or None (resets to default). Operations are supported.

Sizes can be negative (causing a mirror-image reversal) and can extend beyond the window.

Example:

stim.size = 0.8  # Set size to (xsize, ysize) = (0.8, 0.8)
print(stim.size)  # Outputs array([0.8, 0.8])
stim.size += (0.5, -0.5)  # make wider and flatter: (1.3, 0.3)

Tip: if you can see the actual pixel range this corresponds to by looking at stim._sizeRendered

stop(log=True)[source]

Stop the current point in the movie (sound will stop, current frame will not advance). Once stopped the movie cannot be restarted - it must be loaded again.

Use pause() instead if you may need to restart the movie.

Parameters:

log (bool) – Log the stop event.

property units
updateOpacity()

Placeholder method to update colours when set externally, for example updating the pallette attribute of a textbox.

updateTexture()[source]

Update the video texture buffer to the most recent video frame.

property vertices
property verticesPix

This determines the coordinates of the vertices for the current stimulus in pixels, accounting for size, ori, pos and units

property videoSize

Size of the video (w, h) in pixels (tuple). Returns (0, 0) if no video is loaded.

property volume

Audio track volume (int or float). See setVolume for more information about valid values.

property width
property win

The Window object in which the stimulus will be rendered by default. (required)

Example, drawing same stimulus in two different windows and display simultaneously. Assuming that you have two windows and a stimulus (win1, win2 and stim):

stim.win = win1  # stimulus will be drawn in win1
stim.draw()  # stimulus is now drawn to win1
stim.win = win2  # stimulus will be drawn in win2
stim.draw()  # it is now drawn in win2
win1.flip(waitBlanking=False)  # do not wait for next
             # monitor update
win2.flip()  # wait for vertical blanking.

Note that this just changes default window for stimulus.

You could also specify window-to-draw-to when drawing:

stim.draw(win1)
stim.draw(win2)

Back to top