Esempio n. 1
0
int main(int argc, char *argv[])
{
    // get input arguments

    string configFile = "";
    string video_file_left = "", video_file_right = "", video_directory = "";
    int starting_frame_number = 0;
    bool enable_gamma = false;
    float random_results = -1.0;

    int last_frame_number = -1;

    int last_playback_frame_number = -2;

    ConciseArgs parser(argc, argv);
    parser.add(configFile, "c", "config", "Configuration file containing camera GUIDs, etc.", true);
    parser.add(show_display, "d", "show-dispaly", "Enable for visual debugging display. Will reduce framerate significantly.");
    parser.add(show_display_wait, "w", "show-display-wait", "Optional argument to decrease framerate for lower network traffic when forwarding the display.");
    parser.add(show_unrectified, "u", "show-unrectified", "When displaying images, do not apply rectification.");
    parser.add(disable_stereo, "s", "disable-stereo", "Disable online stereo processing.");
    parser.add(force_brightness, "b", "force-brightness", "Force a brightness setting.");
    parser.add(force_exposure, "e", "force-exposure", "Force an exposure setting.");
    parser.add(quiet_mode, "q", "quiet", "Reduce text output.");
    parser.add(video_file_left, "l", "video-file-left", "Do not use cameras, instead use this video file (also requires a right video file).");
    parser.add(video_file_right, "t", "video-file-right", "Right video file, only for use with the -l option.");
    parser.add(video_directory, "i", "video-directory", "Directory to search for videos in (for playback).");
    parser.add(starting_frame_number, "f", "starting-frame", "Frame to start at when playing back videos.");
    parser.add(display_hud, "v", "hud", "Overlay HUD on display images.");
    parser.add(record_hud, "x", "record-hud", "Record the HUD display.");
    parser.add(file_frame_skip, "p", "skip", "Number of frames skipped in recording (for playback).");
    parser.add(enable_gamma, "g", "enable-gamma", "Turn gamma on for both cameras.");
    parser.add(random_results, "R", "random-results", "Number of random points to produce per frame.  Can be a float in which case we'll take a random sample to decide if to produce the last one.  Disables real stereo processing.  Only for debugging / analysis!");
    parser.add(publish_all_images, "P", "publish-all-images", "Publish all images to LCM");
    parser.parse();

    // parse the config file
    if (ParseConfigFile(configFile, &stereoConfig) != true)
    {
        fprintf(stderr, "Failed to parse configuration file, quitting.\n");
        return -1;
    }

    if (video_file_left.length() > 0
        && video_file_right.length() <= 0) {

        fprintf(stderr, "Error: for playback you must specify both "
            "a right and left video file. (Only got a left one.)\n");

        return -1;
    }

     if (video_file_left.length() <= 0
        && video_file_right.length() > 0) {

        fprintf(stderr, "Error: for playback you must specify both "
            "a right and left video file. (Only got a right one.)\n");

        return -1;
    }

    recording_manager.Init(stereoConfig);

    // attempt to load video files / directories
    if (video_file_left.length() > 0) {
        if (recording_manager.LoadVideoFiles(video_file_left, video_file_right) != true) {
            // don't have videos, bail out.
            return -1;
        }
    }

    if (video_directory.length() > 0) {
        if (recording_manager.SetPlaybackVideoDirectory(video_directory) != true) {
            // bail
            return -1;
        }
    }

    recording_manager.SetQuietMode(quiet_mode);
    recording_manager.SetPlaybackFrameNumber(starting_frame_number);



    uint64 guid = stereoConfig.guidLeft;
    uint64 guid2 = stereoConfig.guidRight;

    // start up LCM
    lcm_t * lcm;
    lcm = lcm_create (stereoConfig.lcmUrl.c_str());


    unsigned long elapsed;

    Hud hud;


    // --- setup control-c handling ---
    struct sigaction sigIntHandler;

    sigIntHandler.sa_handler = control_c_handler;
    sigemptyset(&sigIntHandler.sa_mask);
    sigIntHandler.sa_flags = 0;

    sigaction(SIGINT, &sigIntHandler, NULL);
    // --- end ctrl-c handling code ---

    dc1394error_t   err;
    dc1394error_t   err2;


    // tell opencv to use only one core so that we can manage our
    // own threading without a fight
    setNumThreads(1);

    if (recording_manager.UsingLiveCameras()) {
        d = dc1394_new ();
        if (!d)
            cerr << "Could not create dc1394 context" << endl;

        d2 = dc1394_new ();
        if (!d2)
            cerr << "Could not create dc1394 context for camera 2" << endl;

        camera = dc1394_camera_new (d, guid);
        if (!camera)
        {
            cerr << "Could not create dc1394 camera... quitting." << endl;
            exit(1);
        }

        camera2 = dc1394_camera_new (d2, guid2);
        if (!camera2)
            cerr << "Could not create dc1394 camera for camera 2" << endl;
        // reset the bus
        dc1394_reset_bus(camera);
        dc1394_reset_bus(camera2);

        // setup
        err = setup_gray_capture(camera, DC1394_VIDEO_MODE_FORMAT7_1);
        DC1394_ERR_CLN_RTN(err, cleanup_and_exit(camera), "Could not setup camera");

        err2 = setup_gray_capture(camera2, DC1394_VIDEO_MODE_FORMAT7_1);
        DC1394_ERR_CLN_RTN(err2, cleanup_and_exit(camera2), "Could not setup camera number 2");

        // enable camera
        err = dc1394_video_set_transmission(camera, DC1394_ON);
        DC1394_ERR_CLN_RTN(err, cleanup_and_exit(camera), "Could not start camera iso transmission");
        err2 = dc1394_video_set_transmission(camera2, DC1394_ON);
        DC1394_ERR_CLN_RTN(err2, cleanup_and_exit(camera2), "Could not start camera iso transmission for camera number 2");

        InitBrightnessSettings(camera, camera2, enable_gamma);
    }

    if (show_display) {

        namedWindow("Input", CV_WINDOW_AUTOSIZE | CV_WINDOW_KEEPRATIO);
        namedWindow("Input2", CV_WINDOW_AUTOSIZE | CV_WINDOW_KEEPRATIO);
        namedWindow("Stereo", CV_WINDOW_AUTOSIZE | CV_WINDOW_KEEPRATIO);

        namedWindow("Left Block", CV_WINDOW_AUTOSIZE | CV_WINDOW_KEEPRATIO);
        namedWindow("Right Block", CV_WINDOW_AUTOSIZE | CV_WINDOW_KEEPRATIO);

        namedWindow("Debug 1", CV_WINDOW_AUTOSIZE | CV_WINDOW_KEEPRATIO);
        namedWindow("Debug 2", CV_WINDOW_AUTOSIZE | CV_WINDOW_KEEPRATIO);



        setMouseCallback("Input", onMouse); // for drawing disparity lines
        setMouseCallback("Stereo", onMouseStereo, &hud); // for drawing disparity lines

        moveWindow("Input", stereoConfig.displayOffsetX + 100, stereoConfig.displayOffsetY + 100);
        moveWindow("Stereo", stereoConfig.displayOffsetX + 100, stereoConfig.displayOffsetY + 370);
        moveWindow("Input2", stereoConfig.displayOffsetX + 478, stereoConfig.displayOffsetY + 100);
        moveWindow("Left Block", stereoConfig.displayOffsetX + 900, stereoConfig.displayOffsetY + 100);
        moveWindow("Right Block", stereoConfig.displayOffsetX + 1400, stereoConfig.displayOffsetY + 100);

        moveWindow("Debug 1", stereoConfig.displayOffsetX + 900, stereoConfig.displayOffsetY + 670);
        moveWindow("Debug 2", stereoConfig.displayOffsetX + 1400, stereoConfig.displayOffsetY + 670);

    } // show display

    if (show_display || publish_all_images) {
        // if a channel exists, subscribe to it
        if (stereoConfig.stereo_replay_channel.length() > 0) {
            stereo_replay_sub = lcmt_stereo_subscribe(lcm, stereoConfig.stereo_replay_channel.c_str(), &stereo_replay_handler, &hud);
        }

        if (stereoConfig.pose_channel.length() > 0) {
            mav_pose_t_sub = mav_pose_t_subscribe(lcm, stereoConfig.pose_channel.c_str(), &mav_pose_t_handler, &hud);
        }

        if (stereoConfig.gps_channel.length() > 0) {
            mav_gps_data_t_sub = mav_gps_data_t_subscribe(lcm, stereoConfig.gps_channel.c_str(), &mav_gps_data_t_handler, &hud);
        }

        if (stereoConfig.baro_airspeed_channel.length() > 0) {
            baro_airspeed_sub = lcmt_baro_airspeed_subscribe(lcm, stereoConfig.baro_airspeed_channel.c_str(), &baro_airspeed_handler, &hud);
        }

        if (stereoConfig.servo_out_channel.length() > 0) {
            servo_out_sub = lcmt_deltawing_u_subscribe(lcm, stereoConfig.servo_out_channel.c_str(), &servo_out_handler, &hud);
        }

        if (stereoConfig.battery_status_channel.length() > 0) {
            battery_status_sub = lcmt_battery_status_subscribe(lcm, stereoConfig.battery_status_channel.c_str(), &battery_status_handler, &hud);
        }

        if (stereoConfig.cpu_info_channel1.length() > 0) {
            cpu_info_sub1 = lcmt_cpu_info_subscribe(lcm, stereoConfig.cpu_info_channel1.c_str(), &cpu_info_handler, &recording_manager);
            cpu_info_sub2 = lcmt_cpu_info_subscribe(lcm, stereoConfig.cpu_info_channel2.c_str(), &cpu_info_handler, &recording_manager);
            cpu_info_sub3 = lcmt_cpu_info_subscribe(lcm, stereoConfig.cpu_info_channel3.c_str(), &cpu_info_handler, &recording_manager);
        }

        if (stereoConfig.log_size_channel1.length() > 0) {
            log_size_sub1 = lcmt_log_size_subscribe(lcm, stereoConfig.log_size_channel1.c_str(), &log_size_handler, &hud);
            log_size_sub2 = lcmt_log_size_subscribe(lcm, stereoConfig.log_size_channel2.c_str(), &log_size_handler, &hud);
            log_size_sub3 = lcmt_log_size_subscribe(lcm, stereoConfig.log_size_channel3.c_str(), &log_size_handler, &hud);
        }

    } // end show_display || publish_all_images

    // load calibration
    OpenCvStereoCalibration stereoCalibration;

    if (LoadCalibration(stereoConfig.calibrationDir, &stereoCalibration) != true)
    {
        cerr << "Error: failed to read calibration files. Quitting." << endl;
        return -1;
    }

    int inf_disparity_tester, disparity_tester;
    disparity_tester = GetDisparityForDistance(10, stereoCalibration, &inf_disparity_tester);

    std::cout << "computed disparity is = " << disparity_tester << ", inf disparity = " << inf_disparity_tester << std::endl;

    // subscribe to the stereo control channel
    stereo_control_sub = lcmt_stereo_control_subscribe(lcm, stereoConfig.stereoControlChannel.c_str(), &lcm_stereo_control_handler, NULL);


    Mat imgDisp;
    Mat imgDisp2;

    // initilize default parameters
    //PushbroomStereoState state; // HACK

    state.disparity = stereoConfig.disparity;
    state.zero_dist_disparity = stereoConfig.infiniteDisparity;
    state.sobelLimit = stereoConfig.interestOperatorLimit;
    state.horizontalInvarianceMultiplier = stereoConfig.horizontalInvarianceMultiplier;
    state.blockSize = stereoConfig.blockSize;
    state.random_results = random_results;
    state.check_horizontal_invariance = true;

    if (state.blockSize > 10 || state.blockSize < 1)
    {
        fprintf(stderr, "Warning: block size is very large "
            "or small (%d).  Expect trouble.\n", state.blockSize);
    }

    state.sadThreshold = stereoConfig.sadThreshold;

    state.mapxL = stereoCalibration.mx1fp;
    state.mapxR = stereoCalibration.mx2fp;
    state.Q = stereoCalibration.qMat;
    state.show_display = show_display;

    state.lastValidPixelRow = stereoConfig.lastValidPixelRow;

    Mat matL, matR;
    bool quit = false;

    if (recording_manager.UsingLiveCameras()) {
        matL = GetFrameFormat7(camera);
        matR = GetFrameFormat7(camera2);

        if (recording_manager.InitRecording(matL, matR) != true) {
            // failed to init recording, things are going bad.  bail.
            return -1;
        }

        // before we start, turn the cameras on and set the brightness and exposure
        MatchBrightnessSettings(camera, camera2, true, force_brightness, force_exposure);

        // grab a few frames and send them over LCM for the user
        // to verify that everything is working
        if (!show_display && !publish_all_images) {
            printf("Sending init images over LCM... ");
            fflush(stdout);

            for (int i = 0; i < 5; i++) {

                matL = GetFrameFormat7(camera);
                SendImageOverLcm(lcm, "stereo_image_left", matL, 50);

                matR = GetFrameFormat7(camera2);
                SendImageOverLcm(lcm, "stereo_image_right", matR, 50);

                // don't send these too fast, otherwise we'll flood the ethernet link
                // and not actually be helpful

                // wait one second
                printf(".");
                fflush(stdout);

                sleep(1);
            }
            printf(" done.\n");
        }

    } // recording_manager.UsingLiveCameras()

    // spool up worker threads
    PushbroomStereo pushbroom_stereo;

    // start the framerate clock
    struct timeval start, now;
    gettimeofday( &start, NULL );

    while (quit == false) {

        // get the frames from the camera
        if (recording_manager.UsingLiveCameras()) {
            // we would like to match brightness every frame
            // but that would really hurt our framerate
            // match brightness every 10 frames instead
            if (numFrames % MATCH_BRIGHTNESS_EVERY_N_FRAMES == 0)
            {
                MatchBrightnessSettings(camera, camera2);
            }

            // capture images from the cameras
            matL = GetFrameFormat7(camera);
            matR = GetFrameFormat7(camera2);

            // record video
            recording_manager.AddFrames(matL, matR);


        } else {
            // using a video file -- get the next frame
            recording_manager.GetFrames(matL, matR);
        }

        cv::vector<Point3f> pointVector3d;
        cv::vector<uchar> pointColors;
        cv::vector<Point3i> pointVector2d; // for display
        cv::vector<Point3i> pointVector2d_inf; // for display

        // do the main stereo processing
        if (disable_stereo != true) {

            gettimeofday( &now, NULL );
            double before = now.tv_usec + now.tv_sec * 1000 * 1000;

            pushbroom_stereo.ProcessImages(matL, matR, &pointVector3d, &pointColors, &pointVector2d, state);

            gettimeofday( &now, NULL );
            double after = now.tv_usec + now.tv_sec * 1000 * 1000;

            timer_sum += after-before;
            timer_count ++;

        }

        // build an LCM message for the stereo data
        lcmt_stereo msg;


        if (recording_manager.UsingLiveCameras() || stereo_lcm_msg == NULL) {
            msg.timestamp = getTimestampNow();
        } else {
            // if we are replaying videos, preserve the timestamp of the original video
            msg.timestamp = stereo_lcm_msg->timestamp;

        }


        msg.number_of_points = (int)pointVector3d.size();

        float x[msg.number_of_points];
        float y[msg.number_of_points];
        float z[msg.number_of_points];
        uchar grey[msg.number_of_points];

        for (unsigned int i=0;i<pointVector3d.size();i++) {

            x[i] = pointVector3d[i].x / stereoConfig.calibrationUnitConversion;
            y[i] = pointVector3d[i].y / stereoConfig.calibrationUnitConversion;
            z[i] = pointVector3d[i].z / stereoConfig.calibrationUnitConversion;
            grey[i] = pointColors[i];
        }

        msg.x = x;
        msg.y = y;
        msg.z = z;
        msg.grey = grey;
        msg.frame_number = recording_manager.GetFrameNumber();

        if (recording_manager.UsingLiveCameras()) {
            msg.frame_number = msg.frame_number - 1;  // minus one since recording manager has
                                                      // already recorded this frame (above in
                                                      // AddFrames) but we haven't made a message
                                                      // for it yet
        }


        msg.video_number = recording_manager.GetRecVideoNumber();

        // publish the LCM message
        if (last_frame_number != msg.frame_number) {
            lcmt_stereo_publish(lcm, "stereo", &msg);
            last_frame_number = msg.frame_number;
        }

        if (publish_all_images) {
            if (recording_manager.GetFrameNumber() != last_playback_frame_number) {
                SendImageOverLcm(lcm, "stereo_image_left", matL, 80);
                SendImageOverLcm(lcm, "stereo_image_right", matR, 80);

                last_playback_frame_number = recording_manager.GetFrameNumber();
            }

            //process LCM until there are no more messages
            // this allows us to drop frames if we are behind
            while (NonBlockingLcm(lcm)) {}
        }

        Mat matDisp, remapL, remapR;

        if (show_display) {
            // we remap again here because we're just in display
            Mat remapLtemp(matL.rows, matL.cols, matL.depth());
            Mat remapRtemp(matR.rows, matR.cols, matR.depth());

            remapL = remapLtemp;
            remapR = remapRtemp;

            remap(matL, remapL, stereoCalibration.mx1fp, Mat(), INTER_NEAREST);
            remap(matR, remapR, stereoCalibration.mx2fp, Mat(), INTER_NEAREST);

            remapL.copyTo(matDisp);

            //process LCM until there are no more messages
            // this allows us to drop frames if we are behind
            while (NonBlockingLcm(lcm)) {}
        } // end show_display


        if (show_display) {

            for (unsigned int i=0;i<pointVector2d.size();i++) {
                int x2 = pointVector2d[i].x;
                int y2 = pointVector2d[i].y;
                //int sad = pointVector2d[i].z;
                rectangle(matDisp, Point(x2,y2), Point(x2+state.blockSize, y2+state.blockSize), 0,  CV_FILLED);
                rectangle(matDisp, Point(x2+1,y2+1), Point(x2+state.blockSize-1, y2-1+state.blockSize), 255);

            }

            // draw pixel blocks
            if (lineLeftImgPosition >= 0 && lineLeftImgPositionY > 1) {
                DisplayPixelBlocks(remapL, remapR, lineLeftImgPosition - state.blockSize/2, lineLeftImgPositionY - state.blockSize/2, state, &pushbroom_stereo);
            }

            // draw a line for the user to show disparity
            DrawLines(remapL, remapR, matDisp, lineLeftImgPosition, lineLeftImgPositionY, state.disparity, state.zero_dist_disparity);


            if (visualize_stereo_hits == true && stereo_lcm_msg != NULL) {

                // transform the points from 3D space back onto the image's 2D space
                vector<Point3f> lcm_points;
                Get3DPointsFromStereoMsg(stereo_lcm_msg, &lcm_points);

                // draw the points on the unrectified image (to see these
                // you must pass the -u flag)
                Draw3DPointsOnImage(matL, &lcm_points, stereoCalibration.M1, stereoCalibration.D1, stereoCalibration.R1, 128);

            }

            if (show_unrectified == false) {

                imshow("Input", remapL);
                imshow("Input2", remapR);
            } else {
                imshow("Input", matL);
                imshow("Input2", matR);
            }


            if (display_hud) {
                Mat with_hud;

                recording_manager.SetHudNumbers(&hud);

                hud.DrawHud(matDisp, with_hud);

                if (record_hud) {
                    // put this frame into the HUD recording
                    recording_manager.RecFrameHud(with_hud);

                }

                imshow("Stereo", with_hud);
            } else {
                imshow("Stereo", matDisp);
            }


            char key = waitKey(show_display_wait);

            if (key != 255 && key != -1)
            {
                cout << endl << key << endl;
            }

            switch (key)
            {
                case 'T':
                    state.disparity --;
                    break;
                case 'R':
                    state.disparity ++;
                    break;

                case 'w':
                    state.sobelLimit += 10;
                    break;

                case 's':
                    state.sobelLimit -= 10;
                    break;

                case 'd':
                    state.horizontalInvarianceMultiplier -= 0.1;
                    break;

                case 'D':
                    state.horizontalInvarianceMultiplier += 0.1;
                    break;

                case 'g':
                    state.blockSize ++;
                    break;

                case 'b':
                    state.blockSize --;
                    if (state.blockSize < 1) {
                        state.blockSize = 1;
                    }
                    break;

                case 'Y':
                    state.sadThreshold += 50;
                    break;

                case 'y':
                    state.sadThreshold ++;
                    break;

                case 'h':
                    state.sadThreshold --;
                    break;

                case 'H':
                    state.sadThreshold -= 50;
                    break;

                case 'm':
                    if (recording_manager.UsingLiveCameras()) {
                        MatchBrightnessSettings(camera, camera2, true, force_brightness, force_exposure);
                    }
                    break;

                case '1':
                    force_brightness --;
                    if (recording_manager.UsingLiveCameras()) {
                        MatchBrightnessSettings(camera, camera2, true, force_brightness, force_exposure);
                    }
                    break;

                case '2':
                    force_brightness ++;
                    if (recording_manager.UsingLiveCameras()) {
                        MatchBrightnessSettings(camera, camera2, true, force_brightness, force_exposure);
                    }
                    break;

                case '3':
                    force_exposure --;
                    if (recording_manager.UsingLiveCameras()) {
                        MatchBrightnessSettings(camera, camera2, true, force_brightness, force_exposure);
                    }
                    break;

                case '4':
                    force_exposure ++;
                    if (recording_manager.UsingLiveCameras()) {
                        MatchBrightnessSettings(camera, camera2, true, force_brightness, force_exposure);
                    }
                    break;

                case '5':
                    // to show SAD boxes
                    state.sobelLimit = 0;
                    state.sadThreshold = 255;
                    break;

                case 'I':
                    state.check_horizontal_invariance = !state.check_horizontal_invariance;
                    break;

                case '.':
                    recording_manager.SetPlaybackFrameNumber(recording_manager.GetFrameNumber() + 1);
                    break;

                case ',':
                    recording_manager.SetPlaybackFrameNumber(recording_manager.GetFrameNumber() - 1);
                    break;

                case '>':
                    recording_manager.SetPlaybackFrameNumber(recording_manager.GetFrameNumber() + 50);
                    break;

                case '<':
                    recording_manager.SetPlaybackFrameNumber(recording_manager.GetFrameNumber() - 50);
                    break;

                //case 'k':
                //    state.zero_dist_disparity ++;
                 //   break;

                case 'l':
                    state.zero_dist_disparity --;
                    break;

                case 'o':
                    inf_sad_add --;
                    break;

                case 'p':
                    inf_sad_add ++;
                    break;

                case '[':
                    y_offset --;
                    if (y_offset < 0) {
                        y_offset = 0;
                    }
                    break;

                case ']':
                    y_offset ++;
                    break;

                case 'v':
                    display_hud = !display_hud;
                    break;

                case 'c':
                    hud.SetClutterLevel(hud.GetClutterLevel() + 1);
                    break;

                case 'C':
                    hud.SetClutterLevel(hud.GetClutterLevel() - 1);
                    break;

                case '}':
                    hud.SetPitchRangeOfLens(hud.GetPitchRangeOfLens() + 1);
                    break;
                case '{':
                    hud.SetPitchRangeOfLens(hud.GetPitchRangeOfLens() - 1);
                    break;

                case 'S':
                    // take a screen cap of the left and right images
                    // useful for putting into a stereo tuner
                    printf("\nWriting left.ppm...");
                    imwrite("left.ppm", remapL);

                    printf("\nWriting right.ppm...");
                    imwrite("right.ppm", remapR);

                    printf("\ndone.");
                    break;

                case 'V':
                    // record the HUD
                    record_hud = true;
                    recording_manager.RestartRecHud();
                    break;

                    /*
                case 'j':
                    state.debugJ --;
                    break;

                case 'J':
                    state.debugJ ++;
                    break;

                case 'i':
                    state.debugI --;
                    break;

                case 'I':
                    state.debugI ++;
                    break;

                case 'k':
                    state.debugDisparity --;
                    break;

                case 'K':
                    state.debugDisparity ++;
                    break;

                    */

                case 'q':
                    quit = true;
                    break;
            }

            if (key != 255 && key != -1)
            {
                cout << "sadThreshold = " << state.sadThreshold << endl;
                cout << "sobelLimit = " << state.sobelLimit << endl;
                cout << "horizontalInvarianceMultiplier = " << state.horizontalInvarianceMultiplier << endl;
                cout << "brightness: " << force_brightness << endl;
                cout << "exposure: " << force_exposure << endl;
                cout << "disparity = " << state.disparity << endl;
                cout << "inf_disparity = " << state.zero_dist_disparity << endl;
                cout << "inf_sad_add = " << inf_sad_add << endl;
                cout << "blockSize = " << state.blockSize << endl;
                cout << "frame_number = " << recording_manager.GetFrameNumber() << endl;
                cout << "y offset = " << y_offset << endl;
                cout << "PitchRangeOfLens = " << hud.GetPitchRangeOfLens() << endl;
            }
        } // end show_display

        numFrames ++;

        // check for new LCM messages
        NonBlockingLcm(lcm);

        if (quiet_mode == false || numFrames % 100 == 0) {
            // compute framerate
            gettimeofday( &now, NULL );

            elapsed = (now.tv_usec / 1000 + now.tv_sec * 1000) -
            (start.tv_usec / 1000 + start.tv_sec * 1000);

            printf("\r%d frames (%lu ms) - %4.1f fps | %4.1f ms/frame, stereo: %f", numFrames, elapsed, (float)numFrames/elapsed * 1000, elapsed/(float)numFrames, timer_sum/(double)timer_count);
            fflush(stdout);
        }


    } // end main while loop

    printf("\n\n");

    destroyWindow("Input");
    destroyWindow("Input2");
    destroyWindow("Stereo");

    // close camera
    if (recording_manager.UsingLiveCameras()) {
        StopCapture(d, camera);
        StopCapture(d2, camera2);
    }

    return 0;
}
Esempio n. 2
0
int main(int argc, char *argv[])
{
    FILE* imagefile;
    dc1394camera_t *camera;
    unsigned int width, height;
    dc1394video_frame_t *frame=NULL;
    //dc1394featureset_t features;
    dc1394_t * d;
    dc1394camera_list_t * list;
    dc1394error_t err;

    d = dc1394_new ();
    err=dc1394_camera_enumerate (d, &list);
    DC1394_ERR_RTN(err,"Failed to enumerate cameras");

    if (list->num == 0) {
        dc1394_log_error("No cameras found");
        return 1;
    }

    camera = dc1394_camera_new (d, list->ids[0].guid);
    if (!camera) {
        dc1394_log_error("Failed to initialize camera with guid %llx", list->ids[0].guid);
        return 1;
    }
    dc1394_camera_free_list (list);

    printf("Using camera with GUID %"PRIx64"\n", camera->guid);

    /*-----------------------------------------------------------------------
     *  setup capture
     *-----------------------------------------------------------------------*/

    err=dc1394_video_set_iso_speed(camera, DC1394_ISO_SPEED_400);
    DC1394_ERR_CLN_RTN(err,cleanup_and_exit(camera),"Could not set iso speed");

    err=dc1394_video_set_mode(camera, DC1394_VIDEO_MODE_1280x960_RGB8);
    DC1394_ERR_CLN_RTN(err,cleanup_and_exit(camera),"Could not set video mode\n");

    err=dc1394_video_set_framerate(camera, DC1394_FRAMERATE_7_5);
    DC1394_ERR_CLN_RTN(err,cleanup_and_exit(camera),"Could not set framerate\n");

    err=dc1394_capture_setup(camera,4, DC1394_CAPTURE_FLAGS_DEFAULT);
    DC1394_ERR_CLN_RTN(err,cleanup_and_exit(camera),"Could not setup camera-\nmake sure that the video mode and framerate are\nsupported by your camera\n");

    /*-----------------------------------------------------------------------
     *  have the camera start sending us data
     *-----------------------------------------------------------------------*/
    err=dc1394_video_set_transmission(camera, DC1394_ON);
    DC1394_ERR_CLN_RTN(err,cleanup_and_exit(camera),"Could not start camera iso transmission\n");

    /*-----------------------------------------------------------------------
     *  capture one frame
     *-----------------------------------------------------------------------*/
    err=dc1394_capture_dequeue(camera, DC1394_CAPTURE_POLICY_WAIT, &frame);
    DC1394_ERR_CLN_RTN(err,cleanup_and_exit(camera),"Could not capture a frame\n");

    /*-----------------------------------------------------------------------
     *  stop data transmission
     *-----------------------------------------------------------------------*/
    err=dc1394_video_set_transmission(camera,DC1394_OFF);
    DC1394_ERR_CLN_RTN(err,cleanup_and_exit(camera),"Could not stop the camera?\n");

    /*-----------------------------------------------------------------------
     *  save image as 'Image.pgm'
     *-----------------------------------------------------------------------*/
    imagefile=fopen(IMAGE_FILE_NAME, "wb");

    if( imagefile == NULL) {
        perror( "Can't create output file");
        cleanup_and_exit(camera);
    }

    dc1394_get_image_size_from_video_mode(camera, DC1394_VIDEO_MODE_1280x960_RGB8, &width, &height);
    fprintf(imagefile,"P6\n%u %u\n255\n", width, height);
    fwrite(frame->image, 1, height*width*3, imagefile);
    fclose(imagefile);
    printf("wrote: " IMAGE_FILE_NAME " (%d image bytes)\n",height*width*3);

    /*-----------------------------------------------------------------------
     *  close camera
     *-----------------------------------------------------------------------*/
    dc1394_video_set_transmission(camera, DC1394_OFF);
    dc1394_capture_stop(camera);
    dc1394_camera_free(camera);
    dc1394_free (d);
    return 0;
}
Esempio n. 3
0
struct response_struct delete_command(char* token_vector[], int token_count){

  char* part            = NULL;
  char key[KEY_LEN]     = "";
  int length            = 0;
  int i = 0;
  int retval;
  struct keydb_column *tuple = NULL;
  struct keydb_column *head = NULL;
  struct keydb_column *tmp;
  int responselen = 0;
  struct response_struct response;

  response.status = 0;

  if ((response.msg = malloc(sizeof(char) * MSG_SIZE)) == NULL) {
    perror(NULL);
    cleanup_and_exit();
  }

  if (token_count < 2) {
    response.status = 1;
    sprintf(response.msg, "Not enough arguments");
    return response;
  }

  for (i = 1; (part = token_vector[i]) && (i < MAX_ARGS); i++) {
    length += strlen(part);
    if (length > KEY_LEN - 1) {
      response.status = 1;
      sprintf(response.msg, "Key too large");
      return response;
    }

    // Save away the list of key composites
    if ((tmp = malloc(sizeof(struct keydb_column))) == NULL) {
      perror(NULL);
      cleanup_and_exit();
    }
    strncpy(tmp->column, part, KEY_LEN);
    tmp->next = NULL;
    if (tuple == NULL) {
      tuple = tmp;
      head = tmp;
    } else {
      tuple->next = tmp;
      tuple = tuple->next;
      tuple->next = NULL;
    }
    strcat(key, part);
  } 

  if (length == 0) {
    response.status = 1;
    sprintf(response.msg, "Failed to extract key.");
    return response;
  }

  retval = delete_record(key);

  if (retval == 0) {
    if (composite_delete(KEYDB_FD, head) == -1) {
      fprintf(stderr, "Composite key delete failed.");
      response.status = 1;
      sprintf(response.msg, "Internal Error.");
    } else {
      sprintf(response.msg, "Delete OK.");
    }
  } else if (retval == -2) {
    response.status = 1;
    sprintf(response.msg, "Not found.");
  } else {
    response.status = 1;
    sprintf(response.msg, "Could not delete record.");
  } 

  while (head) { // free our list of key composites.
    tmp = head->next;
    free(head);
    head = tmp;
  };
  return response;
}
Esempio n. 4
0
void signal_close(int not_used)
{
    cleanup_and_exit(EXIT_SUCCESS);
}
Esempio n. 5
0
//--------------------------------------------------------------------
int of1394VideoGrabber::initGrabber()
{
	// moved from constructor
	int i;
	
	printf("Making new camera\n");
	
	d = dc1394_new ();
	
	err=dc1394_camera_enumerate (d, &list);
    DC1394_ERR_RTN(err,"Failed to enumerate cameras");
	
	if (list->num == 0) {
		if(err!=0 && bVerbose)printf("\n No cameras found\n ");
		return 1;
	}
	
	camera = dc1394_camera_new (d, list->ids[0].guid);
	if (!camera) {
		if(err!=0 && bVerbose)printf("\n Failed to initialize camera with guid %PRIx64", list->ids[0].guid);
		return 1;
	}
	dc1394_camera_free_list (list);
	

	
	/*-----------------------------------------------------------------------
	 *  setup capture
	 *-----------------------------------------------------------------------*/
	

	

	dc1394_video_set_mode(camera, DC1394_VIDEO_MODE_FORMAT7_0);
	uint32_t f, f2;
	dc1394_format7_get_image_size(camera, DC1394_VIDEO_MODE_FORMAT7_0, &f, &f2);
	
	err=dc1394_capture_setup(camera,4, DC1394_CAPTURE_FLAGS_DEFAULT);
    DC1394_ERR_CLN_RTN(err,cleanup_and_exit(camera),"Could not setup camera-\nmake sure that the video mode and framerate are\nsupported by your camera\n");

	
	
	/*-----------------------------------------------------------------------
	 *  have the camera start sending us data
	 *-----------------------------------------------------------------------*/
	err=dc1394_video_set_transmission(camera, DC1394_ON);
    DC1394_ERR_CLN_RTN(err,cleanup_and_exit(camera),"Could not start camera iso transmission\n");

	dc1394_get_image_size_from_video_mode(camera, video_mode, &width, &height);
	if(err != DC1394_SUCCESS){
		cout<<"get image size error: "<<err<<endl;
	}
	printf("Size from video mode = %i wide %i high\n", width, height);

	pixels	= new unsigned char[width*height*3]; // x3 for RGB
	pixels2	= new unsigned char[width*height*3]; // x3 for RGB

	tex.allocate(width,height,GL_LUMINANCE);

	err = dc1394_capture_dequeue( camera, DC1394_CAPTURE_POLICY_WAIT, &frame ) ;
    DC1394_ERR_CLN_RTN(err,cleanup_and_exit(camera),"Could not capture a frame\n");

	memcpy( pixels, frame->image, width * height*3) ;
	
	dc1394_capture_enqueue( camera, frame ) ;


	
	ofSleepMillis(10);
	startThread(true, false);
	
	failedToInit = false;
	dc1394_feature_set_mode(camera, DC1394_FEATURE_EXPOSURE, DC1394_FEATURE_MODE_MANUAL);
	dc1394_feature_set_mode(camera, DC1394_FEATURE_BRIGHTNESS, DC1394_FEATURE_MODE_MANUAL);
	dc1394_feature_set_mode(camera, DC1394_FEATURE_GAMMA, DC1394_FEATURE_MODE_AUTO);
	dc1394_feature_set_mode(camera, DC1394_FEATURE_SHUTTER, DC1394_FEATURE_MODE_MANUAL);
	dc1394_feature_set_mode(camera, DC1394_FEATURE_GAIN, DC1394_FEATURE_MODE_AUTO);
	dc1394_feature_set_mode(camera, DC1394_FEATURE_IRIS, DC1394_FEATURE_MODE_AUTO);
	dc1394_feature_set_mode(camera, DC1394_FEATURE_WHITE_BALANCE, DC1394_FEATURE_MODE_AUTO);
	dc1394_feature_set_mode(camera, DC1394_FEATURE_TEMPERATURE, DC1394_FEATURE_MODE_AUTO);
	dc1394_feature_set_mode(camera, DC1394_FEATURE_WHITE_SHADING, DC1394_FEATURE_MODE_AUTO);	
	dc1394_feature_set_mode(camera, DC1394_FEATURE_SATURATION, DC1394_FEATURE_MODE_AUTO);		
	dc1394_feature_set_mode(camera, DC1394_FEATURE_HUE, DC1394_FEATURE_MODE_AUTO);		
	
	//Print features
	dc1394_feature_get_all(camera, &features);
	dc1394_feature_print_all(&features, stdout);

	return 0;
}
Esempio n. 6
0
 int main(int argc, char *argv[])
 {
     FILE* imagefile;
     dc1394camera_t *camera;
     unsigned int width, height;
     dc1394video_frame_t *frame=NULL;
     //dc1394featureset_t features;
     dc1394_t * d;
     dc1394camera_list_t * list;
     dc1394error_t err;
     int counter = 0;
     d = dc1394_new ();
     if (!d)
         return 1;
     err=dc1394_camera_enumerate (d, &list);
     DC1394_ERR_RTN(err,"Failed to enumerate cameras");

     if (list->num == 0) {
         dc1394_log_error("No cameras found");
         return 1;
     }

     camera = dc1394_camera_new (d, list->ids[0].guid);
     if (!camera) {
         dc1394_log_error("Failed to initialize camera with guid %llx", list->ids[0].guid);
         return 1;
     }
     dc1394_camera_free_list (list);

     printf("Using camera with GUID %" PRIx64 "\n", camera->guid);

     /*-----------------------------------------------------------------------
      *  setup capture
      *-----------------------------------------------------------------------*/

     err=dc1394_video_set_iso_speed(camera, DC1394_ISO_SPEED_400);
     DC1394_ERR_CLN_RTN(err,cleanup_and_exit(camera),"Could not set iso speed");

     err=dc1394_video_set_mode(camera, DC1394_VIDEO_MODE_FORMAT7_7);
     DC1394_ERR_CLN_RTN(err,cleanup_and_exit(camera),"Could not set video mode\n");

     err=dc1394_video_set_framerate(camera, DC1394_FRAMERATE_7_5);
     DC1394_ERR_CLN_RTN(err,cleanup_and_exit(camera),"Could not set framerate\n");

     err=dc1394_capture_setup(camera,4, DC1394_CAPTURE_FLAGS_DEFAULT);
     DC1394_ERR_CLN_RTN(err,cleanup_and_exit(camera),"Could not setup camera-\nmake sure that the video mode and framerate are\nsupported by your camera\n");

     /*-----------------------------------------------------------------------
      *  have the camera start sending us data
      *-----------------------------------------------------------------------*/
     err=dc1394_video_set_transmission(camera, DC1394_ON);
     DC1394_ERR_CLN_RTN(err,cleanup_and_exit(camera),"Could not start camera iso transmission\n");
     for(;;){
         /*-----------------------------------------------------------------------
          *  capture one frame
          *-----------------------------------------------------------------------*/
         err=dc1394_capture_dequeue(camera, DC1394_CAPTURE_POLICY_WAIT, &frame);
         DC1394_ERR_CLN_RTN(err,cleanup_and_exit(camera),"Could not capture a frame\n");

         dc1394_get_image_size_from_video_mode(camera, DC1394_VIDEO_MODE_FORMAT7_7, &width, &height);

         cv::Mat img = cv::Mat(height, width, CV_8U, frame->image);

         err = dc1394_capture_enqueue(camera, frame);
         frame=NULL;
         cv::imshow("Image", img);

         printf("Frame %d\n", counter);
         counter++;
         cv::waitKey(10);

      }
     /*-----------------------------------------------------------------------
      *  stop data transmission
      *-----------------------------------------------------------------------*/
     err=dc1394_video_set_transmission(camera,DC1394_OFF);
     DC1394_ERR_CLN_RTN(err,cleanup_and_exit(camera),"Could not stop the camera?\n");

     /*-----------------------------------------------------------------------
      *  close camera
      *-----------------------------------------------------------------------*/
     dc1394_video_set_transmission(camera, DC1394_OFF);
     dc1394_capture_stop(camera);
     dc1394_camera_free(camera);
     dc1394_free (d);
     return 0;
 }
Esempio n. 7
0
static NORETURN
fatal(const char *msg)
{
  fprintf(stderr, "%s: %s\n", progname, msg);
  cleanup_and_exit(1);
}
Esempio n. 8
0
int
fn_translate(int key) {
	int out = key;

	switch (key) {
	case XK_Left:		out=XK_Home; 		break;
	case XK_Right:		out=XK_End;		break;
	case XK_Up:		out=XK_Prior;		break;
	case XK_Down:		out=XK_Next;		break;
	case XK_BackSpace:	out=XK_Delete;		break;
	case XK_Tab:		out=XK_Insert;		break;
	case XK_Escape:		out=XK_asciitilde;	break;
	case XK_1:		out=XK_F1;		break;
	case XK_2:		out=XK_F2;		break;
	case XK_3:		out=XK_F3;		break;
	case XK_4:		out=XK_F4;		break;
	case XK_5:		out=XK_F5;		break;
	case XK_6:		out=XK_F6;		break;
	case XK_7:		out=XK_F7;		break;
	case XK_8:		out=XK_F8;		break;
	case XK_9:		out=XK_F9;		break;
	case XK_0:		out=XK_F10;		break;
	case XK_minus:		out=XK_F11;		break;
	case XK_equal:		out=XK_F12;		break;

	case XK_a:		out=XK_adiaeresis;	break;
	case XK_o:		out=XK_odiaeresis;	break;
	case XK_u:		out=XK_udiaeresis;	break;
	case XK_A:		out=XK_Adiaeresis;	break;
	case XK_O:		out=XK_Odiaeresis;	break;
	case XK_U:		out=XK_Udiaeresis;	break;
	case XK_s:		out=XK_ssharp;		break;
	case XK_S:		out=XK_section;		break;
	case XK_e:		out=XK_EuroSign;	break;
	case XK_m:		out=XK_mu;		break;
	case XK_grave:		out=XK_degree;		break;

	case XK_bracketleft:	
		ev_zoom_out(0, 0);
		out=0;
		break;

	case XK_bracketright:	
		ev_zoom_in(0, 0);
		out=0;
		break;

	case XK_x:
		open_emergency_xterm();
		out=0;
		break;

	case XK_f:
		refresh_framerate();
		out=0;
		break;

	case XK_L:
		system("fbvnc 127.0.0.1:1");
		cleanup_and_exit("Bye.", EXIT_OK);
		break;

	case XK_Q:
#if 0
		/* Hack: don't quit if viewing localhost - could be
		 * the primary display. */
		if (!strcmp(hostname, "localhost") ||
		    !strcmp(hostname, "127.0.0.1")) break;
#endif
		cleanup_and_exit("Bye.", EXIT_OK);
		break;
	}
	return out;
}
Esempio n. 9
0
int
ev_quit(fbvnc_event_t *ev, fbvnc_overlay_t *ov) {
	cleanup_and_exit("Bye.", EXIT_OK);
	return 1;
}
stereoCam::stereoCam() {

   
   // Find cameras on the 1394 buses
   d = dc1394_new ();

   // Enumerate cameras connected to the PC
   err = dc1394_camera_enumerate (d, &list);
   if ( err != DC1394_SUCCESS )
   {
       fprintf( stderr, "Unable to look for cameras\n\n"
             "Please check \n"
	     "  - if the kernel modules `ieee1394',`raw1394' and `ohci1394' "
	     "are loaded \n"
             "  - if you have read/write access to /dev/raw1394\n\n");
       nThisCam=-1;
       //return 1;
    }

    if (list->num == 0)
    {
        fprintf( stderr, "No cameras found!\n");
        nThisCam=-1;
        //return 1;
    }

    printf( "There were %d camera(s) found attached to your PC\n", list->num  );

    // Identify cameras. Use the first stereo camera that is found
    for ( nThisCam = 0; nThisCam < list->num; nThisCam++ )
    {
        camera = dc1394_camera_new(d, list->ids[nThisCam].guid);

        if(!camera)
        {
            printf("Failed to initialize camera with guid %llx", 
		   list->ids[nThisCam].guid);
            continue;
        }

        printf( "Camera %d model = '%s'\n", nThisCam, camera->model );

        if ( isStereoCamera(camera))
        {
            printf( "Using this camera\n" );
            break;
        }
        dc1394_camera_free(camera);
   }

   if ( nThisCam == list->num )
   {
      printf( "No stereo cameras were detected\n" );
      nThisCam=-1;
      //return 0;
   }
   // Free memory used by the camera list
   dc1394_camera_free_list (list);


   // query information about this stereo camera
   err = queryStereoCamera( camera, &stereoCamera );
   if ( err != DC1394_SUCCESS )
   {
      fprintf( stderr, "Cannot query all information from camera\n" );
      cleanup_and_exit( camera );
   }

   if ( stereoCamera.nBytesPerPixel != 2 )
   {
      // can't handle XB3 3 bytes per pixel
      fprintf( stderr,
	       "Example not updated to work with XB3 in 3 camera mode yet!\n" );
      cleanup_and_exit( stereoCamera.camera );
   }

   // set the capture mode
   printf( "Setting stereo video capture mode\n" );
   err = setStereoVideoCapture( &stereoCamera );
   if ( err != DC1394_SUCCESS )
   {
      fprintf( stderr, "Could not set up video capture mode\n" );
      cleanup_and_exit( stereoCamera.camera );
   }

   // have the camera start sending us data
   printf( "Start transmission\n" );
   err = startTransmission( &stereoCamera );
   if ( err != DC1394_SUCCESS )
   {
      fprintf( stderr, "Unable to start camera iso transmission\n" );
      cleanup_and_exit( stereoCamera.camera );
   }

   // give the auto-gain algorithms a chance to catch up
   //   printf( "Giving auto-gain algorithm a chance to stabilize\n" );
   //   sleep( 5 );

   // Allocate all the buffers.
   // Unfortunately color processing is a bit inefficient 
   // because of the number of
   // data copies.  Color data needs to be
   // - de-interleaved into separate bayer tile images
   // - color processed into RGB images
   // - de-interleaved to extract the green channel 
   //   for stereo (or other mono conversion)

   // size of buffer for all images at mono8
   nBufferSize = stereoCamera.nRows *
                                stereoCamera.nCols *
                                stereoCamera.nBytesPerPixel;
   // allocate a buffer to hold the de-interleaved images
   pucDeInterlacedBuffer = new unsigned char[ nBufferSize ];
   pucRGBBuffer 	= new unsigned char[ 3 * nBufferSize ];
   pucGreenBuffer 	= new unsigned char[ nBufferSize ];

   // do stereo processing

   printf( "Getting TriclopsContext from camera (slowly)... \n" );
   e = getTriclopsContextFromCamera( &stereoCamera, &triclops );
   TRIERR(e);
   printf( "...got it\n" );

   // make sure we are in subpixel mode
   e = triclopsSetSubpixelInterpolation( triclops, 1 );
   TRIERR(e);
   e = triclopsSetDisparityMapping(triclops,0,60);
   TRIERR(e);
   e = triclopsSetDisparityMappingOn(triclops,1);
   TRIERR(e);
   e = triclopsSetUniquenessValidationMapping(triclops,0);
   TRIERR(e);
   e = triclopsSetTextureValidationMapping(triclops,0);
   TRIERR(e);

   isInRoutine=false;

}
Esempio n. 11
0
int
main (int argc, char *argv[])
{
	/*
	 * The gnome-keyring startup is not as simple as I wish it could be.
	 *
	 * It's often started in the primordial stages of a session, where
	 * there's no DBus, and no proper X display. This is the strange world
	 * of PAM.
	 *
	 * When started with the --login option, we do as little initialization
	 * as possible. We expect a login password on the stdin, and unlock
	 * or create the login keyring.
	 *
	 * Then later we expect gnome-keyring-dameon to be run again with the
	 * --start option. This second gnome-keyring-daemon will hook the
	 * original daemon up with environment variables necessary to initialize
	 * itself and bring it into the session. This second daemon usually exits.
	 *
	 * Without either of these options, we follow a more boring and
	 * predictable startup.
	 */

	/*
	 * Before we do ANYTHING, we drop privileges so we don't become
	 * a security issue ourselves.
	 */
	gkd_capability_obtain_capability_and_drop_privileges ();

#ifdef WITH_STRICT
	g_setenv ("DBUS_FATAL_WARNINGS", "1", FALSE);
	if (!g_getenv ("G_DEBUG"))
		g_log_set_always_fatal (G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING);
#endif

#if !GLIB_CHECK_VERSION(2,35,0)
	g_type_init ();
#endif

#ifdef HAVE_LOCALE_H
	/* internationalisation */
	setlocale (LC_ALL, "");
#endif

#ifdef HAVE_GETTEXT
	bindtextdomain (GETTEXT_PACKAGE, GNOMELOCALEDIR);
	textdomain (GETTEXT_PACKAGE);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
#endif

	egg_libgcrypt_initialize ();

	/* Send all warning or error messages to syslog */
	prepare_logging ();

	parse_arguments (&argc, &argv);

	/* The --version option. This is machine parseable output */
	if (run_version) {
		g_print ("gnome-keyring-daemon: %s\n", VERSION);
		g_print ("testing: %s\n",
#ifdef WITH_DEBUG
		         "enabled");
#else
		         "disabled");
#endif
		exit (0);
	}

	/* The --start option */
	if (run_for_start) {
		if (discover_other_daemon (initialize_daemon_at, TRUE)) {
			/*
			 * Another daemon was initialized, print out environment
			 * for any callers, and quit or go comatose.
			 */
			print_environment ();
			if (run_foreground)
				while (sleep(0x08000000) == 0);
			cleanup_and_exit (0);
		}

	/* The --replace option */
	} else if (run_for_replace) {
		discover_other_daemon (replace_daemon_at, FALSE);
		if (control_directory)
			g_message ("Replacing daemon, using directory: %s", control_directory);
		else
			g_message ("Could not find daemon to replace, staring normally");
	}

	/* Initialize the main directory */
	gkd_util_init_master_directory (control_directory);

	/* Initialize our daemon main loop and threading */
	loop = g_main_loop_new (NULL, FALSE);

	/* Initialize our control socket */
	if (!gkd_control_listen ())
		return FALSE;

	if (perform_unlock) {
		login_password = read_login_password (STDIN);
		atexit (clear_login_password);
	}

	/* The --login option. Delayed initialization */
	if (run_for_login) {
		timeout_id = g_timeout_add_seconds (LOGIN_TIMEOUT, (GSourceFunc) on_login_timeout, NULL);

	/* Not a login daemon. Startup stuff now.*/
	} else {
		/* These are things that can run before forking */
		if (!gkr_daemon_startup_steps (run_components))
			cleanup_and_exit (1);
	}

	signal (SIGPIPE, SIG_IGN);

	/* The whole forking and daemonizing dance starts here. */
	fork_and_print_environment();

	g_unix_signal_add (SIGTERM, on_signal_term, loop);
	g_unix_signal_add (SIGHUP, on_signal_term, loop);
	g_unix_signal_add (SIGUSR1, on_signal_usr1, loop);

	/* Prepare logging a second time, since we may be in a different process */
	prepare_logging();

	/* Remainder initialization after forking, if initialization not delayed */
	if (!run_for_login) {
		gkr_daemon_initialize_steps (run_components);

		/*
		 * Close stdout and so that the caller knows that we're
		 * all initialized, (when run in foreground mode).
		 *
		 * However since some logging goes to stdout, redirect that
		 * to stderr. We don't want the caller confusing that with
		 * valid output anyway.
		 */
		if (dup2 (2, 1) < 1)
			g_warning ("couldn't redirect stdout to stderr");

		g_debug ("initialization complete");
	}

	g_main_loop_run (loop);

	/* This wraps everything up in order */
	egg_cleanup_perform ();

	g_free (control_directory);

	g_debug ("exiting cleanly");
	return 0;
}
Esempio n. 12
0
/*
 * *************************************************************
 * main of connection server
 * *************************************************************
*/
int main(int argc, char *argv[])
{

   srv_opts_t run_options;
   int RequestCmd;
   void *res;


   initialize( &run_options );
   get_arguments ( argc, argv, &run_options );

   if( run_options.run_as_daemon )
   {
      if( (run_options.error_code = start_daemon( &run_options )) != E_NOERR )
      {
         do_log(&run_options, LOG_CRITERROR);
         cleanup_and_exit( &run_options );
      }
   }

   if( (run_options.error_code = make_socket( &run_options )) != E_NOERR )
   {
      do_log(&run_options, LOG_CRITERROR);
      cleanup_and_exit( &run_options );
   }


   if( prepareThreads( &run_options ) != E_NOERR )
   {
         do_log(&run_options, LOG_CRITERROR);
         cleanup_and_exit( &run_options );
   }
   else
   {
      if( (run_options.error_code = ctl_create_thread( &run_options, MAINCTL_THREAD_NUM)) != E_NOERR )
      {
         do_log(&run_options, LOG_CRITERROR);
         cleanup_and_exit( &run_options );
      }
   }

// while no exit request
   RequestCmd = 0;
   do
   {

      if( (run_options.error_code = wait_client( &run_options )) != E_NOERR )
      {
         do_log(&run_options, LOG_CRITERROR);
         cleanup_and_exit( &run_options );
      }
      else
      {
         if( (run_options.error_code = get_request( &run_options )) != E_NOERR )
         {
            do_log(&run_options, LOG_CRITERROR);
            cleanup_and_exit( &run_options );
         }
         else
         {
            switch( RequestCmd =  parse_req( run_options.p_rcv_buf ) )
            {
               case CTLREQ_EXIT:
                  sprintf(run_options.p_rsp_buf, "Assume exit: %s\n", run_options.p_rcv_buf );
                  send_response(&run_options);
                  close(run_options.cli_socket);
                  break;
               case CTLREQ_API:
                  sprintf(run_options.p_rsp_buf, "Assume API: %s\n", run_options.p_rcv_buf );
                  send_response(&run_options);
                  close(run_options.cli_socket);
                  break;
               default:
                  // assume telnet request
                  sprintf(run_options.p_rsp_buf, "Assume telnet: %s\n", run_options.p_rcv_buf );
                  send_response(&run_options);
                  close(run_options.cli_socket);
                  break;
            }
         }
      }

   } while( RequestCmd != CTLREQ_EXIT );

   if( pthread_attr_destroy(&run_options.tattr) != 0 )
   {
      run_options.error_code = E_FAIL;
      run_options.sys_errno = errno;
      sprintf( run_options.logbuffer, "destroy attr failed, errno was %d\n", errno );
      do_log(&run_options, LOG_WARN);
   }

   run_options.mainctl_run = 0;
   run_options.api_run = 0;
   run_options.telnet_run = 0;

   if( run_options.tinfo[MAINCTL_THREAD_NUM].thread_id >= 0 )
   {
      pthread_join(run_options.tinfo[MAINCTL_THREAD_NUM].thread_id, &res);
   }

   if( run_options.tinfo[API_THREAD_NUM].thread_id >= 0 )
   {
      pthread_join(run_options.tinfo[API_THREAD_NUM].thread_id, &res);
   }

   if( run_options.tinfo[TELNET_THREAD_NUM].thread_id >= 0 )
   {
      pthread_join(run_options.tinfo[TELNET_THREAD_NUM].thread_id, &res);
   }

   pthread_cancel(run_options.tinfo[MAINCTL_THREAD_NUM].thread_id);
   pthread_cancel(run_options.tinfo[API_THREAD_NUM].thread_id);
   pthread_cancel(run_options.tinfo[TELNET_THREAD_NUM].thread_id);

   // and die
   cleanup_and_exit( &run_options );
}
Esempio n. 13
0
 void exit_with_code(const LineInfo& line_info, const int exit_code)
 {
     Debug::println(System::Color::error, line_info.to_string());
     cleanup_and_exit(exit_code);
 }
Esempio n. 14
0
int main( int argc, char *argv[] )
{
   dc1394camera_t* 	camera;
   dc1394error_t 	err;
   dc1394_t * d;
   dc1394camera_list_t * list;
   unsigned int nThisCam;

   // Find cameras on the 1394 buses
   d = dc1394_new ();

   // Enumerate cameras connected to the PC
   err = dc1394_camera_enumerate (d, &list);
   if ( err != DC1394_SUCCESS )
   {
       fprintf( stderr, "Unable to look for cameras\n\n"
             "Please check \n"
	         "  - if the kernel modules `ieee1394',`raw1394' and `ohci1394' "
	         "are loaded \n"
	         "  - if you have read/write access to /dev/raw1394\n\n");
       return 1;
    }

    if (list->num == 0)
    {
        fprintf( stderr, "No cameras found!\n");
        return 1;
    }

    printf( "There were %d camera(s) found attached to your PC\n", list->num  );

    // Identify cameras. Use the first stereo camera that is found
    for ( nThisCam = 0; nThisCam < list->num; nThisCam++ )
    {
        camera = dc1394_camera_new(d, list->ids[nThisCam].guid);

        if(!camera)
        {
            printf("Failed to initialize camera with guid %llx", list->ids[nThisCam].guid);
            continue;
        }

        printf( "Camera %d model = '%s'\n", nThisCam, camera->model );

        if ( isStereoCamera(camera))
        {
            printf( "Using this camera\n" );
            break;
        }
        dc1394_camera_free(camera);
   }

   if ( nThisCam == list->num )
   {
      printf( "No stereo cameras were detected\n" );
      return 0;
   }

   // Free memory used by the camera list
   dc1394_camera_free_list (list);

   PGRStereoCamera_t stereoCamera;

   // query information about this stereo camera
   err = queryStereoCamera( camera, &stereoCamera );
   if ( err != DC1394_SUCCESS )
   {
      fprintf( stderr, "Cannot query all information from camera\n" );
      cleanup_and_exit( camera );
   }

   // set the capture mode
   printf( "Setting stereo video capture mode\n" );
   err = setStereoVideoCapture( &stereoCamera );
   if ( err != DC1394_SUCCESS )
   {
      fprintf( stderr, "Could not set up video capture mode\n" );
      cleanup_and_exit( stereoCamera.camera );
   }

   // have the camera start sending us data
   printf( "Start transmission\n" );
   err = startTransmission( &stereoCamera );
   if ( err != DC1394_SUCCESS )
   {
      fprintf( stderr, "Unable to start camera iso transmission\n" );
      cleanup_and_exit( stereoCamera.camera );
   }

   // give the auto-gain algorithms a chance to catch up
   printf( "Wait for the auto-gain algorithm to stabilize\n" );
   sleep( 5 );


   // Allocate all the buffers.
   // Unfortunately color processing is a bit inefficient because of the number of
   // data copies.  Color data needs to be
   // - de-interleaved into separate bayer tile images
   // - color processed into RGB images
   // - de-interleaved to extract the green channel for stereo (or other mono conversion)

   // size of capture buffer
   unsigned int   nBufferSize = stereoCamera.nRows *
                                stereoCamera.nCols *
                                stereoCamera.nBytesPerPixel;
   // allocate a buffer to hold the de-interleaved images
   unsigned char* pucDeInterlacedBuffer = new unsigned char[ nBufferSize ];

   if ( stereoCamera.bColor )
   {
      unsigned char* pucRGBBuffer 	= new unsigned char[ 3 * nBufferSize ];
      unsigned char* pucGreenBuffer 	= new unsigned char[ nBufferSize ];
      unsigned char* pucRightRGB	= NULL;
      unsigned char* pucLeftRGB		= NULL;
      unsigned char* pucCenterRGB	= NULL;
      TriclopsInput input;

      // get the images from the capture buffer and do all required processing
      // note: produces a TriclopsInput that can be used for stereo processing
      extractImagesColor( &stereoCamera,
			  DC1394_BAYER_METHOD_NEAREST,
			  pucDeInterlacedBuffer,
			  pucRGBBuffer,
			  pucGreenBuffer,
			  &pucRightRGB,
			  &pucLeftRGB,
			  &pucCenterRGB,
			  &input );

      // write the color images to file
      if ( !writePpm( "right.ppm", pucRightRGB, stereoCamera.nCols, stereoCamera.nRows ) )
	 printf( "wrote right.ppm\n" );
      if ( !writePpm( "left.ppm", pucLeftRGB, stereoCamera.nCols, stereoCamera.nRows ) )
	 printf( "wrote left.ppm\n" );
      if ( pucCenterRGB != pucLeftRGB )
	 if ( !writePpm( "center.ppm", pucCenterRGB, stereoCamera.nCols, stereoCamera.nRows ) )
	    printf( "wrote center.ppm\n" );

      delete[] pucRGBBuffer;
      delete[] pucGreenBuffer;
   }
   else
   {
      unsigned char* pucRightMono	= NULL;
      unsigned char* pucLeftMono	= NULL;
      unsigned char* pucCenterMono	= NULL;
      TriclopsInput input;
      // get the images from the capture buffer and do all required processing
      // note: produces a TriclopsInput that can be used for stereo processing
      extractImagesMono( &stereoCamera,
			  pucDeInterlacedBuffer,
			  &pucRightMono,
			  &pucLeftMono,
			  &pucCenterMono,
			  &input );


      // write the greyscale images to file
      if ( !writePgm( "right.pgm", pucRightMono, stereoCamera.nCols, stereoCamera.nRows ) )
	 printf( "wrote right.pgm\n" );
      if ( !writePgm( "left.pgm", pucLeftMono, stereoCamera.nCols, stereoCamera.nRows ) )
	 printf( "wrote left.pgm\n" );
      if ( pucCenterMono != pucLeftMono )
	 if ( !writePgm( "center.pgm", pucCenterMono, stereoCamera.nCols, stereoCamera.nRows ) )
	    printf( "wrote center.pgm\n" );
   }

   printf( "Stop transmission\n" );
   //  Stop data transmission
   if ( dc1394_video_set_transmission( stereoCamera.camera, DC1394_OFF ) != DC1394_SUCCESS )
   {
      fprintf( stderr, "Couldn't stop the camera?\n" );
   }

   delete[] pucDeInterlacedBuffer;

   // close camera
   cleanup_and_exit( camera );

   return 0;
}
Esempio n. 15
0
void
gl_setpalettecolor(int i, int r, int g, int b) {
	cleanup_and_exit("palette not implemented", EXIT_ERROR);
}
Esempio n. 16
0
int main(int argc, char* argv[])
{
	struct stat st;

	init_libxpwn(&argc, argv);
	libxpwn_log(logCB);
	libxpwn_loglevel(2);

	printf("---------------------------PLEASE READ THIS---------------------------\n");
	printf("Please make certain that all iTunes related processes are not running\n");
	printf("at this time (use Task Manager, etc. to end them).\n");
	printf("---------------------------PLEASE READ THIS---------------------------\n\n\n");

	if(argc < 3) {
		printf("usage: %s <custom.ipsw> <n82ap|m68ap|n45ap> [loglevel]\n", argv[0]);
		printf("n82ap = 3G iPhone, m68ap = First-generation iPhone, n45ap = iPod touch\n");
		return 0;
	}

	if(argc >= 4) {
		int logLevel;
		sscanf(argv[3], "%d", &logLevel);
		libxpwn_loglevel(logLevel);
	}

	if(stat("restore.img3", &st) < 0) {
		fprintf(stderr, "missing restore.img3\n");
		return 1;
	}

	Stage = 0;
	Status = Disconnected;

	char ibssName[100];
	char wtfName[100];
	sprintf(ibssName, "Firmware/dfu/iBSS.%s.RELEASE.dfu", argv[2]);
	sprintf(wtfName, "Firmware/dfu/WTF.%s.RELEASE.dfu", argv[2]);

	data = NULL;
	loadZipFile(argv[1], &data, "Firmware/dfu/WTF.s5l8900xall.RELEASE.dfu");
	loadZipFile(argv[1], &data, ibssName);
	loadZipFile(argv[1], &data, wtfName);
	loadZipFile(argv[1], &data, "Restore.plist");

	AbstractFile* xallFile = getFileFromOutputState(&data, "Firmware/dfu/WTF.s5l8900xall.RELEASE.dfu");
	AbstractFile* wtfFile = getFileFromOutputState(&data, wtfName);
	AbstractFile* ibssFile = getFileFromOutputState(&data, ibssName);
	AbstractFile* restoreFile = getFileFromOutputState(&data, "Restore.plist");

	GetTempPath(MAX_PATH, tmpFilePath);

	strcat(tmpFilePath, "/restore");
	if(stat(tmpFilePath, &st) < 0) {
		mkdir(tmpFilePath, 0755);
	}

	strcpy(tmpFirmwarePath, tmpFilePath);
	strcat(tmpFirmwarePath, "/Firmware");
	if(stat(tmpFirmwarePath, &st) < 0) {
		mkdir(tmpFirmwarePath, 0755);
	}

	strcpy(tmpDFUPath, tmpFirmwarePath);
	strcat(tmpDFUPath, "/dfu");
	if(stat(tmpDFUPath, &st) < 0) {
		mkdir(tmpDFUPath, 0755);
	}

	strcpy(tmpXALLPath, tmpFilePath);
	strcat(tmpXALLPath, "/");
	strcat(tmpXALLPath, "Firmware/dfu/WTF.s5l8900xall.RELEASE.dfu");

	strcpy(tmpWTFPath, tmpFilePath);
	strcat(tmpWTFPath, "/");
	strcat(tmpWTFPath, wtfName);

	strcpy(tmpIBSSPath, tmpFilePath);
	strcat(tmpIBSSPath, "/");
	strcat(tmpIBSSPath, ibssName);

	strcpy(tmpRestorePath, tmpFilePath);
	strcat(tmpRestorePath, "/");
	strcat(tmpRestorePath, "Restore.plist");

	FILE* file;
	void* buffer;
	size_t length;

	length = xallFile->getLength(xallFile);
	buffer = malloc(length);
	xallFile->read(xallFile, buffer, length);
       	file = fopen(tmpXALLPath, "wb");
	fwrite(buffer, 1, length, file);
	fclose(file);
	free(buffer);
	xallFile->close(xallFile);

	length = wtfFile->getLength(wtfFile);
	buffer = malloc(length);
	wtfFile->read(wtfFile, buffer, length);
       	file = fopen(tmpWTFPath, "wb");
	fwrite(buffer, 1, length, file);
	fclose(file);
	free(buffer);
	wtfFile->close(wtfFile);

	length = ibssFile->getLength(ibssFile);
	buffer = malloc(length);
	ibssFile->read(ibssFile, buffer, length);
       	file = fopen(tmpIBSSPath, "wb");
	fwrite(buffer, 1, length, file);
	fclose(file);
	free(buffer);
	ibssFile->close(ibssFile);

	extractedIPSWPath = argv[1];
	length = restoreFile->getLength(restoreFile);
	buffer = malloc(length);
	restoreFile->read(restoreFile, buffer, length);
       	file = fopen(tmpRestorePath, "wb");
	fwrite(buffer, 1, length, file);
	fclose(file);
	free(buffer);
	restoreFile->close(restoreFile);

	extractedIPSWPath = tmpFilePath;
	bootImagePath = "restore.img3";

	fprintf(stdout, "\nGetting iPhone/iPod status...\n");
	fflush(stdout);

	if(LoadWindowsDLL() < 0) {
		printf("Failed to load iTunes Mobile Device driver!\n");
		cleanup_and_exit();
	}
	
	mach_error_t ret;
	struct am_device_notification *notif; 
	
	ret = AMDeviceNotificationSubscribe(notification, 0, 0, 0, &notif);
	if(ret < 0) {
		printf("Failed to subscribe for device notifications!\n");
		cleanup_and_exit();
	}
	
	ret = AMRestoreRegisterForDeviceNotifications(
						dfu_connect_callback,
						recovery_connect_callback,
						dfu_disconnect_callback,
						recovery_disconnect_callback,
						0,
						NULL);
						
	if(ret < 0) {
		printf("Failed to subscribe for device restore notifications!\n");
		cleanup_and_exit();
	}


	sleep(2);

	char responseBuffer[10];
	int countdown;

	if(Status == Disconnected) {
connectDevice:
		fprintf(stdout, "Is your iPhone/iPod connected to your computer via USB?\n");
		fprintf(stdout, "Please answer (y/n): ");
		fflush(stdout);
		fgets(responseBuffer, 10, stdin);
		if(responseBuffer[0] == 'y' || responseBuffer[0] == 'Y') {
			goto isPoweringOn;
		} else if(responseBuffer[0] == 'n' || responseBuffer[0] == 'N') {
			fprintf(stdout, "Please connect your iPhone/iPod to your computer\n");
			fprintf(stdout, "Press enter when you have connected your iPhone/iPod... ");
			fflush(stdout);
			fgets(responseBuffer, 10, stdin);
			sleep(2);
			if(Status != Disconnected) {
				goto turnOffDevice;
			} else {
isPoweringOn:
				fprintf(stdout, "Is your iPhone currently powering on?\n");
				fprintf(stdout, "Please answer (y/n): ");
				fflush(stdout);
				fgets(responseBuffer, 10, stdin);
				if(responseBuffer[0] == 'y' || responseBuffer[0] == 'Y') {
					fprintf(stdout, "Waiting for iPhone/iPod to power on...\n");
					fflush(stdout);
					while(Status == Disconnected) {
						sleep(1);
					}
					goto turnOffDevice;
				} else if(responseBuffer[0] == 'n' || responseBuffer[0] == 'N') {
					goto beginDFU;
				} else {
					goto isPoweringOn;
				}
			}
		} else {
			goto connectDevice;
		}
	} else {
turnOffDevice:
		fprintf(stdout, "Please turn off your iPhone/iPod without disconnecting the cable connecting it to the computer\n");
		fprintf(stdout, "Press enter when you have turned off your iPhone/iPod... ");
		fflush(stdout);
		fgets(responseBuffer, 10, stdin);

		fprintf(stdout, "Waiting for iPhone/iPod to power off...\n");
		fflush(stdout);
		while(Status != Disconnected) {
			sleep(1);
		}
	}

beginDFU:
	fprintf(stdout, "\n!!! Your device should now be off. If it is not, please make sure it is before proceeding !!!\n\n");

	fprintf(stdout, "Timing is crucial for the following tasks. I will ask you to do the following (DON'T START YET):\n");
	fprintf(stdout, "\t1. Press and hold down the power button for five seconds\n");
	fprintf(stdout, "\t2. Without letting go of the power button, press and hold down the power AND home buttons for ten seconds\n");
	fprintf(stdout, "\t3. Without letting go of the home button, release the power button\n");
	fprintf(stdout, "\t4. Wait 30 seconds while holding down the home button\n");
	fprintf(stdout, "\nTry to get the timing as correct as possible, but don't fret if you miss it by a few seconds. It might still work, and if it doesn't, you can always try again. If you fail, you can always just turn the phone completely off by holding power and home for ten seconds, then pushing power to turn it back on.\n");
	fprintf(stdout, "\nAre you ready to begin?\n");
	fprintf(stdout, "Please answer (y/n): ");
	fflush(stdout);
	fgets(responseBuffer, 10, stdin);
	if(responseBuffer[0] != 'y' && responseBuffer[0] != 'Y')
		goto beginDFU;

	for(countdown = 5; countdown > 0; countdown--) {
		fprintf(stdout, "Beginning process in %d seconds...\n", countdown);
		fflush(stdout);
		sleep(1);
	}

	fprintf(stdout, "\nPress and hold down the POWER button (you should now be just holding the power button)... ");
	fflush(stdout);

	for(countdown = 5; countdown > 0; countdown--) {
		fprintf(stdout, "%d... ", countdown);
		fflush(stdout);
		sleep(1);
	}


	fprintf(stdout, "\n\nPress and hold down the HOME button, DO NOT LET GO OF THE POWER BUTTON (you should now be just holding both the power and home buttons)... ");
	fflush(stdout);

	for(countdown = 10; countdown > 0; countdown--) {
		fprintf(stdout, "%d... ", countdown);
		fflush(stdout);
		sleep(1);
	}

	fprintf(stdout, "\n\nRelease the POWER button, DO NOT LET GO OF THE HOME BUTTON (you should now be just holding the home button)... ");
	fflush(stdout);

	Stage = 2;

	for(countdown = 30; countdown > 0; countdown--) {
		if(Status != Disconnected)
			goto waitForFinish;

		fprintf(stdout, "%d... ", countdown);
		fflush(stdout);
		sleep(1);
	}

	fprintf(stdout, "\n\nEither you did not follow instructions correctly or your USB hardware is malfunctioning. Please use another USB port to connect your iPhone/iPod (NOT through a USB hub) and consider restarting your computer before trying again.\n");
	fflush(stdout);
	cleanup_and_exit();

waitForFinish:
	while(1) {
		msleep(1);
	}
}
Esempio n. 17
0
int main(int argc, char *argv[])
{
    // parse configuration file
    // get input arguments

    OpenCvStereoConfig stereo_config;
    string config_file = "";

    ConciseArgs parser(argc, argv);
    parser.add(config_file, "c", "config", "Configuration file containing camera GUIDs, etc.", true);
    parser.add(left_camera_mode, "l", "left-camera", "Calibrate just the left camera.");
    parser.add(right_camera_mode, "r", "right-camera", "Calibrate just the right camera.");
    parser.add(force_brightness, "b", "brightness", "set brightness to this level");
    parser.add(force_exposure, "e", "exposure", "set exposure to this level");
    parser.parse();

    // parse the config file
    if (ParseConfigFile(config_file, &stereo_config) != true)
    {
        fprintf(stderr, "Failed to parse configuration file, quitting.\n");
        return -1;
    }

    if (left_camera_mode || right_camera_mode)
    {
        stereo_mode = false;
    }

    uint64 guid = stereo_config.guidLeft;
    uint64 guid2 = stereo_config.guidRight;


    dc1394_t        *d;
    dc1394camera_t  *camera;
    dc1394error_t   err;

    Mat frame_array_left[MAX_FRAMES];
    Mat frame_array_right[MAX_FRAMES];

    int numFrames = 0;

    // ----- cam 2 -----
    dc1394_t        *d2;
    dc1394camera_t  *camera2;
    dc1394error_t   err2;

    d = dc1394_new ();
    if (!d)
        g_critical("Could not create dc1394 context");

    d2 = dc1394_new ();
    if (!d2)
        g_critical("Could not create dc1394 context for camera 2");

    camera = dc1394_camera_new (d, guid);
    if (!camera)
        g_critical("Could not create dc1394 camera");

    camera2 = dc1394_camera_new (d2, guid2);
    if (!camera2)
        g_critical("Could not create dc1394 camera for camera 2");

    // setup
    err = setup_gray_capture(camera, DC1394_VIDEO_MODE_FORMAT7_1);
    DC1394_ERR_CLN_RTN(err, cleanup_and_exit(camera), "Could not setup camera");

    err2 = setup_gray_capture(camera2, DC1394_VIDEO_MODE_FORMAT7_1);
    DC1394_ERR_CLN_RTN(err2, cleanup_and_exit(camera2), "Could not setup camera number 2");

    // enable auto-exposure
    // turn on the auto exposure feature
    err = dc1394_feature_set_power(camera, DC1394_FEATURE_EXPOSURE, DC1394_ON);
    DC1394_ERR_RTN(err,"Could not turn on the exposure feature");

    err = dc1394_feature_set_mode(camera, DC1394_FEATURE_EXPOSURE, DC1394_FEATURE_MODE_ONE_PUSH_AUTO);
    DC1394_ERR_RTN(err,"Could not turn on Auto-exposure");

    // enable auto-exposure
    // turn on the auto exposure feature
    err = dc1394_feature_set_power(camera2, DC1394_FEATURE_EXPOSURE, DC1394_ON);
    DC1394_ERR_RTN(err,"Could not turn on the exposure feature for cam2");

    err = dc1394_feature_set_mode(camera2, DC1394_FEATURE_EXPOSURE, DC1394_FEATURE_MODE_ONE_PUSH_AUTO);
    DC1394_ERR_RTN(err,"Could not turn on Auto-exposure for cam2");

    // enable camera
    err = dc1394_video_set_transmission(camera, DC1394_ON);
    DC1394_ERR_CLN_RTN(err, cleanup_and_exit(camera), "Could not start camera iso transmission");
    err2 = dc1394_video_set_transmission(camera2, DC1394_ON);
    DC1394_ERR_CLN_RTN(err2, cleanup_and_exit(camera2), "Could not start camera iso transmission for camera number 2");

    if (left_camera_mode || stereo_mode)
    {
        InitBrightnessSettings(camera, camera2);
        MatchBrightnessSettings(camera, camera2, true, force_brightness, force_exposure);
    } else {
        // use the right camera as the master for brightness
        // since we're calibrating that one
        InitBrightnessSettings(camera2, camera);
        MatchBrightnessSettings(camera2, camera, true);
    }

    // make opencv windows
    if (left_camera_mode || stereo_mode)
    {
    	namedWindow("Input Left", CV_WINDOW_AUTOSIZE);
    	moveWindow("Input Left", 100, 100);
    }

    if (right_camera_mode || stereo_mode)
    {
    	namedWindow("Input Right", CV_WINDOW_AUTOSIZE);
    	moveWindow("Input Right", 478, 100);
    }


    CvSize size;

    Mat cornersL, cornersR;

    int i;

    while (numFrames < MAX_FRAMES) {

        Mat chessL, chessR;

        // each loop dump a bunch of frames to clear the buffer
        MatchBrightnessSettings(camera, camera2, true, force_brightness, force_exposure);
        for (i=0;i<10;i++)
        {
            if (left_camera_mode || stereo_mode)
            {
                chessL = GetFrameFormat7(camera);
            }

            if (right_camera_mode || stereo_mode)
            {
                chessR = GetFrameFormat7(camera2);
            }
        }

        // copy the images for drawing/display
        size = chessL.size();
        Mat chessLc;
        chessLc.create(size, CV_32FC3);
        Mat chessRc;
        chessRc.create(size, CV_32FC3);

        // attempt checkerboard matching
        bool foundPattern = true; // set to true so we can do an OR
                                  // later if we're only using one
                                  // camera

        if (left_camera_mode || stereo_mode)
        {
            foundPattern = findChessboardCorners(chessL, Size(CHESS_X, CHESS_Y), cornersL);
        }

        if (right_camera_mode || stereo_mode)
        {
            foundPattern = foundPattern & findChessboardCorners(chessR, Size(CHESS_X, CHESS_Y), cornersR);
        }

        if (left_camera_mode || stereo_mode)
        {
            cvtColor( chessL, chessLc, CV_GRAY2BGR );
            drawChessboardCorners(chessLc, Size(CHESS_X, CHESS_Y), cornersL, foundPattern);
            imshow("Input Left", chessLc);
        }

        if (right_camera_mode || stereo_mode)
        {
            cvtColor(chessR, chessRc, CV_GRAY2BGR);
            drawChessboardCorners(chessRc, Size(CHESS_X, CHESS_Y), cornersR, foundPattern);

            imshow("Input Right", chessRc);
        }


		// key codes:
		// page up: 654365
		// page down: 65366
		// b: 98
		char key = waitKey();
		//printf("%d\n", (int)key);
		if (key == 98)
		{
		    break;
		} else if (key == 86){
		    if (foundPattern)
		    {
		        // this was a good one -- save it
		        frame_array_left[numFrames] = chessL;
                frame_array_right[numFrames] = chessR;

                // give the user some guidence on the number
                // of frames they should be using
                if (stereo_mode)
                {
                    printf("Saved frame %d / about 10\n", numFrames);
                } else {
                    printf("Saved frame %d / about 20-30\n", numFrames);
                }

                numFrames ++;
            } else {
                printf("Not saving frame since did not find a checkboard.\n");
            }
		} else if (key == 'W') {
            force_brightness +=20;
            cout << "Brightness: " << force_brightness << "\n";
        } else if (key == 'w') {
            force_brightness -=20;
            cout << "Brightness: " << force_brightness << "\n";
        } else if (key == 'E') {
            force_exposure +=20;
            cout << "Exposure: " << force_exposure << "\n";
        } else if (key == 'e') {
            force_exposure -=20;
            cout << "Exposure: " << force_exposure << "\n";
        }
	}

    printf("\n\n");

    // clear out the calibration directory
    printf("Deleting old images...\nrm calibrationImages/*.ppm\n");
    int retval = system("rm calibrationImages/*.ppm");
    if (retval != 0) {
        printf("Warning: Deleting images may have failed.\n");
    }
    printf("done.\n");

    char filename[1000];

    for (i=0;i<numFrames;i++)
    {
        if (left_camera_mode || stereo_mode)
        {
            sprintf(filename, "calibrationImages/cam1-%05d.ppm", i+1);
            imwrite(filename, frame_array_left[i]);
        }

        if (right_camera_mode || stereo_mode)
        {
            sprintf(filename, "calibrationImages/cam2-%05d.ppm", i+1);
            imwrite(filename, frame_array_right[i]);
        }

        printf("Writing frame %d\n", i);
    }

    printf("\n\n");

    destroyWindow("Input Left");
    destroyWindow("Input Right");

    // stop data transmission
    err = dc1394_video_set_transmission(camera, DC1394_OFF);
    DC1394_ERR_CLN_RTN(err,cleanup_and_exit(camera),"Could not stop the camera");

    err2 = dc1394_video_set_transmission(camera2, DC1394_OFF);
    DC1394_ERR_CLN_RTN(err2,cleanup_and_exit(camera2),"Could not stop the camera 2");

    // close camera
    cleanup_and_exit(camera);
    cleanup_and_exit(camera2);
    dc1394_free (d);
    dc1394_free (d2);

    return 0;
}
Esempio n. 18
0
struct response_struct keys_command(char* token_vector[], int token_count) {

  char* part = NULL;
  char key[KEY_LEN] = "";
  int length = 0;
  int i = 0;
  int retval;
  int64_t pos = 0;
  struct keydb_node *node;
  struct keydb_column *list, *tmp, *cursor;
  bool some_content = false; // Does our key list have any keys in it?
  list = NULL; 
  char* tmp_response;
  int response_free_bytes = MSG_SIZE;
  int responselen = 0;
  int column_size;
  struct response_struct response;

  response.status = 0;
  if ((response.msg = malloc(sizeof(char) * MSG_SIZE)) == NULL) {
    perror(NULL);
    cleanup_and_exit();
  }
  bzero(response.msg, MSG_SIZE);

  for (i = 1; (part = token_vector[i]) && (i < MAX_ARGS); i++) {
    length += strlen(part);
    if (length > KEY_LEN - 1) {
      response.status = 1;
      sprintf(response.msg, "Key too large.");
      return response;
    }

    node = keydb_find(KEYDB_FD, part, pos);
    
    if (!(node = keydb_find(KEYDB_FD, part, pos))) {
      response.status = 1;
      sprintf(response.msg, "Not found.");
      return response;
    } 

    if (node->refcount <= 0) {
      response.status = 1;
      sprintf(response.msg, "Not found.");
      return response;
    } 
  
    pos = node->next;
    free(node);
    if (pos == 0) { // There is no next subtree.
      response.status = 1;
      sprintf(response.msg, "No subkeys.");
      return response;
    }

  }

  keydb_tree(KEYDB_FD, pos, &list);
  while (list) {
    if (list->column[0] != '\0') {
      column_size = strlen(list->column) + 2;
      response_free_bytes -= column_size;
      if (response_free_bytes < 1) { // need to expand response.
        responselen = strlen(response.msg);
        responselen += column_size;
        tmp_response = malloc(sizeof(char) * responselen);
        strcpy(tmp_response, response.msg);
        free(response.msg);
        response.msg = tmp_response;
        response_free_bytes = 0;
      }
      strcat(response.msg, list->column);
      strcat(response.msg, " ");
      some_content = true;
    }
    tmp = list->next;
    free(list);
    list = tmp;
  }
  
  if (!some_content) {
    sprintf(response.msg, "No subkeys.");
    response.status = 1;
  }
  response.msg[strlen(response.msg) - 1] = '\0'; // Knock out that last extra space.
  return response;
}
Esempio n. 19
0
int main (int argc, char **argv)
{

    
    char* ntry = (char*)"";
    if (argc > 1) {
        ntry = argv[1];
    }

    double fps = FPS;
    double target_dur = 1.0/fps;
    double tol = 1.0e-3;
    double total_dur = 0.0;

    dc1394_t * d = dc1394_new(); 
    if (!d) {
        return 1;
    }
    dc1394camera_list_t * list;
    dc1394error_t err = dc1394_camera_enumerate (d, &list);
    DC1394_ERR_RTN(err,"Failed to enumerate cameras");
    if (list->num == 0) {                                                  /* Verify that we have at least one camera */
        dc1394_log_error("No cameras found");
        return 1;
    }

    gCamera.init(d, list->ids[0].guid);
    if (!gCamera.cam()) {
        dc1394_log_error("Failed to initialize camera with guid %ld", list->ids[0].guid);
        dc1394_camera_free_list (list);

        return 1;
    }
    dc1394_camera_free_list (list);

    /*-----------------------------------------------------------------------
     *  have the camera start sending us data
     *-----------------------------------------------------------------------*/
    err = gCamera.start_transmission();
    DC1394_ERR_CLN_RTN(err,cleanup_and_exit(gCamera),"Could not start camera iso transmission");

    
    /*-----------------------------------------------------------------------
     *  capture one frame
     *-----------------------------------------------------------------------*/
    uint32_t width = 0;
    uint32_t height = 0;
    gCamera.get_image_size(&width, &height);
    cv::Mat mapping = cv::getRotationMatrix2D(cv::Point2f(width/2.0, height/2.0), 180.0, 1.0);

#ifdef USE_SDL
    static char *var = (char*)"SDL_VIDEO_WINDOW_POS=\"1280,480\"";
    int ret = putenv(var);
    
    if (SDL_Init(SDL_INIT_VIDEO) != 0) {
        std::cerr << "DC1394: Unable to initialize SDL: " <<  SDL_GetError() << std::endl;
        return 1;
    }
    atexit(SDL_Quit);
    SDL_Surface *screen;
    screen = SDL_SetVideoMode(width, height, 24, SDL_HWSURFACE);
    if (screen == NULL) {
        std::cerr << "DC1394: Unable to set SDL video mode:" << SDL_GetError() << std::endl;
    }
    SDL_Event event;
#endif

#ifndef LICKOMETER    
    pthread_t save_thread, acq_thread;
    pthread_create( &save_thread, NULL, &thread_save_image, NULL);
#endif

    pthread_t save_thread, acq_thread;
    pthread_create( &acq_thread, NULL, &thread_acq_image, NULL);

    timespec t_sleep, t_rem;
    t_sleep.tv_sec = 0;
    t_sleep.tv_nsec = 1000;
    
#ifndef STANDALONE
    int s;
    if ((s = socket(SOCKTYPE, SOCK_STREAM, 0)) < 0) {
        perror("DC1394: client: socket");
        cleanup_and_exit(gCamera);
        return 1;
    }

    /*
     * Create the address we will be connecting to.
     */
#ifndef INET
    sockaddr_un sa;
    sa.sun_family = AF_UNIX;

    std::ostringstream tmpfn;
    tmpfn << "fwsocket" << ntry;
    std::cout << "DC1394: socket name " << tmpfn.str() << std::endl;
    
    int nameLen = strlen(tmpfn.str().c_str());
    if (nameLen >= (int) sizeof(sa.sun_path) -1) { /* too long? */
        cleanup_and_exit(gCamera);
        return 1;
    }
    
    sa.sun_path[0] = '\0';  /* abstract namespace */
    strcpy(sa.sun_path+1, tmpfn.str().c_str());
    int len = 1 + nameLen + offsetof(struct sockaddr_un, sun_path);
#else
    sockaddr_in sa;
    bzero((char *) &sa, sizeof(sa));
    sa.sin_family = AF_INET;
    hostent *server = gethostbyname("128.40.156.129");
    bcopy((char *)server->h_addr, 
          (char *)&sa.sin_addr.s_addr,
          server->h_length);
    sa.sin_port = htons(35000);
    int len = sizeof(sa);
#endif    
    /*
     * Try to connect to the address.  For this to
     * succeed, the server must already have bound
     * this address, and must have issued a listen()
     * request.
     *
     * The third argument indicates the "length" of
     * the structure, not just the length of the
     * socket name.
     */
    std::cout << "DC1394: Waiting for connection... " << std::flush;
    while (true) {
        // wait for connection:
        if (connect(s, (sockaddr*)&sa, len) < 0) {
            nanosleep(&t_sleep, &t_rem);
        } else {
            break;
        }
    }
    std::cout << "done" << std::endl;
    bool connected = false;
    std::vector<char> data(BUFSIZE);
    int nrec = recv(s, &data[0], data.size(), 0);
    std::string datastr(data.begin(), data.end());
    if (nrec<=0) {
        std::cerr << "DC1394: Didn't receive start message; exiting now" << std::endl;
        cleanup_and_exit(gCamera);
	close(s);
        return 1;
    }
    connected = true;
    
    std::string ready = "ready";
    while (send(s, ready.c_str(), ready.size(), 0) < 0) {
        perror("DC1394: client: send");
    }

    int flags = 0;
    if (-1 == (flags = fcntl(s, F_GETFL, 0)))
        flags = 0;

    if (fcntl(s, F_SETFL, flags | O_NONBLOCK)==-1) {
        perror("DC1394: client: unblock");
    }
#endif
    
    /* pthread_mutex_lock( &camera_mutex );
       gCamera.wait_for_trigger();
       pthread_mutex_unlock( &camera_mutex );

       Wait for acq_frame_buffer to fill instead
    */
    

    int ncount = 0;
    cv::Mat im(cv::Size(width, height), CV_8UC1);
    cv::Mat thresh = cv::Mat::ones(cv::Size(width, height), CV_8UC1);
    cv::Mat prevs(cv::Size(width, height), CV_8UC1);
    cv::Mat gray(cv::Size(width, height), CV_8UC1);
    
    // wait for image:
    int nframes = get_image(im, mapping, false, -1, "", ncount);
    std::cout << "DC1394: Waiting for first image to arrive... " << std::flush;
    int nwait = 0;
    while (!nframes) {
        nanosleep(&t_sleep, &t_rem);
        std::cout << "." << std::flush;
        nframes = get_image(im, mapping, false, -1, "", ncount);
        nwait++;
#ifdef STANDALONE
	if (nwait > 1000) {
#else
	if (nwait > 100000) {
#endif
            std::cout << "Time out, stopping now\n";
            cleanup_and_exit(gCamera);
	}
    }
    timespec time0;
    clock_gettime(CLOCK_REALTIME, &time0);
    std::cout << "DC1394: image arrived: "
              << IplImage(im).depth << " bits, "
              << IplImage(im).nChannels << " channels, "
              << IplImage(im).widthStep << " step width"  << std::endl;

#ifdef USE_SDL
    SDL_Surface *surface =
        SDL_CreateRGBSurfaceFrom((void*)im.data,
                                 im.cols,
                                 im.rows,
                                 IplImage(im).depth*IplImage(im).nChannels,
                                 IplImage(im).widthStep,
                                 0xffffff, 0xffffff, 0xffffff, 0);
    screen = SDL_GetVideoSurface();
    if(SDL_BlitSurface(surface, NULL, screen, NULL) == 0)
        SDL_UpdateRect(screen, 0, 0, 0, 0);
#else
    cv::namedWindow("DC1394", CV_WINDOW_AUTOSIZE);
    cvMoveWindow("DC1394", 1280, 480);

    cv::imshow("DC1394", im);
#endif

    timespec time1 = time0;
    timespec time2 = time0;
    timespec time3 = time0;
    timespec time4 = time0;
    timespec t_disconnect = time0;
    timespec t_notrigger = time0;

#ifdef STANDALONE
    int s = -1;
#endif

    std::string fn = "";
#ifdef LICKOMETER
    std::string fn_lick = "";
    FILE* fp_lick = NULL;
#endif
    int key = 0;
    int nloop = 0;
    while (true) {
        clock_gettime( CLOCK_REALTIME, &time1);
#ifndef STANDALONE
        std::vector<char> data(BUFSIZE);
        int nrec = recv(s, &data[0], data.size(), 0);
        std::string datastr(data.begin(), data.end());
#endif

        nframes += get_image(im, mapping, false, s, fn, ncount);

#ifndef STANDALONE

        // no update from blender in a long time, terminate process
        if (datastr.find("1")==std::string::npos) {
            if (connected) {
                t_disconnect = time1;
                connected = false;
            } else {
                if (tdiff(time1, t_disconnect) > TIMEOUT) {
                    std::cout << "DC1394: Received termination signal" << std::endl;
                    close(s);
                    pthread_cancel(acq_thread);
                    pthread_cancel(save_thread);
                    return 0;
                }
            }
        } else {
            connected = true;
        }

	/* Explicit termination */
        if (datastr.find("quit")!=std::string::npos) {
            std::cout << "DC1394: Game over signal." << std::endl;
            std::string sclose = "close";
            while (send(s, sclose.c_str(), sclose.size(), 0) < 0) {
                perror("DC1394: client: send");
            }
            close(s);
            pthread_cancel(acq_thread);
            pthread_cancel(save_thread);
            return 0;
        }

        // Stop recording
        if (datastr.find("stop") != std::string::npos && fn != "") {
            fn = "";
#ifdef LICKOMETER
	    fn_lick = "";
	    if (fp_lick) {
                fclose(fp_lick);
		fp_lick = NULL;
            }
#endif
            std::cout << "DC1394: Stopping video" << std::endl;
            connected = true;
            ncount = 0;
        }

        // Start recording
        if (datastr.find("avi") != std::string::npos && datastr.find("stop") == std::string::npos && fn == "") {
            std::size_t startpos = datastr.find("begin")+5; 
            std::size_t endpos = datastr.find("end") - datastr.find("begin") - 5; 
            fn = datastr.substr(startpos, endpos);
            fn = std::string(trunk) + "data/" + fn;
#ifdef LICKOMETER
	    fn_lick = fn + "_lick";
	    fp_lick = fopen(fn_lick.c_str(), "wb");
            std::cout << "DC1394: Recording lick detection, writing to " << fn_lick << std::endl;
#else
            boost::filesystem::path path(fn);
            boost::filesystem::path writepath(path);

            // Test whether dir exists:
            if (!boost::filesystem::exists(writepath)) {
                std::cout << "DC1394: Creating directory " << writepath << std::endl;
                boost::filesystem::create_directories(writepath);
            }
            fn += "/";

            /* check save frame buffer */
            std::size_t nfb = save_frame_buffer.size();
            if (nfb)
                std::cerr << "DC1394: Frame buffer isn't empty!" << std::endl;

            std::cout << "DC1394: Starting video, writing to " << fn << std::endl;
            connected = true;
            ncount = 0;
#endif
        }
#endif // #nstandalone

#ifdef USE_SDL
        if (SDL_PollEvent(&event)) {
#ifdef STANDALONE
            /* Any of these event types will end the program */
            if (event.type == SDL_QUIT
                || event.type == SDL_KEYDOWN
                || event.type == SDL_KEYUP) {
                std::cout << std::endl;
                std::cout << std::endl << "DC1394: Total number of frames was " << nframes << std::endl;
                std::cout << std::endl << "DC1394: Frame buffer: " << acq_frame_buffer.size() << " frames left" << std::endl;
                close(s);
                pthread_cancel(acq_thread);
                pthread_cancel(save_thread);
                return 0;
            }
#endif // STANDALONE
        }
        surface->pixels = (void*)im.data;
        // SDL_CreateRGBSurfaceFrom((void*)IplImage(im).imageData,
        //                          IplImage(im).width,
        //                          IplImage(im).height,
        //                          IplImage(im).depth*IplImage(im).nChannels,
        //                          IplImage(im).widthStep,
        //                          1, 1, 1, 0);
        screen = SDL_GetVideoSurface();
        if(SDL_BlitSurface(surface, NULL, screen, NULL) == 0)
            SDL_UpdateRect(screen, 0, 0, 0, 0);
#else // not SDL
        key = cv::waitKey(2);
        cv::imshow("DC1394", im);
        if (key == 1114155 || key == 65579 || key==43 /*+*/) {
            uint32_t gain = 0;
            err = dc1394_feature_get_value(gCamera.cam(), DC1394_FEATURE_GAIN, &gain);
            DC1394_ERR_CLN_RTN(err,cleanup_and_exit(gCamera),"Can't get gain");
            if (gain < gCamera.get_maxgain()-10) {
                gain += 10;
                pthread_mutex_lock( &camera_mutex );
                err = dc1394_feature_set_value(gCamera.cam(), DC1394_FEATURE_GAIN, gain);
                pthread_mutex_unlock( &camera_mutex );
                std::cout << "DC1394: New gain value: " << gain << std::endl;
                DC1394_ERR_CLN_RTN(err,cleanup_and_exit(gCamera),"Can't set gain");
            }
        }
        if (key == 1114207 || key == 45 /*-*/) {
            uint32_t gain = 0;
            err = dc1394_feature_get_value(gCamera.cam(), DC1394_FEATURE_GAIN, &gain);
            DC1394_ERR_CLN_RTN(err,cleanup_and_exit(gCamera),"Can't get gain");
            if (gain > gCamera.get_mingain()+10) {
                gain -= 10;
                pthread_mutex_lock( &camera_mutex );
                err = dc1394_feature_set_value(gCamera.cam(), DC1394_FEATURE_GAIN, gain);
                pthread_mutex_unlock( &camera_mutex );
                DC1394_ERR_CLN_RTN(err,cleanup_and_exit(gCamera),"Can't set gain");
            }
        }
#endif // not SDL

#ifdef LICKOMETER        
	/* IS THIS ALL YOU NEED THEN?
	   Lick detection */
	/* Not required because the captured image is already gray
	   cv::Mat gray = bgr2gray(im); */
	gray = thresholding(im, LICK_FRAME_THRESHOLD);

        if (nloop != 0) {
	    cv::absdiff(prevs, gray, thresh);
	    double pixel_sum_thresh = cv::sum(thresh)[0];
	    double pixel_sum_gray = cv::sum(gray)[0];
	    if (pixel_sum_thresh > LICK_SUM_THRESHOLD) {
	      std::cout << "DC1394: Lick" << std::endl;
	    }
	    if (fp_lick != NULL) {
                fwrite(&pixel_sum_thresh, sizeof(pixel_sum_thresh), 1, fp_lick);
	        fwrite(&pixel_sum_gray, sizeof(pixel_sum_gray), 1, fp_lick);
	    }
	}

	prevs = gray.clone();
	nloop++;
#endif
#ifdef STANDALONE
        if (key == 1048689 || key == 113 /*q*/) {
            std::cout << "DC1394: Mean frame rate was " << nframes/total_dur << " fps" << std::endl;
            pthread_cancel(acq_thread);
            pthread_cancel(save_thread);
            return 0;
        }
        if (key == 1048691 /*s*/) {
            fn = "";
            std::cout << "DC1394: Stopping video" << std::endl;
            ncount = 0;
        }
        if (key == 1048690 /*r*/) {
            fn = trunk + std::string("tmp/");
            std::cout << "DC1394: Starting video, writing to " << fn << std::endl;
            ncount = 0;
        }
#endif // #standalone
        clock_gettime( CLOCK_REALTIME, &time2);
        double loop_dur = tdiff(time2, time3);
        clock_gettime( CLOCK_REALTIME, &time3);
        double meanfps = 0;

        total_dur = tdiff(time3, time0);
        if (total_dur > 0)
            meanfps = nframes / total_dur;
        double currentfps = ret / loop_dur;
        std::cout << "DC1394: Current fps: " << std::setprecision(7) << currentfps
                  << " Average fps: " << std::setprecision(7) << meanfps << "\r" << std::flush;
#ifdef STANDALONE
        // std::cout << capture_dur << "\t" << target_dur << "\t" << rem << "\t" << loop_dur << std::endl;
#endif
    }

    if (d) {
        dc1394_free(d);
    }

#ifndef STANDALONE
    close(s);
#endif
    return 0;
}
Esempio n. 20
0
void sigterm_handler_child(int s)
{
  // Clean up and exit.
  fprintf(stderr, "Got signal %d\n", s);
  cleanup_and_exit();
}
Esempio n. 21
0
static NORETURN
fatal_perror(const char *msg)
{
  fprintf(stderr, "%s: %s: %s\n", progname, msg, strerror(errno));
  cleanup_and_exit(1);
}
Esempio n. 22
0
int guts(int accept_fd, int listen_fd) {
  
  char buffer[RECV_WINDOW] = "";   // recv buffer
  int msgbuflen = MSG_SIZE;
  char status_msg[MSG_SIZE];
  char *msg; // Incoming message.
  char *send_msg; // Outgoing message.
  char *tmp_msg;
  void *msg_cursor;
  struct response_struct response;   
  int msglen = 0; // length of the assembled message that we receive.
  int recvlen = 0; // how many bytes recv call returns.
  int responselen = 0;   
  int offset;
  int retval;
  char* token_vector[MAX_ARGS] = {'\0'};
  int token_count = 0;

  // Re-register the sigterm handler to our cleanup function.
  signal(SIGTERM, sigterm_handler_child);
  close(listen_fd); // Close this resource from our parent. We don't need it any more.

  while (1) {

    msglen = 0;
    msgbuflen = MSG_SIZE;
    msg = malloc(sizeof(char) * msgbuflen);
    msg_cursor = (void*)msg;
    bzero(msg, msgbuflen);


    // Wait for some data
    while (((recvlen = recv(accept_fd, (void*)buffer, RECV_WINDOW, MSG_PEEK)) == -1) && (errno == EAGAIN));
    if (recvlen == 0) {
      fprintf(stderr, "Client closed the connection.\n");
      close(accept_fd);
      cleanup_and_exit(0);
    };

    // Receive data from our buffered stream until we would block.
    while ((recvlen = recv(accept_fd, (void*)buffer, RECV_WINDOW, 0)) != -1) {
      if (recvlen == 0) {
        fprintf(stderr, "Client closed the connection.\n");
        close(accept_fd);
        cleanup_and_exit(0);
      };

      if (recvlen == -1) {
        fprintf(stderr, "Got error %d from recv.\n", errno);
        close(accept_fd);
        cleanup_and_exit(-1);
      };

      // Extend our message buffer if need be.
      if ((msglen += recvlen) > (msgbuflen)) {
        msgbuflen += msgbuflen;
        offset = msg_cursor - (void*)msg;
        tmp_msg = malloc(sizeof(char) * msgbuflen);
        bzero(tmp_msg, msgbuflen);
        memcpy(tmp_msg, msg, offset);
        msg_cursor = tmp_msg + offset;
        free(msg);
        msg = tmp_msg;
        fprintf(stderr, "msgbuflen expanded to %d\n", msgbuflen);
      }

      memcpy(msg_cursor, (void*)buffer, recvlen);
      msg_cursor += recvlen;
      if (memchr((void*)buffer, '\n', recvlen)) break; // Got a terminator character. Go process our message.

    } 

    tmp_msg = msg;
    strsep(&tmp_msg, "\r\n");

    token_count = tokenize_command(msg, token_vector);

    switch (extract_command(token_vector, token_count))  {

      case 0: // quit
        cleanup_and_exit();
        break;

      case 1: // create
        response = create_command(token_vector, token_count);
        break;

      case 2: // read
        response = read_command(token_vector, token_count);
        break;

      case 3: // delete
        response = delete_command(token_vector, token_count);
        break;

      case 4: // subkeys
        response = keys_command(token_vector, token_count);
        break;

      default:
        if ((response.msg = malloc(sizeof(char) * MSG_SIZE)) == NULL) {
          perror(NULL);
          cleanup_and_exit; 
        }
        bzero(response.msg, MSG_SIZE);
        sprintf(response.msg, "Unknown command.");
        response.status = 1;      
    }

    responselen = prepare_send_msg(response, &send_msg);

    if((send(accept_fd, (void*)send_msg, responselen, 0) == -1)) perror("Send failed");
    free(msg);
    free(response.msg);
    free(send_msg);

  };

  return(0);
}
Esempio n. 23
0
int main(int argc, char **argv)
{
    std::string header = "*** BRONCO v0.1 ***";

    /* Read arguments */
    if (argc != 2) {
        printf("Announce: %s --announce <path-to-file> bronco://<host>[:<port>]\n", argv[0]);
        printf("    Join: %s bronco://<host>[:<port>]/<content_id>\n", argv[0]);
        cleanup_and_exit(EXIT_FAILURE);
    }

    /* Set signal handlers */
    signal(SIGINT, signal_close);
    signal(SIGTERM, signal_close);
    signal(SIGHUP, signal_close);
    
    /* Initialize ncurses */
    initscr();

    /* Get screen dimensions */
    uint32_t maxy = 0;
    uint32_t maxx = 0;
    getmaxyx(stdscr, maxy, maxx);

    /* Create windows */
    header_win = newwin(HEADER_HEIGHT, maxx, 0, 0);
    file_win = newwin(FILE_HEIGHT, maxx, HEADER_HEIGHT, 0);
    info_win = newwin(maxy-HEADER_HEIGHT-FILE_HEIGHT, maxx, HEADER_HEIGHT+FILE_HEIGHT, 0);

    /* Set ncurses options */
    noecho();
    curs_set(0);
    halfdelay(5);
    keypad(stdscr, TRUE);
    scrollok(info_win, TRUE);

    /* Create peer manager */
    struct bronco::peermanager::peer_config c = {10, 10, 5, "localhost", bronco::peermanager::select_port()};
    struct bronco::peermanager::nc_parameters p = {"bin/bronco-nc", 512, 400};

    manager_ptr = new bronco::peermanager(argv[1], &c, &p, &info_printf);

    /* Screen update loop */
    while (1) {
        /* Write content */
        wclear(header_win);
        wclear(file_win);
        mvwprintw(header_win, 0, (maxx - header.size())/2, header.c_str());
        mvwprintw(file_win, 0, 0, " Anders_Bech_-_Store_patter_betyder_undskyld.mp3\n [#####      ]");

        /* Resize and refresh windows */
        update_windows(&maxy, &maxx);

        /* Wait for keypress or timeout */
        int key = wgetch(info_win);
        if (key != ERR)
            info_printf("Key pressed!\n");
    }
    
    /* Finalize */
    cleanup_and_exit(EXIT_SUCCESS);



    return 0;
}
Esempio n. 24
0
struct response_struct create_command(char* token_vector[], int token_count) {

  int length            = 0;
  int i = 0;
  char* part            = NULL;
  char* previous_part   = NULL;
  int retval            = 0;
  char key[KEY_LEN]     = "";
  struct keydb_column *tuple = NULL;
  struct keydb_column *head = NULL;
  struct keydb_column *tmp;
  struct response_struct response;

  response.status = 0;

  if ((response.msg = malloc(sizeof(char) * MSG_SIZE)) == NULL) {
    perror(NULL);
    cleanup_and_exit();
  }
  bzero(response.msg, MSG_SIZE);

  if (token_count < 3) {
    response.status = 1;
    sprintf(response.msg, "Not enough arguments.");
    return response;
  }

  for (i = 1; (part = token_vector[i]) && (i < MAX_ARGS); i++) {

    if (previous_part != NULL) {
      length += strlen(previous_part);
      if (length > KEY_LEN - 1) {
        response.status = 1;
        sprintf(response.msg, "Key too large.");
        return response;
      }

      // Save away the list of key composites
      if ((tmp = malloc(sizeof(struct keydb_column))) == NULL) {
        perror(NULL);
        cleanup_and_exit;
      }
      strncpy(tmp->column, previous_part, KEY_LEN);
      tmp->next = NULL;
      if (tuple == NULL) {
        tuple = tmp;
        head = tmp;
      } else {
        tuple->next = tmp;
        tuple = tuple->next;
        tuple->next = NULL;
      }
      strcat(key, previous_part);

    }
    previous_part = part;
  } 

  if (key[0] == '\0') {
    response.status = 1;
    sprintf(response.msg, "Failed to get value.");
    return response;
  }

  retval = write_record(key, previous_part);
  if (retval == 0) {
    if (composite_insert(KEYDB_FD, head) == -1) {
      delete_record(key); // undo what we did.
      fprintf(stderr, "Composite key insertion failed.");
      response.status = 1;
      sprintf(response.msg, "Internal error.");
    } else {
      sprintf(response.msg, "Write OK.");
    }
  } else if (retval == -2) { // key already exists.
    response.status = 1;
    sprintf(response.msg, "Write failed. Key exists in the index.");
  } else {
    response.status = 1;
    sprintf(response.msg, "Internal error.");
  }

  while (head) { // free our list of key composites.
    tmp = head->next;
    free(head);
    head = tmp;
  };
  return response;
}
Esempio n. 25
0
int
main(int argc, char* argv[])
{
	int c;
	int dirnum = -1;
	uint32 diroff = 0;

	oerror = TIFFSetErrorHandler(NULL);
	owarning = TIFFSetWarningHandler(NULL);
	while ((c = getopt(argc, argv, "d:o:p:eflmsvw?")) != -1)
	    switch (c) {
	    case 'd':
		dirnum = atoi(optarg);
		break;
	    case 'e':
		oerror = TIFFSetErrorHandler(oerror);
		break;
	    case 'l':
		order0 = FILLORDER_LSB2MSB;
		break;
	    case 'm':
		order0 = FILLORDER_MSB2LSB;
		break;
	    case 'o':
		diroff = strtoul(optarg, NULL, 0);
		break;
	    case 'p':
		photo0 = photoArg(optarg);
		break;
	    case 's':
		stoponerr = 1;
		break;
	    case 'w':
		owarning = TIFFSetWarningHandler(owarning);
		break;
	    case 'v':
		verbose = 1;
		break;
	    case '?':
		usage();
		/*NOTREACHED*/
	    }
	filenum = argc - optind;
	if ( filenum < 1)
	        usage();

	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);

	/*
	 * Get the screen size
	 */
	xmax = glutGet(GLUT_SCREEN_WIDTH);
	ymax = glutGet(GLUT_SCREEN_HEIGHT);

	/*
	 * Use 90% of the screen size
	 */
	xmax = xmax - xmax / 10.0;
	ymax = ymax - ymax / 10.0;

        filelist = (char **) _TIFFmalloc(filenum * sizeof(char*));
        if (!filelist) {
                TIFFError(argv[0], "Can not allocate space for the file list.");
                return 1;
        }
        _TIFFmemcpy(filelist, argv + optind, filenum * sizeof(char*));
	fileindex = -1;
	if (nextImage() < 0) {
		_TIFFfree(filelist);
		return 2;
	}
	/*
	 * Set initial directory if user-specified
	 * file was opened successfully.
	 */
	if (dirnum != -1 && !TIFFSetDirectory(tif, dirnum))
	    TIFFError(argv[0], "Error, seeking to directory %d", dirnum);
	if (diroff != 0 && !TIFFSetSubDirectory(tif, diroff))
	    TIFFError(argv[0], "Error, setting subdirectory at %#x", diroff);
	order = order0;
	photo = photo0;
	initImage();
	/*
	 * Create a new window or reconfigure an existing
	 * one to suit the image to be displayed.
	 */
	glutInitWindowSize(width, height);
	snprintf(title, 1024, "%s [%u]", filelist[fileindex],
		(unsigned int) TIFFCurrentDirectory(tif));
	glutCreateWindow(title);
	glutDisplayFunc(raster_draw);
	glutReshapeFunc(raster_reshape);
	glutKeyboardFunc(raster_keys);
	glutSpecialFunc(raster_special);
	glutMainLoop();

	cleanup_and_exit();
        return 0;
}
Esempio n. 26
0
int
main(int argc, char *const *argv)
{
	struct sockaddr_in bindaddr;
	socklen_t addrlen;
	const char *isDA;
	const char *proxyReg;
	int connfd;
	int lfd;
	const int on = 1;

	detachfromtty();

	openlog("slpd", LOG_PID, LOG_DAEMON);

	do_args(argc, argv);

	/* If slpd has been configured to run as a DA, start it and exit */
	isDA = SLPGetProperty("net.slp.isDA");
	proxyReg = SLPGetProperty("net.slp.serializedRegURL");
	if ((isDA && (strcasecmp(isDA, "true") == 0)) || proxyReg) {
		run_slpd();
		return (1);
	}

	if ((lfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		syslog(LOG_ERR, "socket failed: %s", strerror(errno));
		cleanup_and_exit(1);
	}

	(void) setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on));

	(void) memset((void *)&bindaddr, 0, sizeof (bindaddr));
	bindaddr.sin_family = AF_INET;
	bindaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
	bindaddr.sin_port = htons(427);

	if (bind(lfd, (const struct sockaddr *)&bindaddr, sizeof (bindaddr))
	    < 0) {
		syslog(LOG_ERR, "bind failed: %s", strerror(errno));
		cleanup_and_exit(1);
	}

	if (listen(lfd, 1) < 0) {
		syslog(LOG_ERR, "listen failed: %s", strerror(errno));
		cleanup_and_exit(1);
	}

	addrlen = sizeof (bindaddr);
	if ((connfd = accept(lfd, (struct sockaddr *)&bindaddr, &addrlen))
	    < 0) {
		syslog(LOG_ERR, "accept failed: %s", strerror(errno));
		cleanup_and_exit(1);
	}

	(void) close(lfd);

	(void) dup2(connfd, 0);
	(void) close(connfd);
	(void) dup2(0, 1);
	(void) dup2(0, 2);

	run_slpd();

	return (1);
}