Exemplo n.º 1
0
bool Client::setUpService()
{
	// Communication
        memset(&serv_addr, 0, sizeof(struct sockaddr_in));
        if((client_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0)
        {   
                printf("\n Error: Could not create socket \n");
        }   

        serv_addr.sin_family = AF_INET;
        serv_addr.sin_port = htons(9999);

        if(inet_pton(AF_INET, HOSTNAME, &serv_addr.sin_addr) <= 0)
        {   
                printf("\n Error: Connect Failed \n");
                exit(1);
	}

	connectToServer();
	createThreads();


	pthread_create(&input_thread, NULL, inputFunction, (void*)this);

	// TODO: Voice Recode
	return true;
}
Exemplo n.º 2
0
bool Server::setUpService()
{
	// Commnication
	server_socket = socket(AF_INET, SOCK_STREAM, 0);
	memset(&serv_addr, 0, sizeof(struct sockaddr_in));

	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	serv_addr.sin_port = htons(9999);

	bind(server_socket, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
        listen(server_socket, 10);   
		
	startServer();
	createThreads();

	// TODO: pir ...
	pir_monitor::GetInstance()->setUpService(); 

	// face_detection
	face_detect::GetInstance()->setUpService();
	//face_detect::GetInstance()->startMainLoop();

	// maestro
	Maestro::GetInstance()->setUpService();

	return true;
}
Exemplo n.º 3
0
// starts processing threads, allocates memory, and indexes boundary conditions
void DiffEqModel::initializeModel()
{
	// create a matrix that holds the right-hand-side of the diff equation computation
	assert(!posix_memalign((void **)&cmatrix_next,32,sizeof(DATA_TYPE[ni*nj*nk])));
	memset(cmatrix_next,0,sizeof(DATA_TYPE[ni*nj*nk]));

	// find the boundary elements that will require special processing and build a quick index of them
	indexBoundaryConditions();
	
	// make small array of zeros needed to properly handle the edges of the cmatrix
	assert(!posix_memalign((void **)&zeros_ptr,32,sizeof(DATA_TYPE[ni])));
	memset(zeros_ptr,0,sizeof(DATA_TYPE[ni]));

	// create a matrix that holds the previous right-hand-side of the diff equation computation
	assert(!posix_memalign((void **)&dptr_last,32,sizeof(DATA_TYPE[ni*nj*nk])));

	assert(!posix_memalign((void **)&ccl_ptr,32,sizeof(DATA_TYPE[ni])));
	memset(ccl_ptr,0,sizeof(DATA_TYPE[ni]));
	assert(!posix_memalign((void **)&ccr_ptr,32,sizeof(DATA_TYPE[ni])));
	memset(ccr_ptr,0,sizeof(DATA_TYPE[ni]));


#ifndef USE_CUDA
	// might as well make this big enough to have one entry for each layer of the simulation...
	// should result in a minimal amount of context-switching during processing
	workQ = new WorkerInfoQueue(nk);
	
	createThreads();
#else
  cudaModel = new DelsqCUDA(ni,nj,nk,incorp_inject_cnt);
#endif
}
/*******************************************************************************
 * Overloaded Constructor
 * This is public, and it initializes a new UdpRelay object with the given 
 * address parameter. This object instansiates a Socket object and a UdpMulicast
 * object to facilitate communications with local and remote hosts. Private
 * helper functions spin off instance threads and join them when they are done
 * being used.
 * @param udpPort       a character string representing the UDP port number
 *                      the format expected is ###.###.###.###:#####
 */
UdpRelay::UdpRelay(char* udpAddr) {
   // Parse parameter and assign members
   groupIp = strtok(udpAddr, ":");
   groupPort = (unsigned short int)atoi(strtok(NULL, "\0"));
   udpRelayRunning = true;
   // Initialize dynamic members
   localSocket = new Socket(TCP_PORT);
   localUdpMulticast = new UdpMulticast(groupIp, groupPort);
   msgBuffer = new char[BUFFER_MAX_SIZE];
   msgMutex = new pthread_mutex_t;
   cond = new pthread_cond_t;
   // Print welcome message
   printf("> booted up at %s:%d\n", groupIp, groupPort);
   // Create persistent threads
   createThreads();
   // Join persistent threads
   joinThreads();
   // Clean up dynamic members
   delete localSocket;
   localSocket = NULL;
   delete localUdpMulticast;
   localUdpMulticast = NULL;
   delete msgBuffer;
   msgBuffer = NULL;
   delete msgMutex;
   msgMutex = NULL;
   delete cond;
   cond = NULL;
}
Exemplo n.º 5
0
//-----------------------------------------------------------------------------
// 描述: 根据负载情况动态调整线程数量
//-----------------------------------------------------------------------------
void UdpWorkerThreadPool::AdjustThreadCount()
{
    int packetCount, threadCount;
    int minThreads, maxThreads, deltaThreads;
    int packetAlertLine;

    // 取得线程数量上下限
    iseApp().iseOptions().getUdpWorkerThreadCount(
        ownGroup_->getGroupIndex(), minThreads, maxThreads);
    // 取得请求队列中数据包数量警戒线
    packetAlertLine = iseApp().iseOptions().getUdpRequestQueueAlertLine();

    // 检测线程是否工作超时
    checkThreadTimeout();
    // 强行杀死僵死的线程
    killZombieThreads();

    // 取得数据包数量和线程数量
    packetCount = ownGroup_->getRequestQueue().getCount();
    threadCount = threadList_.getCount();

    // 保证线程数量在上下限范围之内
    if (threadCount < minThreads)
    {
        createThreads(minThreads - threadCount);
        threadCount = minThreads;
    }
    if (threadCount > maxThreads)
    {
        terminateThreads(threadCount - maxThreads);
        threadCount = maxThreads;
    }

    // 如果请求队列中的数量超过警戒线,则尝试增加线程数量
    if (threadCount < maxThreads && packetCount >= packetAlertLine)
    {
        deltaThreads = ise::min(maxThreads - threadCount, 3);
        createThreads(deltaThreads);
    }

    // 如果请求队列为空,则尝试减少线程数量
    if (threadCount > minThreads && packetCount == 0)
    {
        deltaThreads = 1;
        terminateThreads(deltaThreads);
    }
}
Exemplo n.º 6
0
bool Screen::startUpdates()
{
	if (!_inited || threads() > 0)
		return false;

	createThreads();
	return true;
}
Exemplo n.º 7
0
int main(void) {
	srand(time(NULL));

	createQueues();

	setupThreads();

	createThreads(cpuThread, cpuThreads, NUMBER_OF_CPU_THREADS);
	createThreads(ioThread, ioThreads, NUMBER_OF_IO_THREADS);
	createThreads(submissionThread, submissionThreads, NUMBER_OF_SUBMISSION_THREADS);

	waitForThreads(cpuThreads);
	waitForThreads(ioThreads);
	waitForThreads(submissionThreads);

	printf("All threads complete.\n");

	return EXIT_SUCCESS;
}
Exemplo n.º 8
0
void AsyncThreadManager::_addWork(detail::AsyncWorkItemBase* item)
{
	lock_guard<recursive_mutex> lck(mMutex);

	if (static_cast<int>(mThreads.size())<mNumThreads)
		createThreads();

	mPendingWork.push(item);
	mWorkAvailable.notify_one();
}
int main (int argc, char ** argv)
{
	if (argc != 3) 
	{
		printf("Use: %s <N> <T>,  onde 'N' é a dimensão da matriz unitária e 'T' é o número de threads.\n", argv[0]);
		return 1;
	}

	//Retira valores dos argumentos passados pela linha de comando
	matrix_size = atoi(argv[1]);
	number_of_threads = atoi(argv[2]);

	//Aloca espaço para variáveis e ponteiros para colunas
	A = allocateMatrix(matrix_size);

	//Gera matrizes A e B
	generateMatrix(A, matrix_size);

	//Imprime A e B (teste)
	if (matrix_size < 20)
		printMatrix(A, matrix_size, "A");

	//Ponteiro com threads
	pthread_t * p_threads;
	//Alocação de espaço para threads de acordo com o número de threads
	p_threads = (pthread_t *) malloc(number_of_threads * sizeof(pthread_t));


	//Inicializa o mutex
  	pthread_mutex_init(&mut, NULL);

	//Captura tempo inicial
	clock_gettime(CLOCK_MONOTONIC, &initial_time);

	//Criação de threads
	createThreads(p_threads, number_of_threads, matrix_size, A);

	//Join das threads
	joinThreads(p_threads);

	//Captura tempo final
	clock_gettime(CLOCK_MONOTONIC, &end_time);
  	
  	//imprime resultado
	printf("A soma de todos os termos é: %d\n", sum);

	//Calcula tempo final
	double elapsed = end_time.tv_sec - initial_time.tv_sec;
	elapsed += (end_time.tv_nsec - initial_time.tv_nsec) / 1000000000.0;
 	printf ("O tempo de processamento foi de: %f segundos\n", elapsed);   
	
	//Inicializa o mutex
  	pthread_mutex_destroy(&mut);  
	return 0;
}
Exemplo n.º 10
0
void func8_1()
{
  Thread_t *threads = test8threads;

  threads = createThreads(TEST8_THREADS, thread_main8,threads);
  assert (threads);

  mutateeIdle = 1;
  while (mutateeIdle);

  /*free (threads);*/
}
Exemplo n.º 11
0
ConvertWindow::ConvertWindow() {
	ui_.setupUi(this);

	createWidgets();
	createToolbarAndMenu();

	createThreads();

	exitProcess_ = false;
	loadError_ = false;
	convertAll_ = false;
}
Exemplo n.º 12
0
void func6_1()
{
#if defined(os_none)
  createLock(&test6lock);
  lockLock(&test6lock); 
  assert (NULL != createThreads(TEST6_THREADS, thread_main6, test6_threads));

  unlockLock(&test6lock); 
  mutateeIdle = 1;
  while (mutateeIdle) {}
#else
#endif
}
Exemplo n.º 13
0
/**************************************************
 * Main                                           *
 **************************************************/
int main() {
    InitLocks();
    
    if (!createThreads(numOfFirstCreateLoop, (void*)DoDummyThread)) { // create first batch of dummy threads
        ErrorExit(RES_CREATE_FAILED);
    }
    Print("Creating the exit thread");
    if (!createThreads(1, (void*)DoExitThread)) { // create the exit thread
        ErrorExit(RES_CREATE_FAILED);
    }
    if (!createThreads(numOfSecondCreateLoop, (void*)DoDummyThread)) { // create second batch of dummy threads
        ErrorExit(RES_CREATE_FAILED);
    }
    
    DoSleep(1000); // wait here to be terminated
    
    // Failsafe - this should not be reached but we want to avoid a hung test.
    ErrorExit(RES_EXIT_TIMEOUT); // never returns
    
    // This can't be reached, simply for successful compilation.
    return RES_SUCCESS;
}
Exemplo n.º 14
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    createThreads();
    createActions();
    createMenus();
    makeConnections();

    setWindowTitle(QString(APP_NAME));
    //showMaximized();
}
Exemplo n.º 15
0
void func5_1()
{
#if defined(os_none)
  createLock(&test5lock);
  lockLock(&test5lock); 
  assert (NULL != createThreads(TEST5_THREADS, thread_main5, test5_threads));

  sleep_ms(999);
  unlockLock(&test5lock); 
  mutateeIdle = 1;
  while (mutateeIdle) {}
#else
#endif
}
Exemplo n.º 16
0
Arquivo: pso.c Projeto: quiin/PSO
int main(int argc, char* argv[]){
	
	//read file
	urandom = fopen("/dev/urandom","r");
	if(urandom == NULL){
		printf("Can't open /dev/urandom !!!\n");
		exit(-1);
	}	
	//choices[0] = function
	//choices[1] = mode
	//choices[2] = totalAnts
	int* choices = checkConsole(argc, argv);
	int i, rc, tmpNumOfAnts, function, mode;
	bestG = NULL;
	function = choices[0];
	mode = choices[1];
	antsTotal = choices[2];
	
	/*printf("Cuantas hormigas quieres tener?\n");
	scanf("%d", &antsTotal);		
	

	printf("Que funcion quieres?\n");
	scanf("%d", &function);

	printf("Que modo quieres? (0 = min 1 = max)\n");
	scanf("%d", &mode);*/
		
	//init semaphore	
	sem_init(&findGlobalBestMutex,0,1);	

	tmpNumOfAnts = antsTotal % ANTS_PER_THREAD;	
	numThreads = tmpNumOfAnts == 0 ? antsTotal / ANTS_PER_THREAD : antsTotal / ANTS_PER_THREAD + 1;	
	
	createThreads(numThreads,antsTotal,tmpNumOfAnts,function,mode);	
	

	for(i = 0; i < numThreads; i++){
		rc = pthread_join(threads[i], NULL);
		if(rc){
			printf("Error joining thread %d pthread_join got %d\n", i, rc);
			exit(-1);
		}
	}
	printf("bestG value: %.2f at (%d,%d)\n", bestG->value,bestG->coos->x,bestG->coos->y);
	close(urandom);

	return 0;
}
Exemplo n.º 17
0
int main (int argc, char *argv[])
{
   struct timespec tStart;
   struct timespec tEnd;
   pthread_t *aThreads;
   THREAD_PARAMS *aParams;
   int64_t * aArray = NULL;

   int64_t iret = 0;
   int64_t cThreads = 0;
   int64_t cTasks = 0;
   bool fBlock = false;
   bool fSimple = true; 
   bool fRandom = false;

   iret = parseCommandLine(argc, argv, &cThreads, &cTasks, &fBlock, &fSimple, &fRandom);

   if (0 == iret) {
      iret = allocateArray(fRandom, cTasks, &aArray);
   }

   if (0 == iret) {
      iret = clock_gettime(CLOCK_REALTIME, &tStart);
   }
   
   if (0 == iret) {
      iret = createThreads(cThreads, cTasks, fBlock, fSimple, aArray, &aThreads, &aParams);
   }

   if (0 == iret) {
      iret = joinThreads(cThreads, cTasks, aThreads, aParams);
      aThreads = NULL;
      aParams = NULL;
   }

   clock_gettime(CLOCK_REALTIME, &tEnd);

   if (0 == iret) {
      //test(fSimple, cTasks, aArray);
   }

   free(aArray);

   struct timespec tsDiff = diff(tStart, tEnd);
   //printf("Elapsed Time: %d.%09d Sec.\n", tsDiff.tv_sec, tsDiff.tv_nsec);
   printf("%d, %d, %s, %s, %s, %d.%09d\n", cThreads, cTasks, fBlock ? "block":"cyclic", fSimple ? "negation":"factorial", fRandom ? "random":"ramp",tsDiff.tv_sec, tsDiff.tv_nsec);
   return(iret);
}
Exemplo n.º 18
0
void func3_1()
{

  createLock(&test3lock);
  mutateeIdle = 1;

  lockLock(&test3lock);
  assert (NULL != createThreads(TEST3_THREADS, thread_main3, test3_threads));

  sleep_ms(999);
  unlockLock(&test3lock);
  dprintf("%s[%d]:  func3_1\n", __FILE__, __LINE__);
  while (mutateeIdle) {}

  dprintf("%s[%d]:  leaving func3_1\n", __FILE__, __LINE__);
}
int main(int argc, char* argv[])
{
    puts(license); // show GPL at start of program output
    
    int threads = promptForMoreThreads();
    ThreadData td[threads];
    createThreads(td, threads);
    
    puts("Main thread created all child threads..");

    joinThreads(td, threads);

    puts("Main thread joined all child threads. Now exiting.\n");

    return 0;
}
Exemplo n.º 20
0
/*! @brief Constructor for the nubot
    
    The parameters are for command line arguements. Webots gives the binary arguements which tell us the 
    robot's number. Consequently, these args are passed down to the webots platform.
 
    @param argc the number of command line arguements
    @param *argv[] the array of command line arguements
 */
NUbot::NUbot(int argc, const char *argv[])
{
    createErrorHandling();
#if DEBUG_NUBOT_VERBOSITY > 4
    debug << "NUbot::NUbot(). Constructing NUPlatform." << endl;
#endif
    // Construct the right Platform
    #ifdef TARGET_IS_NAOWEBOTS
        platform = new NAOWebotsPlatform(argc, argv);
    #endif
    #ifdef TARGET_IS_NAO
        platform = new NAOPlatform();
    #endif
    #ifdef TARGET_IS_CYCLOID
        platform = new CycloidPlatform();
    #endif

#if DEBUG_NUBOT_VERBOSITY > 4
    debug << "NUbot::NUbot(). Constructing modules." << endl;
#endif
    
    // Construct each enabled module 
    #ifdef USE_VISION
        vision = new Vision();
    #endif
    #ifdef USE_LOCALISATION
        localisation = new Localisation();
    #endif
    #ifdef USE_BEHAVIOUR
        behaviour = new Behaviour();
    #endif
    #ifdef USE_MOTION
        motion = new NUMotion();
        #ifdef USE_WALKOPTIMISER
            walkoptimiser = new WalkOptimiserBehaviour(platform, motion->m_walk);
        #endif
    #endif
    #ifdef USE_NETWORK
        network = new Network();
    #endif
    
    createThreads();
    
#if DEBUG_NUBOT_VERBOSITY > 4
    debug << "NUbot::NUbot(). Finished." << endl;
#endif
}
Exemplo n.º 21
0
/**************************************************
 * Main                                           *
 **************************************************/
int main(int argc, const char* argv[]) {
    parseArgs(argc, argv);
    
//    Print("main thread starting the test..."); // FOR DEBUG
    
    InitLocks();
    
    if (!createThreads()) { // returns true if all threads were created successfully
        ErrorExit(RES_CREATE_FAILED);
    }
    
    waitForThreads();
    waitOrExit();
    
    Print("main thread is calling return from main()"); // FOR DEBUG
    return RES_SUCCESS;
}
Exemplo n.º 22
0
int main(void) {
	// Initialize all the hardware
	hardware_init();

	// Prepare the OLED menu
	menu_inflate();

	// Create the threads
	createThreads();

	// Start scheduler
	osKernelStart();

	// We should never get here as control is now taken by the scheduler
	// Infinite loop
	for(;;);
}
Exemplo n.º 23
0
/*! @brief Constructor for the nubot
    
    The parameters are for command line arguements. Webots gives the binary arguements which tell us the 
    robot's number. Consequently, these args are passed down to the webots platform.
 
    @param argc the number of command line arguements
    @param *argv[] the array of command line arguements
 */
NUbot::NUbot(int argc, const char *argv[])
{
    #if DEBUG_NUBOT_VERBOSITY > 0
        debug << "NUbot::NUbot()." << endl;
    #endif
    NUbot::m_this = this;
    
    createErrorHandling();
    createPlatform(argc, argv);
    createBlackboard();
    createNetwork();
    createModules();
    createThreads();
    
    #if DEBUG_NUBOT_VERBOSITY > 0
        debug << "NUbot::NUbot(). Finished." << endl;
    #endif
}
Exemplo n.º 24
0
/*!
 * \brief Run example for a process.
 */
static void runExample(int who)
{
  Who = who;

  randseed();
  randusleep(1000000);
  
  LOGDIAG1("%s: creating shared memory mutex.", WhoName[Who]);

  if( !OptsNoMutex )
  {
    if( shm_mutex_init(ShmKey, &ShmMutex) < 0 )
    {
      LOGERROR("%s: failed to create mutex.", WhoName[Who]);
    }
  }

  if( createThreads() < 0 )
  {
    return;
  }

  switch( Who )
  {
    case WHO_CHILD:
      sleep(3);
      break;
    case WHO_PARENT:
      sleep(4);
      break;
    default:
      break;
  }

  killThreads();

  if( !OptsNoMutex )
  {
    shm_mutex_destroy(&ShmMutex);
  }
}
Exemplo n.º 25
0
//------------------------------------------------------------------------------------
MainWindow::MainWindow(QWidget *parent):
    QMainWindow(parent)
{
    QWidget *_cW = new QWidget(NULL);
    this->setCentralWidget(_cW);
    //--------------------------------------------------------------
    pt_mainLayout = new QVBoxLayout();
    pt_mainLayout->setMargin(APP_MARGIN);
    _cW->setLayout(pt_mainLayout);
    //--------------------------------------------------------------
    pt_display = new QImageWidget();
    pt_mainLayout->addWidget(pt_display);
    //--------------------------------------------------------------
    createThreads();
    //--------------------------------------------------------------
    createActions();
    createMenus();
    //--------------------------------------------------------------
    resize(640,480);
    statusBar()->showMessage(tr("Context menu is available by right click"));
}
MultiStackRoboCupSSL::MultiStackRoboCupSSL(RenderOptions * _opts, int cameras) : MultiVisionStack("RoboCup SSL Multi-Cam",_opts) {
  //add global field calibration parameter
  global_field = new RoboCupField();
  settings->addChild(global_field->getSettings());

  global_ball_settings = new PluginDetectBallsSettings();
  settings->addChild(global_ball_settings->getSettings());

  global_team_settings = new CMPattern::TeamDetectorSettings("robocup-ssl-teams.xml");
  settings->addChild(global_team_settings->getSettings());

  global_team_selector_blue = new CMPattern::TeamSelector("Blue Team", global_team_settings);
  settings->addChild(global_team_selector_blue->getSettings());

  global_team_selector_yellow = new CMPattern::TeamSelector("Yellow Team", global_team_settings);
  settings->addChild(global_team_selector_yellow->getSettings());

  global_network_output_settings = new PluginSSLNetworkOutputSettings();
  settings->addChild(global_network_output_settings->getSettings());
  connect(global_network_output_settings->multicast_port,SIGNAL(wasEdited(VarType *)),this,SLOT(RefreshNetworkOutput()));
  connect(global_network_output_settings->multicast_address,SIGNAL(wasEdited(VarType *)),this,SLOT(RefreshNetworkOutput()));
  connect(global_network_output_settings->multicast_interface,SIGNAL(wasEdited(VarType *)),this,SLOT(RefreshNetworkOutput()));

  udp_server = new RoboCupSSLServer();
  /*if (udp_server->open()==false) {
    fprintf(stderr,"ERROR WHEN TRYING TO OPEN UDP NETWORK SERVER!\n");
    fflush(stderr);
  }*/

  global_plugin_publish_geometry = new PluginPublishGeometry(0,udp_server,*global_field);

  //add parameter for number of cameras
  createThreads(cameras);
  unsigned int n = threads.size();
  for (unsigned int i = 0; i < n;i++) {
    threads[i]->setFrameBuffer(new FrameBuffer(5));
    threads[i]->setStack(new StackRoboCupSSL(_opts,threads[i]->getFrameBuffer(),i,global_field,global_ball_settings,global_plugin_publish_geometry,global_team_selector_blue, global_team_selector_yellow,udp_server,"robocup-ssl-cam-" + QString::number(i).toStdString()));
  }
    //TODO: make LUT widgets aware of each other for easy data-sharing
}
Exemplo n.º 27
0
void func4_1()
{
/*
#if defined(os_linux) && defined(arch_x86)
#else
*/
  dprintf("%s[%d]:  welcome to func4_1\n", __FILE__, __LINE__);
  createLock(&test4lock);


  lockLock(&test4lock); 
   
  assert (NULL != createThreads(TEST3_THREADS, thread_main4, test4_threads));

  unlockLock(&test4lock); 
  mutateeIdle = 1;
  while (mutateeIdle) {}
/*
#endif
*/

}
Exemplo n.º 28
0
int main(int argc ,char *argv[])
{
    int freeIndex= 0;
    int n = 3,opt;
    /*
    while((opt = getopt(argc,argv,"n") != -1))
    {
	switch(opt)
	{
	    case 'n':
		n = atoi(optarg);
		break;
	    default:
		printf("error opt");
		exit(-1);
	}
    }
    */

    if(signal(SIGINT,sig_int) == SIG_ERR)
    {
	perror("signal error");
	exit(-2);
    }
    setbuf(stdout,NULL);
    //setbuf(stdin,NULL);
    createThreads(n);
    while(!g_isExit)
    {
	read(STDIN_FILENO,g_buf,MAX_SIZE);
	pthread_mutex_lock(&g_pthreads[freeIndex].mutex);
	pthread_cond_signal(&g_pthreads[freeIndex].cond);
	pthread_mutex_unlock(&g_pthreads[freeIndex].mutex);
	freeIndex = (freeIndex + 1)%n;
    }
    destroyThreads(n);
}
Exemplo n.º 29
0
 ThreadPool::ThreadPool(int threadNum)
 {
     threadsNum_ = threadNum;
     createThreads();
     isRunning_ = true;
 }
Exemplo n.º 30
0
status_t TunnelPlayer::start(bool sourceAlreadyStarted) {
    CHECK(!mStarted);
    CHECK(mSource != NULL);

    ALOGV("start: sourceAlreadyStarted %d", sourceAlreadyStarted);
    //Check if the source is started, start it
    status_t err;
    if (!sourceAlreadyStarted) {
        err = mSource->start();
        if (err != OK) {
            return err;
        }
    }

    //Create extractor thread, read and initialize all the
    //mutexes and coditional variables
    createThreads();
    ALOGV("Thread Created.");
    // We allow an optional INFO_FORMAT_CHANGED at the very beginning
    // of playback, if there is one, getFormat below will retrieve the
    // updated format, if there isn't, we'll stash away the valid buffer
    // of data to be used on the first audio callback.

    CHECK(mFirstBuffer == NULL);

    MediaSource::ReadOptions options;
    if (mSeeking) {
        options.setSeekTo(mSeekTimeUs);
        mSeeking = false;
    }

    mFirstBufferResult = mSource->read(&mFirstBuffer, &options);
    if (mFirstBufferResult == INFO_FORMAT_CHANGED) {
        ALOGV("INFO_FORMAT_CHANGED!!!");
        CHECK(mFirstBuffer == NULL);
        mFirstBufferResult = OK;
        mIsFirstBuffer = false;
    } else {
        mIsFirstBuffer = true;
    }

    sp<MetaData> format = mSource->getFormat();
    const char *mime;
    bool success = format->findCString(kKeyMIMEType, &mime);
    if (!strcasecmp(mime,MEDIA_MIMETYPE_AUDIO_AAC)) {
        mFormat = AUDIO_FORMAT_AAC;
    }
    else if (!strcasecmp(mime,MEDIA_MIMETYPE_AUDIO_MPEG)) {
        mFormat = AUDIO_FORMAT_MP3;
        ALOGD("TunnelPlayer::start AUDIO_FORMAT_MP3");
    } else {
        ALOGE("TunnelPlayer::UNSUPPORTED");
    }


    CHECK(success);

    success = format->findInt32(kKeySampleRate, &mSampleRate);
    CHECK(success);

    success = format->findInt32(kKeyChannelCount, &numChannels);
    CHECK(success);

    if(!format->findInt32(kKeyChannelMask, &mChannelMask)) {
        // log only when there's a risk of ambiguity of channel mask selection
        ALOGI_IF(numChannels > 2,
                "source format didn't specify channel mask, using (%d) channel order", numChannels);
        mChannelMask = CHANNEL_MASK_USE_CHANNEL_ORDER;
    }
    audio_output_flags_t flags = (audio_output_flags_t) (AUDIO_OUTPUT_FLAG_TUNNEL |
                                                         AUDIO_OUTPUT_FLAG_DIRECT);
    ALOGV("mAudiosink->open() mSampleRate %d, numChannels %d, mChannelMask %d, flags %d",mSampleRate, numChannels, mChannelMask, flags);
    err = mAudioSink->open(
        mSampleRate, numChannels, mChannelMask, mFormat,
        DEFAULT_AUDIOSINK_BUFFERCOUNT,
        &TunnelPlayer::AudioSinkCallback,
        this,
        flags,
        NULL);

    if (err != OK) {
        if (mFirstBuffer != NULL) {
            mFirstBuffer->release();
            mFirstBuffer = NULL;
        }

        if (!sourceAlreadyStarted) {
            mSource->stop();
        }

        ALOGE("Opening a routing session failed");
        return err;
    }

    mIsAudioRouted = true;
    mStarted = true;
    mAudioSink->start();
    mLock.lock();
    ALOGV("Waking up extractor thread");
    mExtractorCv.signal();
    mLock.unlock();
    return OK;
}