Ejemplo n.º 1
0
void DevChannelHK::onGetDecData(char* pBuf, int nSize, FRAME_INFO* pFrameInfo) {
	//InfoL << pFrameInfo->nType;
	switch (pFrameInfo->nType) {
	case T_YV12: {
		if (!m_bVideoSeted) {
			m_bVideoSeted = true;
			VideoInfo video;
			video.iWidth = pFrameInfo->nWidth;
			video.iHeight = pFrameInfo->nHeight;
			video.iFrameRate = pFrameInfo->nFrameRate;
			initVideo(video);
		}
		char *yuv[3];
		int yuv_len[3];
		yuv_len[0] = pFrameInfo->nWidth;
		yuv_len[1] = pFrameInfo->nWidth / 2;
		yuv_len[2] = pFrameInfo->nWidth / 2;
		int dwOffset_Y = pFrameInfo->nWidth * pFrameInfo->nHeight;
		yuv[0] = pBuf;
		yuv[2] = yuv[0] + dwOffset_Y;
		yuv[1] = yuv[2] + dwOffset_Y / 4;
		inputYUV(yuv, yuv_len, pFrameInfo->nStamp);
	}
		break;
	case T_AUDIO16: {
		if (!m_bAudioSeted) {
			m_bAudioSeted = true;
			AudioInfo audio;
			audio.iChannel = pFrameInfo->nWidth;
			audio.iSampleBit = pFrameInfo->nHeight;
			audio.iSampleRate = pFrameInfo->nFrameRate;
			initAudio(audio);
		}
		inputPCM(pBuf, nSize, pFrameInfo->nStamp);
	}
		break;
	default:
		break;
	}
}
qboolean SNDDMA_Init(void)
{
    Com_Printf("Initializing Android Sound subsystem\n");

    /* For now hardcode this all :) */
    dma.channels = 2;
    dma.samples = 32768;
    dma.samplebits = 16;

    dma.submission_chunk = 4096; /* This is in single samples, so this would equal 2048 frames (assuming stereo) in Android terminology */
    dma.speed = 44100; /* This is the native sample frequency of the Milestone */

    bytes_per_sample = dma.samplebits/8;
    buf_size = dma.samples * bytes_per_sample;
    dma.buffer = calloc(1, buf_size);

    chunkSizeBytes = dma.submission_chunk * bytes_per_sample;

    initAudio(dma.buffer, buf_size);

    return qtrue;
}
Ejemplo n.º 3
0
Archivo: audio.c Proyecto: skitt/sysd7
int state10(void)
{
  unsigned char RecBuf[2];
  char v=1;
  int otime,ctime;
  unsigned char Data_next;
  int Control=0;
  serialinit();
  initAudio();
  initCompr();
  
  /* Synch with PC... */
  serialtransmit('A');
  otime=10000000;
  starttimer(SAMPLE_DELAY);
  ctime=gettimer();
  while ( otime > ctime ) {
    otime=ctime;
    ctime=gettimer();
  }
  RecBuf[0] = (getsample());
  otime=1000;
  while (1) {
    /*starttimer(SAMPLE_DELAY);*/
    while ( otime > (otime= gettimer() > 0) );
    RecBuf[v] = (getsample());
    if (v) {
      Control = compress(RecBuf[0],RecBuf[1]);
    } else {
      Control = serialtransmit(Control);
      if (Control) {
	serialclose();
	return Control;
      }
    }
    v=1-v;
  }
}
Ejemplo n.º 4
0
void main(void)
{
  int i;
  /* Set up initial state for audio system */
  initAudio();
  asm("nop");
  while (1){
    /*  This will make the board act as an amplifier... */
    /*-- INactive ...
    setsample(getsample());
    */
    

    /*  This will make the board play a saw-tooth waveform... */
    /*-- Active ... */
    for (i=0;i<256;i+=20) 
      setsample(i);
    for (i=255;i>=0;i-=10)
      setsample(i);
    /**/
  }
  
}
Ejemplo n.º 5
0
static void initSDL(SDL_Window** window, SDL_Renderer** renderer, OffScreenBuffer* osb, SDLInputContext* sdlIC, SDLSoundRingBuffer* srb) {
    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_GAMECONTROLLER) != 0) {
        printSDLErrorAndExit();
    }

    if(!(*window = SDL_CreateWindow("Handmade Hero",
                    SDL_WINDOWPOS_UNDEFINED,
                    SDL_WINDOWPOS_UNDEFINED,
                    SCREEN_WIDTH,
                    SCREEN_HEIGHT,
                    SDL_WINDOW_RESIZABLE))) {
        printSDLErrorAndExit();
    }

    if(!(*renderer = SDL_CreateRenderer(*window, -1, 0))) {
        printSDLErrorAndExit();
    }

    resizeTexture(&gTexture, osb, SCREEN_WIDTH, SCREEN_HEIGHT, *renderer);

    initAudio(srb);
    initInput(sdlIC);

}
Ejemplo n.º 6
0
void configEvent(const std::string& key) {
	// TODO: this could be done better...
	narf::console->println("onPropertyChanged(" + key + ")");
	if (key == "video.renderDistance") {
		renderer->setRenderDistance(config.getInt32(key));
		narf::console->println("Setting renderDistance to " + std::to_string(renderer->getRenderDistance()));
	} else if (key == "video.consoleCursorShape") {
		auto shapeStr = config.getString(key);
		clientConsole->setCursorShape(narf::ClientConsole::cursorShapeFromString(shapeStr));
	} else if (key == "video.vsync") {
		auto vsync = config.getBool(key);
		display->setVsync(vsync);
		narf::console->println("Setting vsync to " + std::to_string(vsync));
	} else if (key == "foo.gravity") {
		world->setGravity(config.getFloat(key));
		narf::console->println("Setting gravity to " + std::to_string(world->getGravity()));
	} else if (key == "misc.tickRate") {
		auto tickRate = config.getDouble(key);
		narf::console->println("Setting tickRate to " + std::to_string(tickRate));
		if (gameLoop) {
			gameLoop->setTickRate(tickRate);
		}
	} else if (key == "misc.maxFrameTime") {
		auto maxFrameTime = config.getDouble(key, 0.25);
		narf::console->println("Setting maxFrameTime to " + std::to_string(maxFrameTime));
		if (gameLoop) {
			gameLoop->setMaxFrameTime(maxFrameTime);
		}
	} else if (key == "video.hudFont" ||
		key == "video.hudFontSize") {
		auto font = setFont(
			"HUD",
			"video.hudFont", "DroidSansMono",
			"video.hudFontSize", 30);
		if (font) {
			if (gameLoop) {
				gameLoop->forceStatusUpdate = true;
			}
			fpsTextBuffer->setFont(font);
			blockInfoBuffer->setFont(font);
			entityInfoBuffer->setFont(font);
			locationBuffer->setFont(font);
		}
	} else if (key == "video.consoleFont" ||
		key == "video.consoleFontSize") {
		auto font = setFont(
			"console",
			"video.consoleFont", "DroidSansMono",
			"video.consoleFontSize", 18);
		if (font) {
			clientConsole->setFont(font);
		}
	} else if (key == "video.stereo.enabled") {
		stereo.enabled = config.getBool(key);
	} else if (key == "video.stereo.cross") {
		stereo.cross = config.getBool(key);
	} else if (key == "video.stereo.separation") {
		stereo.separation = config.getFloat(key);
	} else if (key == "audio.enabled") {
		audioEnabled = config.getBool(key);
		initAudio();
	} else {
		narf::console->println("Config var updated: " + key);
	}
}
Ejemplo n.º 7
0
// Initializes the hardware
void initHardware (void) {
    initIntc();
    initLeds();
    initButtons();
    initAudio();
}
Ejemplo n.º 8
0
bool Game::CreateAndInit()
{
    // If an instance already exists, we'll just keep it as is.
    if (pInstance != NULL)
    {
        return true;
    }

#ifdef GAME_EXECUTABLE
    LoadCompletedCases();
    PopulateCaseSignatureMap();
#endif

    gScreenWidth = 960;
    gScreenHeight = 540;
    gFramerate = 60.0; // FPS (0 for unlimited)

#ifdef GAME_EXECUTABLE
    gIsFullscreen = gEnableFullscreen;

    // Seed the pseudo-random number generator.
    srand((unsigned int)time(NULL));
#endif

    // Turn on ALL THE THINGS.
    if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
    {
        return false;
    }

    atexit(SDL_Quit);

#ifdef GAME_EXECUTABLE
    SDL_StopTextInput();

    // Register all codecs.
    av_register_all();

    gUiThreadId = SDL_ThreadID();
#else
    // Initialize networking for the purposes of checking for updates.
    curl_global_init(CURL_GLOBAL_ALL);
    gpCurlHandle = curl_easy_init();
#endif

#ifdef GAME_EXECUTABLE
    SDL_DisplayMode mode;
    SDL_GetDesktopDisplayMode(0, &mode);

    #ifdef MLI_DEBUG
        #ifdef WIN32
            // Force stdout to console, not text files.
            freopen("CON", "a", stdout);
            freopen("CON", "a", stderr);
        #endif
    #endif

    #ifdef MLI_DEBUG
    cout << gTitle << endl;
    #endif

    SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0");

    double nativeAspectRatio = (double)mode.w / mode.h;
    double gameAspectRatio = (double)gScreenWidth / gScreenHeight;
    bool constraintIsVertical = nativeAspectRatio > gameAspectRatio;

    gScreenScale = constraintIsVertical ? (double)mode.h / gScreenHeight : (double)mode.w / gScreenWidth;

    if (constraintIsVertical)
    {
        gHorizontalOffset = (Uint16)floor(0.5 + (mode.w - gScreenWidth * gScreenScale) / 2);
    }
    else
    {
        gVerticalOffset = (Uint16)floor(0.5 + (mode.h - gScreenHeight * gScreenScale) / 2);
    }
#endif

    SDL_WindowFlags flags = SDL_WINDOW_SHOWN;

#ifdef GAME_EXECUTABLE
    if (gIsFullscreen)
    {
        flags = (SDL_WindowFlags)(flags | SDL_WINDOW_FULLSCREEN_DESKTOP);
    }
#endif

    gpWindow = SDL_CreateWindow(gTitle.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, gScreenWidth, gScreenHeight, flags);

    // If we couldn't get a window, we're pretty screwed.
    if (gpWindow == NULL)
    {
        return false;
    }

#ifdef __WINDOWS
#ifndef LAUNCHER
    // Load and set the window icon - this is needed on Windows,
    // since just having the icon in the .exe doesn't set it for things like
    // the Alt+Tab menu.
    struct SDL_SysWMinfo info;
    SDL_VERSION(&info.version);

    if (SDL_GetWindowWMInfo(gpWindow, &info) && info.subsystem == SDL_SYSWM_WINDOWS)
    {
        HWND hwnd = info.info.win.window;

        const HANDLE hBigIcon =
            LoadImage(
                GetModuleHandle(NULL),
                MAKEINTRESOURCE(IDI_ICON),
                IMAGE_ICON,
                GetSystemMetrics(SM_CXICON),
                GetSystemMetrics(SM_CYICON),
                0);

        if (hBigIcon != NULL)
        {
            SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<WPARAM>(hBigIcon));
        }
    }
#endif
#endif

    gpRenderer = SDL_CreateRenderer(gpWindow, -1, 0);

    // Ditto for the renderer.
    if (gpRenderer == NULL)
    {
        return false;
    }

    // And for the renderer info, too.
    SDL_RendererInfo rendererInfo;

    if (SDL_GetRendererInfo(gpRenderer, &rendererInfo) < 0)
    {
        return false;
    }

    gMaxTextureWidth = rendererInfo.max_texture_width;
    gMaxTextureHeight = rendererInfo.max_texture_height;

#ifdef GAME_EXECUTABLE
    // Initialize audio subsystems.
    initAudio();

    // Set initial volume levels.
    setVolumeMusic(gBackgroundMusicVolume);
    setVolumeSound(gSoundEffectsVolume);
    setVolumeAmbiance(gSoundEffectsVolume);
    setVolumeDialog(gVoiceVolume);

    for (unsigned int i = 0; i < builtInBgmCount; i++)
    {
        ResourceLoader::GetInstance()->PreloadMusic(bgmIdList[i], "BGM/" + bgmIdList[i]);
    }

    for (unsigned int i = 0; i < builtInSfxCount; i++)
    {
        ResourceLoader::GetInstance()->PreloadSound(sfxIdList[i], "SFX/" + sfxIdList[i]);
    }

    TTF_Init();

    MouseHelper::Init();
    KeyboardHelper::Init();
    TextInputHelper::Init();
    EventProviders::Init();

    // We'll be drawing a custom cursor, so let's hide the system cursor.
    SDL_ShowCursor(SDL_DISABLE);
#endif

    pInstance = new Game();
    pInstance->Init();

    return true;
}
Ejemplo n.º 9
0
bool muxerFlv::open(const char *file, ADM_videoStream *s,uint32_t nbAudioTrack,ADM_audioStream **a)
{
    uint32_t fcc=s->getFCC();
    bool r=true;
    char *fileTitle=NULL;

     if(fourCC::check(fcc,(uint8_t *)"FLV1") || isVP6Compatible(fcc))
     {

     }else
        {
            GUI_Error_HIG("Unsupported","Only FLV1 & VP6 supported for video");
            return false;
        }

    if(nbAudioTrack)
        for(int i=0;i<nbAudioTrack;i++)
        {
            uint32_t acc=a[i]->getInfo()->encoding;
            if(acc!=WAV_MP2 && acc!=WAV_MP3 && acc!=WAV_AAC)
            {
                GUI_Error_HIG("Unsupported","Only AAC & mpegaudio supported for audio");
                return false;
            }
            uint32_t fq=a[i]->getInfo()->frequency;
            if(fq!=44100 &&fq!=22050 && fq!=11025)
            {
                GUI_Error_HIG("Unsupported","Only 44.1, 22.050 and 11.025 kHz supported");
                return false;
            }


        }

    if(false==setupMuxer("flv",file))
    {
        printf("[FLV] Failed to open muxer\n");
        return false;
    }

   if(initVideo(s)==false)
    {
        printf("[FLV] Failed to init video\n");
        return false;
    }

    AVCodecContext *c = video_st->codec;
    AVDictionary *dict = NULL;

    rescaleFps(s->getAvgFps1000(),&(c->time_base));
    video_st->time_base=c->time_base;
    
    
    c->gop_size=15;

    if(initAudio(nbAudioTrack,a)==false)
    {
        printf("[FLV] Failed to init audio\n");
        return false;
    }

        int er=avio_open(&(oc->pb), file, AVIO_FLAG_WRITE);
        if (er)
        {
            ADM_error("[Flv]: Failed to open file :%s, er=%d\n",file,er);
            r=false;
            goto finish;
        }

		char buf[64];

        snprintf(buf, sizeof(buf), "%d", AV_TIME_BASE / 10);
        av_dict_set(&dict, "preload", buf, 0);
        av_dict_set(&dict, "max_delay", buf, 0);
		av_dict_set(&dict, "muxrate", "10080000", 0);

        if (avformat_write_header(oc, &dict) < 0)
        {
            printf("[Flv Muxer] Muxer rejected the parameters\n");
            r=false;
            goto finish;
        }
        initialized=true;
finish:
        vStream=s;
        aStreams=a;
        nbAStreams=nbAudioTrack;
        return r;
}
Ejemplo n.º 10
0
bool muxerMp4v2::open(const char *file, ADM_videoStream *s,uint32_t nbAudioTrack,ADM_audioStream **a)
{

        audioDelay=s->getVideoDelay();
        vStream=s;
        nbAStreams=nbAudioTrack;
        aStreams=a;
        videoBufferSize=vStream->getWidth()*vStream->getHeight()*3;
        videoBuffer[0]=new uint8_t[videoBufferSize];
        videoBuffer[1]=new uint8_t[videoBufferSize];
        scratchBuffer=new uint8_t[videoBufferSize];
        in[0].bufferSize=videoBufferSize;
        in[0].data=videoBuffer[0];
        in[1].bufferSize=videoBufferSize;
        in[1].data=videoBuffer[1];
        targetFileName=string(file);
//------Verify everything is ok : Accept Mp4 & H264 for video, AAC for audio ----
        uint32_t fcc=vStream->getFCC();
        if(!isH264Compatible(fcc) && !isMpeg4Compatible(fcc))
        {
            ADM_error("[mp4v2] Only h264 and mp4 video track!\n");
            return false;
        }
        for(int i=0;i<nbAStreams;i++)
        {
            int encoding=aStreams[i]->getInfo()->encoding;
            switch(encoding)
            {
                case WAV_MP2:case WAV_MP3:case WAV_AAC:case WAV_AC3:
                            continue;
                default:
                    GUI_Error_HIG("Audio","Audio format not supported, only AAC/MP3/AC3");
                    return false;
            }            
        }
//------Verify everything is ok : Accept Mp4 & H264 for video, AAC for audio ----
        
        // Create file
        handle=MP4Create( file,  ADM_MP4_OPTIONS_OPEN);
        if(MP4_INVALID_FILE_HANDLE==handle)
        {
            ADM_error("[mp4v2]Cannot create output file %s\n",file);
            return false;
        }
        MP4LogSetLevel(MP4_LOG_INFO);
        
        if (!(MP4SetTimeScale( handle, 90*1000 ))) // 90 kHz tick
        {
            ADM_error("[mp4v2]Cannot set timescale to us\n");
            return false;
        }
        if(false==initVideo())
        {
            ADM_error("Cannot init video\n");
            return false;
        }
        if(false==initAudio())
        {
            ADM_error("Cannot init audio\n");
            return false;
        }

        return true;
er:
        return false;
}
Ejemplo n.º 11
0
//_______________________________________________
uint8_t ADM_ogmWrite::save(const char *name)
{

uint8_t *bufr;
uint32_t len,flags;
uint8_t error=0;


		_fd=fopen(name,"wb");
		if(!_fd)
		{
                        GUI_Error_HIG(QT_TR_NOOP("File error"), QT_TR_NOOP("Cannot open \"%s\" for writing."), name);
			return 0;
		}

		videoStream=new ogm_page(_fd,1);
	
		encoding_gui=new DIA_encoding(25000);
                encoding_gui->setContainer("OGM");
		//______________ Write headers..._____________________
		
		if(!initVideo(name))
		{
			fclose(_fd);
			_fd=NULL;
                        GUI_Error_HIG(QT_TR_NOOP("Could not initialize video"), NULL);
			return 0;
		
		}
		if(!initAudio())
		{
			fclose(_fd);
			_fd=NULL;
                        GUI_Error_HIG(QT_TR_NOOP("Could not initialize audio"), NULL);
			return 0;
		
		}

		encoding_gui->setFps(_fps1000);
		encoding_gui->reset();
		// ___________________Then body_______________________
                uint32_t j=0;
		for( j=0;j<_togo && !error;j++)
		{
			if(!encoding_gui->isAlive())
			{
				error=1;
				continue;
			}
			if(!writeVideo(j)) error=1;
			if(!writeAudio(j)) error=1;
		}
                if(abs(j-_togo)<3 && error) error=0; // might be caused by late B frame
		delete encoding_gui;
		encoding_gui=NULL;
		//________________ Flush______________________
		videoStream->flush();
		endAudio();
		//deleteAudioFilters();
		// ____________Close____________________
		fclose(_fd);
		_fd=NULL;

	return !error;
}
Ejemplo n.º 12
0
int main(void) {
	while (1) {
		state = 0;
		int setTime = 15;
		numPlayers = 2;
		initScreen();
		clearScreen();
		initCharBuffer();
		clean_up();
		initKeyboard();
		initState0();
		initAI();


		//Bypass the menu system for testing
		if (IORD(keys,0) == 8) {
			initPlayer(pOne, MARIO, "pOne", 50, 100, HUMAN);
			initPlayer(pTwo, LUIGI, "pTwo", 50, 100, COMPUTER);
			state = 2;
		} else {
			while (state == 0) {
				decode_scancode(ps2, &decode_mode, buf, &ascii);
				state_0(decode_mode, buf[0]);
			};
			initState1(pOne);
			if(aOn)file_handle = initAudio(fname);
			if(aOn)alt_irq_register(AUDIO_0_IRQ, &ab, (alt_isr_func) write_fifo);
			if(aOn)		alt_up_audio_enable_write_interrupt(ab->audio);
			while (state == 1) {
				decode_scancode(ps2, &decode_mode, buf, &ascii);
				state_1(decode_mode, buf[0], ascii);
				if(aOn)loop_audio(file_handle, fname, ab);
			};
		}

		//clean_up();
		clearCharBuffer();
		clearScreen();

		//enable keyboard IRQ
		void* keyboard_control_register_ptr = (void*) (KEYBOARD_BASE + 4);
		alt_irq_register(KEYBOARD_IRQ, keyboard_control_register_ptr,
				keyboard_ISR);
		alt_up_ps2_enable_read_interrupt(ps2);

		//Draw field and UI to both buffers
		initField();

		updateField();
		drawName(p[pOne].name, p[pTwo].name, p[pThree].name, p[pFour].name);
		drawGas(p[pOne].gas);
		drawHealth(p[pOne].hp, p[pTwo].hp, p[pThree].hp, p[pFour].hp);
		drawBullet(p[pOne].bulletType);
		//drawWindIndicator(1);
		updateScreen();

		updateField();
		drawName(p[pOne].name, p[pTwo].name, p[pThree].name, p[pFour].name);
		drawGas(p[pOne].gas);
		drawHealth(p[pOne].hp, p[pTwo].hp, p[pThree].hp, p[pFour].hp);
		drawBullet(p[pOne].bulletType);
		//drawWindIndicator(1);

		float time;
		alt_timestamp_start();


		int start_timer_flag = 1;
		//printf("NUM PLAYERA %i\n", numPlayers);
		int i;
		while (state == 2) {
			int fallFlag = 1;

			//Checks to see if any players are falling
			while (fallFlag == 1) {
				fallFlag = 0;
				for (i = 0; i < numPlayers; i++) {
					if (p[i].alive) {
						if (p[i].y + TANK_HEIGHT >= SCREEN_HEIGHT-1) {
							p[i].hp = 0;
							p[i].alive = DEAD;
						}
						checkPlayerFalling(i);
						if (p[i].isFalling) {
							undrawPlayer(i);
							updatePlayer(i);
							fallFlag = 1;
						}
					}
				}
				if (fallFlag == 1) {
					updateScreen();
				}
			}

			if(start_timer_flag){
				start_time = (float) alt_timestamp() / (float) alt_timestamp_freq();
				start_timer_flag = 0;
			}
			time = (float) alt_timestamp() / (float) alt_timestamp_freq()-start_time;
			if (time >= setTime) {
				setPlayerTurn();
			}
			if (p[turn].type == HUMAN) {
				runGame();

			} else {
				p[turn].deg = 0;
				aiMain(turn);
				setPlayerTurn();
			}
			printTimer(setTime - time);
			int deadCount = 0;
			for (i = 0; i < numPlayers; i++) {
				if (p[i].alive == DEAD)
					deadCount++;
			}
			if (deadCount == numPlayers - 1) {
				usleep(500000);
				state = 3;
			}
		}

		alt_up_ps2_disable_read_interrupt(ps2);
		if(aOn)alt_up_audio_disable_write_interrupt(ab->audio);

		GameOverScreen();
	}
}
Ejemplo n.º 13
0
void AndroidAudio::reInit()
{
	initAudio();
}
Ejemplo n.º 14
0
// execution begins here
int UltraMain(void) {
    struct display_context * dc;
    struct controller_data cd;

    int lasty=0,lastx=0;
    int d=0;

    // buffer for rendering text strings (only sprintf works at the moment)
    char buf[1024]; 

    // offset for the scrolling waveform
    float offs=0;

    // used to keep track of how many cycles various processes take
    unsigned long time,rendertime,lastrendertime,waittime,lastwaittime;

    // enable MI interrupts (on the CPU)
    set_MI_interrupt(1);

    initDisplay();
    initAudio();

    registerAIhandler(AIcallback);
    registerVIhandler(VIcallback);
   
    while (1) {
	short * sb;
	int sbsize;
	// Mark the value of the COUNT register (increments at half the CPU
	// rate) at the start of the main loop.
	time=read_count();

	while (! (dc=lockDisplay())) ;

	// Mark the time after waiting.
	waittime=time;
	waittime=((time=read_count())-waittime)*2;

	sb=getbuf();
	sbsize=getbufsize();

	for (int c=0;c<sbsize;c++,d++) {
       	    sb[c*2]=sin((d%22050)/22050.0*M_TWOPI*1000.0)*100*((cd.c[0].y-lasty)*c/sbsize+lasty)*(((cd.c[0].x-lastx)*c/sbsize+lastx)/128.0-1.0);
	    sb[c*2+1]=sin((d%22050)/22050.0*M_TWOPI*1000.0)*100*((cd.c[0].y-lasty)*c/sbsize+lasty)*(((cd.c[0].x-lastx)*c/sbsize+lastx)/128.0+1.0);
	}
	writebuffer(sb);

	lastx=cd.c[0].x;
	lasty=cd.c[0].y;

	// this is what really marks the beginning of the current frame

	// read controller data
	controller_Read(&cd);

	// start drawing on the other frame buffer, clear the screen (uses red
	// when the start button on controller 1 is pressed, black otherwise)
	VI_FillScreen(&dc->conf,cd.c[0].err?0:(cd.c[0].start?0xf800:0));

	// print a little info for each controller
	for (int c=0; c < 4; c++) {
	    if (cd.c[c].err) // if controller not present
		sprintf(buf,"controller %d not present",c+1);
	    else {
		sprintf(buf,"controller %d present\nbuttons=0x%04X x=%4d y=%4d",c+1,
		    	cd.c[c].buttons,
		     	cd.c[c].x,
		      	cd.c[c].y);
	    }

	    VI_DrawText(&dc->conf,50,58+2*8*c,buf);
	}

	// draw a waveform
	for (float x=50; x < 250; x++) {
	    VI_DrawPixel(&dc->conf,x,cbrt(sin((x-50)/200*M_TWOPI*4+offs))*250.0/8+175,0x7c0);
	}

	// the waveform can be scrolled by the x axis of the first controller
	if (!cd.c[0].err) offs-=(cd.c[0].x/2*2)/32.0;

	// print up some informative text, and report how long we waited for
	// this frame, and how long the last frame took to render
	sprintf(buf,"buffers: %5d frames: %5d\n%8lu cycles last frame\n%8lu cycles waiting\n%4.2f FPS",buffercount,framecount,lastrendertime,lastwaittime,100000000.0/(lastwaittime+lastrendertime));
	VI_DrawText(&dc->conf,50,26,buf);

	// calculate how many cycles this frame took to render
	rendertime=(read_count()-time)*2;
	lastwaittime=waittime;
	lastrendertime=rendertime;

	showDisplay(dc);
	dc=0;
    }

    return 0;
}
Ejemplo n.º 15
0
bool Main::main(int argc, _TCHAR* argv[])
{
    consoleWindowHandle = GetConsoleWindow();

    /// Initialize time keeping.
    LARGE_INTEGER frequency;
    assert(QueryPerformanceFrequency(&frequency) != 0);
    timeCounterFrequency = static_cast<double>(frequency.QuadPart);
    assert(timeCounterFrequency > 0);
    QueryPerformanceCounter(&startTime);

    /// Register a window class. 
    /// \todo Configure small and large application icons.

    const wchar_t * windowClassName = L"x";
    WNDCLASSEX wcex;
	wcex.cbSize = sizeof(WNDCLASSEX);
	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= GetModuleHandle(NULL);
	wcex.hIcon			= 0; //LoadIcon(hInstance, MAKEINTRESOURCE(IDI_MAIN));
	wcex.hCursor		= 0; //LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName	= NULL;  //MAKEINTRESOURCE(IDC_MAIN);
	wcex.lpszClassName	= windowClassName;
	wcex.hIconSm		= 0; //LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
	ATOM windowClass = RegisterClassExW(&wcex);
    assert(windowClass != 0);

    /// Determine size of window border by creating a temporary window.

    applicationWindowHandle = CreateWindowEx(
        WS_EX_CLIENTEDGE,
        windowClassName,
        L"X",
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT, 
        CW_USEDEFAULT, 
		Platform::screenWidth, 
        Platform::screenHeight,
        NULL,
        NULL,
        GetModuleHandle(NULL),
        NULL);
    assert(applicationWindowHandle != NULL);
    RECT clientRect;
	GetClientRect(applicationWindowHandle, &clientRect);
	int clientRectWidth = clientRect.right;
	int clientRectHeight = clientRect.bottom; 
	RECT windowRect;
	GetWindowRect(applicationWindowHandle, &windowRect);
	int windowRectWidth = windowRect.right - windowRect.left;
	int windowRectHeight = windowRect.bottom - windowRect.top;    
	int windowBorderWidth = windowRectWidth - clientRectWidth;
	int windowBorderHeight = windowRectHeight - clientRectHeight;
	assert(DestroyWindow(applicationWindowHandle));
    Core::run = true;  // Temporary window sets this to false when destroyed.

	/// Calculate the window width and height needed to achieve
    /// the application's desired width and height.
	int windowWidth = Platform::screenWidth + windowBorderWidth;
	int windowHeight = Platform::screenHeight + windowBorderHeight;

    /// Create final application window.
	applicationWindowHandle = CreateWindowEx(
        WS_EX_CLIENTEDGE,
        windowClassName,
        L"Project X",
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT,
        CW_USEDEFAULT, 
		windowWidth, 
        windowHeight,
        NULL,
        NULL,
        GetModuleHandle(NULL),
        NULL);
    assert(applicationWindowHandle != NULL);
    ShowWindow(applicationWindowHandle, SW_SHOW);
    UpdateWindow(applicationWindowHandle);

#if _DEBUG
    /// When debugging, start thread to read Lua commands from console.
    CreateThread(0, 0, consoleThread, 0, 0, 0);
#else
    /// When not debugging, hide console.
    ShowWindow(consoleWindowHandle, SW_HIDE);
#endif

    deviceContext = GetDC(applicationWindowHandle);
    Platform::eglNativeWindowType = (EGLNativeWindowType) applicationWindowHandle;

    // Get the display handle.
    eglDisplay = Platform::getEglDisplay();
    if (eglDisplay == EGL_NO_DISPLAY)
    {
        Platform::error << "No EGL Display.";
        return false;
    }

    // Check OpenGL ES version.    
    EGLint major;
    EGLint minor;
    eglInitialize(eglDisplay, &major, &minor);
    if (!checkEglError())
    {
        Platform::error << "eglInitialize failed.";
        return false;
    }
    if (major == 1 && minor < 4)
    {
        Platform::error << "EGL version 1.4 or later required.";
        return false;
    }

    memset(&frameBufferConfiguration, 0, sizeof(EGLConfig));  // Not sure this is needed.
    eglChooseConfig(eglDisplay, frameBufferAttributes, &frameBufferConfiguration, 1, &numFrameBufferConfigurations);
    if (!checkEglError())
    {
        Platform::error << "Call to eglChooseConfig failed.";
        return false;
    }
    if (numFrameBufferConfigurations == 0)
    {
        Platform::error << "No EGL frame buffer configurations that match the specified requirements.";
        return false;
    }

    // Create a window surface.
    EGLint surfaceAttributes[] = { EGL_RENDER_BUFFER, EGL_BACK_BUFFER, EGL_NONE, EGL_NONE };
    eglSurface = eglCreateWindowSurface(eglDisplay, frameBufferConfiguration, Platform::eglNativeWindowType, surfaceAttributes);
    if (!checkEglError())
    {
        Platform::error << "eglCreateWindowSurface failed.";
        return false;
    }
    if (eglSurface == EGL_NO_SURFACE)
    {
        Platform::error << "Call to eglCreateWindowSurface failed.";
        return false;
    }

    if (!createContext())
    {
        return false;
    }

    if (!initAudio())
    {
        return false;
    }

    if (!Core::init())
    {
        return false;
    }

    /// Enter message loop.
    while (Core::run)
    {
        MSG Msg;
	    while (PeekMessage(&Msg, NULL, 0, 0, PM_REMOVE) > 0)
	    {
            TranslateMessage(&Msg);
            DispatchMessage(&Msg);
	    }

        // Core has not yet drawn requested frame.
        LARGE_INTEGER currentTime;
        QueryPerformanceCounter(&currentTime);
        double totalElapsedSeconds = static_cast<double>(currentTime.QuadPart - startTime.QuadPart) / timeCounterFrequency;
        Core::onMessageQueueEmpty(totalElapsedSeconds);

        Core::renderNextFrame();

        // Core has drawn a frame, so let's render it.
        if (EGL_FALSE == eglSwapBuffers(eglDisplay, eglSurface))
        {
            // eglSwapBuffers will fail after a power event.
            // In this case, we need to reinitialize.
            EGLint error = eglGetError();	
            if (error == EGL_CONTEXT_LOST)
            {
                // Power event; need to "... destroy all contexts and reinitialise OpenGL ES state 
                // and objects to continue rendering." 
                destroyContext();
                if(!createContext())
                {
                    return false;
                }
            }
        }
    }

    Core::shutdown();

    destroyContext();
    eglDestroySurface(eglDisplay, eglSurface);
    eglTerminate(eglDisplay);

    while (waitForConsoleToClose)
    {
        // Wait until user presses enter in console window.
    }

	ReleaseDC(Main::applicationWindowHandle, Main::deviceContext);
	return true;
}
Ejemplo n.º 16
0
bool muxerMkv::open(const char *file, ADM_videoStream *s,uint32_t nbAudioTrack,ADM_audioStream **a)
{
    /* All seems fine, open stuff */
    if(false==setupMuxer("matroska",file))
    {
        ADM_warning("[Mkv] Failed to open muxer (setup)\n");
        return false;
    }
 
   if(initVideo(s)==false) 
    {
        ADM_warning("[Mkv] Failed to init video\n");
        return false;
    }
  
    
        AVCodecContext *c;
        c = video_st->codec;
        rescaleFps(s->getAvgFps1000(),&(c->time_base));
        video_st->time_base=c->time_base;
        c->gop_size=15;
        
        if(true==mkvMuxerConfig.forceDisplayWidth && mkvMuxerConfig.displayWidth)
        {
            //sar=display/code  
            int num=1,den=1;
            av_reduce(&num, &den, mkvMuxerConfig.displayWidth, s->getWidth(),65535);
            c->sample_aspect_ratio.num=num;
            c->sample_aspect_ratio.den=den;
            video_st->sample_aspect_ratio.num=num;
            video_st->sample_aspect_ratio.den=den;
            ADM_info("Forcing display width of %d\n",(int)mkvMuxerConfig.displayWidth);
        }

        if(initAudio(nbAudioTrack,a)==false)
        {
            ADM_warning("[Mkv] Failed to init audio\n");
            return false;
        }
        
        // /audio
        int er = avio_open(&(oc->pb), file, AVIO_FLAG_WRITE);

        if (er)
        {
            ADM_error("[Mkv]: Failed to open file :%s, er=%d\n",file,er);
            return false;
        }

        AVDictionary *dict = NULL;
		char buf[64];
        
        snprintf(buf, sizeof(buf), "%d", AV_TIME_BASE / 10);
        av_dict_set(&dict, "preload", buf, 0);
        av_dict_set(&dict, "max_delay", "200000", 0);
		av_dict_set(&dict, "muxrate", "10080000", 0);

        ADM_assert(avformat_write_header(oc, &dict) >= 0);
        ADM_info("Timebase codec = %d/%d\n",video_st->time_base.num,video_st->time_base.den);
//        ADM_info("Original timebase = %d/%d\n",myTimeBase.num,myTimeBase.den);
        
        
        vStream=s;
        aStreams=a;
        nbAStreams=nbAudioTrack;
        initialized=true;
        return true;
}
Ejemplo n.º 17
0
int
Starcon2Main (void *threadArg)
{
#if CREATE_JOURNAL
{
int ac = argc;
char **av = argv;

while (--ac > 0)
{
	++av;
	if ((*av)[0] == '-')
	{
		switch ((*av)[1])
		{
#if CREATE_JOURNAL
			case 'j':
				++create_journal;
				break;
#endif //CREATE_JOURNAL
		}
	}
}
}
#endif // CREATE_JOURNAL

	{
		/* TODO: Put initAudio back in main where it belongs once threading
		 *       is gone.
		 */
		extern sint32 initAudio (sint32 driver, sint32 flags);
		initAudio (snddriver, soundflags);
	}

	if (!LoadKernel (0,0))
	{
		log_add (log_Fatal, "\n  *** FATAL ERROR: Could not load basic content ***\n\nUQM requires at least the base content pack to run properly.");
		log_add (log_Fatal, "This file is typically called uqm-%d.%d.0.uqm.  UQM was expecting it", P6014_MAJOR_VERSION, P6014_MINOR_VERSION);
		log_add (log_Fatal, "in the %s/packages directory.", baseContentPath);
		log_add (log_Fatal, "Either your installation did not install the content pack at all, or it\ninstalled it in a different directory.\n\nFix your installation and rerun UQM.\n\n  *******************\n");
		exit (EXIT_FAILURE);
	}
	log_add (log_Info, "We've loaded the Kernel");

	Logo ();
	
	GLOBAL (CurrentActivity) = 0;
	// show splash and init the kernel in the meantime
	SplashScreen (BackgroundInitKernel);

//	OpenJournal ();
	while (StartGame ())
	{
		// Initialise a new game
		if (!SetPlayerInputAll ()) {
			log_add (log_Fatal, "Could not set player input.");
			explode ();  // Does not return;
		}
		
		InitGameStructures ();
		InitGameClock ();
		AddInitialGameEvents();

		do
		{
#ifdef DEBUG
			if (debugHook != NULL)
			{
				void (*saveDebugHook) (void);
				saveDebugHook = debugHook;
				debugHook = NULL;
						// No further debugHook calls unless the called
						// function resets debugHook.
				(*saveDebugHook) ();
				continue;
			}
#endif
			SetStatusMessageMode (SMM_DEFAULT);

			if (!((GLOBAL (CurrentActivity) | NextActivity) & CHECK_LOAD))
				ZeroVelocityComponents (&GLOBAL (velocity));
					// not going into talking pet conversation
			else if (GLOBAL (CurrentActivity) & CHECK_LOAD)
				GLOBAL (CurrentActivity) = NextActivity;
			
			if ((GLOBAL (CurrentActivity) & START_ENCOUNTER)
					|| GET_GAME_STATE (CHMMR_BOMB_STATE) == 2)
			{
				if (GET_GAME_STATE (CHMMR_BOMB_STATE) == 2
						&& !GET_GAME_STATE (STARBASE_AVAILABLE))
				{	/* BGD mode */
					InstallBombAtEarth ();
				}
				else if (GET_GAME_STATE (GLOBAL_FLAGS_AND_DATA) == (BYTE)~0
						|| GET_GAME_STATE (CHMMR_BOMB_STATE) == 2)
				{
					GLOBAL (CurrentActivity) |= START_ENCOUNTER;
					VisitStarBase ();
				}
				else
				{
					GLOBAL (CurrentActivity) |= START_ENCOUNTER;
					RaceCommunication ();
				}

				if (!(GLOBAL (CurrentActivity) & (CHECK_ABORT | CHECK_LOAD)))
				{
					GLOBAL (CurrentActivity) &= ~START_ENCOUNTER;
					if (LOBYTE (GLOBAL (CurrentActivity)) == IN_INTERPLANETARY)
						GLOBAL (CurrentActivity) |= START_INTERPLANETARY;
				}
			}
			else if (GLOBAL (CurrentActivity) & START_INTERPLANETARY)
			{
				GLOBAL (CurrentActivity) = MAKE_WORD (IN_INTERPLANETARY, 0);

				DrawAutoPilotMessage (TRUE);
				SetGameClockRate (INTERPLANETARY_CLOCK_RATE);
				ExploreSolarSys ();
			}
			else
			{
				// Entering HyperSpace or QuasiSpace.
				GLOBAL (CurrentActivity) = MAKE_WORD (IN_HYPERSPACE, 0);

				DrawAutoPilotMessage (TRUE);
				SetGameClockRate (HYPERSPACE_CLOCK_RATE);
				Battle (&on_battle_frame);
			}

			LockMutex (GraphicsLock);
			SetFlashRect (NULL);
			UnlockMutex (GraphicsLock);

			LastActivity = GLOBAL (CurrentActivity);

			if (!(GLOBAL (CurrentActivity) & (CHECK_ABORT | CHECK_LOAD))
					&& (LOBYTE (GLOBAL (CurrentActivity)) == WON_LAST_BATTLE 
						|| LOBYTE (GLOBAL (CurrentActivity)) == BLACK_ORB_CUTSCENE 	// JMS: End demo at cutscene upon finding black orb.
						|| GLOBAL_SIS (CrewEnlisted) == (COUNT)~0)) // if died for some reason
			{
				if (GET_GAME_STATE (KOHR_AH_KILLED_ALL))
					InitCommunication (BLACKURQ_CONVERSATION);
						// surrendered to Ur-Quan
				else if (GLOBAL (CurrentActivity) & CHECK_RESTART)
					GLOBAL (CurrentActivity) &= ~CHECK_RESTART;
				break;
			}
		} while (!(GLOBAL (CurrentActivity) & CHECK_ABORT));

		StopSound ();
		UninitGameClock ();
		UninitGameStructures ();
		ClearPlayerInputAll ();
	}
//	CloseJournal ();

	UninitGameKernel ();
	FreeMasterShipList ();
	FreeKernel ();

	MainExited = TRUE;

	(void) threadArg;  /* Satisfying compiler (unused parameter) */
	return 0;
}
Ejemplo n.º 18
0
bool muxerMP4::open(const char *file, ADM_videoStream *s,uint32_t nbAudioTrack,ADM_audioStream **a)
{
    if(!isMpeg4Compatible(s->getFCC()) && !isH264Compatible(s->getFCC()))
    {
        GUI_Error_HIG("Unsupported","Only MP4Video & H264 supported for video");
        return false;
    }
    if(nbAudioTrack)
        for(int i=0; i<nbAudioTrack; i++)
        {
            uint32_t acc=a[i]->getInfo()->encoding;
            if(acc!=WAV_MP2 && acc!=WAV_MP3 && acc!=WAV_AAC)
            {
                GUI_Error_HIG("Unsupported","Only AAC & mpegaudio supported for audio");
                return false;
            }
        }
    /* All seems fine, open stuff */
    const char *f="mp4";
    if(muxerConfig.muxerType==MP4_MUXER_PSP) f="psp";
    if(false==setupMuxer(f,file))
    {
        printf("[MP4] Failed to open muxer\n");
        return false;
    }

    if(initVideo(s)==false)
    {
        printf("[MP4] Failed to init video\n");
        return false;
    }


    AVCodecContext *c;
    AVRational myTimeBase;
    c = video_st->codec;
    rescaleFps(s->getAvgFps1000(),&(c->time_base));
    myTimeBase=video_st->time_base=c->time_base;
    ADM_info("Video stream time base :%d,%d\n",video_st->time_base.num,video_st->time_base.den);
    c->gop_size=15;

    if(initAudio(nbAudioTrack,a)==false)
    {
        printf("[MP4] Failed to init audio\n");
        return false;
    }

    // /audio
    int er = avio_open(&(oc->pb), file, AVIO_FLAG_WRITE);


    ADM_info("Timebase In  = %d/%d\n",myTimeBase.num,myTimeBase.den);

    if (er)
    {
        ADM_error("[Mp4]: Failed to open file :%s, er=%d\n",file,er);
        return false;
    }

    AVDictionary *dict = NULL;
    char buf[64];

    snprintf(buf, sizeof(buf), "%d", AV_TIME_BASE / 10);
    av_dict_set(&dict, "preload", buf, 0);
    av_dict_set(&dict, "max_delay", "200000", 0);
    av_dict_set(&dict, "muxrate", "10080000", 0);
#ifndef _WIN32 // does not work on windows as the file must be opened twice at the same time        
    av_dict_set(&dict, "movflags","faststart",0);
#endif
    ADM_assert(avformat_write_header(oc, &dict) >= 0);

    ADM_info("Timebase codec = %d/%d\n",c->time_base.num,c->time_base.den);
    ADM_info("Timebase stream = %d/%d\n",video_st->time_base.num,video_st->time_base.den);
    if(myTimeBase.den==video_st->time_base.den && video_st->time_base.num==1)
    {
        roundup=myTimeBase.num;
        ADM_warning("Timebase roundup = %d\n",roundup);

    }
    av_dict_free(&dict);
    vStream=s;
    aStreams=a;
    nbAStreams=nbAudioTrack;
    initialized=true;
    return true;
}
Ejemplo n.º 19
0
int VivaVoce::run(void) {
	Memo *memo;

	common->rmg->init();
	common->sipRmg->init();

	common->go=1;

	//randomize
	gettimeofday(&common->currtime,NULL);
	srand(common->currtime.tv_usec);

	if(!stdPorts) {
		common->sipPort=sipPort;
		common->rtpPort=rtpPort;
		common->rtcpPort=rtcpPort;
	}
	if(UdpBase::initTransport(common) <0) {
		return -1;
	}
	if(initAudio(common) <0) {
		printf("Error in opening audio\n");
		return -1;
	}

    startThreads();

	common->isConnected = 0;
	
	AudioIOTest *audioTest = NULL;

	char* ptr;
	char* line;
	printf("\nVIVAVOCE 1.2:\nWelcome %s@%s",
		common->username,
		common->hostname);
	while(1) {
	    char cmd[100];	   
	    //cmd[0] = '\0';
		printf("\n cmd: ");	
        fgets(cmd, sizeof(cmd), stdin);   //gets(cmd) is deprecated so using fgets instead.
        cmd[strlen(cmd) - 1] = '\0';      //remove newline

		if((strncmp("i", cmd, 1)==0)  || (strncmp("invite", cmd, 6)==0)) {
			if(common->isRinging || common->isConnected) {
				printf("\n\tError: Busy with another call.");
				continue;
			}
			line = strtok_r(cmd, " ", &ptr);
			line = strtok_r(NULL, " ", &ptr);

			if(line) {
				printf("Connecting to %s...",line);
				memo = common->sipRmg->allocMemo();
				memo->code=VIVOCE_SIP_INVITE;
				sprintf(memo->bytes,"%s",line);
				common->signalQ->signalData(memo);
			}
			else {
				printf("\n\tError: Invalid remote address.");
				sleep(1);
				continue;
			}
		}
		else if((strncmp("a", cmd, 1)==0) || (strncmp("accept", cmd, 6)==0)) {
			if(!common->isRinging) {
				printf("\n\tError: No incoming request to accept.");
				continue;
			}
			memo = common->sipRmg->allocMemo();
			memo->code = VIVOCE_SIP_ACCEPT;
			common->signalQ->signalData(memo);
		}
		else if((strncmp("r", cmd, 1)==0) || (strncmp("reject", cmd, 6)==0)) {
			if(!common->isRinging) {
				printf("\n\tError: No incoming request to reject.");
				continue;
			}
			memo = common->sipRmg->allocMemo();
			memo->code = VIVOCE_SIP_REJECT;
			common->signalQ->signalData(memo);
		}
		else if((strncmp("b", cmd, 1)==0) || (strncmp("bye", cmd, 3)==0)) {
			if(!common->isConnected) {
				printf("\n\tError: Not connected");
				continue;
			}
			memo = common->sipRmg->allocMemo();
			memo->code = VIVOCE_SIP_BYE;
			common->signalQ->signalData(memo);
		}
/*		else if(strcmp(cmd,"loss")==0) {
			printf("\n\tEnter packet loss probability (percent):");
			scanf("%d",&common->packLossProb);
			if((common->packLossProb<1)||(common->packLossProb>100)) {
				common->packLossProb = 20;
			}
			printf("\n\tPacket loss probability set to %d percent",
				common->packLossProb);
		}*/
		else if((strncmp("d", cmd, 1)==0) || (strncmp("diag", cmd, 4)==0)) {
			printf("\nDiagnostics for SSRC=%ld: %s%s",
				common->rtpMgr->state->SSRC,
				(common->isConnected?"Connected to ":"Disconnected"),
				(common->isConnected?common->remoteName:""));
			printf("\n\tRec=%.0f enc=%.0f snt=%.0f rcv=%.0f dec=%.0f pld=%.0f",
				common->unitsRec,
				common->unitsEnc,
				common->unitsSnt,
				common->unitsRcv,
				common->unitsDec,
				common->unitsPld);
			printf("\n\tSeq=%d cycles=%d snt=%ld rcv=%ld lost=%ld simLost=%d",
				common->rtpMgr->state->sequence,
				common->rtpMgr->state->seqWrap,
				common->rtpMgr->state->nPacketsSent,
				common->rtpMgr->state->nPacketsRecvd,
				common->rtpMgr->state->nPacketsLost,
				common->simLost);
			printf("\n\tSR rcvd=%u, RR rcvd=%u Jitter=%.3f RTT=%ld ms" ,
				common->rtpMgr->state->nSRep,
				common->rtpMgr->state->nRRep,
				common->rtpMgr->state->jitter,
				(common->rtpMgr->state->RTTPropDelay*65536/1000));
			printf("\n\tQ:codec=%d play=%d send=%d signal=%d",
				common->codecQ->count(),
				common->playQ->count(),
				common->sendQ->count(),
				common->signalQ->count());
			printf("\n\trmg:total=%d res=%d Sip:total=%d res=%d",
				common->rmg->getTotal(),
				common->rmg->getNMemosInReserve(),
				common->sipRmg->getTotal(),
				common->sipRmg->getNMemosInReserve());
		}
		else if((strncmp("v", cmd, 1)==0) || (strncmp("verbose", cmd, 7)==0)) {
			if(common->verbose) {
				common->verbose = false;
				printf("\n\tVerbose mode disabled");
			}
			else {
				common->verbose = true;
				printf("\n\tVerbose mode enabled");
			}
		}
		else if(strncmp("w", cmd, 1)==0) {
			memo = common->sipRmg->allocMemo();
			memo->code = VIVOCE_RESPOND;
			common->signalQ->signalData(memo);
			memo = common->rmg->allocMemo();
			memo->code = VIVOCE_RESPOND;
			common->sendQ->signalData(memo);
			memo = common->rmg->allocMemo();
			memo->code = VIVOCE_RESPOND;
			common->codecQ->signalData(memo);
			memo = common->rmg->allocMemo();
			memo->code = VIVOCE_RESPOND;
			common->playQ->signalData(memo);
			common->audrSig=1;
			common->udprSig=1;
		}
		else if((strncmp("t", cmd, 1)==0) || (strncmp("testaudio", cmd, 6)==0)) {
		    if(common->isConnected) {
		        printf("In a call right now, can't run test...\n"); fflush(stdout);
		    }
		    else {
                if (audioTest == NULL) {
                    char *flag = NULL;
                    int f = 0;
    		        line = strtok_r(cmd, " ", &ptr);
    		        line = strtok_r(NULL, " ", &ptr);
    		        if(ptr) {
                        flag = strtok_r(NULL, " ", &ptr);
                        if(flag) f = atoi(flag);
    		        }
    		        if (line && strncmp("c", line, 1) == 0) {
    		            printf("Audio test with codec, flags=%d...\n", f); fflush(stdout);
                        audioTest = new AudioIOTest(common, audioReader, audioWriter, adpcmCodec, true, f);
    		        }
    		        else {
    		            printf("Audio test without codec, flags=%d...\n", f); fflush(stdout);
    		            audioTest = new AudioIOTest(common, audioReader, audioWriter, adpcmCodec, false, f);
    		        }
    		    }
                if (audioTest->running) {
                    audioTest->running = false;
                    delete audioTest;
                    audioTest = NULL;
                }
                else {
                    audioTest->start();
                }
		    }
		}
		else if(!strncmp("m", cmd, 1) || !strncmp("mute", cmd, 4)) {
            common->audioMute = 1 - common->audioMute; //toggle
            if(common->audioMute) {
                printf("Audio muted."); fflush(stdout);
            }
            else {
                printf("Audio unmuted."); fflush(stdout);
            }            
	    }
		else if(!strncmp("s", cmd, 1) || !strncmp("sine", cmd, 4)) {
            common->audioGenTone = 1 - common->audioGenTone; //toggle
            if(common->audioGenTone) {
                printf("Transmitting a generated tone..."); fflush(stdout);
            }
            else {
                printf("Transmitting recorded audio..."); fflush(stdout);
            }
	    }	    
		else if(!strncmp("x", cmd, 1) || !strncmp("q", cmd, 1) || !strncmp("quit", cmd, 4) || !strncmp("exit", cmd, 4)) {
		    //printf("[%s], done...", cmd);
		    if (audioTest && (audioTest->running)) {
                audioTest->running = false;
                delete audioTest;
		    }
            break;
	    }
		else {
			if(strlen(cmd) && strncmp("exit", cmd, 4) && strncmp("x",cmd, 1))
				printf("\n\tUnrecognized command");
		}
	}
	if(common->isConnected) {
		memo = common->sipRmg->allocMemo();
		memo->code = VIVOCE_SIP_BYE;
		common->signalQ->signalData(memo);
		printf("\nDisconnecting.\n"); fflush(stdout);
 
		sleep(1);
	}
	printf("\nShutting down\n");
	common->go=0;
	common->isConnected=0;
	common->signalQ->signal();
	common->sendQ->signal();
	common->codecQ->signal();
	common->playQ->signal();
	common->rtpMgr->close();
	
	printf("\nWaiting for threads to die...\n");
	waitForThreadsToDie();

	common->rmg->clear();
	common->sipRmg->clear();	
	//udpReader->join(NULL);
	if(UdpBase::closeTransport(common) <0) {
		printf("\n\nError in closing sockets... \n");
	}
	printf("Done.\n");
	return 0;
Ejemplo n.º 20
0
AndroidAudio::AndroidAudio(ConfigFile *c, QObject *parent) :
	QObject(parent), mEngineObject(NULL), mEngineEngine(NULL), mOutputMixObject(NULL), mSounds(), mSoundCount(0), mPlayerObject(NULL), myConfig(c), audioEnabled(false)
{
	initAudio();
}
Ejemplo n.º 21
0
void Streamer::Init()
{
    
    //Game* game = (Game*)g_pSceneManager->Find("game");
	initAudio("128.198.85.100", 8000);
	s3eDeviceRegister(S3E_DEVICE_EXIT, &exitCB, 0);
    
    facebook = new CSprite();
    facebook->SetImage(g_pResources->getFacebook());
    facebook->m_X = (float)IwGxGetScreenWidth() / 1.4;
    facebook->m_Y = (float)IwGxGetScreenHeight() / 16;
    facebook->m_W = facebook->GetImage()->GetWidth();
    facebook->m_H = facebook->GetImage()->GetHeight();
    facebook->m_AnchorX = 0.5;
    facebook->m_AnchorY = 0.5;
    facebook->m_ScaleX = (float)IwGxGetScreenWidth() / facebook->GetImage()->GetWidth() / 8;
    facebook->m_ScaleY = (float)IwGxGetScreenHeight() / facebook->GetImage()->GetHeight() / 12;
    
    twitter = new CSprite();
    twitter->SetImage(g_pResources->getTwitter());
    twitter->m_X = (float)IwGxGetScreenWidth() / 1.1;
    twitter->m_Y = (float)IwGxGetScreenHeight() / 16;
    twitter->m_W = twitter->GetImage()->GetWidth();
    twitter->m_H = twitter->GetImage()->GetHeight();
    twitter->m_AnchorX = 0.5;
    twitter->m_AnchorY = 0.5;
    twitter->m_ScaleX = (float)IwGxGetScreenWidth() / twitter->GetImage()->GetWidth() / 8;
    twitter->m_ScaleY = (float)IwGxGetScreenHeight() / twitter->GetImage()->GetHeight() / 12;

    // Create menu background
    header = new CSprite();
    header->SetImage(g_pResources->getHeader());
    header->m_X = (float)IwGxGetScreenWidth() / 3;
    header->m_Y = (float)IwGxGetScreenHeight() / 17;
    header->m_W = header->GetImage()->GetWidth();
    header->m_H = header->GetImage()->GetHeight();
    header->m_AnchorX = 0.5;
    header->m_AnchorY = 0.5;
    // Fit background to screen size
    header->m_ScaleX = (float)IwGxGetScreenWidth() / header->GetImage()->GetWidth() / 1.5;
    header->m_ScaleY = (float)IwGxGetScreenHeight() / header->GetImage()->GetHeight() / 5;
    
    // Create menu background
    CSprite* whiteBanner = new CSprite();
    whiteBanner->SetImage(g_pResources->getWhiteBanner());
    whiteBanner->m_X = (float)IwGxGetScreenWidth() / 2;
    whiteBanner->m_Y = (float)IwGxGetScreenHeight() / 17;
    
    whiteBanner->m_W = whiteBanner->GetImage()->GetWidth();
    whiteBanner->m_H = whiteBanner->GetImage()->GetHeight();
    whiteBanner->m_AnchorX = 0.5;
    whiteBanner->m_AnchorY = 0.5;
    // Fit background to screen size
    whiteBanner->m_ScaleX = (float)IwGxGetScreenWidth() / whiteBanner->GetImage()->GetWidth() / 1;
    whiteBanner->m_ScaleY = (float)IwGxGetScreenHeight() / whiteBanner->GetImage()->GetHeight() / 5;
    
    // Create menu background
    playWrapper = new CSprite();
    playWrapper->SetImage(g_pResources->getPlayWrapper());
    playWrapper->m_X = (float)IwGxGetScreenWidth() / 2;
    playWrapper->m_Y = (float)IwGxGetScreenHeight() / 1.09;
    playWrapper->m_W = playWrapper->GetImage()->GetWidth();
    playWrapper->m_H = playWrapper->GetImage()->GetHeight();
    playWrapper->m_AnchorX = 0.5;
    playWrapper->m_AnchorY = 0.5;
    //playWrapper->m_Alpha = 0.9;
    // Fit background to screen size
    playWrapper->m_ScaleX = (float)IwGxGetScreenWidth() / playWrapper->GetImage()->GetWidth() / 1;
    playWrapper->m_ScaleY = (float)IwGxGetScreenHeight() / playWrapper->GetImage()->GetHeight() / 6;

    playButton = new CSprite();
    playButton->SetImage(g_pResources->getPlayButton());
    playButton->m_X = (float)IwGxGetScreenWidth() / 2;
    playButton->m_Y = (float)IwGxGetScreenHeight() / 1.13;
    //buttonTop = (float)IwGxGetScreenHeight() / 1.14 - (playButton->GetImage()->GetHeight() / 8);
    playButton->m_W = playButton->GetImage()->GetWidth();
    playButton->m_H = playButton->GetImage()->GetHeight();
    playButton->m_AnchorX = 0.5;
    playButton->m_AnchorY = 0.5;
    // Fit background to screen size
    playButton->m_ScaleX = (float)IwGxGetScreenWidth() / playButton->GetImage()->GetWidth() / 3.2;
    playButton->m_ScaleY = (float)IwGxGetScreenHeight() / playButton->GetImage()->GetHeight() / 4.5;
    
    //buttonTop = ((float)IwGxGetScreenHeight() / 1.14) - (playButton->GetImage()->GetHeight() / 3.7);
    
    stopButton = new CSprite();
    stopButton->SetImage(g_pResources->getStopButton());
    stopButton->m_X = (float)IwGxGetScreenWidth() / 2;
    stopButton->m_Y = (float)IwGxGetScreenHeight() / 1.13;
    stopButton->m_W = stopButton->GetImage()->GetWidth();
    stopButton->m_H = stopButton->GetImage()->GetHeight();
    stopButton->m_AnchorX = 0.5;
    stopButton->m_AnchorY = 0.5;
    // Fit background to screen size
    stopButton->m_ScaleX = (float)IwGxGetScreenWidth() / stopButton->GetImage()->GetWidth() / 3.2;
    stopButton->m_ScaleY = (float)IwGxGetScreenHeight() / stopButton->GetImage()->GetHeight() / 4.5;
    
    banner = new CSprite();
    banner->SetImage(g_pResources->getGreyBanner());
    banner->m_X = (float)IwGxGetScreenWidth() / 2;
    banner->m_Y = (float)IwGxGetScreenHeight() /6;
    banner->m_W = banner->GetImage()->GetWidth();
    banner->m_H = banner->GetImage()->GetHeight();
    banner->m_AnchorX = 0.5;
    banner->m_AnchorY = 0.5;
    // Fit background to screen size
    banner->m_ScaleX = (float)IwGxGetScreenWidth() / banner->GetImage()->GetWidth() / 1;
    banner->m_ScaleY = (float)IwGxGetScreenHeight() / banner->GetImage()->GetHeight() / 8;
    
    buttonTop = IwGxGetScreenHeight() / 4;
    
    labelLeft = new CLabel();
	labelLeft->m_Font = g_pResources->getBannerFontSmall();
	labelLeft->m_Text = "Cal.";
    labelLeft->m_Y = IwGxGetDisplayHeight() / 6.5;
    labelLeft->m_W = IwGxGetDisplayWidth() / 2;
    labelLeft->m_ScaleX = 1.0;
    labelLeft->m_AlignHor = IW_2D_FONT_ALIGN_LEFT;
    labelLeft->m_X += 10;
    labelLeft->m_Color = CColor(114, 114, 114, 0xff);
    
    labelRight = new CLabel();
	labelRight->m_Font = g_pResources->getBannerFontSmall();
	labelRight->m_Text = "Events";
    labelRight->m_Y = IwGxGetDisplayHeight() / 6.5;
    labelRight->m_W = IwGxGetDisplayWidth() / 2;
    labelRight->m_AlignHor = IW_2D_FONT_ALIGN_RIGHT;
    labelRight->m_X += (IwGxGetDisplayWidth() / 2.0) -10;
    labelRight->m_Color = CColor(114, 114, 114, 0xff);
    
    labelMain = new CLabel();
	labelMain->m_Font = g_pResources->getBannerFontLarge();
	labelMain->m_Text = "News";
    labelMain->m_Y = IwGxGetDisplayHeight() / 7.5;
    labelMain->m_W = IwGxGetDisplayWidth();
    labelMain->m_AlignHor = IW_2D_FONT_ALIGN_CENTRE;
    
    AddChild(banner);
    AddChild(whiteBanner);
    AddChild(header);
    AddChild(labelRight);
    AddChild(labelLeft);
    AddChild(playWrapper);
    AddChild(playButton);
    AddChild(stopButton);
    AddChild(labelMain);
    AddChild(facebook);
    AddChild(twitter);
    
    stopButton->m_X = IwGxGetScreenWidth() * 2.0;
    currentPage = 0;
    
    
}
Ejemplo n.º 22
0
int main(int argc, char *argv[])
{
	int i, result;

	progname = strrchr(argv[0], '/');
	if (progname == NULL)
		progname = argv[0];
	else
		progname++;
	if (argc == 1)
		usage();

	for (i = 0; i < MAX_SCORES; i++) {
		scoreNames[i] = NULL;
		scores[i] = NULL;
	}

	for (i = 1; i < argc; i++) {
		char *arg = argv[i];
		if (arg[0] == '-') {
			switch (arg[1]) {
				case 'a':
					if (++i >= argc)
						usage();
					rescaleFactor = atof(argv[i]);
					if (fabs(rescaleFactor) > 2.0)
						rescaleFactor = 2.0;
					break;
				case 'B':
					if (++i >= argc)
						usage();
					framesPerBuffer = atof(argv[i]);
					if (framesPerBuffer < MIN_FRAMES_PER_BUF)
						framesPerBuffer = MIN_FRAMES_PER_BUF;
					break;
				case 'c':
					if (++i >= argc)
						usage();
					numOutChannels = atof(argv[i]);
					if (numOutChannels < 1)
						numOutChannels = 1;
					break;
				case 'd':
					if (++i >= argc)
						usage();
					totalDuration = atof(argv[i]);
					if (totalDuration < 0.0)
						totalDuration = 0.0;	// kinda stupid
					break;
				case 'h':
					usage();
					break;
#ifdef HAVE_PORTAUDIO
				case 'n':
					withAudio = 0;
					scoreDelayTime = 0.0;
					break;
#endif
				case 'q':
					printJobOutput = 0;
					break;
				case 'r':
					if (++i >= argc)
						usage();
					sampleRate = atof(argv[i]);
					if (sampleRate < 8000) // be more stringent?
						sampleRate = 8000;
					break;
				case 'v':
					verbose = 1;
					break;
				case 'y':
					if (++i >= argc)
						usage();
					scoreDelayTime = atof(argv[i]);
					if (scoreDelayTime < 0.0)
						scoreDelayTime = 0.0;
					break;
//FIXME: others: call flush after each score? call destroy after each?
				default:
					usage();
			}
		}
		else {
			const char *name = arg;

			/* verify that filename ends in ".sco" */
			char *p = strrchr(name, '.');
			if (p == NULL || strncmp(p, ".sco", 4L)) {
				fprintf(stderr, "Score names must end in \".sco\" (%s).\n", name);
				exit(-1);
			}

			if (numScores < MAX_SCORES) {
				scoreNames[numScores] = name;
				numScores++;
			}
			else {
				fprintf(stderr, "No more than %d scores allowed.\n", MAX_SCORES);
				exit(-1);
			}
		}
	}

#ifdef HAVE_PORTAUDIO
	if (withAudio) {
		result = initAudio();
		if (result)
			return -1;
	}
#endif

	result = initRTcmix();
	if (result)
		return -1;

	result = loadScores();
	if (result)
		return -1;

	printSettings();

	playScores();

	for (i = 0; i < numScores; i++)
		if (scores[i])
			free(scores[i]);

	result = deleteRTcmix();

#ifdef HAVE_PORTAUDIO
	if (withAudio)
		result = deleteAudio();
#endif

	return result;
}
Ejemplo n.º 23
0
int main(int argc, char *argv[])
{
  /*****
   * boolean value indicates when to break main loop
   * (and thus finish this configuration tool)
   *****/
  int request_finish = 0;

  int current         = 0; /***** menu related variables */
  int menu_items      = 7;
  enum state status[] = {invalid, invalid, inactive, inactive, inactive, inactive, invalid};

  WINDOW *mainscr; /***** ncurses related variables */
  int i, j;

  /* ***** detect available mixer devices */

  mixer_devices = scanMixerDevices();
  if (mixer_devices == NULL || mixer_devices->count == 0)
  {
    /* ***** no mixer devices available -> exit! */

    fprintf(stderr, "No mixer devices available!\n");
    fprintf(stderr, "Please purchase a sound card and install it!\n");
    exit(-1);
  }
  else
  {
    if (mixer_devices->count == 1) /***** exactly one mixer device available */
    {
      setMixer(mixer_devices->name[0]); /***** set this mixer */

      if (initMixer() == MIXER_OK) /***** if mixer is ok, keep it */
      {
	status[0] = ok;
	status[2] = invalid;
      }
      else                         /***** otherwise, exit!*/
      {
	fprintf(stderr, "Couldn't init the only available mixer device: /dev/%s\n",
		mixer_devices->name[0]);
	exit(-1);
      }
    }
    else /* ***** more than one device available! */
    {
      /* ***** use /dev/mixer as default if it exists */

      for (i = 0; i < mixer_devices->count; i++)
      {
	if (strcmp(mixer_devices->name[i], "mixer") == 0)
	{
	  setMixer("mixer");
	  if (initMixer() == MIXER_OK)
	  {
	    status[0] = ok;
	    status[2] = invalid;
	  }
	  else
	    noMixer();
	
	  break;
	}
      }
    }
  }

  /* ***** detect available audio devices */

  audio_devices = scanAudioDevices();
  if (audio_devices == NULL || audio_devices->count == 0)
  {
    /* ***** no audio devices available! */

    fprintf(stderr, "No audio device available that\n");
    fprintf(stderr, "supports 16bit recording!\n");
    fprintf(stderr, "Please purchase a sound card and install it!\n");
    exit(-1);
  }
  else
  {
    if (audio_devices->count == 1) /***** exactly one audio device available */
    {
      setAudio(audio_devices->name[0]); /***** set this audio device */

      if (initAudio() == AUDIO_OK) /***** if audio device is ok, keep it */
      {
	status[1] = ok;
      }
      else                         /***** otherwise, exit!*/
      {
	fprintf(stderr, "Couldn't init the only available audio device: /dev/%s\n",
		audio_devices->name[0]);
	exit(-1);
      }
    }
    else /* ***** more than one device available! */
    {
      /* ***** use /dev/dspW as default if it exists */

      for (i = 0; i < audio_devices->count; i++)
      {
	if (strcmp(audio_devices->name[i], "dspW") == 0)
	{
	  setAudio("dspW");
	  if (initAudio() == AUDIO_OK)
	    status[1] = ok;
	  else
	    noAudio();
	
	  break;
	}
      }
    }
  }

  /*****
   * if mixer and audio device have been selected successfully,
   * set menu cursor to next available menu item
   *****/
  if (status[0] == ok && status[1] == ok)
    current = 2;

  /***** ignore Ctrl-C */

  signal(SIGINT, SIG_IGN);

  /* ***** ncurses stuff */

  initscr();      /* initialize the curses library */

  if (color_term != -1) /***** define dialog color pairs if terminal supports colors */
   {
      start_color ();
      if ((color_term = has_colors ()))
      {
         color_term = 1;
         init_pair (1, COLOR_WHITE, COLOR_BLUE);
         init_pair (2, COLOR_YELLOW, COLOR_BLUE);
         init_pair (3, COLOR_BLUE, COLOR_YELLOW);
         init_pair (4, COLOR_YELLOW, COLOR_CYAN);
      }
   }
   else
      color_term = 0;

  keypad(stdscr, TRUE);  /* enable keyboard mapping */
  scrollok (stdscr, FALSE);
  cbreak();              /* take input chars one at a time, no wait for \n */
  noecho();              /* don't echo input */
  refresh();

  mainscr = popupWindow(COLS, LINES); /***** dialog window that contains the main menu */
  leaveok (mainscr, FALSE);

  while (!request_finish)
  {
    wattrset (mainscr, color_term ? COLOR_PAIR(2) | A_BOLD : A_NORMAL); /***** set bg color of the dialog */

    /*****
     * draw a box around the dialog window
     * and empty it.
     *****/
    box(mainscr, 0, 0);
    for (i = 1; i < COLS-1; i++)
      for (j = 1; j < LINES-1; j++)
	mvwaddch(mainscr, j, i, ' ');

    /***** dialog header */

    mvwaddstr(mainscr, 1, 2, "CVoiceControl");
    mvwaddstr(mainscr, 1, COLS - strlen("(c) 2000 Daniel Kiecza") - 2, "(c) 2000 Daniel Kiecza");
    mvwaddseparator(mainscr, 2, COLS);

    mvwaddstr(mainscr, 3, (COLS / 2) - (strlen ("Recording Device Configuration Tool") / 2),
	      "Recording Device Configuration Tool");
    mvwaddseparator(mainscr, 4, COLS);

    /***** main menu */

    mvwaddstr(mainscr, 5, 2, "Please Select:");

    setHighlight(mainscr, status[0], current == 0);
    mvwaddstr(mainscr, 7,5,"Select Mixer Device");
    if (mixerOK() == MIXER_OK)
    {
      mvwaddstr(mainscr, 7,24," ("); waddstr(mainscr, getMixer()); waddstr(mainscr, ")");
    }
    else
      mvwaddstr(mainscr, 7,24," (none selected!)");

    setHighlight(mainscr, status[1], current == 1);
    mvwaddstr(mainscr, 8,5,"Select Audio Device");
    if (audioOK() == AUDIO_OK)
    {
      mvwaddstr(mainscr, 8,24," ("); waddstr(mainscr, getAudio()); waddstr(mainscr, ")");
    }
    else
      mvwaddstr(mainscr, 8,24," (none selected!)");

    setHighlight(mainscr, status[2], current == 2);
    mvwaddstr(mainscr,  9,5,"Adjust Mixer Levels");
    setHighlight(mainscr, status[3], current == 3);
    mvwaddstr(mainscr, 10,5,"Calculate Recording Thresholds");
    setHighlight(mainscr, status[4], current == 4);
    mvwaddstr(mainscr, 11,5,"Estimate Characteristics of Recording Channel");
    setHighlight(mainscr, status[5], current == 5);
    mvwaddstr(mainscr, 12,5,"Write Configuration");
    setHighlight(mainscr, status[6], current == 6);
    mvwaddstr(mainscr, 13,5,"Exit");

    wmove(mainscr, 5, 17);  /***** set cursor to an appropriate location */
    wrefresh(mainscr);     /***** refresh the dialog */

    /* process the command keystroke */

    switch(getch())
    {
    case KEY_UP:   /***** cursor up */
      current = (current == 0 ? menu_items - 1 : current - 1);
      while(status[current] == inactive)
	current = (current == 0 ? menu_items - 1 : current - 1);
      break;
    case KEY_DOWN: /***** cursor down */
      current = (current == menu_items-1 ? 0 : current + 1);
      while(status[current] == inactive)
	current = (current == menu_items-1 ? 0 : current + 1);
      break;
    case ENTER:    /***** handle menu selections */
    case BLANK:
      switch (current)
      {
      case 0: /***** select mixer device */
	status[0] = invalid;
	status[2] = inactive;
	status[3] = inactive;
	status[4] = inactive;
	status[5] = inactive;
	noMixer();
	if (selectMixer() == MIXER_OK)
	{
	  status[0] = ok;
	  status[2] = invalid;
	}
	break;
      case 1: /***** select audio device */
	status[1] = invalid;
	status[3] = inactive;
	status[4] = inactive;
	status[5] = inactive;
	noAudio();
	if (selectAudio() == AUDIO_OK)
	  status[1] = ok;
	break;
      case 2: /***** adjust mixer levels */
	if (adjustMixerLevels())
	{
	  status[2] = ok;
	  status[3] = invalid;
	  status[4] = invalid;
	}
	break;
      case 3: /***** calculate recording thresholds */
	if (calculateThresholds())
	  status[3] = ok;
	else
	  status[3] = invalid;
	break;
      case 4: /***** estimate the characteristics of the recording channel */
	if (estimateChannelMean())
	  status[4] = ok;
	else
	  status[4] = invalid;
	break;
      case 5: /***** save configuration! */
	if (saveConfiguration())
	{
	  status[5] = ok;
	  status[6] = ok;
	}
	break;
      case 6: /***** leave program */
	if (status[6] == ok  ||  (status[6] != ok && safeExit()))
	{
	  wrefresh(mainscr);     /***** refresh the dialog */
  	  request_finish = 1;
	  delwin(mainscr);   /***** delete ncurses dialog window */
	 }
	break;
      }
      break;
    }

    /***** if the configuration is done, activate the menu item "Save Configuration" */

    if (status[0] != ok || status[1] != ok ||
	status[2] != ok || status[3] != ok ||
	status[4] != ok)
      status[5] = inactive;
    else if (status[5] != ok)
      status[5] = invalid;
  }

  endwin();               /* we're done */

  /***** free memory used by the list of mixer and audio devices */

  if (mixer_devices != NULL)
  {
    for (i = 0; i < mixer_devices->count; i++)
      free(mixer_devices->name[i]);
    free(mixer_devices->name);
    free(mixer_devices);
  }

  if (audio_devices != NULL)
  {
    for (i = 0; i < audio_devices->count; i++)
      free(audio_devices->name[i]);
    free(audio_devices->name);
    free(audio_devices);
  }

  exit(0);
}
Ejemplo n.º 24
0
int selectAudio()
{
  int top = 0, current = 0; /***** selection menu related variables */
  int max_view = 9;

  int retval = 0;           /***** return value */

  int request_finish = 0;   /***** leave current dialog, if request_finish is set to 1 */

  int width = 45, height = 15, i, j;               /***** ncurses related variables */
  WINDOW *audioscr = popupWindow (width, height);

  while (!request_finish)
  {
    wattrset (audioscr, color_term ? COLOR_PAIR(2) | A_BOLD : A_NORMAL); /***** set bg color of the dialog */

    /*****
     * draw a box around the dialog window
     * and empty it.
     *****/
    werase (audioscr);
    box (audioscr, 0, 0);
    for (i = 1; i < width-1; i++)
      for (j = 1; j < height-1; j++)
	mvwaddch(audioscr, j, i, ' ');

    /***** dialog header */

    mvwaddstr(audioscr, 1, 2, "Select Audio Device:");
    mvwaddseparator(audioscr, 2, width);

    /***** selection area */

    for (i = 0; i < MIN2(audio_devices->count, max_view); i++)
    {
      setHighlight(audioscr, ok, i == current);
      mvwaddstr(audioscr, 4+i, 4, "/dev/");
      waddstr(audioscr, audio_devices->name[top+i]);
    }
    wattroff(audioscr, A_REVERSE);

    /*****
     * show up/down arrow to the left, if more items are available
     * than can be displayed
     *****/
    if (top > 0)
    {
      mvwaddch(audioscr,4, 2, ACS_UARROW);
      mvwaddch(audioscr,4+1, 2, ACS_VLINE);
    }
    if (audio_devices->count > max_view && top+max_view <= audio_devices->count-1)
    {
      mvwaddch(audioscr,4+max_view-2, 2, ACS_VLINE);
      mvwaddch(audioscr,4+max_view-1, 2, ACS_DARROW);
    }

    wmove(audioscr, 1, 23);  /***** set cursor to an appropriate location */
    wrefresh (audioscr);     /***** refresh the dialog */

    /* process the command keystroke */

    switch(getch())
    {
    case KEY_UP:   /***** cursor up */
      if (current > 0)
	current--;
      else
	top = (top > 0 ? top-1 : 0);
      break;
    case KEY_DOWN: /***** cursor down */
      if (top+current < audio_devices->count-1)
      {
	if (current < max_view-1)
	 current++;
	else
	  top++;
      }
      break;
    case ESCAPE:   /***** Hit Escape to leave dialog */
      retval = AUDIO_ERR;
      request_finish = 1;
      break;
    case ENTER:   /***** make selection with Enter or Space bar */
    case BLANK:
      setAudio(audio_devices->name[top+current]); /***** set audio device to highlighted item */
      retval = initAudio();                       /***** retval is ok, if initAudio() returned ok */
      if (retval == AUDIO_ERR)
	noAudio();
      request_finish = 1;                         /***** leave dialog */
      break;
    }
  }

  delwin(audioscr);   /***** delete ncurses dialog window */
  return(retval);
}
Ejemplo n.º 25
0
void TTInstView::init()
{
    TRY_FUNC_WITH_RETURN(initAudio());
    createStatus();
    setLayout();
}
Ejemplo n.º 26
0
SDL_sound_handler::SDL_sound_handler()
    :
    _audioOpened(false)
{
    initAudio();
}
Ejemplo n.º 27
0
ModelItemSample *recordSample()
{
  /***** allocate memory for the new sample */

  ModelItemSample *new_sample = (ModelItemSample *)malloc(sizeof(ModelItemSample));

  char *tmp_string;
  time_t timer;     /***** used to get the current time, which will become */
  time(&timer);     /***** the main part of the new utterance's ID */

  /***** initialize the audio device */

  if (initMixer() == MIXER_ERR) /***** if mixer error, return nothing */
  {
    free(new_sample);
    return NULL;
  }
  if (igain_level > 0)
    setIGainLevel(igain_level); /***** set IGain and Mic level according */
  setMicLevel(mic_level);     /***** to configuration */

  if (initAudio() == AUDIO_ERR) /***** if audio error, return nothing */
  {
    free(new_sample);
    return NULL;
  }

  /***** connect to microphone, get utterance, disconnect */

  openAudio();
  new_sample->wav_data = getUtterance(&new_sample->wav_length);
  closeAudio();


  if (new_sample->wav_data == NULL) /***** if nothing was recorded, return nothing */
  {
    new_sample->wav_length = 0;
    new_sample->has_wav    = 0;
    free(new_sample);
    return NULL;
  }
  else
    /***** flag says that this sample utterance also contains its original
     * wave data, not only the preprocessed feature vectors
     *****/
    new_sample->has_wav    = 1;

  /***** preprocess the wave data */

  new_sample->data = preprocessUtterance(new_sample->wav_data, new_sample->wav_length, &new_sample->length);

  if (new_sample->data == NULL) /***** if preprocessing failed, return nothing */
  {
    new_sample->length = 0;
    free(new_sample->wav_data);
    free(new_sample);
    return NULL;
  }

  /***** set ID */

  tmp_string = ctime(&timer); /***** get current time */

  /***** set sample ID looks like:  [Thu Feb 10 12:10:53 2000] */

  new_sample->id         = malloc(strlen(tmp_string)+2);
  new_sample->id[0] = '[';
  strcpy(new_sample->id+1, tmp_string);
  new_sample->id[strlen(tmp_string)] = ']';

  new_sample->next   = NULL; /***** next sample pointer is NULL */
  {
    int i;
    for (i = 0; i < 3; i++)
      new_sample->matrix[i] = NULL;
  }

  modified = 1; /***** speaker model has been modified now */

  return(new_sample);
}