Skip to content

Instantly share code, notes, and snippets.

@edwinm
Created November 25, 2009 21:59
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 edwinm/243060 to your computer and use it in GitHub Desktop.
Save edwinm/243060 to your computer and use it in GitHub Desktop.
Old-school webcam by using server-push.
// webcam.c
// Author E. Martin
// July 27th 1997
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#define IMAGEPATH "../video/movie/auto.mpg qt%04d.jpg"
// $HTTP_headers = "HTTP/1.1 200 OK\015\012";
// $HTTP_headers .= "Connection: close\015\012";
// Connection: close\n
#define HEADER "HTTP/1.1 200 OK\nContent-type: multipart/x-mixed-replace;boundary=RandomEnough\n"
#define RANDOMSTRING "\n--RandomEnough\n"
#define ENDSTRING "\n--RandomEnough--\n"
#define CTSTRING "Content-type: image/jpeg\n\n"
#define STDOUT 1
#define IMGMAXSIZE 10000
#define IMGPATHLEN 100
#define noDEBUG
int main()
{
struct stat fi;
char buf[IMGMAXSIZE];
char imgpath[IMGPATHLEN];
double frame;
int fd;
int bytesread;
time_t now;
time_t then;
int thenframe;
double fps=5;
if( write( STDOUT, HEADER, strlen( HEADER ) ) == -1 )
exit(0);
if( write( STDOUT, RANDOMSTRING, strlen( RANDOMSTRING ) ) == -1 )
exit(0);
then = time(NULL);
frame = 1;
thenframe = 1;
while(1) {
sprintf( imgpath, IMAGEPATH, (int) frame );
stat( imgpath, &fi );
if( ( fd = open( imgpath, O_RDONLY ) ) == -1) {
exit(0);
}
if ( ( bytesread = read( fd, buf, fi.st_size ) ) <= 0 )
exit(0);
close(fd);
if( write( STDOUT, CTSTRING, strlen( CTSTRING ) ) == -1 )
exit(0);
if( write( STDOUT, buf, fi.st_size ) == -1 )
exit(0);
if( write( STDOUT, RANDOMSTRING, strlen( RANDOMSTRING ) ) == -1 )
exit(0);
frame += (double) 5.0/fps;
// fsync( STDOUT ); has no effect
now = time(NULL);
if ( difftime( then, now ) > 5 ) {
fps = (double) (frame-thenframe)/5.0;
thenframe = frame;
then = now;
}
usleep( (unsigned long) 1000000/fps );
// if usleep is unavailable, use select( 0, NULL, NULL, NULL, &tv );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment