예제 #1
0
static int encode_update(struct videnc_state **vesp, const struct vidcodec *vc,
			 struct videnc_param *prm, const char *fmtp,
			 videnc_packet_h *pkth, void *arg)
{
	struct videnc_state *st;
	int err = 0;
	(void)fmtp;

	if (!vesp || !vc || !prm || !pkth)
		return EINVAL;

	if (*vesp)
		return 0;

	st = mem_zalloc(sizeof(*st), enc_destructor);
	if (!st)
		return ENOMEM;

	st->encprm = *prm;
	st->pkth = pkth;
	st->arg = arg;

	st->fd = open(v4l2.device, O_RDWR);
	if (st->fd == -1) {
		err = errno;
		warning("Opening video device (%m)\n", err);
		goto out;
	}

	err = print_caps(st->fd);
	if (err)
		goto out;

	err = init_mmap(st, st->fd);
	if (err)
		goto out;

	err = query_buffer(st->fd);
	if (err)
		goto out;

	err = start_streaming(st->fd);
	if (err)
		goto out;

	err = fd_listen(st->fd, FD_READ, read_handler, st);
	if (err)
		goto out;

	info("v4l2_codec: video encoder %s: %d fps, %d bit/s, pktsize=%u\n",
	      vc->name, prm->fps, prm->bitrate, prm->pktsize);

 out:
	if (err)
		mem_deref(st);
	else
		*vesp = st;

	return err;
}
예제 #2
0
int main(int argc, char *argv[])
{
    int sockfd, portno, n;
    struct sockaddr_in serv_addr;
    struct hostent *server;
    int opt=1;

    if (argc < 2) {
       fprintf(stderr,"usage %s port [hostname]\n", argv[0]);
       exit(0);
    }
    portno = atoi(argv[1]);
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
        error("ERROR opening socket");
    // Defaults to localhost
    if (argc == 2) {
        server = gethostbyname("localhost");
    } else {
        server = gethostbyname(argv[2]);
    }
    if (server == NULL) {
        fprintf(stderr,"ERROR, no such host\n");
        exit(0);
    }
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr,
         (char *)&serv_addr.sin_addr.s_addr,
         server->h_length);
    serv_addr.sin_port = htons(portno);
    setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,(const char *)&opt,sizeof(int));
    if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
        error("ERROR connecting");

    char buffer[256] = "The quick brown fox jumps over the lazy dog";
    printf("Client Buffer: %s\n",buffer);

    // Writes to socket
    n = write(sockfd, buffer, strlen(buffer));
    if (n < 0)
         error("ERROR writing to socket");

    // Reads from socket
    bzero(buffer,256);
    n = read(sockfd,buffer,255);
    if (n < 0)
         error("ERROR reading from socket");
    
    // Query buffer after receiving
    query_buffer((uint64_t)buffer, strlen(buffer));
    
    printf("%s\n",buffer);
    close(sockfd);
    return 0;
}
예제 #3
0
static void read_handler(int flags, void *arg)
{
	struct videnc_state *st = arg;
	struct v4l2_buffer buf;
	int err;
	(void)flags;

	memset(&buf, 0, sizeof(buf));

	buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
	buf.memory = V4L2_MEMORY_MMAP;
	buf.index = 0;

	if (-1 == xioctl(st->fd, VIDIOC_DQBUF, &buf)) {
		err = errno;
		warning("v4l2_codec: Retrieving Frame (%m)\n", err);
		return;
	}

#if 0
	debug("image captured at %ld, %ld\n",
	       buf.timestamp.tv_sec, buf.timestamp.tv_usec);
#endif

	{
		struct mbuf mb = {0,0,0,0};
		struct h264_hdr hdr;

		mb.buf = st->buffer;
		mb.pos = 4;
		mb.end = buf.bytesused - 4;
		mb.size = buf.bytesused;

		err = h264_hdr_decode(&hdr, &mb);
		if (err) {
			warning("could not decode H.264 header\n");
		}
		else {
			if (h264_is_keyframe(hdr.type))
				++st->stats.n_key;
			else
				++st->stats.n_delta;
		}
	}

	err = h264_packetize(st->buffer, buf.bytesused,
			     st->encprm.pktsize, st->pkth, st->arg);
	if (err) {
		warning("h264_packetize error (%m)\n", err);
	}

	query_buffer(st->fd);
}
예제 #4
0
int main(int argc, char *argv[])
{
    int sockfd, newsockfd, portno;
    socklen_t clilen;
    char buffer[256];
    struct sockaddr_in serv_addr, cli_addr;
    int n;
    int opt=1;

    if (argc < 2) {
        error("ERROR, no port provided\n");
        exit(1);
    }
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
       error("ERROR opening socket");

    bzero((char *) &serv_addr, sizeof(serv_addr));
    portno = atoi(argv[1]);
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(portno);
    setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,(const char *)&opt,sizeof(int));
    if (bind(sockfd, (struct sockaddr *) &serv_addr,
            sizeof(serv_addr)) < 0)
        error("ERROR on binding");
    listen(sockfd,5);
    clilen = sizeof(cli_addr);

    // Waits here
    newsockfd = accept(sockfd,
                (struct sockaddr *) &cli_addr,
                &clilen);
    if (newsockfd < 0)
        error("ERROR on accept");
    bzero(buffer,256);
    n = read(newsockfd, buffer, 255);
    if (n < 0) error("ERROR reading from socket");

    printf("Server Buffer: %s\n", buffer);
    //Query buffer
    query_buffer((uint64_t)&buffer, 256);

    // Returns a confirmation message
    n = write(newsockfd, "I got your message!", 19);
    if (n < 0) error("ERROR writing to socket");
    close(newsockfd);
    close(sockfd);
    return 0;
}
예제 #5
0
파일: linux_hd_test.c 프로젝트: 3a9LL/panda
int main(){
    int f = open("taintfile", O_DIRECT|O_RDWR);
    assert (f != -1);
    struct stat st;
    stat("taintfile", &st);
    assert(st.st_size != 0);
    char *buf;
    // Required for use of O_DIRECT.  Alignment has to be on the order of 512
    // bytes (size of a sector), and size has to be a multiple of the block
    // size.
    posix_memalign((void**)&buf, 512, 9728);
    int r = read(f, buf, 9728);
    if (r == -1){
        printf("Read Error %d\n", errno);
        exit(1);
    }
    
    label_buffer((uint64_t)buf, st.st_size);
    lseek(f, 0, SEEK_SET);
    r = write(f, buf, 9728);
    if (r == -1){
        printf("Write Error %d\n", errno);
        exit(1);
    }
    close(f);
    //memset(buf, 0, 9728); <-- Don't do this

    f = open("taintfile", O_DIRECT|O_RDWR);
    stat("taintfile", &st);
    assert(st.st_size != 0);
    r = read(f, buf, 9728);
    if (r == -1){
        printf("Read 2 Error %d\n", errno);
        exit(1);
    }
    query_buffer((uint64_t)buf, st.st_size);
    close(f);
    free(buf);
    
    return 0;
}
예제 #6
0
static void * comp_proc(void * para)
{
    int i, j;
    int fd;
    int channel;
    int n_buffers = 0;
    unsigned int length, offset;
    int index, num;
    struct buffer_av buf_av;
    int result;
    struct pollfd pfd;
    unsigned int buf_index;
    unsigned int buf_num;
    char * packet_addr;
    struct packet_header pkt_header;
    Query_Buf_Res * buffers = NULL;				//用于保存获取视频数据
    Spct_Data comp_data;

    int got_video[CHS_PER_CARD];
    int got_audio[CHS_PER_CARD];
    struct timeval v_time_stamp[CHS_PER_CARD];
    struct timeval a_time_stamp[CHS_PER_CARD];
    unsigned int last_vtstamp[CHS_PER_CARD];
    unsigned int last_atstamp[CHS_PER_CARD];
    unsigned int duration;


    DebugPrintf("thread compress\n");

    Ip_Cam_Device * ipcam = (Ip_Cam_Device *) para;

    memset(&buf_av, 0, sizeof(buf_av));

    memset(&got_video, 0, sizeof(got_video));
    memset(&got_audio, 0, sizeof(got_audio));
    memset(&last_vtstamp, 0, sizeof(last_vtstamp));
    memset(&last_atstamp, 0, sizeof(last_atstamp));


    fd = ipcam->comp_fd;
    action_fd = fd;
    n_buffers = request_buffer(fd);

    buffers = calloc(n_buffers, sizeof(* buffers));
    if(!buffers)
            EXIT("Out of memory.");

    for(i = 0; i < n_buffers; ++i)
    {
        if(query_buffer(fd, i, &length, &offset) != 0)
                EXIT("VIDIOC_QUERYBUF");
        buffers[i].length = length;
        buffers[i].start = mmap(NULL, length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset);
        DebugPrintf("buffers[%d].start = 0x%x\n",i, buffers[i].start);
        if(MAP_FAILED == buffers[i].start)
                EXIT("mmap");
    }

    for(index = 0; index < n_buffers; index++)
            if(queue_buffer(fd, index) != 0)
                    EXIT("VIDIOC_QBUF");

    if(streaming_on(fd) != 0)
            EXIT("VIDIOC_STREAMON");
    DebugPrintf("card stream on================================\n");
    pfd.fd = fd;
    pfd.events = POLLIN;

    int comp_proc_count = 0;

    //set_action(fd, catch_sen); // fd threshold time
    /*检测ipcam是否处于运行状态*/
    while(ipcam->status == CAM_STATUS_RUN)
    {
        comp_proc_count++;
        /*定时打印信息*/
        if(comp_proc_count == 3000)
        {
            comp_proc_count = 0;
            PrintScreen("\n----- comp_proc thread running -----\n");
        }

        //IsSetaction(fd);
        /*一个结构体,函数阻塞时间为15s*/
        result = poll(&pfd, 1, 15000);

        /*函数调用失败*/
        if(result < 0)
            DebugPrintf("pool ing errro ==================\n");
        /*在规定时间内没有检测到可读套接字*/
        if(result == 0)
        {
            DebugPrintf("pool ing time out --------------\n");
            exit(1);
        }

        if(result < 0)
            continue;
        if(result == 0)
            continue;

        dequeue_buffer(fd, &buf_av);
        buf_index = buf_av.buf_index;
        buf_num = buf_av.length;
        for(i = 0; i < CHS_PER_CARD; i++)
        {
            index = buf_index & 0xff;
            num = buf_num & 0xff;

            buf_index >>= 8;
            buf_num >>= 8;
            if(index != 0xff)
            {
                /*DATA PACKET*/
                channel = i;

                for(j = 0, packet_addr = buffers[index].start; j < num; j++)
                {
                    /*s数据包处理,动态处理就在此实现*/
                    parse_packet(&packet_addr, &pkt_header);

                    //pkt_header.motion_addr, 4 * 9
                    /*捕捉到动作*/
                    if(pkt_header.motion_flag)
                    {
#if RELEASE_MODE
#else
                        PrintScreen("\n-------------receive a motion------------\n\n");
#endif
                        catchonemotion = 1;
                        is_action = 1;
                    }

                    if (pkt_header.videolost_flag)
                    {
                        //DebugPrintf("video lost\n");
                    }

                    if(pkt_header.audio_flag)
                    {//length
                        if(!got_audio[channel])
                        {
                            got_audio[channel] = 1;
                            //a_time_stamp[channel] = buf_av.timestamp;
                            a_time_stamp[channel].tv_usec = ((pkt_header.audio_timestamp % 32768) * 1000ULL * 1000ULL) >> 15;
                            a_time_stamp[channel].tv_sec = (pkt_header.audio_timestamp >> 15) + (a_time_stamp[channel].tv_usec / 1000000);
                            a_time_stamp[channel].tv_usec %= 1000000;
                        }
                        else
                        {
                            duration = pkt_header.audio_timestamp - last_atstamp[channel];
                            a_time_stamp[channel].tv_usec += ((duration % 32768) * 1000ULL * 1000ULL) >> 15;
                            a_time_stamp[channel].tv_sec += (duration >> 15) + (a_time_stamp[channel].tv_usec / 1000000);
                            a_time_stamp[channel].tv_usec %= 1000000;

                        }
                        last_atstamp[channel] = pkt_header.audio_timestamp;

                        //DebugPrintf("audio frame\n");
                        comp_data.channel = channel;
                        comp_data.type = DATA_AUDIO;
                        comp_data.flags = 0;
                        comp_data.timestamp = a_time_stamp[channel];
                        comp_data.size = pkt_header.audio_length;
                        comp_data.data = pkt_header.audio_addr;
                        ipcam->fun(ipcam->datahandler, &comp_data);
                    }

                    if(pkt_header.video_flag)
                    {
                        if(!got_video[channel])
                        {
                            got_video[channel] = 1;
                            //v_time_stamp[channel] = buf_av.timestamp;
                            v_time_stamp[channel].tv_usec = ((pkt_header.video_timestamp % 32768) * 1000ULL * 1000ULL) >> 15;
                            v_time_stamp[channel].tv_sec = (pkt_header.video_timestamp >> 15) + (v_time_stamp[channel].tv_usec / 1000000);
                            v_time_stamp[channel].tv_usec %= 1000000;
                        }
                        else
                        {
                            duration = pkt_header.video_timestamp - last_vtstamp[channel];
                            v_time_stamp[channel].tv_usec += ((duration % 32768) * 1000ULL * 1000ULL) >> 15;
                            v_time_stamp[channel].tv_sec += (duration >> 15) + (v_time_stamp[channel].tv_usec / 1000000);
                            v_time_stamp[channel].tv_usec %= 1000000;
                        }
                        last_vtstamp[channel] = pkt_header.video_timestamp;

                        comp_data.channel = channel;
                        comp_data.type = DATA_VIDEO;
                        comp_data.flags = pkt_header.video_type;
                        comp_data.timestamp = v_time_stamp[channel];
                        comp_data.size = pkt_header.video_length;
                        comp_data.data = pkt_header.video_addr;
                        ipcam->fun(ipcam->datahandler, &comp_data);
                    }
예제 #7
0
파일: main.c 프로젝트: gerpayt/camshot
void *capture_func(void *ptr)
{
    unsigned char *rgb_buffer;
    int ready_buf;
    char cur_name[64];
    int i;
    struct timeval timestamp;

    if( b_shared_mem )
    {
        rgb_buffer = p_shm;
    }
    else
    {
        rgb_buffer = (unsigned char *)malloc(req_width*req_height*3);
    }

    for(;;)
    {
        /* Wait for the start condition */
        pthread_mutex_lock(&cond_mutex);
        pthread_cond_wait(&condition, &cond_mutex);
        pthread_mutex_unlock(&cond_mutex);

        /* queue one buffer and 'refresh it' */
        /* @todo Change 2 to some #define */
        for(i=0; i<2; i++)
        {
            queue_buffer(i);
        }
        for(i=0; i<2 - 1; i++)
        {
            dequeue_buffer();
        }

        /* get the idx of ready buffer */
		ready_buf = dequeue_buffer();

        if( b_verbose )
        {
            printf("Buffer %d ready. Length: %uB\n", ready_buf, image_buffers[ready_buf].length);
        }

        switch( check_pixelformat() )
        {
            case V4L2_PIX_FMT_YUYV:
                /* convert data to rgb */
                if( convert_yuv_to_rgb_buffer(
                                    (unsigned char *)(image_buffers[ready_buf].start), 
                                    rgb_buffer, req_width, req_height) == 0 )
                {
                    if( b_verbose )
                    {
                        printf("\tConverted to rgb.\n");
                    }
                }
                break;
            default:
                print_pixelformat(stderr);
                fprintf(stderr,"\n");
                return NULL;
        }

        timestamp = query_buffer(0);

        /* make the image */

        /* create the file name */
        if( b_named_filename )
        {
            sprintf(cur_name, "%s%s", psz_output_dir, psz_output_filename);
        }
        else if( !b_named_pipe )
            sprintf(cur_name, "%scamshot_%lu.bmp", psz_output_dir, timestamp.tv_sec);
        else
            sprintf(cur_name, "%s", psz_named_pipe);

        switch( e_outfmt )
        {
            case FORMAT_BMP:
                make_bmp(rgb_buffer, 
                         cur_name, 
                         req_width, 
                         req_height);
                break;
            case FORMAT_RGB:
                make_rgb(rgb_buffer, 
                         cur_name, 
                         req_width, 
                         req_height);
                break;
            default:
                fprintf(stderr, "Not supported format requested!\n");
                break;
        }   
    }

    return NULL;
}
예제 #8
0
int __cdecl main(void) 
{
    WSADATA wsaData;
    int iResult;

    SOCKET ListenSocket = INVALID_SOCKET;
    SOCKET ClientSocket = INVALID_SOCKET;

    struct addrinfo *result = NULL;
    struct addrinfo hints;

    int iSendResult;
    char recvbuf[DEFAULT_BUFLEN];
    int recvbuflen = DEFAULT_BUFLEN;
    
    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %d\n", iResult);
        return 1;
    }

    ZeroMemory(&hints, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;

    // Resolve the server address and port
    iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
    if ( iResult != 0 ) {
        printf("getaddrinfo failed with error: %d\n", iResult);
        WSACleanup();
        return 1;
    }

    // Create a SOCKET for connecting to server
    ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
    if (ListenSocket == INVALID_SOCKET) {
        printf("socket failed with error: %ld\n", WSAGetLastError());
        freeaddrinfo(result);
        WSACleanup();
        return 1;
    }

    // Setup the TCP listening socket
    iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
    if (iResult == SOCKET_ERROR) {
        printf("bind failed with error: %d\n", WSAGetLastError());
        freeaddrinfo(result);
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    freeaddrinfo(result);

    iResult = listen(ListenSocket, SOMAXCONN);
    if (iResult == SOCKET_ERROR) {
        printf("listen failed with error: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    // Accept a client socket
    ClientSocket = accept(ListenSocket, NULL, NULL);
    if (ClientSocket == INVALID_SOCKET) {
        printf("accept failed with error: %d\n", WSAGetLastError());
        closesocket(ListenSocket);
        WSACleanup();
        return 1;
    }

    // No longer need server socket
    closesocket(ListenSocket);

    // Receive until the peer shuts down the connection
    do {

        iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
        if (iResult > 0) {
            printf("Bytes received: %d\n", iResult);
			// rwhelan: query buffer
			query_buffer((unsigned int)recvbuf, iResult);
			printf("Addr: 0x%x\n", (unsigned int)recvbuf);
			printf("Contents: %s\n", recvbuf);

        // Echo the buffer back to the sender
            iSendResult = send( ClientSocket, recvbuf, iResult, 0 );
            if (iSendResult == SOCKET_ERROR) {
                printf("send failed with error: %d\n", WSAGetLastError());
                closesocket(ClientSocket);
                WSACleanup();
                return 1;
            }
            printf("Bytes sent: %d\n", iSendResult);
        }
        else if (iResult == 0)
            printf("Connection closing...\n");
        else  {
            printf("recv failed with error: %d\n", WSAGetLastError());
            closesocket(ClientSocket);
            WSACleanup();
            return 1;
        }

    } while (iResult > 0);

    // shutdown the connection since we're done
    iResult = shutdown(ClientSocket, SD_SEND);
    if (iResult == SOCKET_ERROR) {
        printf("shutdown failed with error: %d\n", WSAGetLastError());
        closesocket(ClientSocket);
        WSACleanup();
        return 1;
    }

    // cleanup
    closesocket(ClientSocket);
    WSACleanup();

	printf("Press any key to continue.\n");
	getchar();

    return 0;
}