Skip to content

Instantly share code, notes, and snippets.

@dillonchr
Last active April 22, 2021 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dillonchr/f83fe3cab7649b132a3c28f0316e81d1 to your computer and use it in GitHub Desktop.
Save dillonchr/f83fe3cab7649b132a3c28f0316e81d1 to your computer and use it in GitHub Desktop.
macbook webcam snapper

copied from: https://gist.github.com/docPhil99/d8667de1e8c5e96e2203f2bc0f28f89d

Capture and stream a webcam

To capture using the iSight camera on a Mac, or infact any other webcam connected to the Mac, we can use FFmpeg. First get a list of the devices installed.

ffmpeg -f avfoundation -list_devices true -i "" 

This will list the aviable video and audio devices.

The below will capture at 30fps and the set video size to a file. ffmpeg -f avfoundation -framerate 30 -video_size 640x480 -i "0:none" out.avi

The -i 0:none will select the 0 indexed video source and no audio.

We can stream this to the network with

ffmpeg -f avfoundation -framerate 30 -video_size 640x480 -i "0:none" -vcodec libx264 -preset ultrafast -tune zerolatency -pix_fmt yuv422p -f mpegts udp://localhost:12345

This can be viewed using VLC or OpenCV, although there maybe a significant lactancy in the stream.

To save the stream to file, it might be useful to save it as multiple files so out.avi does not get too big. We can change the output file every minute or so with the segment filter

For example, this captures my webcam and saves to a new file every 60 seconds. ffmpeg -f avfoundation -framerate 25 -video_size 640x480 -i "0:none" -flags +global_header -f segment -segment_time 60 -segment_format_options movflags=+faststart -reset_timestamps 1 test%d.mp4

#!/bin/bash
OUT="/tmp/$(date +"%Y-%m-%d_%H-%M-%S").jpg"
if [ "$#" -gt "0" ]
then
OUT="$1"
fi
# had to choose 1 instead of 0 because Snap took precedence!
# [AVFoundation indev @ 0x7fba4a025a00] AVFoundation video devices:
# [AVFoundation indev @ 0x7fba4a025a00] [0] Snap Camera
# [AVFoundation indev @ 0x7fba4a025a00] [1] FaceTime HD Camera (Built-in)
# [AVFoundation indev @ 0x7fba4a025a00] [2] Capture screen 0
# [AVFoundation indev @ 0x7fba4a025a00] [3] Capture screen 1
# [AVFoundation indev @ 0x7fba4a025a00] AVFoundation audio devices:
# [AVFoundation indev @ 0x7fba4a025a00] [0] MacBook Pro Microphone
ffmpeg -f avfoundation -framerate 30 -i "1" -vframes 1 "$OUT"
if [ "$?" -eq "0" ]
then
mv "$OUT" ~/snapshots
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment