#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <error.h>
#include <string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include <fcntl.h>
#include <linux/videodev2.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <strings.h>
struct buffer
{
void* start;
unsigned int length;
}*buffers;
int main(void)
{
char id[10];
int ret;
int sockfd;
sockfd = socket(AF_INET ,SOCK_STREAM, 0);
if(sockfd == -1)
{
printf("socket failed\n");
exit(-1);
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(9999);
addr.sin_addr.s_addr= inet_addr("127.0.0.1");
ret = connect(sockfd, (struct sockaddr *)&addr, sizeof(addr));
if(ret == -1)
{
printf("connect failed!\n");
return 0;
}
printf("connect success!\n");
strcpy(id, "video");
send(sockfd, id, sizeof(id),0);
int fd = open("/dev/video0",O_RDWR);
if(fd<0)
return -1;
struct v4l2_capability cap;
ioctl(fd,VIDIOC_QUERYCAP,&cap);
printf("Driver Name:%s\nCard Name:%s\nBus info:%s\nDriver Version:%u.%u.%u\n",cap.driver,cap.card,cap.bus_info,(cap.version>>16)&0XFF, (cap.version>>8)&0XFF,cap.version&0XFF);
struct v4l2_format fmt;
fmt.fmt.pix.width = 1024;
fmt.fmt.pix.height = 768;
fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_MJPEG;
ioctl(fd, VIDIOC_S_FMT,&fmt);
struct v4l2_requestbuffers req;
memset(&req,0,sizeof(req));
req.count = 3;
req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
req.memory = V4L2_MEMORY_MMAP;
ioctl(fd, VIDIOC_REQBUFS,&req);
buffers = (struct buffer*)calloc(req.count, sizeof (*buffers));
if (!buffers) {
fprintf(stderr, "Out of memory/n");
exit(EXIT_FAILURE);
}
for (unsigned int n_buffers = 0; n_buffers < req.count; ++n_buffers)
{
struct v4l2_buffer buf;
memset(&buf,0,sizeof(buf));
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = n_buffers;
if (-1 == ioctl(fd, VIDIOC_QUERYBUF, &buf)) exit(-1);
buffers[n_buffers].length = buf.length;
buffers[n_buffers].start = mmap(NULL,buf.length,PROT_READ | PROT_WRITE ,MAP_SHARED,fd, buf.m.offset);
if (MAP_FAILED == buffers[n_buffers].start) exit(-1);
}
unsigned int i;
enum v4l2_buf_type type;
for (i = 0; i < 3; ++i)
{
struct v4l2_buffer buf;
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = i;
ioctl(fd, VIDIOC_QBUF, &buf);
}
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
ioctl(fd, VIDIOC_STREAMON, &type);
struct v4l2_buffer buf;
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
while(1) {
ioctl(fd, VIDIOC_DQBUF, &buf);
send(sockfd, &(buf.bytesused), 4, 0);
send(sockfd, buffers[buf.index].start, buf.bytesused, 0);
ioctl(fd, VIDIOC_QBUF, &buf);
usleep(500);
}
close(sockfd);
close(fd);
return 0;
}
|