查看完整版本: [-- Re:linux 下v4l2视频采集的问题 --]

QTCN开发网 -> Qt基础编程 -> Re:linux 下v4l2视频采集的问题 [打印本页] 登录 -> 注册 -> 回复主题 -> 发表主题

lkppost 2008-10-15 16:58

Re:linux 下v4l2视频采集的问题

如题,流程基本调通,就是从内存读取数据保存的时候不知道该如何操作,请各位帮忙看一下。多谢。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <assert.h>
#include <getopt.h>              // getopt_long()
#include <fcntl.h>
#include <unistd.h>                        // low-level i/o 
#include <errno.h>
#include<malloc.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<sys/time.h>
#include<sys/mman.h>
#include<sys/ioctl.h>
#include <asm/types.h>            // for videodev2.h
#include <linux/videodev2.h>

#include <jpeglib.h>
using namespace std;
#define CLEAR(x) memset (&(x), 0, sizeof (x))
typedef enum {
    IO_METHOD_READ,
    IO_METHOD_MMAP,
    IO_METHOD_USERPTR,
} io_method;
struct buffer {
    void * start;
    size_t length;
};
const char * dev_name= "/dev/video0";
static io_method io = IO_METHOD_MMAP;
const int pixel_format= V4L2_PIX_FMT_YUV420;
static int fd = -1;
struct buffer * buffers= NULL;
static unsigned int n_buffers = 0;

static void errno_exit(const char * s) {
    fprintf(stderr, "%s error %d, %s\n", s, errno, strerror(errno));
    exit(EXIT_FAILURE);
}
static int xioctl(int fd, int request, void * arg) {
    int r;
    do
        r = ioctl(fd, request, arg);
    while (-1 == r && EINTR == errno);
    return r;
}
int save_jpeg(char *buf, int size) //淇濆瓨閲囬泦鍒扮殑鍥惧儚鍒版枃浠朵腑
{
    FILE *fp, *fp1;
    static int inc=0;
    fp=fopen(DEVICE,"w+")   
    char bewf[128];
    sprintf(bewf, "image-%d.jpeg", inc);
    if ((fp1=fopen(bewf, "w+"))==NULL) {
        perror("open");
        exit(1);
    }
    if(fwrite(buf, size, 1, fp)==NULL)
    {
        perror("write");
        exit(1);
    }
    inc++;
    fclose(fp1);
    fclose(fp);
}
static void process_image(char * p, ssize_t size) {
    save_jpeg((char *)p,size);
    /*char * buf;
     buf = (char *)p;
     for(int i = 0;i<100;i++)
     {
     printf("%x  \n",*buf++);
     }*/
    /*static int no_image = 0;
     char filename[1024];
     int fd;
     ssize_t written = 0;

     snprintf(fiename, sizeof(filename), "/tmp/webcam-%5.5d.%s", no_image++,
     pixel_format == V4L2_PIX_FMT_YUV420 ? "yuv" : "raw");

     fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR);
     if (fd < 0) {
     fputc('*', stdout);
     fflush(stdout);
     return;
     }
     do {
     int ret;
     ret = write(fd, (char *)p + written, size - written);
     if (ret < 0) {
     fputc('+', stdout);
     fflush(stdout);
     return;
     }
     written += ret;
     } while (written < size);
     close(fd);*/
    /*char picbuf[size];
    unsigned char outbuf[size];
    unsigned char i_tmp;
    static int i_loop = 0;
    char s_namebuf[128];
    FILE *f_out;
    sprintf(s_namebuf, "./vidout/out_%d.ppm", i_loop++);
    cout<<s_namebuf<<endl;
    f_out = fopen(s_namebuf, "w+");
    memcpy(picbuf,  p, size);
    for (int i_swap=0; i_swap<size; i_swap+=3) {
        outbuf[i_swap+0] = picbuf[i_swap+2];
        outbuf[i_swap+1] = picbuf[i_swap+1];
        outbuf[i_swap+2] = picbuf[i_swap+0];
    }
    fwrite(outbuf, size, 1,f_out);
    fclose(f_out);
    cout<<"******************"<<endl;*/
    fputc('.', stdout);
    fflush(stdout);
}
static int read_frame(void) {
    struct v4l2_buffer buf;
    unsigned int i;
    CLEAR (buf);
    buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    buf.memory = V4L2_MEMORY_MMAP;
    if (-1 == xioctl(fd, VIDIOC_DQBUF, &buf)) {
        switch (errno) {
        case EAGAIN:
            return 0;
        case EIO:
            //Could ignore EIO, see spec.
            //fall through
        default:
            errno_exit("VIDIOC_DQBUF");
        }
    }
    assert(buf.index < n_buffers);
    process_image((char *)buffers[buf.index].start, buf.length);
    if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
        errno_exit("VIDIOC_QBUF");
    return 1;
}
static void mainloop(void) {
    unsigned int count;
    count = 10;
    while (count-- > 0) {
        for (;;) {
            fd_set fds;
            /*struct timeval tv;
             int r;
             FD_ZERO (&fds);
             FD_SET (fd, &fds);
             tv.tv_sec = 2;// Timeout.
             tv.tv_usec = 0;
             r = select(fd + 1, &fds, NULL, NULL, &tv);
             if (-1 == r) {
             if (EINTR == errno)
             continue;
             errno_exit("select");
             }
             if (0 == r) {
             fprintf(stderr, "select timeout\n");
             exit(EXIT_FAILURE);
             }*/
            if (read_frame())
                break;
        }
    }
}
static void stop_capturing(void) {
    cout<<endl<<"stop_capturing"<<endl;
}
static void start_capturing(void) {
    cout<<"start_capturing"<<endl;
    unsigned int i;
    enum v4l2_buf_type type;
    for (i = 0; i < n_buffers; ++i) {
        struct v4l2_buffer buf;
        CLEAR (buf);
        buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        buf.memory = V4L2_MEMORY_MMAP;
        buf.index = i;
        if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
            errno_exit("VIDIOC_QBUF");
    }
    type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    if (-1 == xioctl(fd, VIDIOC_STREAMON, &type))
        errno_exit("VIDIOC_STREAMON");
}
static void uninit_device(void) {
    unsigned int i;
    for (i = 0; i < n_buffers; ++i)
        if (-1 == munmap(buffers.start, buffers.length))
            errno_exit("munmap");

    free(buffers);
}
static void init_read(unsigned int buffer_size) {
    buffers = (buffer *)calloc(1, sizeof (*buffers));
    if (!buffers) {
        fprintf(stderr, "Out of memory\n");
        exit(EXIT_FAILURE);
    }
    buffers[0].length = buffer_size;
    buffers[0].start = malloc(buffer_size);
    if (!buffers[0].start) {
        fprintf(stderr, "Out of memory\n");
        exit(EXIT_FAILURE);
    }
}
static void init_mmap(void) {
    struct v4l2_requestbuffers req;
    CLEAR (req);
    req.count = 4;
    req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    req.memory = V4L2_MEMORY_MMAP;
    if (-1 == xioctl(fd, VIDIOC_REQBUFS, &req)) {
        if (EINVAL == errno) {
            fprintf(stderr, "%s does not support memory mapping\n", dev_name);
            exit(EXIT_FAILURE);
        } else {
            errno_exit("VIDIOC_REQBUFS");
        }
    }
    cout<<"VIDIOC_REQBUFS success!"<<endl;
    if (req.count < 2) {
        fprintf(stderr, "Insufficient buffer memory on %s\n",
        dev_name);
        exit(EXIT_FAILURE);
    }
    buffers = (buffer *)calloc(req.count, sizeof (*buffers));
    if (!buffers) {
        fprintf(stderr, "Out of memory\n");
        exit(EXIT_FAILURE);
    }
    for (n_buffers = 0; n_buffers < req.count; ++n_buffers) {
        struct v4l2_buffer buf;
        CLEAR (buf);
        buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        buf.memory = V4L2_MEMORY_MMAP;
        buf.index = n_buffers;
        if (-1 == xioctl(fd, VIDIOC_QUERYBUF, &buf))
            errno_exit("VIDIOC_QUERYBUF");
        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)
            errno_exit("mmap");
    }
}
static void init_userp(unsigned int buffer_size) {
    struct v4l2_requestbuffers req;
    unsigned int page_size;
    page_size = getpagesize();
    buffer_size = (buffer_size + page_size - 1) & ~(page_size - 1);
    CLEAR (req);
    req.count = 4;
    req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    req.memory = V4L2_MEMORY_USERPTR;
    if (-1 == xioctl(fd, VIDIOC_REQBUFS, &req)) {
        if (EINVAL == errno) {
            fprintf(stderr, "%s does not support "
            "user pointer i/o\n", dev_name);
            exit(EXIT_FAILURE);
        } else {
            errno_exit("VIDIOC_REQBUFS");
        }
    }
    cout<<"VIDIOC_REQBUFS success!"<<endl;
    buffers = (buffer *)calloc(4, sizeof (*buffers));
    if (!buffers) {
        fprintf(stderr, "Out of memory\n");
        exit(EXIT_FAILURE);
    }
    for (n_buffers = 0; n_buffers < 4; ++n_buffers) {
        buffers[n_buffers].length = buffer_size;
        buffers[n_buffers].start = memalign(page_size, buffer_size);
        if (!buffers[n_buffers].start) {
            fprintf(stderr, "Out of memory\n");
            exit(EXIT_FAILURE);
        }
    }
}
static void init_device(void) {
    struct v4l2_capability cap;
    struct v4l2_cropcap cropcap;
    struct v4l2_crop crop;
    struct v4l2_format fmt;
    unsigned int min;
    if (-1 == xioctl(fd, VIDIOC_QUERYCAP, &cap)) {
        if (EINVAL == errno) {
            fprintf(stderr, "%s is no V4L2 device\n",dev_name);
            exit(EXIT_FAILURE);
        } else {
            errno_exit("VIDIOC_QUERYCAP");
        }
    }
    cout<<"VIDIOC_QUERYCAP success!"<<endl;
    if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
        fprintf(stderr, "%s is no video capture device\n", dev_name);
        exit(EXIT_FAILURE);
    }
    //Select video input, video standard and tune here.
    CLEAR (cropcap);
    cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    if (0 == xioctl(fd, VIDIOC_CROPCAP, &cropcap)) {
        crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        crop.c = cropcap.defrect; //reset to default
        if (-1 == xioctl(fd, VIDIOC_S_CROP, &crop)) {
            switch (errno) {
            case EINVAL:
                //Cropping not supported.
                break;
            default:
                //Errors ignored.
                break;
            }
        }
    } else {
        //Errors ignored.
    }
    CLEAR (fmt);
    fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    fmt.fmt.pix.width = 320;
    fmt.fmt.pix.height = 240;
    fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
    fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
    if (-1 == xioctl(fd, VIDIOC_S_FMT, &fmt))
        errno_exit("VIDIOC_S_FMT");
    //Note VIDIOC_S_FMT may change width and height.
    // Buggy driver paranoia.
    min = fmt.fmt.pix.width * 2;
    if (fmt.fmt.pix.bytesperline < min)
        fmt.fmt.pix.bytesperline = min;
    min = fmt.fmt.pix.bytesperline * fmt.fmt.pix.height;
    if (fmt.fmt.pix.sizeimage < min)
        fmt.fmt.pix.sizeimage = min;
    init_mmap();
}
static void close_device(void) {
    if (-1 == close(fd))
        errno_exit("close");
    fd = -1;
}
static void open_device(void) {
    struct stat st;
    cout<<"dev_name"<<dev_name<<endl;
    if (-1 == stat(dev_name, &st)) {
        fprintf(stderr, "Cannot identify 鈥?s鈥? %d, %s\n", dev_name, errno,
        strerror(errno));
        exit(EXIT_FAILURE);
    }

    if (!S_ISCHR (st.st_mode)) {
        fprintf(stderr, "%s is no device\n", dev_name);
        exit(EXIT_FAILURE);
    }
    fd = open(dev_name, O_RDWR | O_NONBLOCK, 0);
    if (-1 == fd) {
        fprintf(stderr, "Cannot open 鈥?s鈥? %d, %s\n",
        dev_name, errno, strerror (errno));
        exit(EXIT_FAILURE);
    }
    cout<<"open success!"<<endl;
}
int main(int argc, char ** argv) {
    io = IO_METHOD_MMAP;
    open_device();
    init_device();
    start_capturing();
    mainloop();
    stop_capturing();
    uninit_device();
    close_device();
    exit(EXIT_SUCCESS);
    return 0;
}

lkppost 2008-10-16 11:32
没人理我,[s:6][s:6][s:6]

jwqacqy 2009-12-10 16:40
你的QT加JPG选项了啊?

duduqq 2009-12-10 21:13
把BUF转成QIMAGE啊

visitorone 2009-12-11 11:43
就只有int save_jpeg(char *buf, int size)是你自己写的好像,其它都是例子的代码

保存成jpeg应该没有这么容易的把,大概看了下,你是将图像数据一个字节一个字节的写进文件里,这个应该是写成PPM文件的方式,不是写成jpeg的,而且你的代码里获取图像数据也是yuv420的格式,应该写成ppm都不会成功。

建议你把const int pixel_format= V4L2_PIX_FMT_YUV420  后面改成RGB24或者GREY,然后用你的方法写成PPM 看看是不是能成功,再考虑找个算法保存成JPEG的。

slbbls 2010-01-06 15:11
为什么我调试的时候在mainloop();下会timeout呢,这是怎么回事?


查看完整版本: [-- Re:linux 下v4l2视频采集的问题 --] [-- top --]



Powered by phpwind v8.7 Code ©2003-2011 phpwind
Gzip disabled