Exemplo n.º 1
0
/**
 * main
 */
int main(int argc, const char **argv)
{
   // Our main data storage vessel..
   RASPIVID_STATE state;
   int exit_code = EX_OK;

   MMAL_STATUS_T status = MMAL_SUCCESS;
   MMAL_PORT_T *camera_preview_port = NULL;
   MMAL_PORT_T *camera_video_port = NULL;
   MMAL_PORT_T *camera_still_port = NULL;
   MMAL_PORT_T *preview_input_port = NULL;
   MMAL_PORT_T *encoder_input_port = NULL;
   MMAL_PORT_T *encoder_output_port = NULL;
   FILE *output_file = NULL;

   bcm_host_init();

   // Register our application with the logging system
   vcos_log_register("RaspiVid", VCOS_LOG_CATEGORY);

   signal(SIGINT, signal_handler);

   default_status(&state);

   // Do we have any parameters
   if (argc == 1)
   {
      fprintf(stderr, "\n%s Camera App %s\n\n", basename(argv[0]), VERSION_STRING);

      display_valid_parameters(basename(argv[0]));
      exit(EX_USAGE);
   }

   // Parse the command line and put options in to our status structure
   if (parse_cmdline(argc, argv, &state))
   {
      status = -1;
      exit(EX_USAGE);
   }

   if (state.verbose)
   {
      fprintf(stderr, "\n%s Camera App %s\n\n", basename(argv[0]), VERSION_STRING);
      dump_status(&state);
   }

   // OK, we have a nice set of parameters. Now set up our components
   // We have three components. Camera, Preview and encoder.

   if ((status = create_camera_component(&state)) != MMAL_SUCCESS)
   {
      vcos_log_error("%s: Failed to create camera component", __func__);
      exit_code = EX_SOFTWARE;
   }
   else if ((status = raspipreview_create(&state.preview_parameters)) != MMAL_SUCCESS)
   {
      vcos_log_error("%s: Failed to create preview component", __func__);
      destroy_camera_component(&state);
      exit_code = EX_SOFTWARE;
   }
   else if ((status = create_encoder_component(&state)) != MMAL_SUCCESS)
   {
      vcos_log_error("%s: Failed to create encode component", __func__);
      raspipreview_destroy(&state.preview_parameters);
      destroy_camera_component(&state);
      exit_code = EX_SOFTWARE;
   }
   else
   {
      PORT_USERDATA callback_data;

      if (state.verbose)
         fprintf(stderr, "Starting component connection stage\n");

      camera_preview_port = state.camera_component->output[MMAL_CAMERA_PREVIEW_PORT];
      camera_video_port   = state.camera_component->output[MMAL_CAMERA_VIDEO_PORT];
      camera_still_port   = state.camera_component->output[MMAL_CAMERA_CAPTURE_PORT];
      preview_input_port  = state.preview_parameters.preview_component->input[0];
      encoder_input_port  = state.encoder_component->input[0];
      encoder_output_port = state.encoder_component->output[0];

      if (state.preview_parameters.wantPreview )
      {
         if (state.verbose)
         {
            fprintf(stderr, "Connecting camera preview port to preview input port\n");
            fprintf(stderr, "Starting video preview\n");
         }

         // Connect camera to preview
         status = connect_ports(camera_preview_port, preview_input_port, &state.preview_connection);
      }
      else
      {
         status = MMAL_SUCCESS;
      }

      if (status == MMAL_SUCCESS)
      {
         if (state.verbose)
            fprintf(stderr, "Connecting camera stills port to encoder input port\n");

         // Now connect the camera to the encoder
         status = connect_ports(camera_video_port, encoder_input_port, &state.encoder_connection);

         if (status != MMAL_SUCCESS)
         {
            vcos_log_error("%s: Failed to connect camera video port to encoder input", __func__);
            goto error;
         }

         if (state.filename)
         {
            if (state.filename[0] == '-')
            {
               output_file = stdout;

               // Ensure we don't upset the output stream with diagnostics/info
               state.verbose = 0;
            }
            else
            {
               if (state.verbose)
                  fprintf(stderr, "Opening output file \"%s\"\n", state.filename);

               output_file = fopen(state.filename, "wb");
            }

            if (!output_file)
            {
               // Notify user, carry on but discarding encoded output buffers
               vcos_log_error("%s: Error opening output file: %s\nNo output file will be generated\n", __func__, state.filename);
            }
         }

         // Set up our userdata - this is passed though to the callback where we need the information.
         callback_data.file_handle = output_file;
         callback_data.pstate = &state;
         callback_data.abort = 0;

         encoder_output_port->userdata = (struct MMAL_PORT_USERDATA_T *)&callback_data;

         if (state.verbose)
            fprintf(stderr, "Enabling encoder output port\n");

         // Enable the encoder output port and tell it its callback function
         status = mmal_port_enable(encoder_output_port, encoder_buffer_callback);

         if (status != MMAL_SUCCESS)
         {
            vcos_log_error("Failed to setup encoder output");
            goto error;
         }

         if (state.demoMode)
         {
            // Run for the user specific time..
            int num_iterations = state.timeout / state.demoInterval;
            int i;

            if (state.verbose)
               fprintf(stderr, "Running in demo mode\n");

            for (i=0;state.timeout == 0 || i<num_iterations;i++)
            {
               raspicamcontrol_cycle_test(state.camera_component);
               vcos_sleep(state.demoInterval);
            }
         }
         else
         {
            // Only encode stuff if we have a filename and it opened
            if (output_file)
            {
               int wait;

               if (state.verbose)
                  fprintf(stderr, "Starting video capture\n");

               if (mmal_port_parameter_set_boolean(camera_video_port, MMAL_PARAMETER_CAPTURE, 1) != MMAL_SUCCESS)
               {
                  goto error;
               }

               // Send all the buffers to the encoder output port
               {
                  int num = mmal_queue_length(state.encoder_pool->queue);
                  int q;
                  for (q=0;q<num;q++)
                  {
                     MMAL_BUFFER_HEADER_T *buffer = mmal_queue_get(state.encoder_pool->queue);

                     if (!buffer)
                        vcos_log_error("Unable to get a required buffer %d from pool queue", q);

                     if (mmal_port_send_buffer(encoder_output_port, buffer)!= MMAL_SUCCESS)
                        vcos_log_error("Unable to send a buffer to encoder output port (%d)", q);

                  }
               }

               // Now wait until we need to stop. Whilst waiting we do need to check to see if we have aborted (for example
               // out of storage space)
               // Going to check every ABORT_INTERVAL milliseconds

               for (wait = 0; state.timeout == 0 || wait < state.timeout; wait+= ABORT_INTERVAL)
               {
                  vcos_sleep(ABORT_INTERVAL);
                  if (callback_data.abort)
                     break;
               }

               if (state.verbose)
                  fprintf(stderr, "Finished capture\n");
            }
            else
            {
               if (state.timeout)
                  vcos_sleep(state.timeout);
               else
                  for (;;) vcos_sleep(ABORT_INTERVAL);
            }
         }
      }
      else
      {
         mmal_status_to_int(status);
         vcos_log_error("%s: Failed to connect camera to preview", __func__);
      }

error:

      mmal_status_to_int(status);

      if (state.verbose)
         fprintf(stderr, "Closing down\n");

      // Disable all our ports that are not handled by connections
      check_disable_port(camera_still_port);
      check_disable_port(encoder_output_port);

      if (state.preview_parameters.wantPreview )
         mmal_connection_destroy(state.preview_connection);
      mmal_connection_destroy(state.encoder_connection);

      // Can now close our file. Note disabling ports may flush buffers which causes
      // problems if we have already closed the file!
      if (output_file && output_file != stdout)
         fclose(output_file);

      /* Disable components */
      if (state.encoder_component)
         mmal_component_disable(state.encoder_component);

      if (state.preview_parameters.preview_component)
         mmal_component_disable(state.preview_parameters.preview_component);

      if (state.camera_component)
         mmal_component_disable(state.camera_component);

      destroy_encoder_component(&state);
      raspipreview_destroy(&state.preview_parameters);
      destroy_camera_component(&state);

      if (state.verbose)
         fprintf(stderr, "Close down completed, all components disconnected, disabled and destroyed\n\n");
   }

   if (status != MMAL_SUCCESS)
      raspicamcontrol_check_configuration(128);

   return exit_code;
}
Exemplo n.º 2
0
/**
 * main
 */
int main(int argc, const char **argv)
{
    // Our main data storage vessel..
    RASPIVID_STATE state;

    MMAL_STATUS_T status = -1;
    MMAL_PORT_T *camera_video_port = NULL;
    MMAL_PORT_T *camera_still_port = NULL;
    MMAL_PORT_T *preview_input_port = NULL;
    MMAL_PORT_T *encoder_input_port = NULL;
    MMAL_PORT_T *encoder_output_port = NULL;

    time_t timer_begin,timer_end;
    double secondsElapsed;

    bcm_host_init();
    signal(SIGINT, signal_handler);

    // read default status
    default_status(&state);

    // init windows and OpenCV Stuff
    cvNamedWindow("camcvWin", CV_WINDOW_AUTOSIZE);
    int w=state.width;
    int h=state.height;
    dstImage = cvCreateImage(cvSize(w,h), IPL_DEPTH_8U, 3);
    py = cvCreateImage(cvSize(w,h), IPL_DEPTH_8U, 1);		// Y component of YUV I420 frame
    pu = cvCreateImage(cvSize(w/2,h/2), IPL_DEPTH_8U, 1);	// U component of YUV I420 frame
    pv = cvCreateImage(cvSize(w/2,h/2), IPL_DEPTH_8U, 1);	// V component of YUV I420 frame
    pu_big = cvCreateImage(cvSize(w,h), IPL_DEPTH_8U, 1);
    pv_big = cvCreateImage(cvSize(w,h), IPL_DEPTH_8U, 1);
    image = cvCreateImage(cvSize(w,h), IPL_DEPTH_8U, 3);	// final picture to display


    // create camera
    if (!create_camera_component(&state))
    {
        vcos_log_error("%s: Failed to create camera component", __func__);
    }
    else if (!raspipreview_create(&state.preview_parameters))
    {
        vcos_log_error("%s: Failed to create preview component", __func__);
        destroy_camera_component(&state);
    }
    else
    {
        PORT_USERDATA callback_data;

        camera_video_port   = state.camera_component->output[MMAL_CAMERA_VIDEO_PORT];
        camera_still_port   = state.camera_component->output[MMAL_CAMERA_CAPTURE_PORT];

        VCOS_STATUS_T vcos_status;

        callback_data.pstate = &state;

        vcos_status = vcos_semaphore_create(&callback_data.complete_semaphore, "RaspiStill-sem", 0);
        vcos_assert(vcos_status == VCOS_SUCCESS);

        // assign data to use for callback
        camera_video_port->userdata = (struct MMAL_PORT_USERDATA_T *)&callback_data;

        // init timer
        time(&timer_begin);


        // start capture
        if (mmal_port_parameter_set_boolean(camera_video_port, MMAL_PARAMETER_CAPTURE, 1) != MMAL_SUCCESS)
        {
            goto error;
        }

        // Send all the buffers to the video port

        int num = mmal_queue_length(state.video_pool->queue);
        int q;
        for (q=0; q<num; q++)
        {
            MMAL_BUFFER_HEADER_T *buffer = mmal_queue_get(state.video_pool->queue);

            if (!buffer)
                vcos_log_error("Unable to get a required buffer %d from pool queue", q);

            if (mmal_port_send_buffer(camera_video_port, buffer)!= MMAL_SUCCESS)
                vcos_log_error("Unable to send a buffer to encoder output port (%d)", q);
        }


        // Now wait until we need to stop
        vcos_sleep(state.timeout);

error:

        mmal_status_to_int(status);


        // Disable all our ports that are not handled by connections
        check_disable_port(camera_still_port);

        if (state.camera_component)
            mmal_component_disable(state.camera_component);

        //destroy_encoder_component(&state);
        raspipreview_destroy(&state.preview_parameters);
        destroy_camera_component(&state);

    }
    if (status != 0)
        raspicamcontrol_check_configuration(128);

    time(&timer_end);  /* get current time; same as: timer = time(NULL)  */
    cvReleaseImage(&dstImage);
    cvReleaseImage(&pu);
    cvReleaseImage(&pv);
    cvReleaseImage(&py);
    cvReleaseImage(&pu_big);
    cvReleaseImage(&pv_big);

    secondsElapsed = difftime(timer_end,timer_begin);

    printf ("%.f seconds for %d frames : FPS = %f\n", secondsElapsed,nCount,(float)((float)(nCount)/secondsElapsed));

    return 0;
}
Exemplo n.º 3
0
/**
 * main
 */
int main(int argc, const char **argv)
{
    // Our main data storage vessel..
    RASPISTILLYUV_STATE state;

    MMAL_STATUS_T status = MMAL_SUCCESS;
    MMAL_PORT_T *camera_preview_port = NULL;
    MMAL_PORT_T *camera_video_port = NULL;
    MMAL_PORT_T *camera_still_port = NULL;
    MMAL_PORT_T *preview_input_port = NULL;
    FILE *output_file = NULL;

    bcm_host_init();

    // Register our application with the logging system
    vcos_log_register("RaspiStill", VCOS_LOG_CATEGORY);

    signal(SIGINT, signal_handler);

    // Do we have any parameters
    if (argc == 1)
    {
        fprintf(stderr, "\n%s Camera App %s\n\n", basename(argv[0]), VERSION_STRING);

        display_valid_parameters(basename(argv[0]));
        exit(0);
    }

    default_status(&state);

    // Parse the command line and put options in to our status structure
    if (parse_cmdline(argc, argv, &state))
    {
        status = -1;
        exit(0);
    }

    if (state.verbose)
    {
        fprintf(stderr, "\n%s Camera App %s\n\n", basename(argv[0]), VERSION_STRING);
        dump_status(&state);
    }

    // OK, we have a nice set of parameters. Now set up our components
    // We have two components. Camera and Preview
    // Camera is different in stills/video, but preview
    // is the same so handed off to a separate module

    if ((status = create_camera_component(&state)) != MMAL_SUCCESS)
    {
        vcos_log_error("%s: Failed to create camera component", __func__);
    }
    else if ((status = raspipreview_create(&state.preview_parameters)) != MMAL_SUCCESS)
    {
        vcos_log_error("%s: Failed to create preview component", __func__);
        destroy_camera_component(&state);
    }
    else
    {
        PORT_USERDATA callback_data;

        if (state.verbose)
            fprintf(stderr, "Starting component connection stage\n");

        camera_preview_port = state.camera_component->output[MMAL_CAMERA_PREVIEW_PORT];
        camera_video_port   = state.camera_component->output[MMAL_CAMERA_VIDEO_PORT];
        camera_still_port   = state.camera_component->output[MMAL_CAMERA_CAPTURE_PORT];
        preview_input_port  = state.preview_parameters.preview_component->input[0];

        if (state.preview_parameters.wantPreview )
        {
            if (state.verbose)
            {
                fprintf(stderr, "Connecting camera preview port to preview input port\n");
                fprintf(stderr, "Starting video preview\n");
            }

            // Connect camera to preview
            status = connect_ports(camera_preview_port, preview_input_port, &state.preview_connection);
        }
        else
        {
            status = MMAL_SUCCESS;
        }

        if (status == MMAL_SUCCESS)
        {
            VCOS_STATUS_T vcos_status;

            if (state.filename)
            {
                if (state.verbose)
                    fprintf(stderr, "Opening output file %s\n", state.filename);

                output_file = fopen(state.filename, "wb");
                if (!output_file)
                {
                    // Notify user, carry on but discarding output buffers
                    vcos_log_error("%s: Error opening output file: %s\nNo output file will be generated\n", __func__, state.filename);
                }
            }

            // Set up our userdata - this is passed though to the callback where we need the information.
            callback_data.file_handle = output_file;
            callback_data.pstate = &state;

            vcos_status = vcos_semaphore_create(&callback_data.complete_semaphore, "RaspiStill-sem", 0);
            vcos_assert(vcos_status == VCOS_SUCCESS);

            camera_still_port->userdata = (struct MMAL_PORT_USERDATA_T *)&callback_data;

            if (state.verbose)
                fprintf(stderr, "Enabling camera still output port\n");

            // Enable the camera still output port and tell it its callback function
            status = mmal_port_enable(camera_still_port, camera_buffer_callback);

            if (status != MMAL_SUCCESS)
            {
                vcos_log_error("Failed to setup camera output");
                goto error;
            }

            if (state.verbose)
                fprintf(stderr, "Starting video preview\n");

            int num_iterations =  state.timelapse ? state.timeout / state.timelapse : 1;
            int frame;
            FILE *output_file = NULL;

            for (frame = 1; frame<=num_iterations; frame++)
            {
                if (state.timelapse)
                    vcos_sleep(state.timelapse);
                else
                    vcos_sleep(state.timeout);

                // Open the file
                if (state.filename)
                {
                    if (state.filename[0] == '-')
                    {
                        output_file = stdout;

                        // Ensure we don't upset the output stream with diagnostics/info
                        state.verbose = 0;
                    }
                    else
                    {
                        char *use_filename = state.filename;

                        if (state.timelapse)
                            asprintf(&use_filename, state.filename, frame);

                        if (state.verbose)
                            fprintf(stderr, "Opening output file %s\n", use_filename);

                        output_file = fopen(use_filename, "wb");

                        if (!output_file)
                        {
                            // Notify user, carry on but discarding encoded output buffers
                            vcos_log_error("%s: Error opening output file: %s\nNo output file will be generated\n", __func__, use_filename);
                        }

                        // asprintf used in timelapse mode allocates its own memory which we need to free
                        if (state.timelapse)
                            free(use_filename);
                    }

                    callback_data.file_handle = output_file;
                }

                // And only do the capture if we have specified a filename and its opened OK
                if (output_file)
                {
                    // Send all the buffers to the camera output port
                    {
                        int num = mmal_queue_length(state.camera_pool->queue);
                        int q;

                        for (q=0; q<num; q++)
                        {
                            MMAL_BUFFER_HEADER_T *buffer = mmal_queue_get(state.camera_pool->queue);

                            if (!buffer)
                                vcos_log_error("Unable to get a required buffer %d from pool queue", q);

                            if (mmal_port_send_buffer(camera_still_port, buffer)!= MMAL_SUCCESS)
                                vcos_log_error("Unable to send a buffer to camera output port (%d)", q);
                        }
                    }

                    if (state.verbose)
                        fprintf(stderr, "Starting capture %d\n", frame);

                    // Fire the capture
                    if (mmal_port_parameter_set_boolean(camera_still_port, MMAL_PARAMETER_CAPTURE, 1) != MMAL_SUCCESS)
                    {
                        vcos_log_error("%s: Failed to start capture", __func__);
                    }
                    else
                    {
                        // Wait for capture to complete
                        // For some reason using vcos_semaphore_wait_timeout sometimes returns immediately with bad parameter error
                        // even though it appears to be all correct, so reverting to untimed one until figure out why its erratic
                        vcos_semaphore_wait(&callback_data.complete_semaphore);

                        if (state.verbose)
                            fprintf(stderr, "Finished capture %d\n", frame);
                    }

                    // Ensure we don't die if get callback with no open file
                    callback_data.file_handle = NULL;

                    if (output_file != stdout)
                        fclose(output_file);
                }
            }
            vcos_semaphore_delete(&callback_data.complete_semaphore);
        }
        else
        {
            mmal_status_to_int(status);
            vcos_log_error("%s: Failed to connect camera to preview", __func__);
        }

error:

        mmal_status_to_int(status);

        if (state.verbose)
            fprintf(stderr, "Closing down\n");

        if (output_file)
            fclose(output_file);

        // Disable all our ports that are not handled by connections
        check_disable_port(camera_video_port);

        if (state.preview_parameters.wantPreview )
            mmal_connection_destroy(state.preview_connection);

        /* Disable components */
        if (state.preview_parameters.preview_component)
            mmal_component_disable(state.preview_parameters.preview_component);

        if (state.camera_component)
            mmal_component_disable(state.camera_component);

        raspipreview_destroy(&state.preview_parameters);
        destroy_camera_component(&state);

        if (state.verbose)
            fprintf(stderr, "Close down completed, all components disconnected, disabled and destroyed\n\n");
    }

    if (status != MMAL_SUCCESS)
        raspicamcontrol_check_configuration(128);

    return 0;
}
Exemplo n.º 4
0
/**
 * main
 */
int main(int argc, const char **argv)
{
	// *** MODIFICATION: OpenCV modifications.
	// Load previous image.
	IplImage* prevImage = cvLoadImage("motion1.jpg", CV_LOAD_IMAGE_COLOR);
		
	// Create two arrays with the same number of channels than the original one.		
	avg1 = cvCreateMat(prevImage->height,prevImage->width,CV_32FC3);
	avg2 = cvCreateMat(prevImage->height,prevImage->width,CV_32FC3);
		
	// Create image of 32 bits.
	IplImage* image32 = cvCreateImage(cvSize(prevImage->width,prevImage->height), 32,3);
												
	// Convert image to 32 bits.
	cvConvertScale(prevImage,image32,1/255,0);
		
	// Set data from previous image into arrays.
	cvSetData(avg1,image32->imageData,image32->widthStep);
	cvSetData(avg2,image32->imageData,image32->widthStep);
	// *** MODIFICATION end
	
   // Our main data storage vessel..
   RASPISTILL_STATE state;

   MMAL_STATUS_T status = MMAL_SUCCESS;
   MMAL_PORT_T *camera_preview_port = NULL;
   MMAL_PORT_T *camera_video_port = NULL;
   MMAL_PORT_T *camera_still_port = NULL;
   MMAL_PORT_T *preview_input_port = NULL;
   MMAL_PORT_T *encoder_input_port = NULL;
   MMAL_PORT_T *encoder_output_port = NULL;

   bcm_host_init();

   // Register our application with the logging system
   vcos_log_register("fast", VCOS_LOG_CATEGORY);

   signal(SIGINT, signal_handler);

   default_status(&state);     
   
   if (state.verbose)
   {
      fprintf(stderr, "\n%s Camera App %s\n\n", basename(argv[0]), VERSION_STRING);      
   }

   // OK, we have a nice set of parameters. Now set up our components
   // We have three components. Camera, Preview and encoder.
   // Camera and encoder are different in stills/video, but preview
   // is the same so handed off to a separate module

   if ((status = create_camera_component(&state)) != MMAL_SUCCESS)
   {
      vcos_log_error("%s: Failed to create camera component", __func__);
   }
   else if ((status = raspipreview_create(&state.preview_parameters)) != MMAL_SUCCESS)
   {
      vcos_log_error("%s: Failed to create preview component", __func__);
      destroy_camera_component(&state);
   }
   else if ((status = create_encoder_component(&state)) != MMAL_SUCCESS)
   {
      vcos_log_error("%s: Failed to create encode component", __func__);
      raspipreview_destroy(&state.preview_parameters);
      destroy_camera_component(&state);
   }
   else
   {
      PORT_USERDATA callback_data;

      if (state.verbose)
         fprintf(stderr, "Starting component connection stage\n");
         
      camera_preview_port = state.camera_component->output[MMAL_CAMERA_PREVIEW_PORT];
      camera_video_port   = state.camera_component->output[MMAL_CAMERA_VIDEO_PORT];
      camera_still_port   = state.camera_component->output[MMAL_CAMERA_CAPTURE_PORT];
      preview_input_port  = state.preview_parameters.preview_component->input[0];
      encoder_input_port  = state.encoder_component->input[0];
      encoder_output_port = state.encoder_component->output[0];

      if (state.preview_parameters.wantPreview )
      {
         if (state.verbose)
         {
            fprintf(stderr, "Connecting camera preview port to preview input port\n");
            fprintf(stderr, "Starting video preview\n");
         }

         // *** USER: remove preview
         // Connect camera to preview
         //status = connect_ports(camera_preview_port, preview_input_port, &state.preview_connection);

      }
      else
      {
         status = MMAL_SUCCESS;
      }

      if (status == MMAL_SUCCESS)
      {
         VCOS_STATUS_T vcos_status;

         if (state.verbose)
            fprintf(stderr, "Connecting camera stills port to encoder input port\n");

         // Now connect the camera to the encoder
         status = connect_ports(camera_still_port, encoder_input_port, &state.encoder_connection);
         

         if (status != MMAL_SUCCESS)
         {
            vcos_log_error("%s: Failed to connect camera video port to encoder input", __func__);
            goto error;
         }

         // Set up our userdata - this is passed though to the callback where we need the information.
         // Null until we open our filename
         callback_data.file_handle = NULL;
         callback_data.pstate = &state;
         vcos_status = vcos_semaphore_create(&callback_data.complete_semaphore, "RaspiStill-sem", 0);

         vcos_assert(vcos_status == VCOS_SUCCESS);

         if (status != MMAL_SUCCESS)
         {
            vcos_log_error("Failed to setup encoder output");
            goto error;
         }
         
         FILE *output_file = NULL;
         
         int frame = 1;
         
         // Enable the encoder output port
         encoder_output_port->userdata = (struct MMAL_PORT_USERDATA_T *)&callback_data;
         
         if (state.verbose)
			fprintf(stderr, "Enabling encoder output port\n");
			
		// Enable the encoder output port and tell it its callback function
		status = mmal_port_enable(encoder_output_port, encoder_buffer_callback);
		
		// Create an empty matrix with the size of the buffer.
		CvMat* buf = cvCreateMat(1,60000,CV_8UC1);
		
		// Keep buffer that gets frames from queue.
		MMAL_BUFFER_HEADER_T *buffer;
		
		// Image to be displayed.
		IplImage* image;
		
		// Keep number of buffers and index for the loop.
		int num, q; 
		
		while(1) 
		{
			// Send all the buffers to the encoder output port
			num = mmal_queue_length(state.encoder_pool->queue);
			
			for (q=0;q<num;q++)
			{
				buffer = mmal_queue_get(state.encoder_pool->queue);
				
				if (!buffer)
					vcos_log_error("Unable to get a required buffer %d from pool queue", q);
					
				if (mmal_port_send_buffer(encoder_output_port, buffer)!= MMAL_SUCCESS)
					vcos_log_error("Unable to send a buffer to encoder output port (%d)", q);
			} // for
			
			if (mmal_port_parameter_set_boolean(camera_still_port, MMAL_PARAMETER_CAPTURE, 1) != MMAL_SUCCESS)
				vcos_log_error("%s: Failed to start capture", __func__);
			
			else
			{
				// Wait for capture to complete
				// For some reason using vcos_semaphore_wait_timeout sometimes returns immediately with bad parameter error
				// even though it appears to be all correct, so reverting to untimed one until figure out why its erratic
				vcos_semaphore_wait(&callback_data.complete_semaphore);
				if (state.verbose)
					fprintf(stderr, "Finished capture %d\n", frame);
			} // else
			
			// Copy buffer from camera to matrix.
			buf->data.ptr = buffer->data;
			
			// This workaround is needed for the code to work
			// *** TODO: investigate why.
			printf("Until here works\n");
			
			// Decode the image and display it.
			image = cvDecodeImage(buf, CV_LOAD_IMAGE_COLOR);
		
			// Destinations
			CvMat* res1 = cvCreateMat(image->height,image->width,CV_8UC3);
			CvMat* res2 = cvCreateMat(image->height,image->width,CV_8UC3);
		
			// Update running averages and then scale, calculate absolute values
			// and convert the result 8-bit.
			// *** USER:change the value of the weight.
			cvRunningAvg(image,avg2,0.0001, NULL);		
			cvConvertScaleAbs(avg2, res2, 1,0);
		
			cvRunningAvg(image,avg1,0.1, NULL);
			cvConvertScaleAbs(avg1, res1, 1,0);
				
			// Show images
			cvShowImage("img",image);
			cvShowImage("avg1",res1);
			cvShowImage("avg2",res2);
			cvWaitKey(20);
		
			// Update previous image.
			cvSaveImage("motion1.jpg", image, 0);
		} // end while 
		
		vcos_semaphore_delete(&callback_data.complete_semaphore);
         
      }
      else
      {
         mmal_status_to_int(status);
         vcos_log_error("%s: Failed to connect camera to preview", __func__);
      }

error:

      mmal_status_to_int(status);

      if (state.verbose)
         fprintf(stderr, "Closing down\n");

      // Disable all our ports that are not handled by connections
      check_disable_port(camera_video_port);
      check_disable_port(encoder_output_port);

      if (state.preview_parameters.wantPreview )
         mmal_connection_destroy(state.preview_connection);

      mmal_connection_destroy(state.encoder_connection);

      /* Disable components */
      if (state.encoder_component)
         mmal_component_disable(state.encoder_component);

      if (state.preview_parameters.preview_component)
         mmal_component_disable(state.preview_parameters.preview_component);

      if (state.camera_component)
         mmal_component_disable(state.camera_component);

      destroy_encoder_component(&state);
      raspipreview_destroy(&state.preview_parameters);
      destroy_camera_component(&state);

      if (state.verbose)
         fprintf(stderr, "Close down completed, all components disconnected, disabled and destroyed\n\n");
   }

   if (status != MMAL_SUCCESS)
      raspicamcontrol_check_configuration(128);
      
   return 0;
}
Exemplo n.º 5
0
/**
 * main
 */
int main(int argc, const char **argv)
{
   // Our main data storage vessel..
   RASPIVID_STATE state;

   MMAL_STATUS_T status;
   MMAL_PORT_T *camera_preview_port = NULL;
   MMAL_PORT_T *camera_video_port = NULL;
   MMAL_PORT_T *camera_still_port = NULL;
   MMAL_PORT_T *preview_input_port = NULL;
   MMAL_PORT_T *encoder_input_port = NULL;
   MMAL_PORT_T *encoder_output_port = NULL;
   FILE *output_file = NULL;

   // Register our application with the logging system
   vcos_log_register("RaspiVid", VCOS_LOG_CATEGORY);

   printf("\nRaspiVid Camera App\n");
   printf("===================\n\n");

   signal(SIGINT, signal_handler);

   default_status(&state);

   // Do we have any parameters
   if (argc == 1)
   {
      display_valid_parameters();
      exit(0);
   }

   // Parse the command line and put options in to our status structure
   if (parse_cmdline(argc, argv, &state))
   {
      status = -1;
      exit(0);
   }

   if (state.verbose)
      dump_status(&state);

   // OK, we have a nice set of parameters. Now set up our components
   // We have three components. Camera, Preview and encoder.

   if (!create_camera_component(&state))
   {
      vcos_log_error("%s: Failed to create camera component", __func__);
   }
   else if (!raspipreview_create(&state.preview_parameters))
   {
      vcos_log_error("%s: Failed to create preview component", __func__);
      destroy_camera_component(&state);
   }
   else if (!create_encoder_component(&state))
   {
      vcos_log_error("%s: Failed to create encode component", __func__);
      raspipreview_destroy(&state.preview_parameters);
      destroy_camera_component(&state);
   }
   else
   {
      PORT_USERDATA callback_data;

      if (state.verbose)
         printf("Starting component connection stage\n");

      camera_preview_port = state.camera_component->output[MMAL_CAMERA_PREVIEW_PORT];
      camera_video_port   = state.camera_component->output[MMAL_CAMERA_VIDEO_PORT];
      camera_still_port   = state.camera_component->output[MMAL_CAMERA_CAPTURE_PORT];
      preview_input_port  = state.preview_parameters.preview_component->input[0];
      encoder_input_port  = state.encoder_component->input[0];
      encoder_output_port = state.encoder_component->output[0];

      if (state.preview_parameters.wantPreview )
      {
         if (state.verbose)
         {
            printf("Connecting camera preview port to preview input port\n");
            printf("Starting video preview\n");
         }

         // Connect camera to preview
         status = connect_ports(camera_preview_port, preview_input_port, &state.preview_connection);
      }

      if (status == MMAL_SUCCESS)
      {
         VCOS_STATUS_T vcos_status;

         if (state.verbose)
            printf("Connecting camera stills port to encoder input port\n");

         // Now connect the camera to the encoder
         status = connect_ports(camera_video_port, encoder_input_port, &state.encoder_connection);

         if (status != MMAL_SUCCESS)
         {
            vcos_log_error("%s: Failed to connect camera video port to encoder input", __func__);
            goto error;
         }

         if (state.filename)
         {
            if (state.verbose)
               printf("Opening output file %s\n", state.filename);
            output_file = fopen(state.filename, "wb");
            if (!output_file)
            {
               // Notify user, carry on but discarding encoded output buffers
               vcos_log_error("%s: Error opening output file: %s\nNo output file will be generated\n", __func__, state.filename);
            }
         }

         // Set up our userdata - this is passed though to the callback where we need the information.
         callback_data.file_handle = output_file;
         callback_data.pstate = &state;

         vcos_status = vcos_semaphore_create(&callback_data.complete_semaphore, "RaspiStill-sem", 0);
         vcos_assert(vcos_status == VCOS_SUCCESS);


         encoder_output_port->userdata = (struct MMAL_PORT_USERDATA_T *)&callback_data;

         if (state.verbose)
            printf("Enabling encoder output port\n");

         // Enable the encoder output port and tell it its callback function
         status = mmal_port_enable(encoder_output_port, encoder_buffer_callback);

         if (status != MMAL_SUCCESS)
         {
            vcos_log_error("Failed to setup encoder output");
            goto error;
         }

         if (state.demoMode)
         {
            // Run for the user specific time..
            int num_iterations = state.timeout / state.demoInterval;
            int i;

            printf("Running in demo mode\n");
            for (i=0;i<num_iterations;i++)
            {
               raspicamcontrol_cycle_test(state.camera_component);
               vcos_sleep(state.demoInterval);
            }
         }
         else
         {
            // Only encode stuff if we have a filename and it opened
            if (output_file)
            {
               if (state.verbose)
                  printf("Starting video capture\n");


               if (mmal_port_parameter_set_boolean(camera_video_port, MMAL_PARAMETER_CAPTURE, 1) != MMAL_SUCCESS)
               {
                  goto error;
               }

               // Send all the buffers to the encoder output port
               {
                  int num = mmal_queue_length(state.encoder_pool->queue);
                  int q;
                  for (q=0;q<num;q++)
                  {
                     MMAL_BUFFER_HEADER_T *buffer = mmal_queue_get(state.encoder_pool->queue);

                     if (!buffer)
                        vcos_log_error("Unable to get a required buffer %d from pool queue", q);

                     if (mmal_port_send_buffer(encoder_output_port, buffer)!= MMAL_SUCCESS)
                        vcos_log_error("Unable to send a buffer to encoder output port (%d)", q);

                  }
               }

               // Now wait until we need to stop
               vcos_sleep(state.timeout);

               printf("Finished capture\n");
            }
            else
               vcos_sleep(state.timeout);
         }
      }
      else
      {
         mmal_status_to_int(status);
         vcos_log_error("%s: Failed to connect camera to preview", __func__);
      }

error:

      mmal_status_to_int(status);

      if (state.verbose)
         printf("Closing down\n");

      // Disable all our ports that are not handled by connections
      check_disable_port(camera_still_port);
      check_disable_port(encoder_output_port);

      if (state.preview_parameters.wantPreview )
         mmal_connection_destroy(state.preview_connection);
      mmal_connection_destroy(state.encoder_connection);

      // Can now close our file. Note disabling ports may flush buffers which causes
      // problems if we have already closed the file!
      if (output_file)
         fclose(output_file);

      /* Disable components */
      if (state.encoder_component)
         mmal_component_disable(state.encoder_component);

      if (state.preview_parameters.preview_component)
         mmal_component_disable(state.preview_parameters.preview_component);

      if (state.camera_component)
         mmal_component_disable(state.camera_component);

      destroy_encoder_component(&state);
      raspipreview_destroy(&state.preview_parameters);
      destroy_camera_component(&state);

      if (state.verbose)
         printf("Close down completed, all components disconnected, disabled and destroyed\n\n");
   }

   return 0;
}
Exemplo n.º 6
0
/**
 * main
 */
int main(int argc, const char **argv)
{
   // Our main data storage vessel..
   RASPISTILLYUV_STATE state;
   int exit_code = EX_OK;

   MMAL_STATUS_T status = MMAL_SUCCESS;
   MMAL_PORT_T *camera_preview_port = NULL;
   MMAL_PORT_T *camera_video_port = NULL;
   MMAL_PORT_T *camera_still_port = NULL;
   MMAL_PORT_T *preview_input_port = NULL;
   FILE *output_file = NULL;

   bcm_host_init();

   // Register our application with the logging system
   vcos_log_register("RaspiStill", VCOS_LOG_CATEGORY);

   signal(SIGINT, signal_handler);

   // Disable USR1 for the moment - may be reenabled if go in to signal capture mode
   signal(SIGUSR1, SIG_IGN);

   default_status(&state);

   // Do we have any parameters
   if (argc == 1)
   {
      fprintf(stdout, "\n%s Camera App %s\n\n", basename(argv[0]), VERSION_STRING);

      display_valid_parameters(basename(argv[0]));
      exit(EX_USAGE);
   }

   default_status(&state);

   // Parse the command line and put options in to our status structure
   if (parse_cmdline(argc, argv, &state))
   {
      status = -1;
      exit(EX_USAGE);
   }

   if (state.verbose)
   {
      fprintf(stderr, "\n%s Camera App %s\n\n", basename(argv[0]), VERSION_STRING);
      dump_status(&state);
   }

   // OK, we have a nice set of parameters. Now set up our components
   // We have two components. Camera and Preview
   // Camera is different in stills/video, but preview
   // is the same so handed off to a separate module

   if ((status = create_camera_component(&state)) != MMAL_SUCCESS)
   {
      vcos_log_error("%s: Failed to create camera component", __func__);
      exit_code = EX_SOFTWARE;
   }
   else if ((status = raspipreview_create(&state.preview_parameters)) != MMAL_SUCCESS)
   {
      vcos_log_error("%s: Failed to create preview component", __func__);
      destroy_camera_component(&state);
      exit_code = EX_SOFTWARE;
   }
   else
   {
      PORT_USERDATA callback_data;

      if (state.verbose)
         fprintf(stderr, "Starting component connection stage\n");

      camera_preview_port = state.camera_component->output[MMAL_CAMERA_PREVIEW_PORT];
      camera_video_port   = state.camera_component->output[MMAL_CAMERA_VIDEO_PORT];
      camera_still_port   = state.camera_component->output[MMAL_CAMERA_CAPTURE_PORT];

      // Note we are lucky that the preview and null sink components use the same input port
      // so we can simple do this without conditionals
      preview_input_port  = state.preview_parameters.preview_component->input[0];

      // Connect camera to preview (which might be a null_sink if no preview required)
      status = connect_ports(camera_preview_port, preview_input_port, &state.preview_connection);

      if (status == MMAL_SUCCESS)
      {
         VCOS_STATUS_T vcos_status;

         // Set up our userdata - this is passed though to the callback where we need the information.
         // Null until we open our filename
         callback_data.file_handle = NULL;
         callback_data.pstate = &state;

         vcos_status = vcos_semaphore_create(&callback_data.complete_semaphore, "RaspiStill-sem", 0);
         vcos_assert(vcos_status == VCOS_SUCCESS);

         camera_still_port->userdata = (struct MMAL_PORT_USERDATA_T *)&callback_data;

         if (state.verbose)
            fprintf(stderr, "Enabling camera still output port\n");

         // Enable the camera still output port and tell it its callback function
         status = mmal_port_enable(camera_still_port, camera_buffer_callback);

         if (status != MMAL_SUCCESS)
         {
            vcos_log_error("Failed to setup camera output");
            goto error;
         }

         if (state.verbose)
            fprintf(stderr, "Starting video preview\n");


         int frame, keep_looping = 1;
         FILE *output_file = NULL;
         char *use_filename = NULL;      // Temporary filename while image being written
         char *final_filename = NULL;    // Name that file gets once writing complete

         frame = 0;

         while (keep_looping)
         {
             keep_looping = wait_for_next_frame(&state, &frame);

            // Open the file
            if (state.filename)
            {
               if (state.filename[0] == '-')
               {
                  output_file = stdout;

                  // Ensure we don't upset the output stream with diagnostics/info
                  state.verbose = 0;
               }
               else
               {
                  vcos_assert(use_filename == NULL && final_filename == NULL);
                  status = create_filenames(&final_filename, &use_filename, state.filename, frame);
                  if (status  != MMAL_SUCCESS)
                  {
                     vcos_log_error("Unable to create filenames");
                     goto error;
                  }

                  if (state.verbose)
                     fprintf(stderr, "Opening output file %s\n", final_filename);
                     // Technically it is opening the temp~ filename which will be ranamed to the final filename

                  output_file = fopen(use_filename, "wb");

                  if (!output_file)
                  {
                     // Notify user, carry on but discarding encoded output buffers
                     vcos_log_error("%s: Error opening output file: %s\nNo output file will be generated\n", __func__, use_filename);
                  }
               }

               callback_data.file_handle = output_file;
            }

            if (output_file)
            {
               int num, q;

               // There is a possibility that shutter needs to be set each loop.
               if (mmal_status_to_int(mmal_port_parameter_set_uint32(state.camera_component->control, MMAL_PARAMETER_SHUTTER_SPEED, state.camera_parameters.shutter_speed) != MMAL_SUCCESS))
                  vcos_log_error("Unable to set shutter speed");


               // Send all the buffers to the camera output port
               num = mmal_queue_length(state.camera_pool->queue);

               for (q=0;q<num;q++)
               {
                  MMAL_BUFFER_HEADER_T *buffer = mmal_queue_get(state.camera_pool->queue);

                  if (!buffer)
                     vcos_log_error("Unable to get a required buffer %d from pool queue", q);

                  if (mmal_port_send_buffer(camera_still_port, buffer)!= MMAL_SUCCESS)
                     vcos_log_error("Unable to send a buffer to camera output port (%d)", q);
               }

               if (state.burstCaptureMode && frame==1)
               {
                  mmal_port_parameter_set_boolean(state.camera_component->control,  MMAL_PARAMETER_CAMERA_BURST_CAPTURE, 1);
               }

               if (state.verbose)
                  fprintf(stderr, "Starting capture %d\n", frame);

               if (mmal_port_parameter_set_boolean(camera_still_port, MMAL_PARAMETER_CAPTURE, 1) != MMAL_SUCCESS)
               {
                  vcos_log_error("%s: Failed to start capture", __func__);
               }
               else
               {
                  // Wait for capture to complete
                  // For some reason using vcos_semaphore_wait_timeout sometimes returns immediately with bad parameter error
                  // even though it appears to be all correct, so reverting to untimed one until figure out why its erratic
                  vcos_semaphore_wait(&callback_data.complete_semaphore);
                  if (state.verbose)
                     fprintf(stderr, "Finished capture %d\n", frame);
               }

               // Ensure we don't die if get callback with no open file
               callback_data.file_handle = NULL;

               if (output_file != stdout)
               {
                  rename_file(&state, output_file, final_filename, use_filename, frame);
               }
            }

            if (use_filename)
            {
               free(use_filename);
               use_filename = NULL;
            }
            if (final_filename)
            {
               free(final_filename);
               final_filename = NULL;
            }
         } // end for (frame)
         
         vcos_semaphore_delete(&callback_data.complete_semaphore);
      }
      else
      {
         mmal_status_to_int(status);
         vcos_log_error("%s: Failed to connect camera to preview", __func__);
      }

error:

      mmal_status_to_int(status);

      if (state.verbose)
         fprintf(stderr, "Closing down\n");

      if (output_file)
         fclose(output_file);

      // Disable all our ports that are not handled by connections
      check_disable_port(camera_video_port);

      if (state.preview_connection)
         mmal_connection_destroy(state.preview_connection);

      /* Disable components */
      if (state.preview_parameters.preview_component)
         mmal_component_disable(state.preview_parameters.preview_component);

      if (state.camera_component)
         mmal_component_disable(state.camera_component);

      raspipreview_destroy(&state.preview_parameters);
      destroy_camera_component(&state);

      if (state.verbose)
         fprintf(stderr, "Close down completed, all components disconnected, disabled and destroyed\n\n");
   }

   if (status != MMAL_SUCCESS)
      raspicamcontrol_check_configuration(128);

   return exit_code;
}
Exemplo n.º 7
0
int main(int argc, char **argv)
{
   MMAL_STATUS_T status = MMAL_EINVAL;
   MMAL_COMPONENT_T *decoder = 0;
   MMAL_POOL_T *pool_in = 0, *pool_out = 0;
   MMAL_BOOL_T eos_sent = MMAL_FALSE, eos_received = MMAL_FALSE;
   unsigned int count;

   if (argc < 2)
   {
      fprintf(stderr, "invalid arguments\n");
      return -1;
   }

   vcos_semaphore_create(&context.semaphore, "example", 1);

   SOURCE_OPEN(argv[1]);

   /* Create the decoder component.
    * This specific component exposes 2 ports (1 input and 1 output). Like most components
    * its expects the format of its input port to be set by the client in order for it to
    * know what kind of data it will be fed. */
   status = mmal_component_create(MMAL_COMPONENT_DEFAULT_VIDEO_DECODER, &decoder);
   CHECK_STATUS(status, "failed to create decoder");

   /* Enable control port so we can receive events from the component */
   decoder->control->userdata = (void *)&context;
   status = mmal_port_enable(decoder->control, control_callback);
   CHECK_STATUS(status, "failed to enable control port");

   /* Get statistics on the input port */
   MMAL_PARAMETER_CORE_STATISTICS_T stats = {{0}};
   stats.hdr.id = MMAL_PARAMETER_CORE_STATISTICS;
   stats.hdr.size = sizeof(MMAL_PARAMETER_CORE_STATISTICS_T);
   status = mmal_port_parameter_get(decoder->input[0], &stats.hdr);
   CHECK_STATUS(status, "failed to get stats");
   fprintf(stderr, "stats: %i, %i", stats.stats.buffer_count, stats.stats.max_delay);

   /* Set the zero-copy parameter on the input port */
   MMAL_PARAMETER_BOOLEAN_T zc = {{MMAL_PARAMETER_ZERO_COPY, sizeof(zc)}, MMAL_TRUE};
   status = mmal_port_parameter_set(decoder->input[0], &zc.hdr);
   fprintf(stderr, "status: %i\n", status);

   /* Set the zero-copy parameter on the output port */
   status = mmal_port_parameter_set_boolean(decoder->output[0], MMAL_PARAMETER_ZERO_COPY, MMAL_TRUE);
   fprintf(stderr, "status: %i\n", status);

   /* Set format of video decoder input port */
   MMAL_ES_FORMAT_T *format_in = decoder->input[0]->format;
   format_in->type = MMAL_ES_TYPE_VIDEO;
   format_in->encoding = MMAL_ENCODING_H264;
   format_in->es->video.width = 1280;
   format_in->es->video.height = 720;
   format_in->es->video.frame_rate.num = 30;
   format_in->es->video.frame_rate.den = 1;
   format_in->es->video.par.num = 1;
   format_in->es->video.par.den = 1;
   /* If the data is known to be framed then the following flag should be set:
    * format_in->flags |= MMAL_ES_FORMAT_FLAG_FRAMED; */

   SOURCE_READ_CODEC_CONFIG_DATA(codec_header_bytes, codec_header_bytes_size);
   status = mmal_format_extradata_alloc(format_in, codec_header_bytes_size);
   CHECK_STATUS(status, "failed to allocate extradata");
   format_in->extradata_size = codec_header_bytes_size;
   if (format_in->extradata_size)
      memcpy(format_in->extradata, codec_header_bytes, format_in->extradata_size);

   status = mmal_port_format_commit(decoder->input[0]);
   CHECK_STATUS(status, "failed to commit format");

   /* Our decoder can do internal colour conversion, ask for a conversion to RGB565 */
   MMAL_ES_FORMAT_T *format_out = decoder->output[0]->format;
   format_out->encoding = MMAL_ENCODING_RGB16;
   status = mmal_port_format_commit(decoder->output[0]);
   CHECK_STATUS(status, "failed to commit format");

   /* Display the output port format */
   fprintf(stderr, "%s\n", decoder->output[0]->name);
   fprintf(stderr, " type: %i, fourcc: %4.4s\n", format_out->type, (char *)&format_out->encoding);
   fprintf(stderr, " bitrate: %i, framed: %i\n", format_out->bitrate,
           !!(format_out->flags & MMAL_ES_FORMAT_FLAG_FRAMED));
   fprintf(stderr, " extra data: %i, %p\n", format_out->extradata_size, format_out->extradata);
   fprintf(stderr, " width: %i, height: %i, (%i,%i,%i,%i)\n",
           format_out->es->video.width, format_out->es->video.height,
           format_out->es->video.crop.x, format_out->es->video.crop.y,
           format_out->es->video.crop.width, format_out->es->video.crop.height);

   /* The format of both ports is now set so we can get their buffer requirements and create
    * our buffer headers. We use the buffer pool API to create these. */
   decoder->input[0]->buffer_num = decoder->input[0]->buffer_num_min;
   decoder->input[0]->buffer_size = decoder->input[0]->buffer_size_min;
   decoder->output[0]->buffer_num = decoder->output[0]->buffer_num_min;
   decoder->output[0]->buffer_size = decoder->output[0]->buffer_size_min;
   pool_in = mmal_pool_create(decoder->input[0]->buffer_num,
                              decoder->input[0]->buffer_size);
   pool_out = mmal_pool_create(decoder->output[0]->buffer_num,
                               decoder->output[0]->buffer_size);

   /* Create a queue to store our decoded video frames. The callback we will get when
    * a frame has been decoded will put the frame into this queue. */
   context.queue = mmal_queue_create();

   /* Store a reference to our context in each port (will be used during callbacks) */
   decoder->input[0]->userdata = (void *)&context;
   decoder->output[0]->userdata = (void *)&context;

   /* Enable all the input port and the output port.
    * The callback specified here is the function which will be called when the buffer header
    * we sent to the component has been processed. */
   status = mmal_port_enable(decoder->input[0], input_callback);
   CHECK_STATUS(status, "failed to enable input port");
   status = mmal_port_enable(decoder->output[0], output_callback);
   CHECK_STATUS(status, "failed to enable output port");

   /* Component won't start processing data until it is enabled. */
   status = mmal_component_enable(decoder);
   CHECK_STATUS(status, "failed to enable component");

   /* Start decoding */
   fprintf(stderr, "start decoding\n");

   /* This is the main processing loop */
   for (count = 0; !eos_received && count < 500; count++)
   {
      MMAL_BUFFER_HEADER_T *buffer;

      /* Wait for buffer headers to be available on either of the decoder ports */
      vcos_semaphore_wait(&context.semaphore);

      /* Check for errors */
      if (context.status != MMAL_SUCCESS)
         break;

      /* Send data to decode to the input port of the video decoder */
      if (!eos_sent && (buffer = mmal_queue_get(pool_in->queue)) != NULL)
      {
         SOURCE_READ_DATA_INTO_BUFFER(buffer);
         if(!buffer->length) eos_sent = MMAL_TRUE;

         buffer->flags = buffer->length ? 0 : MMAL_BUFFER_HEADER_FLAG_EOS;
         buffer->pts = buffer->dts = MMAL_TIME_UNKNOWN;
         fprintf(stderr, "sending %i bytes\n", (int)buffer->length);
         status = mmal_port_send_buffer(decoder->input[0], buffer);
         CHECK_STATUS(status, "failed to send buffer");
      }

      /* Get our decoded frames */
      while ((buffer = mmal_queue_get(context.queue)) != NULL)
      {
         /* We have a frame, do something with it (why not display it for instance?).
          * Once we're done with it, we release it. It will automatically go back
          * to its original pool so it can be reused for a new video frame.
          */
         eos_received = buffer->flags & MMAL_BUFFER_HEADER_FLAG_EOS;

         if (buffer->cmd)
            fprintf(stderr, "received event %4.4s", (char *)&buffer->cmd);
         else
            fprintf(stderr, "decoded frame (flags %x)\n", buffer->flags);
         mmal_buffer_header_release(buffer);
      }

      /* Send empty buffers to the output port of the decoder */
      while ((buffer = mmal_queue_get(pool_out->queue)) != NULL)
      {
         status = mmal_port_send_buffer(decoder->output[0], buffer);
         CHECK_STATUS(status, "failed to send buffer");
      }
}

   /* Stop decoding */
   fprintf(stderr, "stop decoding\n");

   /* Stop everything. Not strictly necessary since mmal_component_destroy()
    * will do that anyway */
   mmal_port_disable(decoder->input[0]);
   mmal_port_disable(decoder->output[0]);
   mmal_component_disable(decoder);

 error:
   /* Cleanup everything */
   if (decoder)
      mmal_component_destroy(decoder);
   if (pool_in)
      mmal_pool_destroy(pool_in);
   if (pool_out)
      mmal_pool_destroy(pool_out);
   if (context.queue)
      mmal_queue_destroy(context.queue);

   SOURCE_CLOSE();
   vcos_semaphore_delete(&context.semaphore);
   return status == MMAL_SUCCESS ? 0 : -1;
}
Exemplo n.º 8
0
/**
 * main
 */
int main(int argc, const char **argv)
{
   // Our main data storage vessel..
   RASPISTILL_STATE state;

   MMAL_STATUS_T status = -1;
   MMAL_PORT_T *camera_preview_port = NULL;
   MMAL_PORT_T *camera_video_port = NULL;
   MMAL_PORT_T *camera_still_port = NULL;
   MMAL_PORT_T *preview_input_port = NULL;
   MMAL_PORT_T *encoder_input_port = NULL;
   MMAL_PORT_T *encoder_output_port = NULL;

   bcm_host_init();


   signal(SIGINT, signal_handler);

   default_status(&state);

   if (!create_camera_component(&state))
   {
      vcos_log_error("%s: Failed to create camera component", __func__);
   }
   else if ( (status = raspipreview_create(&state.preview_parameters)) != MMAL_SUCCESS)
   {
      vcos_log_error("%s: Failed to create preview component", __func__);
      destroy_camera_component(&state);
   }
   else if (!create_encoder_component(&state))
   {
      vcos_log_error("%s: Failed to create encode component", __func__);
      raspipreview_destroy(&state.preview_parameters);
      destroy_camera_component(&state);
   }
   else
   {
      PORT_USERDATA callback_data;

		// *** PR : we don't want preview
      camera_preview_port = NULL;//state.camera_component->output[MMAL_CAMERA_PREVIEW_PORT];
      camera_video_port   = state.camera_component->output[MMAL_CAMERA_VIDEO_PORT];
      camera_still_port   = state.camera_component->output[MMAL_CAMERA_CAPTURE_PORT];
      preview_input_port  = state.preview_parameters.preview_component->input[0];
      encoder_input_port  = state.encoder_component->input[0];
      encoder_output_port = state.encoder_component->output[0];

      if (state.preview_parameters.wantPreview )
      {
         if (state.verbose)
         {
            fprintf(stderr, "Connecting camera preview port to preview input port\n");
            fprintf(stderr, "Starting video preview\n");
         }
		// PR : we don't want preview
        // Connect camera to preview
        // status = connect_ports(camera_preview_port, preview_input_port, &state.preview_connection);
      }
          VCOS_STATUS_T vcos_status;

         if (state.verbose)
            fprintf(stderr, "Connecting camera stills port to encoder input port\n");

         // Now connect the camera to the encoder
         status = connect_ports(camera_still_port, encoder_input_port, &state.encoder_connection);

         if (status != MMAL_SUCCESS)
         {
            vcos_log_error("%s: Failed to connect camera video port to encoder input", __func__);
            goto error;
         }

         // Set up our userdata - this is passed though to the callback where we need the information.
         // Null until we open our filename
         callback_data.file_handle = NULL;
         callback_data.pstate = &state;
         vcos_status = vcos_semaphore_create(&callback_data.complete_semaphore, "RaspiStill-sem", 0);

         vcos_assert(vcos_status == VCOS_SUCCESS);

         encoder_output_port->userdata = (struct MMAL_PORT_USERDATA_T *)&callback_data;

         if (state.verbose)
            fprintf(stderr, "Enabling encoder output port\n");

         // Enable the encoder output port and tell it its callback function
         status = mmal_port_enable(encoder_output_port, encoder_buffer_callback);

         if (status != MMAL_SUCCESS)
         {
            vcos_log_error("Failed to setup encoder output");
            goto error;
         }

                {
            int num_iterations =  state.timelapse ? state.timeout / state.timelapse : 1;
            int frame;
            for (frame = 1;frame<=num_iterations; frame++)
            {
               if (state.timelapse)
                  vcos_sleep(state.timelapse);
               else
                  vcos_sleep(state.timeout);

                  // Send all the buffers to the encoder output port
                  int num = mmal_queue_length(state.encoder_pool->queue);
                  int q;

                  for (q=0;q<num;q++)
                  {
                     MMAL_BUFFER_HEADER_T *buffer = mmal_queue_get(state.encoder_pool->queue);

                     if (!buffer)
                        vcos_log_error("Unable to get a required buffer %d from pool queue", q);

                     if (mmal_port_send_buffer(encoder_output_port, buffer)!= MMAL_SUCCESS)
                        vcos_log_error("Unable to send a buffer to encoder output port (%d)", q);
                  }

                  
                  if (mmal_port_parameter_set_boolean(camera_still_port, MMAL_PARAMETER_CAPTURE, 1) != MMAL_SUCCESS)
                  {
                     vcos_log_error("%s: Failed to start capture", __func__);
                  }
                  else
                  {
                     // Wait for capture to complete
                     // For some reason using vcos_semaphore_wait_timeout sometimes returns immediately with bad parameter error
                     // even though it appears to be all correct, so reverting to untimed one until figure out why its erratic
                     vcos_semaphore_wait(&callback_data.complete_semaphore);
                     
                   }

                                

            } // end for (frame)

            vcos_semaphore_delete(&callback_data.complete_semaphore);
         }
      
error:

      mmal_status_to_int(status);

   
      // Disable all our ports that are not handled by connections
      check_disable_port(camera_video_port);
      check_disable_port(encoder_output_port);

		// PR : we don't want preview
      //if (state.preview_parameters.wantPreview )
        // mmal_connection_destroy(state.preview_connection);

      mmal_connection_destroy(state.encoder_connection);

      /* Disable components */
      if (state.encoder_component)
         mmal_component_disable(state.encoder_component);

      if (state.preview_parameters.preview_component)
         mmal_component_disable(state.preview_parameters.preview_component);

      if (state.camera_component)
         mmal_component_disable(state.camera_component);

      destroy_encoder_component(&state);
      raspipreview_destroy(&state.preview_parameters);
      destroy_camera_component(&state);

      if (state.verbose)
         fprintf(stderr, "Close down completed, all components disconnected, disabled and destroyed\n\n");
   }
   if (status != 0)
      raspicamcontrol_check_configuration(128);



   return 0;
}
Exemplo n.º 9
0
int main (int argc, char* argv[]) {

  MMAL_STATUS_T status;
  int i, max, fd, length, cam_setting;
  unsigned long int cam_setting_long;
  char readbuf[20];
  char *filename_temp, *filename_temp2, *cmd_temp;

  bcm_host_init();
  
  //
  // read arguments
  //
  unsigned char of_set = 0;
  for(i=1; i<argc; i++) {
    if(strcmp(argv[i], "--version") == 0) {
      printf("RaspiMJPEG Version ");
      printf(VERSION);
      printf("\n");
      exit(0);
    }
    else if(strcmp(argv[i], "-w") == 0) {
      i++;
      width = atoi(argv[i]);
    }
    else if(strcmp(argv[i], "-h") == 0) {
      i++;
      height = atoi(argv[i]);
    }
    else if(strcmp(argv[i], "-wp") == 0) {
      i++;
      width_pic = atoi(argv[i]);
    }
    else if(strcmp(argv[i], "-hp") == 0) {
      i++;
      height_pic = atoi(argv[i]);
    }
    else if(strcmp(argv[i], "-q") == 0) {
      i++;
      quality = atoi(argv[i]);
    }
    else if(strcmp(argv[i], "-d") == 0) {
      i++;
      divider = atoi(argv[i]);
    }
    else if(strcmp(argv[i], "-p") == 0) {
      mp4box = 1;
    }
    else if(strcmp(argv[i], "-ic") == 0) {
      i++;
      image2_cnt = atoi(argv[i]);
    }
    else if(strcmp(argv[i], "-vc") == 0) {
      i++;
      video_cnt = atoi(argv[i]);
    }
    else if(strcmp(argv[i], "-of") == 0) {
      i++;
      jpeg_filename = argv[i];
      of_set = 1;
    }
    else if(strcmp(argv[i], "-if") == 0) {
      i++;
      jpeg2_filename = argv[i];
      of_set = 1;
    }
    else if(strcmp(argv[i], "-cf") == 0) {
      i++;
      pipe_filename = argv[i];
    }
    else if(strcmp(argv[i], "-vf") == 0) {
      i++;
      h264_filename = argv[i];
    }
    else if(strcmp(argv[i], "-sf") == 0) {
      i++;
      status_filename = argv[i];
    }
    else if(strcmp(argv[i], "-pa") == 0) {
      autostart = 0;
      idle = 1;
    }
    else if(strcmp(argv[i], "-md") == 0) {
      motion_detection = 1;
    }
    else if(strcmp(argv[i], "-fp") == 0) {
      preview_mode = RES_4_3;
    }
    else if(strcmp(argv[i], "-audio") == 0) {
      audio_mode = 1;
    }
    else error("Invalid arguments");
  }
  if(!of_set) error("Output file not specified");
  
  //
  // init
  //
  if(autostart) start_all();
  if(motion_detection) {
    if(system("motion") == -1) error("Could not start Motion");
  }

  //
  // run
  //
  if(autostart) {
    if(pipe_filename != 0) printf("MJPEG streaming, ready to receive commands\n");
    else printf("MJPEG streaming\n");
  }
  else {
    if(pipe_filename != 0) printf("MJPEG idle, ready to receive commands\n");
    else printf("MJPEG idle\n");
  }

  struct sigaction action;
  memset(&action, 0, sizeof(struct sigaction));
  action.sa_handler = term;
  sigaction(SIGTERM, &action, NULL);
  sigaction(SIGINT, &action, NULL);
  
  if(status_filename != 0) {
    status_file = fopen(status_filename, "w");
    if(!status_file) error("Could not open/create status-file");
    if(autostart) {
      if(!motion_detection) {
        fprintf(status_file, "ready");
      }
      else fprintf(status_file, "md_ready");
    }
    else fprintf(status_file, "halted");
    fclose(status_file);
  }
  
  while(running) {
    if(pipe_filename != 0) {

      fd = open(pipe_filename, O_RDONLY | O_NONBLOCK);
      if(fd < 0) error("Could not open PIPE");
      fcntl(fd, F_SETFL, 0);
      length = read(fd, readbuf, 20);
      close(fd);

      if(length) {
        if((readbuf[0]=='p') && (readbuf[1]=='m')) {
          stop_all();
          readbuf[0] = ' ';
          readbuf[1] = ' ';
          readbuf[length] = 0;
          if(strcmp(readbuf, "   4_3") == 0) preview_mode = RES_4_3;
          else if(strcmp(readbuf, "   16_9_STD") == 0) preview_mode = RES_16_9_STD;
          else if(strcmp(readbuf, "   16_9_WIDE") == 0) preview_mode = RES_16_9_WIDE;
          start_all();
          printf("Changed preview mode\n");
          if(status_filename != 0) {
            status_file = fopen(status_filename, "w");
            fprintf(status_file, "ready");
            fclose(status_file);
          }
        }
        else if((readbuf[0]=='c') && (readbuf[1]=='a')) {
          if(readbuf[3]=='1') {
            if(!capturing) {
              status = mmal_component_enable(h264encoder);
              if(status != MMAL_SUCCESS) error("Could not enable h264encoder");
              pool_h264encoder = mmal_port_pool_create(h264encoder->output[0], h264encoder->output[0]->buffer_num, h264encoder->output[0]->buffer_size);
              if(!pool_h264encoder) error("Could not create pool");
              status = mmal_connection_create(&con_cam_h264, camera->output[1], h264encoder->input[0], MMAL_CONNECTION_FLAG_TUNNELLING | MMAL_CONNECTION_FLAG_ALLOCATION_ON_INPUT);
              if(status != MMAL_SUCCESS) error("Could not create connecton camera -> video converter");
              status = mmal_connection_enable(con_cam_h264);
              if(status != MMAL_SUCCESS) error("Could not enable connection camera -> video converter");
              currTime = time(NULL);
              localTime = localtime (&currTime);
              if(mp4box) {
                asprintf(&filename_temp, h264_filename, video_cnt, localTime->tm_year+1900, localTime->tm_mon+1, localTime->tm_mday, localTime->tm_hour, localTime->tm_min, localTime->tm_sec);
                asprintf(&filename_temp2, "%s.h264", filename_temp);
              }
              else {
                asprintf(&filename_temp2, h264_filename, video_cnt, localTime->tm_year+1900, localTime->tm_mon+1, localTime->tm_mday, localTime->tm_hour, localTime->tm_min, localTime->tm_sec);
              }
              h264output_file = fopen(filename_temp2, "wb");
              free(filename_temp2);
              if(mp4box) { 
			if(audio_mode) {
				asprintf(&cmd_temp, "/usr/bin/arecord -q -D hw:1,0 -f S16_LE -t wav | /usr/bin/lame - %s.mp3 -S &", filename_temp);
				printf("Audio recording with \"%s\\n", cmd_temp);
                		if(system(cmd_temp) == -1) error("Could not start audio recording");
			}
			free(filename_temp);
	      }
              if(!h264output_file) error("Could not open/create video-file");
              status = mmal_port_enable(h264encoder->output[0], h264encoder_buffer_callback);
              if(status != MMAL_SUCCESS) error("Could not enable video port");
              max = mmal_queue_length(pool_h264encoder->queue);
              for(i=0;i<max;i++) {
                MMAL_BUFFER_HEADER_T *h264buffer = mmal_queue_get(pool_h264encoder->queue);
                if(!h264buffer) error("Could not create video pool header");
                status = mmal_port_send_buffer(h264encoder->output[0], h264buffer);
                if(status != MMAL_SUCCESS) error("Could not send buffers to video port");
              }
              mmal_port_parameter_set_boolean(camera->output[1], MMAL_PARAMETER_CAPTURE, 1);
              if(status != MMAL_SUCCESS) error("Could not start capture");
              printf("Capturing started\n");
              if(status_filename != 0) {
                status_file = fopen(status_filename, "w");
                if(!motion_detection) fprintf(status_file, "video");
                else fprintf(status_file, "md_video");
                fclose(status_file);
              }
              capturing = 1;
            }
          }
          else {
            if(capturing) {
              mmal_port_parameter_set_boolean(camera->output[1], MMAL_PARAMETER_CAPTURE, 0);
              if(status != MMAL_SUCCESS) error("Could not stop capture");
              status = mmal_port_disable(h264encoder->output[0]);
              if(status != MMAL_SUCCESS) error("Could not disable video port");
              status = mmal_connection_destroy(con_cam_h264);
              if(status != MMAL_SUCCESS) error("Could not destroy connection camera -> video encoder");
              mmal_port_pool_destroy(h264encoder->output[0], pool_h264encoder);
              if(status != MMAL_SUCCESS) error("Could not destroy video buffer pool");
              status = mmal_component_disable(h264encoder);
              if(status != MMAL_SUCCESS) error("Could not disable video converter");
              fclose(h264output_file);
              h264output_file = NULL;
              printf("Capturing stopped\n");
              if(mp4box) {
                printf("Boxing started\n");
                status_file = fopen(status_filename, "w");
                if(!motion_detection) fprintf(status_file, "boxing");
                else fprintf(status_file, "md_boxing");
                fclose(status_file);
                asprintf(&filename_temp, h264_filename, video_cnt, localTime->tm_year+1900, localTime->tm_mon+1, localTime->tm_mday, localTime->tm_hour, localTime->tm_min, localTime->tm_sec);
		if(audio_mode) {
                	asprintf(&cmd_temp, "/usr/bin/killall arecord > /dev/null");
			if(system(cmd_temp) == -1) error("Could not stop audio recording");
			free(cmd_temp);
                	asprintf(&cmd_temp, "MP4Box -fps 25 -add %s.h264 -add %s.mp3 %s > /dev/null", filename_temp, filename_temp, filename_temp);
		} else {
			asprintf(&cmd_temp, "MP4Box -fps 25 -add %s.h264 %s > /dev/null", filename_temp, filename_temp);
		}
                if(system(cmd_temp) == -1) error("Could not start MP4Box");
                asprintf(&filename_temp2, "%s.h264", filename_temp);
                remove(filename_temp2);
                free(filename_temp2);
		if (audio_mode) {
                	asprintf(&filename_temp2, "%s.mp3", filename_temp);
                	remove(filename_temp2);
                	free(filename_temp2);
		}
                free(filename_temp);
                free(cmd_temp);
                printf("Boxing stopped\n");
              }
              video_cnt++;
              if(status_filename != 0) {
                status_file = fopen(status_filename, "w");
                if(!motion_detection) fprintf(status_file, "ready");
                else fprintf(status_file, "md_ready");
                fclose(status_file);
              }
              capturing = 0;
            }
          }
        }
        else if((readbuf[0]=='i') && (readbuf[1]=='m')) {
          capt_img();
        }
        else if((readbuf[0]=='t') && (readbuf[1]=='l')) {
          readbuf[0] = ' ';
          readbuf[1] = ' ';
          readbuf[length] = 0;
          time_between_pic = atoi(readbuf);
          if(time_between_pic) {
            if(status_filename != 0) {
              status_file = fopen(status_filename, "w");
              fprintf(status_file, "timelapse");
              fclose(status_file);
            }
            timelapse = 1;
            printf("Timelapse started\n");
          }
          else {
            if(status_filename != 0) {
              status_file = fopen(status_filename, "w");
              fprintf(status_file, "ready");
              fclose(status_file);
            }
            timelapse = 0;
            printf("Timelapse stopped\n");
          }
        }
        else if((readbuf[0]=='s') && (readbuf[1]=='h')) {
          readbuf[0] = ' ';
          readbuf[1] = ' ';
          readbuf[length] = 0;
          cam_setting = atoi(readbuf);
          MMAL_RATIONAL_T value = {cam_setting, 100};
          status = mmal_port_parameter_set_rational(camera->control, MMAL_PARAMETER_SHARPNESS, value);
          if(status != MMAL_SUCCESS) error("Could not set sharpness");
          printf("Sharpness: %d\n", cam_setting);
        }
        else if((readbuf[0]=='c') && (readbuf[1]=='o')) {
          readbuf[0] = ' ';
          readbuf[1] = ' ';
          readbuf[length] = 0;
          cam_setting = atoi(readbuf);
          MMAL_RATIONAL_T value = {cam_setting, 100};
          status = mmal_port_parameter_set_rational(camera->control, MMAL_PARAMETER_CONTRAST, value);
          if(status != MMAL_SUCCESS) error("Could not set contrast");
          printf("Contrast: %d\n", cam_setting);
        }
        else if((readbuf[0]=='b') && (readbuf[1]=='r')) {
          readbuf[0] = ' ';
          readbuf[1] = ' ';
          readbuf[length] = 0;
          cam_setting = atoi(readbuf);
          MMAL_RATIONAL_T value = {cam_setting, 100};
          status = mmal_port_parameter_set_rational(camera->control, MMAL_PARAMETER_BRIGHTNESS, value);
          if(status != MMAL_SUCCESS) error("Could not set brightness");
          printf("Brightness: %d\n", cam_setting);
        }
        else if((readbuf[0]=='s') && (readbuf[1]=='a')) {
          readbuf[0] = ' ';
          readbuf[1] = ' ';
          readbuf[length] = 0;
          cam_setting = atoi(readbuf);
          MMAL_RATIONAL_T value = {cam_setting, 100};
          status = mmal_port_parameter_set_rational(camera->control, MMAL_PARAMETER_SATURATION, value);
          if(status != MMAL_SUCCESS) error("Could not set saturation");
          printf("Saturation: %d\n", cam_setting);
        }
        else if((readbuf[0]=='i') && (readbuf[1]=='s')) {
          readbuf[0] = ' ';
          readbuf[1] = ' ';
          readbuf[length] = 0;
          cam_setting = atoi(readbuf);
          status = mmal_port_parameter_set_uint32(camera->control, MMAL_PARAMETER_ISO, cam_setting);
          if(status != MMAL_SUCCESS) error("Could not set ISO");
          printf("ISO: %d\n", cam_setting);
        }
        else if((readbuf[0]=='v') && (readbuf[1]=='s')) {
          if(readbuf[3]=='1') {
            status = mmal_port_parameter_set_boolean(camera->control, MMAL_PARAMETER_VIDEO_STABILISATION, 1);
            printf("Video Stabilisation ON\n");
          }
          else {
            status = mmal_port_parameter_set_boolean(camera->control, MMAL_PARAMETER_VIDEO_STABILISATION, 0);
            printf("Video Stabilisation OFF\n");
          }
          if(status != MMAL_SUCCESS) error("Could not set video stabilisation");
        }
        else if((readbuf[0]=='e') && (readbuf[1]=='c')) {
          readbuf[0] = ' ';
          readbuf[1] = ' ';
          readbuf[length] = 0;
          cam_setting = atoi(readbuf);
          status = mmal_port_parameter_set_int32(camera->control, MMAL_PARAMETER_EXPOSURE_COMP, cam_setting);
          if(status != MMAL_SUCCESS) error("Could not set exposure compensation");
          printf("Exposure Compensation: %d\n", cam_setting);
        }
        else if((readbuf[0]=='e') && (readbuf[1]=='m')) {
          readbuf[0] = ' ';
          readbuf[1] = ' ';
          readbuf[length] = 0;
          MMAL_PARAM_EXPOSUREMODE_T mode = MMAL_PARAM_EXPOSUREMODE_OFF;
          if(strcmp(readbuf, "   auto") == 0) mode = MMAL_PARAM_EXPOSUREMODE_AUTO;
          else if(strcmp(readbuf, "   night") == 0) mode = MMAL_PARAM_EXPOSUREMODE_NIGHT;
          else if(strcmp(readbuf, "   nightpreview") == 0) mode = MMAL_PARAM_EXPOSUREMODE_NIGHTPREVIEW;
          else if(strcmp(readbuf, "   backlight") == 0) mode = MMAL_PARAM_EXPOSUREMODE_BACKLIGHT;
          else if(strcmp(readbuf, "   spotlight") == 0) mode = MMAL_PARAM_EXPOSUREMODE_SPOTLIGHT;
          else if(strcmp(readbuf, "   sports") == 0) mode = MMAL_PARAM_EXPOSUREMODE_SPORTS;
          else if(strcmp(readbuf, "   snow") == 0) mode = MMAL_PARAM_EXPOSUREMODE_SNOW;
          else if(strcmp(readbuf, "   beach") == 0) mode = MMAL_PARAM_EXPOSUREMODE_BEACH;
          else if(strcmp(readbuf, "   verylong") == 0) mode = MMAL_PARAM_EXPOSUREMODE_VERYLONG;
          else if(strcmp(readbuf, "   fixedfps") == 0) mode = MMAL_PARAM_EXPOSUREMODE_FIXEDFPS;
          else if(strcmp(readbuf, "   antishake") == 0) mode = MMAL_PARAM_EXPOSUREMODE_ANTISHAKE;
          else if(strcmp(readbuf, "   fireworks") == 0) mode = MMAL_PARAM_EXPOSUREMODE_FIREWORKS;
          MMAL_PARAMETER_EXPOSUREMODE_T exp_mode = {{MMAL_PARAMETER_EXPOSURE_MODE,sizeof(exp_mode)}, mode};
          status = mmal_port_parameter_set(camera->control, &exp_mode.hdr);
          if(status != MMAL_SUCCESS) error("Could not set exposure mode");
          printf("Exposure mode changed\n");
        }
        else if((readbuf[0]=='w') && (readbuf[1]=='b')) {
          readbuf[0] = ' ';
          readbuf[1] = ' ';
          readbuf[length] = 0;
          MMAL_PARAM_AWBMODE_T awb_mode = MMAL_PARAM_AWBMODE_OFF;
          if(strcmp(readbuf, "   auto") == 0) awb_mode = MMAL_PARAM_AWBMODE_AUTO;
          else if(strcmp(readbuf, "   auto") == 0) awb_mode = MMAL_PARAM_AWBMODE_AUTO;
          else if(strcmp(readbuf, "   sun") == 0) awb_mode = MMAL_PARAM_AWBMODE_SUNLIGHT;
          else if(strcmp(readbuf, "   cloudy") == 0) awb_mode = MMAL_PARAM_AWBMODE_CLOUDY;
          else if(strcmp(readbuf, "   shade") == 0) awb_mode = MMAL_PARAM_AWBMODE_SHADE;
          else if(strcmp(readbuf, "   tungsten") == 0) awb_mode = MMAL_PARAM_AWBMODE_TUNGSTEN;
          else if(strcmp(readbuf, "   fluorescent") == 0) awb_mode = MMAL_PARAM_AWBMODE_FLUORESCENT;
          else if(strcmp(readbuf, "   incandescent") == 0) awb_mode = MMAL_PARAM_AWBMODE_INCANDESCENT;
          else if(strcmp(readbuf, "   flash") == 0) awb_mode = MMAL_PARAM_AWBMODE_FLASH;
          else if(strcmp(readbuf, "   horizon") == 0) awb_mode = MMAL_PARAM_AWBMODE_HORIZON;
          MMAL_PARAMETER_AWBMODE_T param = {{MMAL_PARAMETER_AWB_MODE,sizeof(param)}, awb_mode};
          status = mmal_port_parameter_set(camera->control, &param.hdr);
          if(status != MMAL_SUCCESS) error("Could not set white balance");
          printf("White balance changed\n");
        }
        else if((readbuf[0]=='r') && (readbuf[1]=='o')) {
          readbuf[0] = ' ';
          readbuf[1] = ' ';
          readbuf[length] = 0;
          cam_setting = atoi(readbuf);
          status = mmal_port_parameter_set_int32(camera->output[0], MMAL_PARAMETER_ROTATION, cam_setting);
          if(status != MMAL_SUCCESS) error("Could not set rotation (0)");
          status = mmal_port_parameter_set_int32(camera->output[1], MMAL_PARAMETER_ROTATION, cam_setting);
          if(status != MMAL_SUCCESS) error("Could not set rotation (1)");
          status = mmal_port_parameter_set_int32(camera->output[2], MMAL_PARAMETER_ROTATION, cam_setting);
          if(status != MMAL_SUCCESS) error("Could not set rotation (2)");
          printf("Rotation: %d\n", cam_setting);
        }
        else if((readbuf[0]=='q') && (readbuf[1]=='u')) {
          readbuf[0] = ' ';
          readbuf[1] = ' ';
          readbuf[length] = 0;
          cam_setting = atoi(readbuf);
          status = mmal_port_parameter_set_uint32(jpegencoder2->output[0], MMAL_PARAMETER_JPEG_Q_FACTOR, cam_setting);
          if(status != MMAL_SUCCESS) error("Could not set quality");
          printf("Quality: %d\n", cam_setting);
        }
        else if((readbuf[0]=='b') && (readbuf[1]=='i')) {
          readbuf[0] = ' ';
          readbuf[1] = ' ';
          readbuf[length] = 0;
          cam_setting_long = strtoull(readbuf, NULL, 0);
          h264encoder->output[0]->format->bitrate = cam_setting_long;
          status = mmal_port_format_commit(h264encoder->output[0]);
          if(status != MMAL_SUCCESS) error("Could not set bitrate");
          printf("Bitrate: %lu\n", cam_setting_long);
        }
        else if((readbuf[0]=='r') && (readbuf[1]=='u')) {
          if(readbuf[3]=='0') {
            stop_all();
            idle = 1;
            printf("Stream halted\n");
            if(status_filename != 0) {
              status_file = fopen(status_filename, "w");
              fprintf(status_file, "halted");
              fclose(status_file);
            }
          }
          else {
            start_all();
            idle = 0;
            printf("Stream continued\n");
            if(status_filename != 0) {
              status_file = fopen(status_filename, "w");
              fprintf(status_file, "ready");
              fclose(status_file);
            }
          }
        }
        else if((readbuf[0]=='m') && (readbuf[1]=='d')) {
          if(readbuf[3]=='0') {
            motion_detection = 0;
            if(system("killall motion") == -1) error("Could not stop Motion");
            printf("Motion detection stopped\n");
            if(status_filename != 0) {
              status_file = fopen(status_filename, "w");
              fprintf(status_file, "ready");
              fclose(status_file);
            }
          }
          else {
            motion_detection = 1;
            if(system("motion") == -1) error("Could not start Motion");
            printf("Motion detection started\n");
            if(status_filename != 0) {
              status_file = fopen(status_filename, "w");
              fprintf(status_file, "md_ready");
              fclose(status_file);
            }
          }
        }
      }

    }
    if(timelapse) {
      tl_cnt++;
      if(tl_cnt >= time_between_pic) {
        if(capturing == 0) {
          capt_img();
          tl_cnt = 0;
        }
      }
    }
    usleep(100000);
  }
  
  printf("SIGINT/SIGTERM received, stopping\n");
  
  //
  // tidy up
  //
  if(!idle) stop_all();

  return 0;

}
Exemplo n.º 10
0
/**
 * main
 */
int main(int argc, const char **argv)
{
  // Our main data storage vessel..
  RASPIVID_STATE state;

  MMAL_STATUS_T status = -1;
  MMAL_PORT_T *camera_video_port = NULL;
  MMAL_PORT_T *camera_still_port = NULL;
  MMAL_PORT_T *preview_input_port = NULL;
  MMAL_PORT_T *encoder_input_port = NULL;
  MMAL_PORT_T *encoder_output_port = NULL;

  time_t timer_begin,timer_end;
  double secondsElapsed;

  bcm_host_init();
  signal(SIGINT, signal_handler);

  // read default status
  default_status(&state);

  // init windows and OpenCV Stuff
  cvNamedWindow("camcvWin", CV_WINDOW_AUTOSIZE);
  int w=state.width;
  int h=state.height;

  int minsz = 20;
  int maxsz = 80;
  float scalefact = 1.2;
  int minneigh = 3;
  char tracking = 1;
  int i;
  // List of long program options, to be passed as "--option=xx"
  char *params[] = {"minsize", "maxsize", "scalefactor", "minneighbors", "disabletracking"};

  for (i = 1; i < argc; i++)
  {
    const char *s = argv[i];
    int parnum;

    if (s[0] == '-' && s[1] == '-')
    {
      for (parnum = 0; parnum < sizeof(params) / sizeof(*params); parnum++)
      {
        int len = strlen(params[parnum]);
        if (strstr(s + 2, params[parnum]) == s + 2 && s[len + 2] == '=')
        {
          s += len + 3;
          switch (parnum)
          {
            case 0:
              minsz = atoi(s);
              break;
            case 1:
              maxsz = atoi(s);
              break;
            case 2:
              scalefact = atof(s);
              break;
            case 3:
              minneigh = atoi(s);
              break;
            case 4:
              if (!strcmp(s, "true"))
                tracking = 0;
              else if (!strcmp(s, "false"))
                tracking = 1;
              else
                fprintf(stderr, "Unknown option for --disabletracking: '%s'. Known values are 'true' and 'false'\n", s);
          }
          break;
        }
      }
    }
  }

  fprintf(stderr, "Minimum window search size: %dpx\n", minsz);
  fprintf(stderr, "Maximum window search size: %dpx\n", maxsz);
  fprintf(stderr, "Scale factor: %f\n", scalefact);
  fprintf(stderr, "Minimum required neighbors: %d\n", minneigh);
  fprintf(stderr, "Tracking: %s\n", tracking ? "true" : "false");

  initFaceDetect(state.width, state.height, scalefact, minneigh, minsz, maxsz, tracking);

  // create camera
  if (!create_camera_component(&state))
    {
      vcos_log_error("%s: Failed to create camera component", __func__);
    }
  else if (raspipreview_create(&state.preview_parameters) != MMAL_SUCCESS)
    {
      vcos_log_error("%s: Failed to create preview component", __func__);
      destroy_camera_component(&state);
    }
  else
    {
      PORT_USERDATA callback_data;

      camera_video_port   = state.camera_component->output[MMAL_CAMERA_VIDEO_PORT];
      camera_still_port   = state.camera_component->output[MMAL_CAMERA_CAPTURE_PORT];

      VCOS_STATUS_T vcos_status;

      callback_data.pstate = &state;

      vcos_status = vcos_semaphore_create(&callback_data.complete_semaphore, "RaspiStill-sem", 0);
      vcos_assert(vcos_status == VCOS_SUCCESS);

      // assign data to use for callback
      camera_video_port->userdata = (struct MMAL_PORT_USERDATA_T *)&callback_data;

      // init timer
      time(&timer_begin);


      // start capture
      if (mmal_port_parameter_set_boolean(camera_video_port, MMAL_PARAMETER_CAPTURE, 1) != MMAL_SUCCESS)
	{
	  goto error;
	}

      // Send all the buffers to the video port

      int num = mmal_queue_length(state.video_pool->queue);
      int q;
      for (q=0;q<num;q++)
	{
	  MMAL_BUFFER_HEADER_T *buffer = mmal_queue_get(state.video_pool->queue);

	  if (!buffer)
	    vcos_log_error("Unable to get a required buffer %d from pool queue", q);

	  if (mmal_port_send_buffer(camera_video_port, buffer)!= MMAL_SUCCESS)
	    vcos_log_error("Unable to send a buffer to encoder output port (%d)", q);
	}


      // Now wait until we need to stop
      vcos_sleep(state.timeout);

    error:

      mmal_status_to_int(status);


      // Disable all our ports that are not handled by connections
      check_disable_port(camera_still_port);

      if (state.camera_component)
	mmal_component_disable(state.camera_component);

      //destroy_encoder_component(&state);
      raspipreview_destroy(&state.preview_parameters);
      destroy_camera_component(&state);

    }
  if (status != 0)
    raspicamcontrol_check_configuration(128);

  time(&timer_end);  /* get current time; same as: timer = time(NULL)  */

  secondsElapsed = difftime(timer_end,timer_begin);

  printf ("%.f seconds for %d frames : FPS = %f\n", secondsElapsed,nCount,(float)((float)(nCount)/secondsElapsed));

  return 0;
}
Exemplo n.º 11
0
void internelVideoWithDetails(char *filename, int width, int height, int duration) {
   RASPISTILL_STATE state;   
   MMAL_STATUS_T status = MMAL_SUCCESS;   
   
   
   MMAL_PORT_T *camera_video_port = NULL;
   MMAL_PORT_T *encoder_input_port = NULL;
   MMAL_PORT_T *encoder_output_port = NULL; 
   FILE *output_file = NULL;
    
   if (width > 1920) {
       width = 1920;
   } else if (width < 20) {
       width = 20;
   }
   if (height > 1080) {
       height = 1080;       
   } else if (height < 20) {
       height = 20;
   }
   
   bcm_host_init();       

   default_status(&state);   
   state.width = width;
   state.height = height;
   state.quality = 0;
   state.videoEncode = 1;
   state.filename = filename;
   if ((status = create_video_camera_component(&state)) != MMAL_SUCCESS) {       
      vcos_log_error("%s: Failed to create camera component", __func__);
   } else if ((status = create_video_encoder_component(&state)) != MMAL_SUCCESS) {     
      vcos_log_error("%s: Failed to create encode component", __func__);      
      destroy_camera_component(&state);
   } else {       
      PORT_USERDATA callback_data;    
      camera_video_port   = state.camera_component->output[MMAL_CAMERA_VIDEO_PORT];
      encoder_input_port  = state.encoder_component->input[0];
      encoder_output_port = state.encoder_component->output[0];

        // Now connect the camera to the encoder
      status = connect_ports(camera_video_port, encoder_input_port, &state.encoder_connection);  
     
      if (status != MMAL_SUCCESS) {
          vcos_log_error("%s: Failed to connect camera video port to encoder input", __func__);
          goto error;
      }
      
      // Set up our userdata - this is passed though to the callback where we need the information.
      // Null until we open our filename     
      callback_data.pstate = &state;      
     

      if (status != MMAL_SUCCESS) {
          vcos_log_error("Failed to setup encoder output");
          goto error;
      }
      
      if (state.filename) {
          output_file = fopen(state.filename, "wb");
          callback_data.file_handle = output_file;
          callback_data.pstate = &state;
          callback_data.abort = 0;
      }

      encoder_output_port->userdata = (struct MMAL_PORT_USERDATA_T *)&callback_data;
                                                     
      int wait;

      // Enable the encoder output port and tell it its callback function
      status = mmal_port_enable(encoder_output_port, encoder_buffer_callback);
      if (mmal_port_parameter_set_boolean(camera_video_port, MMAL_PARAMETER_CAPTURE, 1) != MMAL_SUCCESS) {
          goto error;
      }
     // Send all the buffers to the encoder output port
     {
          int num = mmal_queue_length(state.encoder_pool->queue);
          int q;
          for (q=0;q<num;q++) {
             MMAL_BUFFER_HEADER_T *buffer = mmal_queue_get(state.encoder_pool->queue);

             if (!buffer)
                vcos_log_error("Unable to get a required buffer %d from pool queue", q);

             if (mmal_port_send_buffer(encoder_output_port, buffer)!= MMAL_SUCCESS)
                vcos_log_error("Unable to send a buffer to encoder output port (%d)", q);

          }
       }
       for (wait = 0; wait < duration; wait+= ABORT_INTERVAL)  {
          vcos_sleep(ABORT_INTERVAL);
          if (callback_data.abort)
             break;
       }
     
     
     
     
        
      // Disable encoder output port
      status = mmal_port_disable(encoder_output_port);
      
      
           
       vcos_semaphore_delete(&callback_data.complete_semaphore);      
    }
error:    
    mmal_status_to_int(status);
     
    // Disable all our ports that are not handled by connections 
    check_disable_port(encoder_output_port);  
    if (output_file && output_file != stdout)
         fclose(output_file);
      
    mmal_connection_destroy(state.encoder_connection);

    if (state.encoder_component)
        mmal_component_disable(state.encoder_component);
     

    if (state.camera_component)
        mmal_component_disable(state.camera_component);

    destroy_encoder_component(&state);     
    destroy_camera_component(&state);
     

    if (status != MMAL_SUCCESS)
        raspicamcontrol_check_configuration(128);
    
}
Exemplo n.º 12
0
uint8_t *internelPhotoWithDetails(int width, int height, int quality,MMAL_FOURCC_T encoding, PicamParams *parms, long *sizeread) {
   RASPISTILL_STATE state;   
   MMAL_STATUS_T status = MMAL_SUCCESS;   
   
   MMAL_PORT_T *preview_input_port = NULL;
   MMAL_PORT_T *camera_preview_port = NULL;
   MMAL_PORT_T *camera_still_port = NULL;
   MMAL_PORT_T *encoder_input_port = NULL;
   MMAL_PORT_T *encoder_output_port = NULL;  
   if (width > 2592) {
       width = 2592;
   } else if (width < 20) {
       width = 20;
   }
   if (height > 1944) {
       height = 1944;       
   } else if (height < 20) {
       height = 20;
   }
   if (quality > 100) {
       quality = 100;
   } else if (quality < 0) {
       quality = 85; 
   }
   bcm_host_init();          
   default_status(&state);   
   state.width = width;
   state.height = height;
   state.quality = quality;
   state.encoding = encoding;
   state.videoEncode = 0;
   state.camera_parameters.exposureMode = parms->exposure;
   state.camera_parameters.exposureMeterMode = parms->meterMode;
   state.camera_parameters.awbMode = parms->awbMode;
   state.camera_parameters.imageEffect = parms->imageFX;   
   state.camera_parameters.ISO = parms->ISO;
   state.camera_parameters.sharpness = parms->sharpness;           
   state.camera_parameters.contrast = parms->contrast;              
   state.camera_parameters.brightness= parms->brightness;          
   state.camera_parameters.saturation = parms->saturation;           
   state.camera_parameters.videoStabilisation = parms->videoStabilisation;    /// 0 or 1 (false or true)
   state.camera_parameters.exposureCompensation = parms->exposureCompensation; 
   state.camera_parameters.rotation = parms->rotation;
   state.camera_parameters.hflip = parms->hflip;
   state.camera_parameters.vflip = parms->vflip;
      
   MMAL_COMPONENT_T *preview = 0;
   
   if ((status = create_video_camera_component(&state)) != MMAL_SUCCESS) {       
      vcos_log_error("%s: Failed to create camera component", __func__);
   } else if ((status = mmal_component_create("vc.null_sink", &preview)) != MMAL_SUCCESS)  {
      vcos_log_error("%s: Failed to create preview component", __func__);
      destroy_camera_component(&state);   
   } else if ((status = create_encoder_component(&state)) != MMAL_SUCCESS) {     
      vcos_log_error("%s: Failed to create encode component", __func__);      
      destroy_camera_component(&state);
   } else {       
      status = mmal_component_enable(preview);
      state.preview_component = preview;            
      PORT_USERDATA callback_data;    
      camera_preview_port = state.camera_component->output[MMAL_CAMERA_PREVIEW_PORT];
      camera_still_port   = state.camera_component->output[MMAL_CAMERA_CAPTURE_PORT];
      encoder_input_port  = state.encoder_component->input[0];
      encoder_output_port = state.encoder_component->output[0];
      preview_input_port  = state.preview_component->input[0];
      
      status = connect_ports(camera_preview_port, preview_input_port, &state.preview_connection);
    
      VCOS_STATUS_T vcos_status;
         

        // Now connect the camera to the encoder
      status = connect_ports(camera_still_port, encoder_input_port, &state.encoder_connection);      
      if (status != MMAL_SUCCESS) {
          vcos_log_error("%s: Failed to connect camera video port to encoder input", __func__);
          goto error;
      }
      
      // Set up our userdata - this is passed though to the callback where we need the information.
      // Null until we open our filename     
      callback_data.pstate = &state;      
      vcos_status = vcos_semaphore_create(&callback_data.complete_semaphore, "picam-sem", 0);
     
      vcos_assert(vcos_status == VCOS_SUCCESS);

      if (status != MMAL_SUCCESS) {
          vcos_log_error("Failed to setup encoder output");
          goto error;
      }
            
       
      int num, q;                                                
      // Enable the encoder output port
      encoder_output_port->userdata = (struct MMAL_PORT_USERDATA_T *)&callback_data;

      // Enable the encoder output port and tell it its callback function
      status = mmal_port_enable(encoder_output_port, encoder_buffer_callback);

      // Send all the buffers to the encoder output port
      num = mmal_queue_length(state.encoder_pool->queue);

      for (q=0;q<num;q++) {
         MMAL_BUFFER_HEADER_T *buffer = mmal_queue_get(state.encoder_pool->queue);

         if (!buffer)
            vcos_log_error("Unable to get a required buffer %d from pool queue", q);

         if (mmal_port_send_buffer(encoder_output_port, buffer)!= MMAL_SUCCESS)
            vcos_log_error("Unable to send a buffer to encoder output port (%d)", q);
      }

      

      if (mmal_port_parameter_set_boolean(camera_still_port, MMAL_PARAMETER_CAPTURE, 1) != MMAL_SUCCESS) {
         vcos_log_error("%s: Failed to start capture", __func__);
      } else {
         // Wait for capture to complete
         // For some reason using vcos_semaphore_wait_timeout sometimes returns immediately with bad parameter error
         // even though it appears to be all correct, so reverting to untimed one until figure out why its erratic
         vcos_semaphore_wait(&callback_data.complete_semaphore);                
      }                       
      // Disable encoder output port
      status = mmal_port_disable(encoder_output_port);
      
      *sizeread = state.bytesStored;
           
       vcos_semaphore_delete(&callback_data.complete_semaphore);      
    }
error:    
    mmal_status_to_int(status);
     
    // Disable all our ports that are not handled by connections     
    check_disable_port(encoder_output_port);  
    mmal_connection_destroy(state.encoder_connection);

    if (state.encoder_component)
        mmal_component_disable(state.encoder_component);
     
    if (state.preview_component) {
         mmal_component_disable(state.preview_component);        
         mmal_component_destroy(state.preview_component);
         state.preview_component = NULL;    
    }
    if (state.camera_component)
        mmal_component_disable(state.camera_component);
    
    
    destroy_encoder_component(&state);     
    destroy_camera_component(&state);
     

    if (status != MMAL_SUCCESS)
        raspicamcontrol_check_configuration(128);
    
    return state.filedata;
}
Exemplo n.º 13
0
/**
 * main
 */
int main(int argc, const char **argv)
{
	// Our main data storage vessel..
	RASPISTILL_STATE state;
	
	MMAL_STATUS_T status = -1;
	MMAL_PORT_T *camera_preview_port = NULL;
	MMAL_PORT_T *camera_video_port = NULL;
	MMAL_PORT_T *camera_still_port = NULL;
	MMAL_PORT_T *preview_input_port = NULL;
	MMAL_PORT_T *encoder_input_port = NULL;
	MMAL_PORT_T *encoder_output_port = NULL;
	
	bcm_host_init();
	clock_t elapsedTime;
	
	time_t timer_begin,timer_end;
  	double secondsElapsed;
	
  	time(&timer_begin);  /* get current time; same as: timer = time(NULL)  */

	// create window
	cvNamedWindow("camcvWin", CV_WINDOW_AUTOSIZE);//CV_WINDOW_NORMAL);//CV_WINDOW_AUTOSIZE); 
	//cvResizeWindow("camcvWin",640,480);	
	signal(SIGINT, signal_handler);
	
	default_status(&state);
	
	if (!create_camera_component(&state))
	{
	   vcos_log_error("%s: Failed to create camera component", __func__);
	}
	else if ( (status = raspipreview_create(&state.preview_parameters)) != MMAL_SUCCESS)
	{
	   vcos_log_error("%s: Failed to create preview component", __func__);
	   destroy_camera_component(&state);
	}
	else if (!create_encoder_component(&state))
	{
	   vcos_log_error("%s: Failed to create encode component", __func__);
	   raspipreview_destroy(&state.preview_parameters);
	   destroy_camera_component(&state);
	}
	else
	{
		PORT_USERDATA callback_data;
		
		// *** PR : we don't want preview
		camera_preview_port = NULL;//state.camera_component->output[MMAL_CAMERA_PREVIEW_PORT];
		camera_video_port   = state.camera_component->output[MMAL_CAMERA_VIDEO_PORT];
		camera_still_port   = state.camera_component->output[MMAL_CAMERA_CAPTURE_PORT];
		preview_input_port  = state.preview_parameters.preview_component->input[0];
		encoder_input_port  = state.encoder_component->input[0];
		encoder_output_port = state.encoder_component->output[0];
		
		if (state.preview_parameters.wantPreview )
		{
        	// PR : we don't want preview
        	// Connect camera to preview
        	// status = connect_ports(camera_preview_port, preview_input_port, &state.preview_connection);
      	}
        VCOS_STATUS_T vcos_status;

        // Now connect the camera to the encoder
        status = connect_ports(camera_still_port, encoder_input_port, &state.encoder_connection);

		if (status != MMAL_SUCCESS)
		{
		  vcos_log_error("%s: Failed to connect camera video port to encoder input", __func__);
		  goto error;
		}
		
		// Set up our userdata - this is passed though to the callback where we need the information.
		// Null until we open our filename
		//callback_data.file_handle = NULL;
		callback_data.pstate = &state;
		vcos_status = vcos_semaphore_create(&callback_data.complete_semaphore, "RaspiStill-sem", 0);
		
		vcos_assert(vcos_status == VCOS_SUCCESS);
		
		encoder_output_port->userdata = (struct MMAL_PORT_USERDATA_T *)&callback_data;
		
		// Enable the encoder output port and tell it its callback function
		status = mmal_port_enable(encoder_output_port, encoder_buffer_callback);
		
		if (status != MMAL_SUCCESS)
		{
		   vcos_log_error("Failed to setup encoder output");
		   goto error;
		}

                
		int num_iterations =  100;
		int frame,num,q;
		elapsedTime= clock();
		printf("time=%d\n",elapsedTime);
		
		for (frame = 1;frame<=num_iterations; frame++)
		{
		      // Send all the buffers to the encoder output port
		      num = mmal_queue_length(state.encoder_pool->queue);
		      
		      for (q=0;q<num;q++)
		      {
		         MMAL_BUFFER_HEADER_T *buffer = mmal_queue_get(state.encoder_pool->queue);
		
		         //if (!buffer)
		           // vcos_log_error("Unable to get a required buffer %d from pool queue", q);
		
		         if (mmal_port_send_buffer(encoder_output_port, buffer)!= MMAL_SUCCESS)
		            vcos_log_error("Unable to send a buffer to encoder output port (%d)", q);
		      }
		
		      
		      if (mmal_port_parameter_set_boolean(camera_still_port, MMAL_PARAMETER_CAPTURE, 1) != MMAL_SUCCESS)
		      {
		         vcos_log_error("%s: Failed to start capture", __func__);
		      }
		      else
		      {
		         // Wait for capture to complete
		         // For some reason using vcos_semaphore_wait_timeout sometimes returns immediately with bad parameter error
		         // even though it appears to be all correct, so reverting to untimed one until figure out why its erratic
		         vcos_semaphore_wait(&callback_data.complete_semaphore);
		       }
		       
		} // end for (frame)
 			
		vcos_semaphore_delete(&callback_data.complete_semaphore);
        // compute elapsed time since begin of the loop and display
		 
error:

		mmal_status_to_int(status);
		
		
		// Disable all our ports that are not handled by connections
		check_disable_port(camera_video_port);
		check_disable_port(encoder_output_port);
		
		// PR : we don't want preview
		//if (state.preview_parameters.wantPreview )
		// mmal_connection_destroy(state.preview_connection);
		
		mmal_connection_destroy(state.encoder_connection);
		
		/* Disable components */
		if (state.encoder_component)
		mmal_component_disable(state.encoder_component);
		
		if (state.preview_parameters.preview_component)
		mmal_component_disable(state.preview_parameters.preview_component);
		
		if (state.camera_component)
		mmal_component_disable(state.camera_component);
		
		destroy_encoder_component(&state);
		raspipreview_destroy(&state.preview_parameters);
		destroy_camera_component(&state);
		
	}
   if (status != 0)
      raspicamcontrol_check_configuration(128);

	// compute FPS
	time(&timer_end);  /* get current time; same as: timer = time(NULL)  */

  secondsElapsed = difftime(timer_end,timer_begin);

  printf ("%.f seconds for %d frames : FPS = %f", secondsElapsed,nbFrames,(float)((float)(nbFrames)/secondsElapsed));



	printf("time=%d\n",clock());
		
	elapsedTime=clock()-elapsedTime;
		printf ("(time) %d clicks (%f seconds). nb Frames = %d. FPS = %f\n",elapsedTime,((float)elapsedTime)/CLOCKS_PER_SEC, nbFrames, (float)nbFrames/(((float)elapsedTime)/CLOCKS_PER_SEC));   


   return 0;
}