static int write_segmenttemplate_bynumber(MPD_CREATE_CTXT_T *pCtxt, const MPD_ADAPTATION_T *pAdaptation, const MPD_SEGMENT_LIST_T *pSegs, const char *initMediaUrl, unsigned int startNumber, char *buf, unsigned int szbuf) { int rc = 0; unsigned int idx = 0; char mediaUrl[VSX_MAX_PATH_LEN]; if((rc = writepath(pCtxt, -1, "$Number$", mediaUrl, sizeof(mediaUrl), pAdaptation->padaptationTag)) < 0) { return rc; } if((rc = write_tag_segmenttemplate_start(pAdaptation->pMedia, mediaUrl, initMediaUrl, startNumber, &buf[idx], szbuf - idx)) < 0) { return rc; } idx += rc; MPD_WRITE_RET("<SegmentTimeline>"MPD_EOL); if((rc = write_tag_segmententry(pAdaptation->pMedia->timescale, pAdaptation->pMedia->duration, pAdaptation->pMedia->durationPreceeding, &buf[idx], szbuf - idx)) < 0) { return rc; } idx += rc; MPD_WRITE("</SegmentTimeline>"MPD_EOL); MPD_WRITE_RET("</SegmentTemplate>"MPD_EOL); return idx > 0 ? idx : rc; }
static int write_init_path(const MPD_CREATE_CTXT_T *pCtxt, int outidx, char *buf, unsigned int szbuf, const char *adaptationtag) { return writepath(pCtxt, outidx, "init", buf, szbuf, adaptationtag); }
static int write_segmenttemplate_bytime(MPD_CREATE_CTXT_T *pCtxt, const MPD_ADAPTATION_T *pAdaptation, const MPD_SEGMENT_LIST_T *pSegs, const char *initMediaUrl, char *buf, unsigned int szbuf) { int rc = 0; unsigned int idx = 0; unsigned int indexInSegments; unsigned int indexSegment = 0; char mediaUrl[VSX_MAX_PATH_LEN]; if((rc = writepath(pCtxt, -1, "$Time$", mediaUrl, sizeof(mediaUrl), pAdaptation->padaptationTag)) < 0) { return rc; } if((rc = write_tag_segmenttemplate_start(pAdaptation->pMedia, mediaUrl, initMediaUrl, -1, &buf[idx], szbuf - idx)) < 0) { return rc; } idx += rc; if(pSegs->indexInSegments > 0) { indexInSegments = pSegs->indexInSegments - 1; } else { indexInSegments = pSegs->indexCount - 1; } MPD_WRITE_RET("<SegmentTimeline>"MPD_EOL); for(indexSegment = 0; indexSegment < pSegs->indexCount; indexSegment++) { if(++indexInSegments >= pSegs->indexCount) { indexInSegments = 0; } if(!pSegs->pSegments[indexInSegments].valid) { continue; } if((rc = write_tag_segmententry(pSegs->pSegments[indexInSegments].media.timescale, pSegs->pSegments[indexInSegments].media.duration, pSegs->pSegments[indexInSegments].media.durationPreceeding, &buf[idx], szbuf - idx)) < 0) { return rc; } idx += rc; } // end of for(indexSegment... MPD_WRITE_RET("</SegmentTimeline>"MPD_EOL); MPD_WRITE_RET("</SegmentTemplate>"MPD_EOL); return idx > 0 ? idx : rc; }
int main (int argc, char **argv) { char* ntry = (char*)""; if (argc > 1) { ntry = argv[1]; } double fps = FPS; double target_dur = 1.0/fps; double tol = 1.0e-3; double total_dur = 0.0; dc1394_t * d = dc1394_new(); if (!d) { return 1; } dc1394camera_list_t * list; dc1394error_t err = dc1394_camera_enumerate (d, &list); DC1394_ERR_RTN(err,"Failed to enumerate cameras"); if (list->num == 0) { /* Verify that we have at least one camera */ dc1394_log_error("No cameras found"); return 1; } gCamera.init(d, list->ids[0].guid); if (!gCamera.cam()) { dc1394_log_error("Failed to initialize camera with guid %ld", list->ids[0].guid); dc1394_camera_free_list (list); return 1; } dc1394_camera_free_list (list); /*----------------------------------------------------------------------- * have the camera start sending us data *-----------------------------------------------------------------------*/ err = gCamera.start_transmission(); DC1394_ERR_CLN_RTN(err,cleanup_and_exit(gCamera),"Could not start camera iso transmission"); /*----------------------------------------------------------------------- * capture one frame *-----------------------------------------------------------------------*/ uint32_t width = 0; uint32_t height = 0; gCamera.get_image_size(&width, &height); cv::Mat mapping = cv::getRotationMatrix2D(cv::Point2f(width/2.0, height/2.0), 180.0, 1.0); #ifdef USE_SDL static char *var = (char*)"SDL_VIDEO_WINDOW_POS=\"1280,480\""; int ret = putenv(var); if (SDL_Init(SDL_INIT_VIDEO) != 0) { std::cerr << "DC1394: Unable to initialize SDL: " << SDL_GetError() << std::endl; return 1; } atexit(SDL_Quit); SDL_Surface *screen; screen = SDL_SetVideoMode(width, height, 24, SDL_HWSURFACE); if (screen == NULL) { std::cerr << "DC1394: Unable to set SDL video mode:" << SDL_GetError() << std::endl; } SDL_Event event; #endif #ifndef LICKOMETER pthread_t save_thread, acq_thread; pthread_create( &save_thread, NULL, &thread_save_image, NULL); #endif pthread_t save_thread, acq_thread; pthread_create( &acq_thread, NULL, &thread_acq_image, NULL); timespec t_sleep, t_rem; t_sleep.tv_sec = 0; t_sleep.tv_nsec = 1000; #ifndef STANDALONE int s; if ((s = socket(SOCKTYPE, SOCK_STREAM, 0)) < 0) { perror("DC1394: client: socket"); cleanup_and_exit(gCamera); return 1; } /* * Create the address we will be connecting to. */ #ifndef INET sockaddr_un sa; sa.sun_family = AF_UNIX; std::ostringstream tmpfn; tmpfn << "fwsocket" << ntry; std::cout << "DC1394: socket name " << tmpfn.str() << std::endl; int nameLen = strlen(tmpfn.str().c_str()); if (nameLen >= (int) sizeof(sa.sun_path) -1) { /* too long? */ cleanup_and_exit(gCamera); return 1; } sa.sun_path[0] = '\0'; /* abstract namespace */ strcpy(sa.sun_path+1, tmpfn.str().c_str()); int len = 1 + nameLen + offsetof(struct sockaddr_un, sun_path); #else sockaddr_in sa; bzero((char *) &sa, sizeof(sa)); sa.sin_family = AF_INET; hostent *server = gethostbyname("128.40.156.129"); bcopy((char *)server->h_addr, (char *)&sa.sin_addr.s_addr, server->h_length); sa.sin_port = htons(35000); int len = sizeof(sa); #endif /* * Try to connect to the address. For this to * succeed, the server must already have bound * this address, and must have issued a listen() * request. * * The third argument indicates the "length" of * the structure, not just the length of the * socket name. */ std::cout << "DC1394: Waiting for connection... " << std::flush; while (true) { // wait for connection: if (connect(s, (sockaddr*)&sa, len) < 0) { nanosleep(&t_sleep, &t_rem); } else { break; } } std::cout << "done" << std::endl; bool connected = false; std::vector<char> data(BUFSIZE); int nrec = recv(s, &data[0], data.size(), 0); std::string datastr(data.begin(), data.end()); if (nrec<=0) { std::cerr << "DC1394: Didn't receive start message; exiting now" << std::endl; cleanup_and_exit(gCamera); close(s); return 1; } connected = true; std::string ready = "ready"; while (send(s, ready.c_str(), ready.size(), 0) < 0) { perror("DC1394: client: send"); } int flags = 0; if (-1 == (flags = fcntl(s, F_GETFL, 0))) flags = 0; if (fcntl(s, F_SETFL, flags | O_NONBLOCK)==-1) { perror("DC1394: client: unblock"); } #endif /* pthread_mutex_lock( &camera_mutex ); gCamera.wait_for_trigger(); pthread_mutex_unlock( &camera_mutex ); Wait for acq_frame_buffer to fill instead */ int ncount = 0; cv::Mat im(cv::Size(width, height), CV_8UC1); cv::Mat thresh = cv::Mat::ones(cv::Size(width, height), CV_8UC1); cv::Mat prevs(cv::Size(width, height), CV_8UC1); cv::Mat gray(cv::Size(width, height), CV_8UC1); // wait for image: int nframes = get_image(im, mapping, false, -1, "", ncount); std::cout << "DC1394: Waiting for first image to arrive... " << std::flush; int nwait = 0; while (!nframes) { nanosleep(&t_sleep, &t_rem); std::cout << "." << std::flush; nframes = get_image(im, mapping, false, -1, "", ncount); nwait++; #ifdef STANDALONE if (nwait > 1000) { #else if (nwait > 100000) { #endif std::cout << "Time out, stopping now\n"; cleanup_and_exit(gCamera); } } timespec time0; clock_gettime(CLOCK_REALTIME, &time0); std::cout << "DC1394: image arrived: " << IplImage(im).depth << " bits, " << IplImage(im).nChannels << " channels, " << IplImage(im).widthStep << " step width" << std::endl; #ifdef USE_SDL SDL_Surface *surface = SDL_CreateRGBSurfaceFrom((void*)im.data, im.cols, im.rows, IplImage(im).depth*IplImage(im).nChannels, IplImage(im).widthStep, 0xffffff, 0xffffff, 0xffffff, 0); screen = SDL_GetVideoSurface(); if(SDL_BlitSurface(surface, NULL, screen, NULL) == 0) SDL_UpdateRect(screen, 0, 0, 0, 0); #else cv::namedWindow("DC1394", CV_WINDOW_AUTOSIZE); cvMoveWindow("DC1394", 1280, 480); cv::imshow("DC1394", im); #endif timespec time1 = time0; timespec time2 = time0; timespec time3 = time0; timespec time4 = time0; timespec t_disconnect = time0; timespec t_notrigger = time0; #ifdef STANDALONE int s = -1; #endif std::string fn = ""; #ifdef LICKOMETER std::string fn_lick = ""; FILE* fp_lick = NULL; #endif int key = 0; int nloop = 0; while (true) { clock_gettime( CLOCK_REALTIME, &time1); #ifndef STANDALONE std::vector<char> data(BUFSIZE); int nrec = recv(s, &data[0], data.size(), 0); std::string datastr(data.begin(), data.end()); #endif nframes += get_image(im, mapping, false, s, fn, ncount); #ifndef STANDALONE // no update from blender in a long time, terminate process if (datastr.find("1")==std::string::npos) { if (connected) { t_disconnect = time1; connected = false; } else { if (tdiff(time1, t_disconnect) > TIMEOUT) { std::cout << "DC1394: Received termination signal" << std::endl; close(s); pthread_cancel(acq_thread); pthread_cancel(save_thread); return 0; } } } else { connected = true; } /* Explicit termination */ if (datastr.find("quit")!=std::string::npos) { std::cout << "DC1394: Game over signal." << std::endl; std::string sclose = "close"; while (send(s, sclose.c_str(), sclose.size(), 0) < 0) { perror("DC1394: client: send"); } close(s); pthread_cancel(acq_thread); pthread_cancel(save_thread); return 0; } // Stop recording if (datastr.find("stop") != std::string::npos && fn != "") { fn = ""; #ifdef LICKOMETER fn_lick = ""; if (fp_lick) { fclose(fp_lick); fp_lick = NULL; } #endif std::cout << "DC1394: Stopping video" << std::endl; connected = true; ncount = 0; } // Start recording if (datastr.find("avi") != std::string::npos && datastr.find("stop") == std::string::npos && fn == "") { std::size_t startpos = datastr.find("begin")+5; std::size_t endpos = datastr.find("end") - datastr.find("begin") - 5; fn = datastr.substr(startpos, endpos); fn = std::string(trunk) + "data/" + fn; #ifdef LICKOMETER fn_lick = fn + "_lick"; fp_lick = fopen(fn_lick.c_str(), "wb"); std::cout << "DC1394: Recording lick detection, writing to " << fn_lick << std::endl; #else boost::filesystem::path path(fn); boost::filesystem::path writepath(path); // Test whether dir exists: if (!boost::filesystem::exists(writepath)) { std::cout << "DC1394: Creating directory " << writepath << std::endl; boost::filesystem::create_directories(writepath); } fn += "/"; /* check save frame buffer */ std::size_t nfb = save_frame_buffer.size(); if (nfb) std::cerr << "DC1394: Frame buffer isn't empty!" << std::endl; std::cout << "DC1394: Starting video, writing to " << fn << std::endl; connected = true; ncount = 0; #endif } #endif // #nstandalone #ifdef USE_SDL if (SDL_PollEvent(&event)) { #ifdef STANDALONE /* Any of these event types will end the program */ if (event.type == SDL_QUIT || event.type == SDL_KEYDOWN || event.type == SDL_KEYUP) { std::cout << std::endl; std::cout << std::endl << "DC1394: Total number of frames was " << nframes << std::endl; std::cout << std::endl << "DC1394: Frame buffer: " << acq_frame_buffer.size() << " frames left" << std::endl; close(s); pthread_cancel(acq_thread); pthread_cancel(save_thread); return 0; } #endif // STANDALONE } surface->pixels = (void*)im.data; // SDL_CreateRGBSurfaceFrom((void*)IplImage(im).imageData, // IplImage(im).width, // IplImage(im).height, // IplImage(im).depth*IplImage(im).nChannels, // IplImage(im).widthStep, // 1, 1, 1, 0); screen = SDL_GetVideoSurface(); if(SDL_BlitSurface(surface, NULL, screen, NULL) == 0) SDL_UpdateRect(screen, 0, 0, 0, 0); #else // not SDL key = cv::waitKey(2); cv::imshow("DC1394", im); if (key == 1114155 || key == 65579 || key==43 /*+*/) { uint32_t gain = 0; err = dc1394_feature_get_value(gCamera.cam(), DC1394_FEATURE_GAIN, &gain); DC1394_ERR_CLN_RTN(err,cleanup_and_exit(gCamera),"Can't get gain"); if (gain < gCamera.get_maxgain()-10) { gain += 10; pthread_mutex_lock( &camera_mutex ); err = dc1394_feature_set_value(gCamera.cam(), DC1394_FEATURE_GAIN, gain); pthread_mutex_unlock( &camera_mutex ); std::cout << "DC1394: New gain value: " << gain << std::endl; DC1394_ERR_CLN_RTN(err,cleanup_and_exit(gCamera),"Can't set gain"); } } if (key == 1114207 || key == 45 /*-*/) { uint32_t gain = 0; err = dc1394_feature_get_value(gCamera.cam(), DC1394_FEATURE_GAIN, &gain); DC1394_ERR_CLN_RTN(err,cleanup_and_exit(gCamera),"Can't get gain"); if (gain > gCamera.get_mingain()+10) { gain -= 10; pthread_mutex_lock( &camera_mutex ); err = dc1394_feature_set_value(gCamera.cam(), DC1394_FEATURE_GAIN, gain); pthread_mutex_unlock( &camera_mutex ); DC1394_ERR_CLN_RTN(err,cleanup_and_exit(gCamera),"Can't set gain"); } } #endif // not SDL #ifdef LICKOMETER /* IS THIS ALL YOU NEED THEN? Lick detection */ /* Not required because the captured image is already gray cv::Mat gray = bgr2gray(im); */ gray = thresholding(im, LICK_FRAME_THRESHOLD); if (nloop != 0) { cv::absdiff(prevs, gray, thresh); double pixel_sum_thresh = cv::sum(thresh)[0]; double pixel_sum_gray = cv::sum(gray)[0]; if (pixel_sum_thresh > LICK_SUM_THRESHOLD) { std::cout << "DC1394: Lick" << std::endl; } if (fp_lick != NULL) { fwrite(&pixel_sum_thresh, sizeof(pixel_sum_thresh), 1, fp_lick); fwrite(&pixel_sum_gray, sizeof(pixel_sum_gray), 1, fp_lick); } } prevs = gray.clone(); nloop++; #endif #ifdef STANDALONE if (key == 1048689 || key == 113 /*q*/) { std::cout << "DC1394: Mean frame rate was " << nframes/total_dur << " fps" << std::endl; pthread_cancel(acq_thread); pthread_cancel(save_thread); return 0; } if (key == 1048691 /*s*/) { fn = ""; std::cout << "DC1394: Stopping video" << std::endl; ncount = 0; } if (key == 1048690 /*r*/) { fn = trunk + std::string("tmp/"); std::cout << "DC1394: Starting video, writing to " << fn << std::endl; ncount = 0; } #endif // #standalone clock_gettime( CLOCK_REALTIME, &time2); double loop_dur = tdiff(time2, time3); clock_gettime( CLOCK_REALTIME, &time3); double meanfps = 0; total_dur = tdiff(time3, time0); if (total_dur > 0) meanfps = nframes / total_dur; double currentfps = ret / loop_dur; std::cout << "DC1394: Current fps: " << std::setprecision(7) << currentfps << " Average fps: " << std::setprecision(7) << meanfps << "\r" << std::flush; #ifdef STANDALONE // std::cout << capture_dur << "\t" << target_dur << "\t" << rem << "\t" << loop_dur << std::endl; #endif } if (d) { dc1394_free(d); } #ifndef STANDALONE close(s); #endif return 0; }
int main(int argc, const char *argv[]) { // Validate input parameters if (argc < 15) { std::cerr << "Missing parameters! Usage:" << std::endl; std::cerr << argv[0]; std::cerr << " <Read/WriteDir> <InputImg> <OutputImg> "; std::cerr << "[seedX] [seedY] [seedZ] [initDist] "; std::cerr << "[sigma] [sigmoid K1] [sigmoid K2] "; std::cerr << "[propagation] [curvature] [advection] [iterations]"; std::cerr << std::endl; return EXIT_FAILURE; } const unsigned int Dimension = 3; typedef float InputPixelType; typedef unsigned char OutputPixelType; typedef itk::Image< InputPixelType, Dimension > InputImageType; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; //////////////////////////////////////////////// // 1) Read the input image typedef itk::ImageFileReader< InputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); std::string readpath( argv[1] ); readpath.append( argv[2] ); reader->SetFileName( readpath ); reader->Update(); //////////////////////////////////////////////// // 2) Curvature anisotropic diffusion typedef itk::CurvatureAnisotropicDiffusionImageFilter< InputImageType, InputImageType > SmoothingFilterType; SmoothingFilterType::Pointer smoothing = SmoothingFilterType::New(); smoothing->SetTimeStep(0.04); smoothing->SetNumberOfIterations(5); smoothing->SetConductanceParameter(9.0); smoothing->SetInput( reader->GetOutput() ); //////////////////////////////////////////////// // 3) Gradient magnitude recursive Gaussian const double sigma = atof(argv[8]); typedef itk::GradientMagnitudeRecursiveGaussianImageFilter< InputImageType, InputImageType > GradientFilterType; GradientFilterType::Pointer gradientMagnitude = GradientFilterType::New(); gradientMagnitude->SetSigma( sigma ); gradientMagnitude->SetInput( smoothing->GetOutput() ); //////////////////////////////////////////////// // 4) Sigmoid mapping const double K1 = atof(argv[9]); const double K2 = atof(argv[10]); typedef itk::SigmoidImageFilter< InputImageType, InputImageType > SigmoidFilterType; SigmoidFilterType::Pointer sigmoid = SigmoidFilterType::New(); sigmoid->SetOutputMinimum(0.0); sigmoid->SetOutputMaximum(1.0); sigmoid->SetAlpha( (K2 - K1)/6 ); sigmoid->SetBeta( (K1 + K2)/2 ); sigmoid->SetInput( gradientMagnitude->GetOutput() ); //////////////////////////////////////////////// // 5) Segmentation with geodesic active contour typedef itk::FastMarchingImageFilter< InputImageType, InputImageType > FastMarchingFilterType; FastMarchingFilterType::Pointer fastMarching = FastMarchingFilterType::New(); typedef itk::GeodesicActiveContourLevelSetImageFilter< InputImageType, InputImageType > GeodesicActiveContourFilterType; GeodesicActiveContourFilterType::Pointer geodesicActiveContour = GeodesicActiveContourFilterType::New(); const double propagation = atof( argv[11] ); const double curvature = atof( argv[12] ); const double advection = atof( argv[13] ); const double iterations = atoi( argv[14] ); geodesicActiveContour->SetPropagationScaling( propagation ); geodesicActiveContour->SetCurvatureScaling( curvature ); geodesicActiveContour->SetAdvectionScaling( advection ); geodesicActiveContour->SetMaximumRMSError(0.01); geodesicActiveContour->SetNumberOfIterations( iterations ); geodesicActiveContour->SetInput( fastMarching->GetOutput() ); geodesicActiveContour->SetFeatureImage( sigmoid->GetOutput() ); //////////////////////////////////////////////// // 6) Binary thresholding typedef itk::BinaryThresholdImageFilter< InputImageType, OutputImageType > ThresholdingFilterType; ThresholdingFilterType::Pointer thresholder = ThresholdingFilterType::New(); thresholder->SetLowerThreshold(-1000.0); thresholder->SetUpperThreshold(0.0); thresholder->SetOutsideValue(0); thresholder->SetInsideValue(255); thresholder->SetInput( geodesicActiveContour->GetOutput() ); //////////////////////////////////////////////// // 7) Finish setting up fast marching typedef FastMarchingFilterType::NodeContainer NodeContainer; typedef FastMarchingFilterType::NodeType NodeType; NodeContainer::Pointer seeds = NodeContainer::New(); InputImageType::IndexType seedPosition; seedPosition[0] = atoi( argv[4] ); seedPosition[1] = atoi( argv[5] ); seedPosition[2] = atoi( argv[6] ); const double initialDistance = atof( argv[7] ); const double seedValue = -initialDistance; NodeType node; node.SetValue( seedValue ); node.SetIndex( seedPosition ); seeds->Initialize(); seeds->InsertElement(0, node); fastMarching->SetTrialPoints( seeds ); fastMarching->SetSpeedConstant(1.0); fastMarching->SetOutputSize( reader->GetOutput()->GetBufferedRegion().GetSize() ); fastMarching->SetOutputRegion( reader->GetOutput()->GetBufferedRegion() ); fastMarching->SetOutputSpacing( reader->GetOutput()->GetSpacing() ); fastMarching->SetOutputOrigin( reader->GetOutput()->GetOrigin() ); //////////////////////////////////////////////// // 7) Write output image typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); std::string writepath( argv[1] ); writepath.append( argv[3] ); writer->SetFileName( writepath ); writer->SetInput( thresholder->GetOutput() ); try { writer->Update(); } catch( itk::ExceptionObject &excep ) { std::cerr << "Exception caught!" << std::endl; std::cerr << excep << std::endl; return EXIT_FAILURE; } // The following writer is used to save the output of the sigmoid mapping typedef itk::ImageFileWriter< InputImageType > InternalWriterType; InternalWriterType::Pointer speedWriter = InternalWriterType::New(); speedWriter->SetInput( sigmoid->GetOutput() ); std::string sigmoidpath( argv[1] ); speedWriter->SetFileName( sigmoidpath.append("SigmoidForGeodesic.mha")); speedWriter->Update(); return 0; }