Recording gameplay videos on RetroPie

Credits: this is a slightly corrected and shortened version of How To Record A GamePlay Video From A RetroPie by selsine, which is itself based on Recording Live Gameplay in RetroPie’s RetroArch Emulators Natively on the Raspberry Pi by Retro Resolution.

RetroPie is based on RetroArch. RetroArch has a feature to record gameplay videos, but the current version of RetroPie has it disabled, presumably because it was thought to be too intensive to run properly on a Raspberry Pi.

These instructions tell you how to turn the recording feature on, and set it up. This works perfectly on my Raspberry Pi 3, allowing me to record video and sound from games I am playing.

The code for this is here: github.com/andybalaam/retropie-recording – this was code written by RetroRevolution, with small corrections and additions by me.

Before you start, you should have RetroPie working and connected to the Internet, and updated to the latest version.

Note: you should make a backup of your RetroPie before you start, because if you type the command below you could completely break it, meaning you will have to wipe your SD card and start fresh.

Turning on the recording feature

RetroArch uses the ffmpeg program to record video. To turn on recording, we need to log into the Pi using ssh, download and compile ffmpeg, and then recompile RetroArch with recording support turned on.

Log in to the Pi using ssh

Find out the IP address of your Pi by choosing “RetroPie setup” in the RetroPie menu and choosing “Show IP Address”. Write down the IP address (four numbers with dots in between – for example: 192.168.0.3).

On your Linux* computer open a Terminal and type:

ssh pi@192.168.0.3

(put in the IP address you wrote down instead of 192.168.0.3)

When it asks for your password, type: raspberry

If this works right, you should see something like this:
The RetroPie Project joystick logo

* Note: if you don’t have Linux, this should work OK on a Mac, or on Windows you could try using PuTTY.

Download and compile ffmpeg

Log in to the RetroPie as described above. The commands shown below should all be typed in to the window where you are logged in to the RetroPie.

Download the script ffmpeg-install.sh by typing this:

wget https://github.com/andybalaam/retropie-recording/raw/master/ffmpeg-install.sh

Now run it like this:

bash ffmpeg-install.sh

(Note: DON’T use sudo to run this – just type exactly what is written above.)

Now wait a long time for this to work. If it prints out errors, something went wrong – read what it says, and you may need to edit the ffmpeg-install.sh script to figure out what to do. Leave a comment and include the errors you saw if you need help.

Hopefully it will end successfully and print:

FFmpeg and Codec Installation Complete

If so, you are ready to move on to recompiling RetroArch:

Recompile RetroArch with recording turned on

Download the script build-retroarch-with-ffmpeg.sh by typing this:

wget https://github.com/andybalaam/retropie-recording/raw/master/build-retroarch-with-ffmpeg.sh

Now run it like this:

bash build-retroarch-with-ffmpeg.sh

It should finish in about 10 minutes, and print:

Building RetroArch with ffmpeg enabled complete

If it printed that, your RetroPie now has recording support! Restart your RetroPie:

Restart the RetroPie

Restart your RetroPie.

If you want to check that recording support is enabled, Look for “Checking FFmpeg Has Been Enabled in RetroArch” on the RetroResolution guide.

Now you need to set up RetroPie to record your emulator.

Setting up recording for your emulator

To set up an emulator, you need a general recording config file (the same for all emulators), and a launch config for the actual emulator you are using.

Create the recording config file

Log into the RetroPie as described in the first section, and type this to download the recording config file. If you want to change settings like what file format to record in, this is the file you will need to change.

wget https://github.com/andybalaam/retropie-recording/blob/master/recording-config.cfg

Create a launch config for your emulator

Each RetroPie emulator has a config file that describes how to launch it. For example, the NES emulator’s version is in /opt/retropie/configs/nes/emulators.cfg.

To get a list of all the emulators, log into your RetroPie and type:

ls /opt/retropie/configs

In that list you will see, for example, “nes” for the NES emulators, and “gb” for the GameBoy emulators. Find the one you want to edit, and edit it with the nano editor by typing:

nano /opt/retropie/configs/gb/emulators.cfg

(Instead of “gb” type the right name for the emulator you want to use, from the list you got when you typed the “ls” command above.)

Now you need to add a new line in this file. Each line describes how to launch an emulator. You should copy an existing line, and add some more stuff to the end.

For example, my version of this file looks like this:

lr-gambatte = "/opt/retropie/emulators/retroarch/bin/retroarch -L /opt/retropie/libretrocores/lr-gambatte/gambatte_libretro.so --config /opt/retropie/configs/gb/retroarch.cfg %ROM%"
lr-gambatte-record = "/opt/retropie/emulators/retroarch/bin/retroarch -L /opt/retropie/libretrocores/lr-gambatte/gambatte_libretro.so --config /opt/retropie/configs/gb/retroarch.cfg --record /home/pi/recording_GB_$(date +%Y-%m-%d-%H%M%S).mkv --recordconfig /home/pi/recording-config.cfg %ROM%"
default = "lr-gambatte"
lr-tgbdual = "/opt/retropie/emulators/retroarch/bin/retroarch -L /opt/retropie/libretrocores/lr-tgbdual/tgbdual_libretro.so --config /opt/retropie/configs/gb/retroarch.cfg %ROM%"

The line I added is coloured: The green parts are things copied from the line above, and the red parts are new – those parts tell the launcher to use the recording config we made in the previous section.

When you’ve made your edits, press Ctrl-X to exit nano, and type “Y” when it asks whether you want to save.

Once you’ve done something similar to this for every emulator you want to record with, you are ready to actually do the recording!

Actually doing a recording

Launching a game with recording turned on

In the normal RetroPie interface, go to your emulator and start it, but press the A button while it’s launching, and choose “Select emulator for ROM”. In the list that comes up, choose the new line you added in emulators.cfg. In our example, that was called “lr-gambatte-record”.

Now play the game, and exit when you are finished. If all goes well, the recording will have been saved!

(Note: doing this means that every time you launch this game it will be recorded. To stop it doing this, press the “A” button while it’s launching, choose “Select emulator for ROM” and choose the normal line – in our example that would be “lr-gambatte”.)

Getting the recorded files

To get your recording off the RetroPie, go back to your computer, open a terminal, and type:

scp pi@192.168.0.3:recording_*.mkv ./

This will copy all recorded videos from your RetroPie onto your computer (into your home directory, unless you did a cd commmand before you typed the above).

Now you should delete the files from your RetroPie. Log in to the RetroPie as described in the first section, and delete all recording files by typing this:

Note: This deletes all your recordings, and you can’t undo!

rm recording_*.mkv

Note: This deletes all your recordings, and you can’t undo!

Safer: recording onto a USB stick

Note: recording directly onto the RetroPie like we described above is dangerous because you could fill up all the disk space or corrupt your SD card, which could make RetroPie stop working, meaning you need to wipe your SD card and set up RetroPie again.

It’s safer to record onto a separate USB disk. To find out how, read “Recording to an External Storage Device” in Retro Resolution’s guide.

Broken Levels Challenge – Egham Raspberry Pi Jam July 2017

Today at the Egham Raspberry Pi Jam we did two things:

1. The Broken Levels Challenge

Some nasty person came and broke our levels for our game Rabbit Escape and we need you to fix them!

To play this game you will need a PC version of Rabbit Escape, our Broken Levels, and the instruction sheets. Let us know how you get on!

2. Python Traffic Lights Programming Workshop

I ran a workshop to learn a bit of Python programming using this resource sheet Pi Stop Traffic Lights.

We had a lot of fun, and hopefully some people even learnt a little bit of coding.

Raspberry Pi Jam “Chaos Car!”

Raspberry Pi 1
+ battery pack
+ Bluetooth USB dongle
+ i-racer bluetooth car
+ Raspberry Pi camera
+ some Python code
+ loads of sellotape
=

Chaos car!

Here’s the code:

#!/usr/bin/env python2

import os
import random
import bluetooth
import sys
import time

car_name = "DaguCar"

def find_car_mac( car_name ):
    ret = None

    print "Scanning for a device called %s..." % car_name

    devices = bluetooth.discover_devices()

    for addr in devices:
        dev_name = bluetooth.lookup_name( addr )
        if dev_name == car_name:
            print "Car found!  (MAC=%s)" % addr
            time.sleep( 1 )
            return addr
        else:
            print "Skipping device named '%s'." % dev_name

    sys.stderr.write( "Couldn't find a device called %s!\n" % car_name )
    sys.exit( 1 )


#car_mac = find_car_mac( car_name )

print "Using hard-coded MAC address"
car_mac = "20:13:04:23:05:71"

print "Connecting to the car at %s..." % car_mac

sock = bluetooth.BluetoothSocket( bluetooth.RFCOMM )
sock.connect( ( car_mac, 1 ) )

class Car:
    def turn_right(self):
        print("looking right")
        sock.send( '\x6A' )
    def turn_left(self):
        print("looking left")
        sock.send( '\x5A' )
    def roll_forward(self):
        print("watch out in front coming forward")
        sock.send( '\x1A' )
    def roll_backward(self):
        print("beep beep going backward")
        sock.send( '\x2A' )
    def wait(self):
        print("waiting")
        sock.send( '\x00' )

car = Car()

instruction = ["turn right", "turn left", "roll forward", "roll backward", "wait"]

while True:
    ci = random.choice(instruction)
    if ci == "turn right":
        car.turn_right()
    elif ci == "turn left":
        car.turn_left()
    elif ci == "roll forward":
        car.roll_forward()
    elif ci == "roll backward":
        car.roll_backward()
    elif ci == "wait":
        car.wait()
    time.sleep(0.5)

Improving the code to avoid bumping into walls is left as an exercise for the reader.

Which Raspberry Pi photo was funniest?

We had a great day at the Egham Raspberry Pi Jam, and Rabbit Escape and our Photo Booth:

seemed to go down well:


But which photo was funniest? Here are some of the entries (I had to choose kids’ ones without faces to go on here, but there were some other great ones!):





But the winner has to be the eyeball wearing a hat!

Thanks everyone, see you next time!

Raspberry Pi Funniest Photo Game

For our latest Egham Raspberry Pi Jam, we worked on a photo booth program, using the Raspberry Pi camera. Here’s how we did it.

Downloads: funniest-photo-game.odp, photo-booth.zip.

Update 1: fixed a bug where it tried to create a directory that already exists

Update 2: see the winning photo!

Equipment

What we did

  • Made and decorated a box that held the Pi and camera steady for taking photos:
    Decorated Box for Raspberry Pi
    (Note the holes for the wires!)
  • Created some costumes (see “Costumes” below)
  • Wrote a Python program (see “Program” below) to display pictures on top of the camera picture, and take photos
  • Wrote up the instructions and competition rules

Costumes

We made lots of costumes that show up over the picture. They all needed to be 1280×720 pixels, PNG files that use Indexed Color mode. (In Gimp we clicked “Image”, then “Mode”, then “Indexed Color” before choosing “File” then “Export” or “Overwrite” to save them as .png files.)

Here are some examples:

Once we’d made the costumes we put them in a directory called “costumes” next to the program file, photo-booth.py.

Setup

To get the Pi ready to run our program we needed to type these commands:

sudo apt-get update
sudo apt-get install python-picamera
sudo apt-get install python-imaging

Once we’d done this, we created the Python program and directories described in the next section, and then we ran the program with:

python photo-booth.py

Program

We made a directory to hold our program on the Desktop of our Raspberry Pi, which we called “photo-booth”. Inside that, we made a “costumes” directory containing our costumes, and a “gallery” directory to hold the saved photos. Also inside “photo-booth” we saved this code as “photo-booth.py”:

import io
import picamera
from PIL import Image
import time
import pygame
import subprocess
import os

class PhotoBooth:
    def __init__( self, camera ):
        self.camera = camera
        self.costumes = os.listdir( 'costumes' )
        self.current_overlay = None
        self.cos_num= 0
        self.current_costume = None

        self.set_up_camera()

        self.change_costume(0)

    def set_up_camera(self):
        self.camera.resolution = ( 1280, 720 )
        self.camera.framerate = 24
        self.camera.start_preview()

    def change_costume(self, change):
        self.cos_num += change
        self.cos_num = self.cos_num%len(self.costumes)
        self.current_costume = Image.open( 'costumes/'+self.costumes[self.cos_num])
        self.overlay(self.current_costume, 128)

    def overlay(self, image, alpha):
        pad = Image.new('RGB', (
            ((image.size[0] + 31) // 32) * 32,
            ((image.size[1] + 15) // 16) * 16,
            ))
        pad.paste(image, (0, 0))

        if self.current_overlay is not None:
            self.camera.remove_overlay(self.current_overlay)

        self.current_overlay = camera.add_overlay(pad.tostring(), size=image.size)
        self.current_overlay.alpha = alpha
        self.current_overlay.layer = 3

    def take_photo(self):
        stream = io.BytesIO()
        camera.capture( stream, format='jpeg' )
        stream.seek( 0 )
        captimg = Image.open( stream )
        imgrgba = self.current_costume.convert("RGBA")
        captimg.paste( imgrgba, ( 0, -100 ), imgrgba )
        self.overlay(captimg, 255)
        captimg.save( 'gallery/photo%d.png' % time.time().real )
        self.overlay(self.current_costume, 128)

    def run(self):
            while True:
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        return
                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_LEFT:
                            self.change_costume(1)
                        if event.key == pygame.K_RIGHT:
                            self.change_costume(-1)
                        if event.key == pygame.K_SPACE:
                            self.take_photo()
                        if event.key == pygame.K_ESCAPE:
                            return
                        if event.key == pygame.K_g:
                            subprocess.call('ls gallery/*.png | head -1 | xargs xdg-open', shell = True)
                            return
                    if event.type == pygame.MOUSEBUTTONDOWN:
                        self.take_photo()

pygame.init()
pygame.display.set_mode()
if not os.path.exists( 'gallery' ):
    os.makedirs( 'gallery' )

with picamera.PiCamera() as camera:
    booth = PhotoBooth( camera )
    booth.run()

Download code and costumes

You can download the code and costumes we used here: photo-booth.zip.

If you have any questions, feel free to leave a comment below!