void CCCSHandler::writeStatus(wxFFile& file)
{
	for (unsigned int i = 0U; i < m_count; i++) {
		CCCSHandler* handler = m_handlers[i];
		if (handler != NULL) {
			struct tm* tm = ::gmtime(&handler->m_time);

			switch (handler->m_direction) {
				case DIR_OUTGOING:
					if (handler->m_state == CS_ACTIVE) {
						wxString text;
						text.Printf(wxT("%04d-%02d-%02d %02d:%02d:%02d: CCS link - Rptr: %s Remote: %s Dir: Outgoing\n"),
							tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, 
							handler->m_callsign.c_str(), handler->m_yourCall.c_str());
						file.Write(text);
					}
					break;

				case DIR_INCOMING:
					if (handler->m_state == CS_ACTIVE) {
						wxString text;
						text.Printf(wxT("%04d-%02d-%02d %02d:%02d:%02d: CCS link - Rptr: %s Remote: %s Dir: Incoming\n"),
							tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, 
							handler->m_callsign.c_str(), handler->m_yourCall.c_str());
						file.Write(text);
					}
					break;
			}
		}
	}
}
void SilentBlockFile::SaveXML(int depth, wxFFile &xmlFile)
{
   for(int i = 0; i < depth; i++)
      xmlFile.Write("\t");
   xmlFile.Write("<silentblockfile ");
   xmlFile.Write(wxString::Format("len='%d' ", mLen));
   xmlFile.Write("/>\n");
}
Exemple #3
0
// test a wxFFile and wxFFileInput/OutputStreams of a known type
// 
void FileKindTestCase::TestFILE(wxFFile& file, bool expected)
{
    CPPUNIT_ASSERT(file.IsOpened());
    CPPUNIT_ASSERT((wxGetFileKind(file.fp()) == wxFILE_KIND_DISK) == expected);
    CPPUNIT_ASSERT((file.GetKind() == wxFILE_KIND_DISK) == expected);

    wxFFileInputStream inStream(file);
    CPPUNIT_ASSERT(inStream.IsSeekable() == expected);

    wxFFileOutputStream outStream(file);
    CPPUNIT_ASSERT(outStream.IsSeekable() == expected);
}
Exemple #4
0
bool FLACImportFileHandle::Init()
{
#ifdef LEGACY_FLAC
   bool success = mFile->set_filename(OSINPUT(mFilename));
   if (!success) {
      return false;
   }
   mFile->set_metadata_respond(FLAC__METADATA_TYPE_STREAMINFO);
   mFile->set_metadata_respond(FLAC__METADATA_TYPE_VORBIS_COMMENT);
   FLAC::Decoder::File::State state = mFile->init();
   if (state != FLAC__FILE_DECODER_OK) {
      return false;
   }
#else
   if (!mHandle.Open(mFilename, wxT("rb"))) {
      return false;
   }

   // Even though there is an init() method that takes a filename, use the one that
   // takes a file handle because wxWidgets can open a file with a Unicode name and
   // libflac can't (under Windows).
   //
   // Responsibility for closing the file is passed to libflac.
   // (it happens when mFile->finish() is called)
   bool result = mFile->init(mHandle.fp())?true:false;
   mHandle.Detach();

   if (result != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
      return false;
   }
#endif
   mFile->process_until_end_of_metadata();

#ifdef LEGACY_FLAC
   state = mFile->get_state();
   if (state != FLAC__FILE_DECODER_OK) {
      return false;
   }
#else
   // not necessary to check state, error callback will catch errors, but here's how:
   if (mFile->get_state() > FLAC__STREAM_DECODER_READ_FRAME) {
      return false;
   }
#endif

   if (!mFile->is_valid() || mFile->get_was_error()) {
      // This probably is not a FLAC file at all
      return false;
   }
   return true;
}
Exemple #5
0
void systemStopGameRecording()
{
    if (!game_recording)
        return;

    if (game_file.Write(&game_frame, sizeof(game_frame)) != sizeof(game_frame) || game_file.Write(&game_joypad, sizeof(game_joypad)) != sizeof(game_joypad) || !game_file.Close())
        wxLogError(_("Error writing game recording"));

    game_recording = false;
    MainFrame* mf = wxGetApp().frame;
    mf->cmd_enable &= ~CMDEN_GREC;
    mf->cmd_enable |= CMDEN_NGREC | CMDEN_NGPLAY;
    mf->enable_menus();
}
void CDPlusHandler::writeStatus(wxFFile& file)
{
	for (unsigned int i = 0U; i < m_maxReflectors; i++) {
		CDPlusHandler* reflector = m_reflectors[i];
		if (reflector != NULL) {
			wxString text;

			struct tm* tm = ::gmtime(&reflector->m_time);

			if (reflector->m_linkState == DPLUS_LINKED) {
				switch (reflector->m_direction) {
					case DIR_OUTGOING:
						text.Printf(wxT("%04d-%02d-%02d %02d:%02d:%02d: DPlus link - Type: Dongle Rptr: %s Refl: %s Dir: Outgoing\n"),
							tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, 
							reflector->m_repeater.c_str(), reflector->m_reflector.c_str());
						break;

					case DIR_INCOMING:
						text.Printf(wxT("%04d-%02d-%02d %02d:%02d:%02d: DPlus link - Type: Dongle User: %s Dir: Incoming\n"),
							tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, 
							reflector->m_reflector.c_str());
						break;
				}

				file.Write(text);
			}
		}
	}
}
Exemple #7
0
bool DbgGdb::ExecuteCmd( const wxString &cmd )
{
    if( m_gdbProcess ) {
        if ( m_info.enableDebugLog ) {
#if DBG_LOG
            if(gfp.IsOpened()) {
                gfp.Write(wxString::Format( wxT( "DEBUG>>%s\n" ), cmd.c_str() ));
                gfp.Flush();
            }
#else
            m_observer->UpdateAddLine( wxString::Format( wxT( "DEBUG>>%s" ), cmd.c_str() ) );
#endif
        }
        return m_gdbProcess->Write( cmd );
    }
    return false;
}
Exemple #8
0
void systemStartGameRecording(const wxString &fname)
{
	GameArea* panel = wxGetApp().frame->GetPanel();

	if (!panel || panel->game_type() == IMAGE_UNKNOWN ||
	        !panel->emusys->emuWriteState)
	{
		wxLogError(_("No game in progress to record"));
		return;
	}

	systemStopGamePlayback();
	wxString fn = fname;

	if (fn.size() < 4 || !wxString(fn.substr(fn.size() - 4)).IsSameAs(wxT(".vmv"), false))
		fn.append(wxT(".vmv"));

	u32 version = 1;

	if (!game_file.Open(fn.c_str(), wxT("wb")) ||
	        game_file.Write(&version, sizeof(version)) != sizeof(version))
	{
		wxLogError(_("Cannot open output file %s"), fname.c_str());
		return;
	}

	fn[fn.size() - 1] = wxT('0');

	if (!panel->emusys->emuWriteState(fn.mb_fn_str()))
	{
		wxLogError(_("Error writing game recording"));
		game_file.Close();
		return;
	}

	game_frame = 0;
	game_joypad = 0;
	game_recording = true;
	MainFrame* mf = wxGetApp().frame;
	mf->cmd_enable &= ~(CMDEN_NGREC | CMDEN_GPLAY | CMDEN_NGPLAY);
	mf->cmd_enable |= CMDEN_GREC;
	mf->enable_menus();
}
static bool IsMcdFormatted( wxFFile& fhand )
{
	static const char formatted_string[] = "Sony PS2 Memory Card Format";
	static const int fmtstrlen = sizeof( formatted_string )-1;

	char dest[fmtstrlen];

	fhand.Read( dest, fmtstrlen );
	return memcmp( formatted_string, dest, fmtstrlen ) == 0;
}
Exemple #10
0
void PPToken::print(wxFFile &fp)
{
#if 0
	wxString buff;
	buff << wxT("Name          : ") << name << wxT("\n");
	buff << wxT("replacement   : ") << replacement << wxT("\n");
	buff << wxT("isFunctionLike: ") << isFunctionLike << wxT("\n");
	if(isFunctionLike) {
		for(size_t i=0; i<args.size(); i++) {
			buff << wxT("Arg: ") << args.Item(i) << wxT("\n");
		}
	}
	buff << wxT(" ---- \n");
	fp.Write(buff);
#else
	wxString buff;
	buff << name << wxT("(") << (flags & IsFunctionLike) << wxT(")") << wxT("=") << replacement << wxT("\n");
	fp.Write(buff);
#endif
}
Exemple #11
0
void systemStopGamePlayback()
{
	if (!game_playback)
		return;

	game_file.Close();
	game_playback = false;
	MainFrame* mf = wxGetApp().frame;
	mf->cmd_enable &= ~CMDEN_GPLAY;
	mf->cmd_enable |= CMDEN_NGREC | CMDEN_NGPLAY;
	mf->enable_menus();
}
// Returns FALSE if the seek failed (is outside the bounds of the file).
bool FileMemoryCard::Seek( wxFFile& f, u32 adr )
{
	const u32 size = f.Length();

	// If anyone knows why this filesize logic is here (it appears to be related to legacy PSX
	// cards, perhaps hacked support for some special emulator-specific memcard formats that
	// had header info?), then please replace this comment with something useful.  Thanks!  -- air

	u32 offset = 0;

	if( size == MCD_SIZE + 64 )
		offset = 64;
	else if( size == MCD_SIZE + 3904 )
		offset = 3904;
	else
	{
		// perform sanity checks here?
	}

	return f.Seek( adr + offset );
}
static bool IsMcdFormatted( wxFFile& fhand )
{
	static const char formatted_psx[] = "MC";
	static const char formatted_string[] = "Sony PS2 Memory Card Format";
	static const int fmtstrlen = sizeof( formatted_string )-1;

	char dest[fmtstrlen];

	fhand.Read( dest, fmtstrlen );

	bool formatted = memcmp( formatted_string, dest, fmtstrlen ) == 0;
	if(!formatted) formatted = memcmp( formatted_psx, dest, 2 ) == 0;

	return formatted;
}
void CXReflectorDPlusHandler::writeStatus(wxFFile& file)
{
    for (unsigned int i = 0U; i < m_maxReflectors; i++) {
        CXReflectorDPlusHandler* reflector = m_reflectors[i];
        if (reflector != NULL) {
            struct tm* tm = ::gmtime(&reflector->m_time);

            wxString text;
            text.Printf(wxT("%04d-%02d-%02d %02d:%02d:%02d: DPlus link - Type: Dongle User: %s Dir: Inbound\n"),
                        tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec,
                        reflector->m_reflector.c_str());

            file.Write(text);
        }
    }
}
Exemple #15
0
void systemStartGamePlayback(const wxString& fname)
{
    GameArea* panel = wxGetApp().frame->GetPanel();

    if (!panel || panel->game_type() == IMAGE_UNKNOWN || !panel->emusys->emuReadState) {
        wxLogError(_("No game in progress to record"));
        return;
    }

    if (game_recording) {
        wxLogError(_("Cannot play game recording while recording"));
        return;
    }

    systemStopGamePlayback();
    wxString fn = fname;

    if (fn.size() < 4 || !wxString(fn.substr(fn.size() - 4)).IsSameAs(wxT(".vmv"), false))
        fn.append(wxT(".vmv"));

    u32 version;

    if (!game_file.Open(fn.c_str(), wxT("rb")) || game_file.Read(&version, sizeof(version)) != sizeof(version) || wxUINT32_SWAP_ON_BE(version) != 1) {
        wxLogError(_("Cannot open recording file %s"), fname.c_str());
        return;
    }

    u32 gf, jp;

    if (game_file.Read(&gf, sizeof(gf)) != sizeof(gf) || game_file.Read(&jp, sizeof(jp)) != sizeof(jp)) {
        wxLogError(_("Error reading game recording"));
        game_file.Close();
        return;
    }

    game_next_frame = wxUINT32_SWAP_ON_BE(gf);
    game_next_joypad = wxUINT32_SWAP_ON_BE(jp);
    fn[fn.size() - 1] = wxT('0');

    if (!panel->emusys->emuReadState(fn.mb_fn_str())) {
        wxLogError(_("Error reading game recording"));
        game_file.Close();
        return;
    }

    game_frame = 0;
    game_joypad = 0;
    game_playback = true;
    MainFrame* mf = wxGetApp().frame;
    mf->cmd_enable &= ~(CMDEN_NGREC | CMDEN_GREC | CMDEN_NGPLAY);
    mf->cmd_enable |= CMDEN_GPLAY;
    mf->enable_menus();
}
Exemple #16
0
    void GenerateHeaderCode(wxFFile& file)
    {

        file.Write(_T("class ") + m_className + _T(" : public ") + m_parentClassName
                   + _T(" {\nprotected:\n"));
        size_t i;
        for(i=0;i<m_wdata.Count();++i)
        {
            const XRCWidgetData& w = m_wdata.Item(i);
            if( !IsRealClass(w.GetClass()) ) continue;
            if( w.GetName().Length() == 0 ) continue;
            file.Write(
                _T(" ") + w.GetClass() + _T("* ") + w.GetName()
                + _T(";\n"));
        }
        file.Write(_T("\nprivate:\n void InitWidgetsFromXRC(){\n")
                   _T("  wxXmlResource::Get()->LoadObject(this,NULL,_T(\"")
                   +  m_className
                   +  _T("\"), _T(\"")
                   +  m_parentClassName
                   +  _T("\"));\n"));
        for(i=0;i<m_wdata.Count();++i)
        {
            const XRCWidgetData& w = m_wdata.Item(i);
            if( !IsRealClass(w.GetClass()) ) continue;
            if( w.GetName().Length() == 0 ) continue;
            file.Write( _T("  ")
                        + w.GetName()
                        + _T(" = XRCCTRL(*this,\"")
                        + w.GetName()
                        + _T("\",")
                        + w.GetClass()
                        + _T(");\n")
                );
        }
        file.Write(_T(" }\n"));

        file.Write(
            _T("public:\n")
            + m_className
            + _T("::")
            + m_className
            + _T("(){\n")
            + _T("  InitWidgetsFromXRC();\n")
              _T(" }\n")
              _T("};\n")
        );
    };
void PCMAliasBlockFile::SaveXML(int depth, wxFFile &xmlFile)
{
   for(int i = 0; i < depth; i++)
      xmlFile.Write("\t");
   xmlFile.Write("<pcmaliasblockfile ");
   xmlFile.Write(wxString::Format("summaryfile='%s' ",
                                  XMLTagHandler::XMLEsc(mFileName.GetFullName()).c_str()));
   xmlFile.Write(wxString::Format("aliasfile='%s' ",
                                  XMLTagHandler::XMLEsc(mAliasedFileName.GetFullPath()).c_str()));
   xmlFile.Write(wxString::Format("aliasstart='%d' ", mAliasStart));
   xmlFile.Write(wxString::Format("aliaslen='%d' ", mLen));
   xmlFile.Write(wxString::Format("aliaschannel='%d' ", mAliasChannel));
   xmlFile.Write(wxString::Format("min='%s' ",
            Internat::ToString(mMin).c_str()));
   xmlFile.Write(wxString::Format("max='%s' ",
            Internat::ToString(mMax).c_str()));
   xmlFile.Write(wxString::Format("rms='%s'",
            Internat::ToString(mRMS).c_str()));
   xmlFile.Write("/>\n");
}
Exemple #18
0
bool OggImportFileHandle::Import(TrackFactory *trackFactory, Track ***outTracks,
                                 int *outNumTracks, Tags *tags)
{
   wxASSERT(mFile->IsOpened());

   /* -1 is for the current logical bitstream */
   vorbis_info *vi = ov_info(mVorbisFile, -1);
   vorbis_comment *vc = ov_comment(mVorbisFile, -1);

   WaveTrack **channels = new WaveTrack *[vi->channels];

   int c;
   for (c = 0; c < vi->channels; c++) {
      channels[c] = trackFactory->NewWaveTrack(int16Sample, vi->rate);

      if (vi->channels == 2) {
         switch (c) {
         case 0:
            channels[c]->SetChannel(Track::LeftChannel);
            channels[c]->SetLinked(true);
            break;
         case 1:
            channels[c]->SetChannel(Track::RightChannel);
            channels[c]->SetTeamed(true);
            break;
         }
   }
      else {
         channels[c]->SetChannel(Track::MonoChannel);
      }
   }

/* The number of bytes to get from the codec in each run */
#define CODEC_TRANSFER_SIZE 4096

/* The number of samples to read between calls to the callback.
 * Balance between responsiveness of the GUI and throughput of import. */
#define SAMPLES_PER_CALLBACK 100000

   short *mainBuffer = new short[CODEC_TRANSFER_SIZE];

   /* determine endianness (clever trick courtesy of Nicholas Devillard,
    * (http://www.eso.org/~ndevilla/endian/) */
   int testvar = 1, endian;
   if(*(char *)&testvar)
      endian = 0;  // little endian
   else
      endian = 1;  // big endian

   /* number of samples currently in each channel's buffer */
   bool cancelled = false;
   long bytesRead = 0;
   long samplesRead = 0;
   int bitstream = 0;
   int samplesSinceLastCallback = 0;

   // You would think that the stream would already be seeked to 0, and
   // indeed it is if the file is legit.  But I had several ogg files on
   // my hard drive that have malformed headers, and this added call
   // causes them to be read correctly.  Otherwise they have lots of
   // zeros inserted at the beginning
   ov_pcm_seek(mVorbisFile, 0);
   
   do {
      /* get data from the decoder */
      bytesRead = ov_read(mVorbisFile, (char *) mainBuffer,
                          CODEC_TRANSFER_SIZE,
                          endian,
                          2,    // word length (2 for 16 bit samples)
                          1,    // signed
                          &bitstream);

      if (bytesRead < 0) {
         /* Malformed Ogg Vorbis file. */
         /* TODO: Return some sort of meaningful error. */
         break;
      }

      samplesRead = bytesRead / vi->channels / sizeof(short);

      /* give the data to the wavetracks */
      for (c = 0; c < vi->channels; c++)
          channels[c]->Append((char *)(mainBuffer + c),
                              int16Sample,
                              samplesRead,
                              vi->channels);

      samplesSinceLastCallback += samplesRead;
      if (samplesSinceLastCallback > SAMPLES_PER_CALLBACK) {
          if( mProgressCallback )
             cancelled = mProgressCallback(mUserData,
                                           ov_time_tell(mVorbisFile) /
                                           ov_time_total(mVorbisFile, bitstream));
          samplesSinceLastCallback -= SAMPLES_PER_CALLBACK;
      }

   } while (!cancelled && bytesRead != 0 && bitstream == 0);

   delete[]mainBuffer;

   bool res = (!cancelled && bytesRead >= 0);

   if (!res) {
      for(c = 0; c < vi->channels; c++) {
         delete channels[c];
      }
      delete[] channels;

      return false;
   }

   *outNumTracks = vi->channels;
   *outTracks = new Track *[vi->channels];
   for (c = 0; c < vi->channels; c++) {
      channels[c]->Flush();
         (*outTracks)[c] = channels[c];
   }
      delete[] channels;

   if (vc) {
      tags->Clear();
      for (c = 0; c < vc->comments; c++) {
         wxString comment = UTF8CTOWX(vc->user_comments[c]);
         tags->SetTag(comment.BeforeFirst(wxT('=')),
                      comment.AfterFirst(wxT('=')));
      }
   }

   return true;
}
bool FLACImportFileHandle::Init()
{
#ifdef EXPERIMENTAL_OD_FLAC
   mDecoderTask=new ODDecodeFlacTask;

   ODFlacDecoder* odDecoder = (ODFlacDecoder*)mDecoderTask->CreateFileDecoder(mFilename);
   if(!odDecoder || !odDecoder->ReadHeader())
   {
      //DELETE the task only if it failed to read - otherwise the OD man takes care of it.
      delete mDecoderTask;
      return false;
   }
   //copy the meta data over to the class

   mSampleRate=odDecoder->mSampleRate;
   mNumChannels=odDecoder->mNumChannels;
   mBitsPerSample=odDecoder->mBitsPerSample;

   mNumSamples=odDecoder->mNumSamples;
   mBitsPerSample=odDecoder->mBitsPerSample;
   mFormat=odDecoder->mFormat;
   mStreamInfoDone=true;


   return true;
#endif
#ifdef LEGACY_FLAC
   bool success = mFile->set_filename(OSINPUT(mFilename));
   if (!success) {
      return false;
   }
   mFile->set_metadata_respond(FLAC__METADATA_TYPE_STREAMINFO);
   mFile->set_metadata_respond(FLAC__METADATA_TYPE_VORBIS_COMMENT);
   FLAC::Decoder::File::State state = mFile->init();
   if (state != FLAC__FILE_DECODER_OK) {
      return false;
   }
#else
   if (!mHandle.Open(mFilename, wxT("rb"))) {
      return false;
   }

   // Even though there is an init() method that takes a filename, use the one that
   // takes a file handle because wxWidgets can open a file with a Unicode name and
   // libflac can't (under Windows).
   //
   // Responsibility for closing the file is passed to libflac.
   // (it happens when mFile->finish() is called)
   bool result = mFile->init(mHandle.fp())?true:false;
   mHandle.Detach();

   if (result != FLAC__STREAM_DECODER_INIT_STATUS_OK) {
      return false;
   }
#endif
   mFile->process_until_end_of_metadata();

#ifdef LEGACY_FLAC
   state = mFile->get_state();
   if (state != FLAC__FILE_DECODER_OK) {
      return false;
   }
#else
   // not necessary to check state, error callback will catch errors, but here's how:
   if (mFile->get_state() > FLAC__STREAM_DECODER_READ_FRAME) {
      return false;
   }
#endif

   if (!mFile->is_valid() || mFile->get_was_error()) {
      // This probably is not a FLAC file at all
      return false;
   }
   return true;
}
Exemple #20
0
int OggImportFileHandle::Import(TrackFactory *trackFactory, Track ***outTracks,
                                int *outNumTracks, Tags *tags)
{
   wxASSERT(mFile->IsOpened());

   CreateProgress();

   //Number of streams used may be less than mVorbisFile->links,
   //but this way bitstream matches array index.
   mChannels = new WaveTrack **[mVorbisFile->links];

   int i,c;
   for (i = 0; i < mVorbisFile->links; i++)
   {
      //Stream is not used
      if (mStreamUsage[i] == 0)
      {
         //This is just a padding to keep bitstream number and
         //array indices matched.
         mChannels[i] = NULL;
         continue;
      }

      vorbis_info *vi = ov_info(mVorbisFile, i);
      vorbis_comment *vc = ov_comment(mVorbisFile, i);

      mChannels[i] = new WaveTrack *[vi->channels];

      for (c = 0; c < vi->channels; c++) {
         mChannels[i][c] = trackFactory->NewWaveTrack(int16Sample, vi->rate);

         if (vi->channels == 2) {
            switch (c) {
         case 0:
            mChannels[i][c]->SetChannel(Track::LeftChannel);
            mChannels[i][c]->SetLinked(true);
            break;
         case 1:
            mChannels[i][c]->SetChannel(Track::RightChannel);
            mChannels[i][c]->SetTeamed(true);
            break;
            }
         }
         else {
            mChannels[i][c]->SetChannel(Track::MonoChannel);
         }
      }
   }

/* The number of bytes to get from the codec in each run */
#define CODEC_TRANSFER_SIZE 4096

/* The number of samples to read between calls to the callback.
 * Balance between responsiveness of the GUI and throughput of import. */
#define SAMPLES_PER_CALLBACK 100000

   short *mainBuffer = new short[CODEC_TRANSFER_SIZE];

   /* determine endianness (clever trick courtesy of Nicholas Devillard,
    * (http://www.eso.org/~ndevilla/endian/) */
   int testvar = 1, endian;
   if(*(char *)&testvar)
      endian = 0;  // little endian
   else
      endian = 1;  // big endian

   /* number of samples currently in each channel's buffer */
   bool cancelled = false;
   long bytesRead = 0;
   long samplesRead = 0;
   int bitstream = 0;
   int samplesSinceLastCallback = 0;

   // You would think that the stream would already be seeked to 0, and
   // indeed it is if the file is legit.  But I had several ogg files on
   // my hard drive that have malformed headers, and this added call
   // causes them to be read correctly.  Otherwise they have lots of
   // zeros inserted at the beginning
   ov_pcm_seek(mVorbisFile, 0);
   
   do {
      /* get data from the decoder */
      bytesRead = ov_read(mVorbisFile, (char *) mainBuffer,
                          CODEC_TRANSFER_SIZE,
                          endian,
                          2,    // word length (2 for 16 bit samples)
                          1,    // signed
                          &bitstream);

      if (bytesRead < 0) {
         /* Malformed Ogg Vorbis file. */
         /* TODO: Return some sort of meaningful error. */
         break;
      }

      samplesRead = bytesRead / mVorbisFile->vi[bitstream].channels / sizeof(short);

      /* give the data to the wavetracks */
      if (mStreamUsage[bitstream] != 0)
      {
         for (c = 0; c < mVorbisFile->vi[bitstream].channels; c++)
            mChannels[bitstream][c]->Append((char *)(mainBuffer + c),
            int16Sample,
            samplesRead,
            mVorbisFile->vi[bitstream].channels);
      }

      samplesSinceLastCallback += samplesRead;
      if (samplesSinceLastCallback > SAMPLES_PER_CALLBACK) {
          cancelled = !mProgress->Update(ov_time_tell(mVorbisFile),
                                         ov_time_total(mVorbisFile, bitstream));
          samplesSinceLastCallback -= SAMPLES_PER_CALLBACK;

      }
   } while (!cancelled && bytesRead != 0);

   delete[]mainBuffer;

   bool res = (!cancelled && bytesRead >= 0);

   if (!res) {
      for (i = 0; i < mVorbisFile->links; i++)
      {
         if (mChannels[i])
         {
            for(c = 0; c < mVorbisFile->vi[bitstream].channels; c++) {
               if (mChannels[i][c])
                  delete mChannels[i][c];
            }
            delete[] mChannels[i];
         }
      }
      delete[] mChannels;
      return (cancelled ? eImportCancelled : eImportFailed);
   }

   *outNumTracks = 0;
   for (int s = 0; s < mVorbisFile->links; s++)
   {
      if (mStreamUsage[s] != 0)
         *outNumTracks += mVorbisFile->vi[s].channels;
   }

   *outTracks = new Track *[*outNumTracks];
   
   int trackindex = 0;
   for (i = 0; i < mVorbisFile->links; i++)
   {
      if (mChannels[i])
      {
         for (c = 0; c < mVorbisFile->vi[i].channels; c++) {
            mChannels[i][c]->Flush();
            (*outTracks)[trackindex++] = mChannels[i][c];
         }
         delete[] mChannels[i];
      }      
   }
   delete[] mChannels;

   //\todo { Extract comments from each stream? }
   if (mVorbisFile->vc[0].comments > 0) {
      tags->Clear();
      for (c = 0; c < mVorbisFile->vc[0].comments; c++) {
         wxString comment = UTF8CTOWX(mVorbisFile->vc[0].user_comments[c]);
         wxString name = comment.BeforeFirst(wxT('='));
         wxString value = comment.AfterFirst(wxT('='));
         if (name.Upper() == wxT("DATE") && !tags->HasTag(TAG_YEAR)) {
            long val;
            if (value.Length() == 4 && value.ToLong(&val)) {
               name = TAG_YEAR;
            }
         }
         tags->SetTag(name, value);
      }
   }

   return eImportSuccess;
}
Exemple #21
0
void DbgGdb::Poke()
{
    static wxRegEx reCommand( wxT( "^([0-9]{8})" ) );



    //poll the debugger output
    wxString curline;
    if ( !m_gdbProcess || m_gdbOutputArr.IsEmpty() ) {
        return;
    }

    while ( DoGetNextLine( curline ) ) {

        GetDebugeePID(curline);

        // For string manipulations without damaging the original line read
        wxString tmpline ( curline );
        StripString( tmpline );
        tmpline.Trim().Trim( false );
        if ( m_info.enableDebugLog ) {
            //Is logging enabled?

            if ( curline.IsEmpty() == false && !tmpline.StartsWith( wxT( ">" ) ) ) {
                wxString strdebug( wxT( "DEBUG>>" ) );
                strdebug << curline;
#if DBG_LOG
                if(gfp.IsOpened()) {
                    gfp.Write(strdebug);
                    gfp.Flush();
                }
#else
                m_observer->UpdateAddLine( strdebug );
#endif
            }
        }

        if ( reConnectionRefused.Matches( curline ) ) {
            StripString( curline );
#ifdef __WXGTK__
            m_consoleFinder.FreeConsole();
#endif
            m_observer->UpdateAddLine( curline );
            m_observer->UpdateGotControl( DBG_EXITED_NORMALLY );
            return;
        }

        // Check for "Operation not permitted" usually means
        // that the process does not have enough permission to
        // attach to the process
        if( curline.Contains(wxT("Operation not permitted")) ) {
#ifdef __WXGTK__
            m_consoleFinder.FreeConsole();
#endif
            m_observer->UpdateAddLine( _("Failed to start debugger: permission denied") );
            m_observer->UpdateGotControl( DBG_EXITED_NORMALLY );
            return;

        }

        if( tmpline.StartsWith( wxT( ">" ) ) ) {
            // Shell line, probably user command line
            continue;
        }

        if ( curline.StartsWith( wxT( "~" ) ) || curline.StartsWith( wxT( "&" ) ) || curline.StartsWith("@") ) {

            // lines starting with ~ are considered "console stream" message
            // and are important to the CLI handler
            bool consoleStream( false );
            bool targetConsoleStream(false);

            if ( curline.StartsWith( wxT( "~" ) ) ) {
                consoleStream = true;
            }

            if ( curline.StartsWith( wxT( "@" ) ) ) {
                targetConsoleStream = true;
            }

            // Filter out some gdb error lines...
            if ( FilterMessage( curline ) ) {
                continue;
            }

            StripString( curline );

            // If we got a valid "CLI Handler" instead of writing the output to
            // the output view, concatenate it into the handler buffer
            if ( targetConsoleStream ) {
                m_observer->UpdateAddLine( curline );

            } else if ( consoleStream && GetCliHandler()) {
                GetCliHandler()->Append( curline );

            } else if ( consoleStream ) {
                // log message
                m_observer->UpdateAddLine( curline );

            }

        } else if ( reCommand.Matches( curline ) ) {

            //not a gdb message, get the command associated with the message
            wxString id = reCommand.GetMatch( curline, 1 );

            if ( GetCliHandler() && GetCliHandler()->GetCommandId() == id ) {
                // probably the "^done" message of the CLI command
                GetCliHandler()->ProcessOutput( curline );
                SetCliHandler( NULL ); // we are done processing the CLI

            } else {
                //strip the id from the line
                curline = curline.Mid( 8 );
                DoProcessAsyncCommand( curline, id );

            }
        } else if ( curline.StartsWith( wxT( "^done" ) ) || curline.StartsWith( wxT( "*stopped" ) ) ) {
            //Unregistered command, use the default AsyncCommand handler to process the line
            DbgCmdHandlerAsyncCmd cmd( m_observer, this );
            cmd.ProcessOutput( curline );
        } else {
            //Unknow format, just log it
            if( m_info.enableDebugLog && !FilterMessage( curline ) ) {
                m_observer->UpdateAddLine( curline );
            }
        }
    }
}
Exemple #22
0
// return information about the given joystick, -1 for default joystick
u32 systemReadJoypad(int joy)
{
	if (joy < 0 || joy > 3)
		joy = gopts.default_stick - 1;

	uint32_t ret = joypress[joy];

	if (turbo)
		ret |= KEYM_SPEED;

	u32 af = autofire;

	if (ret & KEYM_AUTO_A)
	{
		ret |= KEYM_A;
		af |= KEYM_A;
	}

	if (ret & KEYM_AUTO_B)
	{
		ret |= KEYM_B;
		af |= KEYM_B;
	}

	static int autofire_trigger = 1;
	static bool autofire_state = true;
	u32 af_but = af & ret;

	if (af_but)
	{
		if (!autofire_state)
			ret &= ~af_but;

		if (!--autofire_trigger)
		{
			autofire_trigger = gopts.autofire_rate;
			autofire_state = !autofire_state;
		}
	}
	else
	{
		autofire_state = true;
		autofire_trigger = gopts.autofire_rate;
	}

	// disallow opposite directionals simultaneously
	ret &= ~((ret & (KEYM_LEFT | KEYM_DOWN | KEYM_MOTION_DOWN | KEYM_MOTION_RIGHT)) >> 1);
	ret &= REALKEY_MASK;

	if (game_recording)
	{
		u32 rret = ret & ~(KEYM_SPEED | KEYM_CAPTURE);

		if (rret != game_joypad)
		{
			game_joypad = rret;
			u32 gf = wxUINT32_SWAP_ON_BE(game_frame);
			u32 jp = wxUINT32_SWAP_ON_BE(game_joypad);

			if (game_file.Write(&gf, sizeof(gf)) != sizeof(gf) ||
			        game_file.Write(&jp, sizeof(jp)) != sizeof(jp))
			{
				game_file.Close();
				game_recording = false;
				wxLogError(_("Error writing game recording"));
			}
		}
	}
	else if (game_playback)
	{
		while (game_frame >= game_next_frame)
		{
			game_joypad = game_next_joypad;
			u32 gf, jp;

			if (game_file.Read(&gf, sizeof(gf)) != sizeof(gf) ||
			        game_file.Read(&jp, sizeof(jp)) != sizeof(jp))
			{
				game_file.Close();
				game_playback = false;
				wxString msg(_("Playback ended"));
				systemScreenMessage(msg);
				break;
			}

			game_next_frame = wxUINT32_SWAP_ON_BE(gf);
			game_next_joypad = wxUINT32_SWAP_ON_BE(jp);
		}

		ret = game_joypad;
	}

	return ret;
}
Exemple #23
0
int OggImportFileHandle::Import(TrackFactory *trackFactory, TrackHolders &outTracks,
                                Tags *tags)
{
   outTracks.clear();

   wxASSERT(mFile->IsOpened());

   CreateProgress();

   //Number of streams used may be less than mVorbisFile->links,
   //but this way bitstream matches array index.
   mChannels.resize(mVorbisFile->links);

   int i = -1;
   for (auto &link: mChannels)
   {
      ++i;

      //Stream is not used
      if (mStreamUsage[i] == 0)
      {
         //This is just a padding to keep bitstream number and
         //array indices matched.
         continue;
      }

      vorbis_info *vi = ov_info(mVorbisFile, i);

      link.resize(vi->channels);

      int c = - 1;
      for (auto &channel : link) {
         ++c;

         channel = trackFactory->NewWaveTrack(mFormat, vi->rate);

         if (vi->channels == 2) {
            switch (c) {
         case 0:
            channel->SetChannel(Track::LeftChannel);
            channel->SetLinked(true);
            break;
         case 1:
            channel->SetChannel(Track::RightChannel);
            break;
            }
         }
         else {
            channel->SetChannel(Track::MonoChannel);
         }
      }
   }

/* The number of bytes to get from the codec in each run */
#define CODEC_TRANSFER_SIZE 4096

/* The number of samples to read between calls to the callback.
 * Balance between responsiveness of the GUI and throughput of import. */
#define SAMPLES_PER_CALLBACK 100000

   short *mainBuffer = new short[CODEC_TRANSFER_SIZE];

   /* determine endianness (clever trick courtesy of Nicholas Devillard,
    * (http://www.eso.org/~ndevilla/endian/) */
   int testvar = 1, endian;
   if(*(char *)&testvar)
      endian = 0;  // little endian
   else
      endian = 1;  // big endian

   /* number of samples currently in each channel's buffer */
   int updateResult = eProgressSuccess;
   long bytesRead = 0;
   long samplesRead = 0;
   int bitstream = 0;
   int samplesSinceLastCallback = 0;

   // You would think that the stream would already be seeked to 0, and
   // indeed it is if the file is legit.  But I had several ogg files on
   // my hard drive that have malformed headers, and this added call
   // causes them to be read correctly.  Otherwise they have lots of
   // zeros inserted at the beginning
   ov_pcm_seek(mVorbisFile, 0);

   do {
      /* get data from the decoder */
      bytesRead = ov_read(mVorbisFile, (char *) mainBuffer,
                          CODEC_TRANSFER_SIZE,
                          endian,
                          2,    // word length (2 for 16 bit samples)
                          1,    // signed
                          &bitstream);

      if (bytesRead == OV_HOLE) {
         wxFileName ff(mFilename);
         wxLogError(wxT("Ogg Vorbis importer: file %s is malformed, ov_read() reported a hole"),
                    ff.GetFullName().c_str());
         /* http://lists.xiph.org/pipermail/vorbis-dev/2001-February/003223.html
          * is the justification for doing this - best effort for malformed file,
          * hence the message.
          */
         continue;
      } else if (bytesRead < 0) {
         /* Malformed Ogg Vorbis file. */
         /* TODO: Return some sort of meaningful error. */
         wxLogError(wxT("Ogg Vorbis importer: ov_read() returned error %i"),
                    bytesRead);
         break;
      }

      samplesRead = bytesRead / mVorbisFile->vi[bitstream].channels / sizeof(short);

      /* give the data to the wavetracks */
      auto iter = mChannels.begin();
      std::advance(iter, bitstream);
      if (mStreamUsage[bitstream] != 0)
      {
         auto iter2 = iter->begin();
         for (int c = 0; c < mVorbisFile->vi[bitstream].channels; ++iter2, ++c)
            iter2->get()->Append((char *)(mainBuffer + c),
            int16Sample,
            samplesRead,
            mVorbisFile->vi[bitstream].channels);
      }

      samplesSinceLastCallback += samplesRead;
      if (samplesSinceLastCallback > SAMPLES_PER_CALLBACK) {
          updateResult = mProgress->Update(ov_time_tell(mVorbisFile),
                                         ov_time_total(mVorbisFile, bitstream));
          samplesSinceLastCallback -= SAMPLES_PER_CALLBACK;

      }
   } while (updateResult == eProgressSuccess && bytesRead != 0);

   delete[]mainBuffer;

   int res = updateResult;
   if (bytesRead < 0)
     res = eProgressFailed;

   if (res == eProgressFailed || res == eProgressCancelled) {
      return res;
   }

   for (auto &link : mChannels)
   {
      for (auto &channel : link) {
         channel->Flush();
         outTracks.push_back(std::move(channel));
      }
   }

   //\todo { Extract comments from each stream? }
   if (mVorbisFile->vc[0].comments > 0) {
      tags->Clear();
      for (int c = 0; c < mVorbisFile->vc[0].comments; c++) {
         wxString comment = UTF8CTOWX(mVorbisFile->vc[0].user_comments[c]);
         wxString name = comment.BeforeFirst(wxT('='));
         wxString value = comment.AfterFirst(wxT('='));
         if (name.Upper() == wxT("DATE") && !tags->HasTag(TAG_YEAR)) {
            long val;
            if (value.Length() == 4 && value.ToLong(&val)) {
               name = TAG_YEAR;
            }
         }
         tags->SetTag(name, value);
      }
   }

   return res;
}
Exemple #24
0
    void GenerateHeaderCode(wxFFile& file)
    {

        file.Write(_T("class ") + m_className + _T(" : public ") + m_parentClassName
                   + _T(" {\nprotected:\n"));
        size_t i;
        for(i=0;i<m_wdata.Count();++i)
        {
            const XRCWidgetData& w = m_wdata.Item(i);
            if( !IsRealClass(w.GetClass()) ) continue;
            if( w.GetName().Length() == 0 ) continue;
            file.Write(
                _T(" ") + w.GetClass() + _T("* ") + w.GetName()
                + _T(";\n"));
        }
        file.Write(_T("\nprivate:\n void InitWidgetsFromXRC(wxWindow *parent){\n")
                   _T("  wxXmlResource::Get()->LoadObject(this,parent,_T(\"")
                   +  m_className
                   +  _T("\"), _T(\"")
                   +  m_parentClassName
                   +  _T("\"));\n"));
        for(i=0;i<m_wdata.Count();++i)
        {
            const XRCWidgetData& w = m_wdata.Item(i);
            if( !IsRealClass(w.GetClass()) ) continue;
            if( w.GetName().Length() == 0 ) continue;
            file.Write( _T("  ")
                        + w.GetName()
                        + _T(" = XRCCTRL(*this,\"")
                        + w.GetName()
                        + _T("\",")
                        + w.GetClass()
                        + _T(");\n"));
        }
        file.Write(_T(" }\n"));

        file.Write( _T("public:\n"));

        if ( m_ancestorClassNames.size() == 1 )
        {
            file.Write
                 (
                    m_className +
                    _T("(") +
                        *m_ancestorClassNames.begin() +
                        _T(" *parent=NULL){\n") +
                    _T("  InitWidgetsFromXRC((wxWindow *)parent);\n")
                    _T(" }\n")
                    _T("};\n")
                 );
        }
        else
        {
            file.Write(m_className + _T("(){\n") +
                       _T("  InitWidgetsFromXRC(NULL);\n")
                       _T(" }\n")
                       _T("};\n"));

            for ( StringSet::const_iterator it = m_ancestorClassNames.begin();
                  it != m_ancestorClassNames.end();
                  ++it )
            {
                file.Write(m_className + _T("(") + *it + _T(" *parent){\n") +
                            _T("  InitWidgetsFromXRC((wxWindow *)parent);\n")
                            _T(" }\n")
                            _T("};\n"));
            }
        }
    }