Example #1
0
bool CPFCManager::GetFileEntry(const CStdString& strPath, sFileEntry& item) {
  VECFILEENTRY items;
  // we need to list the pfs
  if (!GetEntriesList(strPath, items)) return false;

  CURL urlPath(strPath);
  CStdString strFileName = urlPath.GetFileName();

  for (VECFILEENTRY::iterator it2 = items.begin(); it2 != items.end(); ++it2)
  {
    if (CStdString(it2->FileName) == strFileName)
    {
      memcpy(&item, &(*it2), sizeof(sFileEntry));
      return true;
    }
  }

  return false;
}
void TestAcceptanceTests::TestSimpleDocumentWithOneScentence()
{
	RTFfile outFile(new RTFFileContext());

	DocFileReader reader;
	
	InputFileData ifd;
	ifd.AssignFileName(GET_TEST_FILE_PATH(_T("Simple.doc")));

	assertTest( reader.ReadFile(ifd , &outFile) );
	assertTest(outFile.GetCount() == 5);
	int i=1;
	assertMessage(outFile.At(i++)->GetType() == rotFormatting, _T("we should get a para first with formatting for first para of document"));
	assertMessage(outFile.At(i++)->GetType() == rotChrfmt, _T("we should get a chrfmt before the text"));
	assertMessage(outFile.At(i)->GetType() == rotPcdata, _T("the first item in the collection should be a string")); // or should it? characterformatting first?
	const RTFPCData* pText = dynamic_cast<const RTFPCData*>(outFile.At(i++));
	assertTest(CStdString(pText->GetContent().GetData()) == _T("The quick brown fox jumps over the lazy dog."));
	assertMessage(outFile.At(i++)->GetType() == rotFormatting, _T("the second item should be a paragraph break"));

}
Example #3
0
void TestCOMLayer::TestOpenDocument()
{
	WSDocNonCom wsdDocIn;
	wsdDocIn.SetAuthor(CStdString(_T("Alfie")));
	wsdDocIn.SetClass(CStdString(_T("PreSchool")));
	wsdDocIn.SetDescription(CStdString(_T("Short and fluffy")));
	wsdDocIn.SetDocId(CStdString(_T("afnb")));
	wsdDocIn.SetExtension(CStdString(_T("Dummy")));
	wsdDocIn.SetFileSizehigh(24);
	wsdDocIn.SetFileSizeLow(2);
	wsdDocIn.SetFlags(0x54407);
	wsdDocIn.SetLocalFile(CStdString(_T("Tractor")));
	wsdDocIn.SetModifiedTime(20011127.080230);
	wsdDocIn.SetOperator(CStdString(_T("Keith")));
	wsdDocIn.SetType(CStdString(_T("Boy")));
	LOCALFILESTORELib::tagWSDOCUMENT wsDoc;
	wsdDocIn.InitializeWSDOCUMENT((WSDOCUMENT*)&wsDoc);
	HRESULT hr = m_pLFS->raw_OpenDocument(&wsDoc);
	assertTest(m_pWorker->m_sLastMethodCalled == _T("OpenDocument"));
	assertTest(hr == S_TEST);
	assertTest(wsdDocIn == m_pWorker->m_wsd);
}
Example #4
0
void OggOpusFile::Open(CStdString& filename, fileOpenModeEnum mode, bool stereo, int sampleRate)
{
	if(m_sampleRate == 0)
	{
		m_sampleRate = sampleRate;
	}

	if(!m_filename.Equals(filename))
	{
		m_filename = filename + GetExtension();
	}
	fout = NULL;
	m_mode = mode;
	if (mode == READ)
	{
		fout = ACE_OS::fopen((PCSTR)m_filename, "rb");
	}
	else
	{
		FileRecursiveMkdir(m_filename, CONFIG.m_audioFilePermissions, CONFIG.m_audioFileOwner, CONFIG.m_audioFileGroup, CONFIG.m_audioOutputPathMcf);
		fout = ACE_OS::fopen((PCSTR)m_filename, "wb");
		if(CONFIG.m_audioFilePermissions)
		{
			FileSetPermissions(m_filename, CONFIG.m_audioFilePermissions);
		}

		if(CONFIG.m_audioFileGroup.size() && CONFIG.m_audioFileOwner.size())
		{
			FileSetOwnership(m_filename, CONFIG.m_audioFileOwner, CONFIG.m_audioFileGroup);
		}
	}
	if(!fout)
	{
		throw(CStdString("Could not open file: ") + m_filename);
	}

    Init();
    WriteHeader();
    //Close();

}
Example #5
0
bool ZipWrapper::AddFolderToZip(const std::tstring& sFilename)
{
	WIN32_FIND_DATA fd;

	HANDLE hFile = FindFirstFile(CStdString(sFilename + _T("\\*.*")).c_str(), &fd);
	
	if (hFile == INVALID_HANDLE_VALUE)
		return false;

	while (FindNextFile(hFile, &fd))
	{
		std::tstring sFile = fd.cFileName;
		if (sFile.compare(_T("..")) == 0)
			continue;
		if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
			AddFolderToZip(sFilename + _T("\\") + fd.cFileName);
		else AddFileToZip(sFilename + _T("\\") + fd.cFileName);
	}
	FindClose(hFile);
	return true;
}
Example #6
0
void CUDiskDevice::Update()
{
  CVariant properties = CDBusUtil::GetAll("org.freedesktop.UDisks", m_DeviceKitUDI.c_str(), "org.freedesktop.UDisks.Device");

  m_isFileSystem = CStdString(properties["IdUsage"].asString()) == "filesystem";
  if (m_isFileSystem)
  {
    m_UDI         = properties["IdUuid"].asString();
    m_Label       = properties["IdLabel"].asString();
    m_FileSystem  = properties["IdType"].asString();
  }
  else
  {
    m_UDI.clear();
    m_Label.clear();
    m_FileSystem.clear();
  }

  m_isMounted   = properties["DeviceIsMounted"].asBoolean();
  if (m_isMounted && properties["DeviceMountPaths"].size() > 0)
    m_MountPath   = properties["DeviceMountPaths"][0].asString();
  else
    m_MountPath.clear();

  m_PartitionSizeGiB = properties["PartitionSize"].asUnsignedInteger() / 1024.0 / 1024.0 / 1024.0;
  m_isPartition = properties["DeviceIsPartition"].asBoolean();
  m_isSystemInternal = properties["DeviceIsSystemInternal"].asBoolean();
  m_isOptical = properties["DeviceIsOpticalDisc"].asBoolean();
  if (m_isPartition)
  {
    CVariant isRemovable = CDBusUtil::GetVariant("org.freedesktop.UDisks", properties["PartitionSlave"].asString().c_str(), "org.freedesktop.UDisks.Device", "DeviceIsRemovable");

    if ( !isRemovable.isNull() )
      m_isRemovable = isRemovable.asBoolean();
    else
      m_isRemovable = false;
  }
  else
    m_isRemovable = properties["DeviceIsRemovable"].asBoolean();
}
Example #7
0
void TestCOMLayer::TestSaveDocument()
{
	WSDocNonCom wsdDocIn;
	wsdDocIn.SetAuthor(CStdString(_T("Ted")));
	wsdDocIn.SetClass(CStdString(_T("Russell")));
	wsdDocIn.SetDescription(CStdString(_T("Mr Fluffy")));
	wsdDocIn.SetDocId(CStdString(_T("ECR")));
	wsdDocIn.SetExtension(CStdString(_T("Legs")));
	wsdDocIn.SetFileSizehigh(24);
	wsdDocIn.SetFileSizeLow(6);
	wsdDocIn.SetFlags(0x54408);
	wsdDocIn.SetLocalFile(CStdString(_T("Digger")));
	wsdDocIn.SetModifiedTime(20011109.072835);
	wsdDocIn.SetOperator(CStdString(_T("Guy")));
	wsdDocIn.SetType(CStdString(_T("Rascal")));
	LOCALFILESTORELib::tagWSDOCUMENT wsDoc;
	wsdDocIn.InitializeWSDOCUMENT((WSDOCUMENT*)&wsDoc);
	HRESULT hr = m_pLFS->raw_SaveDocument(&wsDoc, 111);
	assertTest(hr == S_TEST);
	assertTest(m_pWorker->m_sLastMethodCalled == _T("SaveDocument"));
	assertTest(wsdDocIn == m_pWorker->m_wsd);
	assertTest(m_pWorker->m_lFlags == 111);
}
void TestOnMappedNetworkDrives::TestLockDoc()
{
	CStdString sMappedDriveLetter = m_NetDriveHelper.GetMapNetworkDriveLetter();
	assertMessage(!sMappedDriveLetter.IsEmpty(), _T("Cannot map network drive - used to just skip test"));

	DocProviderWorker	objWorker;
	CStdString			sDocID(DocumentID::GetDocProviderId() + sMappedDriveLetter + _T("/") + TEST_DOC _T(".doc"));
	CStdString			sLockFileName(sMappedDriveLetter + _T("\\") + TEST_DOC _T(".doc_tart.lock"));
	WSDocNonCom			wsDoc;
	
	HRESULT hr = objWorker.LockDocumentAsOtherUserForTesting(sDocID, _T("tart"), _T(""), LOCK_DOCUMENT);
	CStdString sMessage;
	sMessage.Format(_T("%s: 0x%x"), _T("GetDocument should return S_OK, but returned "), hr);
	assertMessage(S_OK == hr, sMessage.c_str());
	
	if (_taccess(sLockFileName, 0) == -1)
	{
		assertMessage(false, _T("Lock file does not exist"));
	}
	DocumentID dID(sDocID);
	objWorker.m_plockMgr->RemoveLock(dID, CStdString(_T("tart")));
}
Example #9
0
bool CIMDocInfo::Populate(IManage::INRTDocumentPtr& pINRTDocument)
{
	LOG_WS_FUNCTION_SCOPE();

	if (pINRTDocument == NULL)
	{
		LOG_WS_ERROR(_T("Document pointer was null"));
		return false;
	}

	try
	{
		IManage::INRTDatabasePtr pINRTDatabase = pINRTDocument->Database;
		IManage::INRTSessionPtr  pINRTSession  = pINRTDatabase->Session;

		m_sDatabaseName = pINRTDatabase->Name;
		m_sServerName   = pINRTSession->ServerName;
		m_sUserId       = pINRTSession->UserID;
		m_sEncPassword  = pINRTSession->Password;
		m_sDescription  = pINRTDocument->Description;
		m_sExtension    = pINRTDocument->Extension;
		m_lDocNum       = pINRTDocument->Number;
		m_lVerNum       = pINRTDocument->Version;

		return true;
	}
	catch(_com_error& e)
	{
		CStdString sMsg;
		sMsg.Format(_T("Failed : %s"), CStdString(e.ErrorMessage()).c_str());
		LOG_WS_ERROR(sMsg.c_str());
	}
	catch(...)
	{
		LOG_WS_ERROR(_T("Caught unknown exception"));
		ATLASSERT(false);
	}
	return false;
}
void TestDocFileformfield::TestTranslateBinaryProperty()
{
    CStdString expectedName(_T("Text1"));
    RTFfile theFile(new RTFFileContext);
    AutoDocFileReaderImpl4Tests reader(DEFAULT_FORMTEXT_FILE, &theFile);
    reader.Initialize();

    WordParserInfo wpi(&reader);

    WrdFormFieldBinaryData data;
    WrdEshRoot root;
    data.setCP(11);
    wpi.m_Reader.read(data);

    CQuickBuildString conversionResult = _T("");
    RTFFileContext context;
    DocFileFormField docFileFormField(&context);
    assertTest(docFileFormField.TranslateBinaryProperty(conversionResult , data.getFieldNameDataReference()));

    std::strstream msg;
    msg << _T("Expected [") << expectedName << _T("], but the received [") << conversionResult << _T("]") << std::ends;
    assertMessage(expectedName == conversionResult, CStdString(msg.str()));
}
Example #11
0
CStdString CTestUtils::CopyTestFileToTempFile(const CStdString& sSource)
{
	if(_taccess(sSource, 0) != 0)
	{
		CStdStringA sError;
		sError.Format("CTestUtils::CopyTestFileToTempFile - source file (%s) doesn't exist.", sSource.c_str());
		throw std::exception(sError.c_str());
	}

	TCHAR szTempPath[ MAX_PATH ] = {0};
	::GetTempPath( MAX_PATH, szTempPath );
	TCHAR szTempFileName[MAX_PATH] = {0};
	::GetTempFileName( szTempPath, _T( "wst" ), 0, szTempFileName );

	if (!CopyFile(sSource.c_str(), szTempFileName, false))
	{
		CStdStringA sError;
		sError.Format("CTestUtils::CopyTestFileToTempFile copy file failed - source file (%s) destination file (%s)", sSource.c_str(), szTempFileName);
		throw std::exception(sError.c_str());
	}
	return CStdString(szTempFileName);

}
Example #12
0
std::vector<WSDocNonCom> DMSHelper::GetAllRelatedDraftsForUser(CStdStringW sDocID)
{
	try
	{
		std::vector<WSDocNonCom> vsAllRelations = GetAllRelatedSynergyDocs(sDocID);
		std::vector<WSDocNonCom> vsAllRelationsForUser;
		CStdString sCurrentUser = GetCurrentDmsUser(sDocID);

		for (unsigned int i=0; i<vsAllRelations.size(); i++)
		{
			WSDocNonCom& wsdThis = vsAllRelations[i];
			if ((wsdThis.GetExtension().CompareNoCase(CStdString(DRAFT_FILE_EXTENSION)) == 0) &&
				IncludeThisDraftForUser(wsdThis.GetAuthor(), sCurrentUser))
			{
				vsAllRelationsForUser.push_back(wsdThis);
			}
		}
		return vsAllRelationsForUser;
	}
	catch(_com_error& e)
	{
		LOG_WS_ERROR_RESULT(e);
		throw;
	}
	catch(std::exception& e)
	{
		LOG_WS_ERROR_RESULT(e);
		throw;
	}
	catch(TCHAR*& e)
	{
		CStdString sErr(e);
		sErr.append(_T("(TCHAR*): This exception was thrown"));
		LOG_WS_ERROR(sErr);
		throw;
	}
}
Example #13
0
void TestDocReader::TestTabChanges()
{
	DocReader dr;
	dr.OpenFile(TEST_TABS_TC_DOC);

	CStdStringW sExp = L"\t\t\t\t\t\t\t\t\t\tABC\t1.23\tDEF\tGHI\tFFF\r";
	sExp += "Abc\t222.23\t\t\t\t\tdef\tghi\tddd\r";
	sExp += "Aaa\t10.87	b\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tcb\tccc\txxx\r";
	sExp += "Ddd\t1.44994\t\t\t\t\t\t\r";
	sExp += "ABC\t1.23	DEF	GHI	aaa\t\t\t\r";
	sExp += "Abc\t222.\t\t\txxx\r";
	sExp += "Aaa\t10.87\tbcb\tccc\tzzz\r";
	sExp += "Ddd\t1.44994\teEEee\tfffLeft\tright\r";
	sExp += "Left\tRIGHT\r";

	CStdStringW sGot = dr.GetMainDocumentText();
	for (unsigned int i=0; i<(x64_int_cast)sExp.size(); i++)
	{
		OutputDebugString(CStdString(sGot.substr(i,1)));
		assertTest(sGot[i] == sExp[i]);
	}

	assertTest(dr.GetMainDocumentText() == sExp);
}
Example #14
0
CStdString CStdString::Left(int iLength) const
{
    if( iLength < 0 ) iLength = 0;
    if( iLength > GetLength() ) iLength = GetLength();
    return CStdString(m_pstr, iLength);
}
Example #15
0
int main(int argc, char *argv[])
{
  struct termios new_termios;

  tcgetattr(STDIN_FILENO, &orig_termios);

  new_termios             = orig_termios;
  new_termios.c_lflag     &= ~(ICANON | ECHO | ECHOCTL | ECHONL);
  new_termios.c_cflag     |= HUPCL;
  new_termios.c_cc[VMIN]  = 0;

  CStdString last_sub = "";

  tcsetattr(STDIN_FILENO, TCSANOW, &new_termios);
  on_exit(restore_termios, &orig_termios);

  CStdString            m_filename;
  double                m_incr                = 0;
  CRBP                  g_RBP;
  COMXCore              g_OMX;
  bool                  m_stats               = false;
  bool                  m_dump_format         = false;
  bool                  m_3d                  = false;
  bool                  m_refresh             = false;
  double                startpts              = 0;
  TV_GET_STATE_RESP_T   tv_state;

  struct option longopts[] = {
    { "info",         no_argument,        NULL,          'i' },
    { "help",         no_argument,        NULL,          'h' },
    { "aidx",         required_argument,  NULL,          'n' },
    { "adev",         required_argument,  NULL,          'o' },
    { "stats",        no_argument,        NULL,          's' },
    { "passthrough",  no_argument,        NULL,          'p' },
    { "deinterlace",  no_argument,        NULL,          'd' },
    { "hw",           no_argument,        NULL,          'w' },
    { "3d",           no_argument,        NULL,          '3' },
    { "hdmiclocksync", no_argument,       NULL,          'y' },
    { "refresh",      no_argument,        NULL,          'r' },
    { "sid",          required_argument,  NULL,          't' },
    { 0, 0, 0, 0 }
  };

  int c;
  while ((c = getopt_long(argc, argv, "wihn:o:cslpd3yt:r", longopts, NULL)) != -1)  
  {
    switch (c) 
    {
      case 'r':
        m_refresh = true;
        break;
      case 'y':
        m_hdmi_clock_sync = true;
        break;
      case '3':
        m_3d = true;
        break;
      case 'd':
        m_Deinterlace = true;
        break;
      case 'w':
        m_use_hw_audio = true;
        break;
      case 'p':
        m_passthrough = true;
        break;
      case 's':
        m_stats = true;
        break;
      case 'o':
        deviceString = optarg;
        if(deviceString != CStdString("local") && deviceString != CStdString("hdmi"))
        {
          print_usage();
          return 0;
        }
        deviceString = "omx:" + deviceString;
        break;
      case 'i':
        m_dump_format = true;
        break;
      case 't':
        m_subtitle_index = atoi(optarg) - 1;
        if(m_subtitle_index < 0)
          m_subtitle_index = 0;
        m_show_subtitle = true;
        break;
      case 'n':
        m_audio_index_use = atoi(optarg) - 1;
        if(m_audio_index_use < 0)
          m_audio_index_use = 0;
        break;
      case 0:
        break;
      case 'h':
        print_usage();
        return 0;
        break;
      case ':':
        return 0;
        break;
      default:
        return 0;
        break;
    }
  }

  if (optind >= argc) {
    print_usage();
    return 0;
  }

  m_filename = argv[optind];

  CLog::Init("./");

  g_RBP.Initialize();
  g_OMX.Initialize();

  m_av_clock = new OMXClock();

  m_thread_player = true;

  if(!m_omx_reader.Open(m_filename.c_str(), m_dump_format))
    goto do_exit;

  if(m_dump_format)
    goto do_exit;

  m_bMpeg         = m_omx_reader.IsMpegVideo();
  m_has_video     = m_omx_reader.VideoStreamCount();
  m_has_audio     = m_omx_reader.AudioStreamCount();
  m_has_subtitle  = m_omx_reader.SubtitleStreamCount();

  if(!m_av_clock->OMXInitialize(m_has_video, m_has_audio))
    goto do_exit;

  if(m_hdmi_clock_sync && !m_av_clock->HDMIClockSync())
      goto do_exit;

  m_omx_reader.GetHints(OMXSTREAM_AUDIO, m_hints_audio);
  m_omx_reader.GetHints(OMXSTREAM_VIDEO, m_hints_video);

  if(m_audio_index_use != -1)
    m_omx_reader.SetActiveStream(OMXSTREAM_AUDIO, m_audio_index_use);
          
  if(m_has_video && !m_player_video.Open(m_hints_video, m_av_clock, m_Deinterlace,  m_bMpeg, 
                                         m_hdmi_clock_sync, m_thread_player))
    goto do_exit;

  if(m_has_video && m_refresh)
  {
    memset(&tv_state, 0, sizeof(TV_GET_STATE_RESP_T));
    m_BcmHost.vc_tv_get_state(&tv_state);

    if(m_filename.find("3DSBS") != string::npos)
      m_3d = true;

    SetVideoMode(m_hints_video.width, m_hints_video.height, m_player_video.GetFPS(), m_3d);

  }

  // This is an upper bound check on the subtitle limits. When we pulled the subtitle
  // index from the user we check to make sure that the value is larger than zero, but
  // we couldn't know without scanning the file if it was too high. If this is the case
  // then we replace the subtitle index with the maximum value possible.
  if(m_has_subtitle && m_subtitle_index > (m_omx_reader.SubtitleStreamCount() - 1))
  {
    m_subtitle_index = m_omx_reader.SubtitleStreamCount() - 1;
  }

  // Here we actually enable the subtitle streams if we have one available.
  if (m_has_subtitle && m_subtitle_index <= (m_omx_reader.SubtitleStreamCount() - 1))
  {
    m_omx_reader.SetActiveStream(OMXSTREAM_SUBTITLE, m_subtitle_index);
    m_show_subtitle = true;
  }
  else
  {
    m_show_subtitle = false;
  }

  m_omx_reader.GetHints(OMXSTREAM_AUDIO, m_hints_audio);

  if(m_has_audio && !m_player_audio.Open(m_hints_audio, m_av_clock, &m_omx_reader, deviceString, 
                                         m_passthrough, m_use_hw_audio, m_thread_player))
    goto do_exit;

  m_av_clock->SetSpeed(DVD_PLAYSPEED_NORMAL);
  m_av_clock->OMXStateExecute();
  m_av_clock->OMXStart();

  struct timespec starttime, endtime;

  while(!m_stop)
  {
    int ch[8];
    int chnum = 0;

    if(g_abort)
      goto do_exit;
    
    while((ch[chnum] = getchar()) != EOF) chnum++;
    if (chnum > 1) ch[0] = ch[chnum - 1] | (ch[chnum - 2] << 8);

    switch(ch[0])
    {
      case 'z':
        m_tv_show_info = !m_tv_show_info;
        vc_tv_show_info(m_tv_show_info);
        break;
      case '1':
        SetSpeed(m_av_clock->OMXPlaySpeed() - 1);
        break;
      case '2':
        SetSpeed(m_av_clock->OMXPlaySpeed() + 1);
        break;
      case 'j':
        m_omx_reader.SetActiveStream(OMXSTREAM_AUDIO, m_omx_reader.GetAudioIndex() - 1);
        break;
      case 'k':
        m_omx_reader.SetActiveStream(OMXSTREAM_AUDIO, m_omx_reader.GetAudioIndex() + 1);
        break;
      case 'i':
        if(m_omx_reader.GetChapterCount() > 0)
        {
          m_omx_reader.SeekChapter(m_omx_reader.GetChapter() - 1, &startpts);
          FlushStreams(startpts);
        }
        else
        {
          m_incr = -600.0;
        }
        break;
      case 'o':
        if(m_omx_reader.GetChapterCount() > 0)
        {
          m_omx_reader.SeekChapter(m_omx_reader.GetChapter() + 1, &startpts);
          FlushStreams(startpts);
        }
        else
        {
          m_incr = 600.0;
        }
        break;
      case 'n':
        if(m_omx_reader.GetSubtitleIndex() > 0)
        {
          m_omx_reader.SetActiveStream(OMXSTREAM_SUBTITLE, m_omx_reader.GetSubtitleIndex() - 1);
          m_player_video.FlushSubtitles();
        }
        break;
      case 'm':
        if(m_omx_reader.GetSubtitleIndex() > 0)
        {
          m_omx_reader.SetActiveStream(OMXSTREAM_SUBTITLE, m_omx_reader.GetSubtitleIndex() + 1);
          m_player_video.FlushSubtitles();
        }
        break;
      case 's':
        m_show_subtitle = !m_show_subtitle;
        break;
      case 'q':
        m_stop = true;
        goto do_exit;
        break;
      case 0x5b44: // key left
        if(m_omx_reader.CanSeek()) m_incr = -30.0;
        break;
      case 0x5b43: // key right
        if(m_omx_reader.CanSeek()) m_incr = 30.0;
        break;
      case 0x5b41: // key up
        if(m_omx_reader.CanSeek()) m_incr = 600.0;
        break;
      case 0x5b42: // key down
        if(m_omx_reader.CanSeek()) m_incr = -600.0;
        break;
      case ' ':
      case 'p':
        m_Pause = !m_Pause;
        if(m_Pause)
        {
          SetSpeed(OMX_PLAYSPEED_PAUSE);
          m_av_clock->OMXPause();
        }
        else
        {
          SetSpeed(OMX_PLAYSPEED_NORMAL);
          m_av_clock->OMXResume();
        }
        break;
      case '-':
        m_player_audio.SetCurrentVolume(m_player_audio.GetCurrentVolume() - 50);
        printf("Current Volume: %.2fdB\n", m_player_audio.GetCurrentVolume() / 100.0f);
        break;
      case '+':
        m_player_audio.SetCurrentVolume(m_player_audio.GetCurrentVolume() + 50);
        printf("Current Volume: %.2fdB\n", m_player_audio.GetCurrentVolume() / 100.0f);
        break;
      default:
        break;
    }

    if(m_Pause)
    {
      OMXClock::OMXSleep(2);
      continue;
    }

    if(m_incr != 0 && !m_bMpeg)
    {
      int    seek_flags   = 0;
      double seek_pos     = 0;
      double pts          = 0;

      pts = m_av_clock->GetPTS();

      seek_pos = (pts / DVD_TIME_BASE) + m_incr;
      seek_flags = m_incr < 0.0f ? AVSEEK_FLAG_BACKWARD : 0;

      seek_pos *= 1000.0f;

      m_incr = 0;

      if(m_omx_reader.SeekTime(seek_pos, seek_flags, &startpts))
        FlushStreams(startpts);

      m_player_video.Close();
      if(m_has_video && !m_player_video.Open(m_hints_video, m_av_clock, m_Deinterlace,  m_bMpeg, 
                                         m_hdmi_clock_sync, m_thread_player))
        goto do_exit;
    }

    /* when the audio buffer runs under 0.1 seconds we buffer up */
    if(m_has_audio)
    {
      if(m_player_audio.GetDelay() < 0.1f && !m_buffer_empty)
      {
        if(!m_av_clock->OMXIsPaused())
        {
          m_av_clock->OMXPause();
          //printf("buffering start\n");
          m_buffer_empty = true;
          clock_gettime(CLOCK_REALTIME, &starttime);
        }
      }
      if(m_player_audio.GetDelay() > (AUDIO_BUFFER_SECONDS * 0.75f) && m_buffer_empty)
      {
        if(m_av_clock->OMXIsPaused())
        {
          m_av_clock->OMXResume();
          //printf("buffering end\n");
          m_buffer_empty = false;
        }
      }
      if(m_buffer_empty)
      {
        clock_gettime(CLOCK_REALTIME, &endtime);
        if((endtime.tv_sec - starttime.tv_sec) > 1)
        {
          m_buffer_empty = false;
          m_av_clock->OMXResume();
          //printf("buffering timed out\n");
        }
      }
    }

    if(!m_omx_pkt)
      m_omx_pkt = m_omx_reader.Read();

    if(m_has_video && m_omx_pkt && m_omx_reader.IsActive(OMXSTREAM_VIDEO, m_omx_pkt->stream_index))
    {
      if(m_player_video.AddPacket(m_omx_pkt))
        m_omx_pkt = NULL;
      else
        OMXClock::OMXSleep(10);

      if(m_tv_show_info)
      {
        char response[80];
        vc_gencmd(response, sizeof response, "render_bar 4 video_fifo %d %d %d %d", 
                m_player_video.GetDecoderBufferSize()-m_player_video.GetDecoderFreeSpace(),
                0 , 0, m_player_video.GetDecoderBufferSize());
        vc_gencmd(response, sizeof response, "render_bar 5 audio_fifo %d %d %d %d", 
                (int)(100.0*m_player_audio.GetDelay()), 0, 0, 100*AUDIO_BUFFER_SECONDS);
      }
    }
    else if(m_has_audio && m_omx_pkt && m_omx_pkt->codec_type == AVMEDIA_TYPE_AUDIO)
    {
      if(m_player_audio.AddPacket(m_omx_pkt))
        m_omx_pkt = NULL;
      else
        OMXClock::OMXSleep(10);
    }
    else if(m_omx_pkt && m_omx_reader.IsActive(OMXSTREAM_SUBTITLE, m_omx_pkt->stream_index))
    {
      if(m_omx_pkt->size && (m_omx_pkt->hints.codec == CODEC_ID_TEXT || 
                             m_omx_pkt->hints.codec == CODEC_ID_SSA))
      {
        if(m_player_video.AddPacket(m_omx_pkt))
          m_omx_pkt = NULL;
        else
          OMXClock::OMXSleep(10);
      }
      else
      {
        m_omx_reader.FreePacket(m_omx_pkt);
        m_omx_pkt = NULL;
      }
    }
    else
    {
      if(m_omx_pkt)
      {
        m_omx_reader.FreePacket(m_omx_pkt);
        m_omx_pkt = NULL;
      }
    }

    /* player got in an error state */
    if(m_player_audio.Error())
    {
      printf("audio player error. emergency exit!!!\n");
      goto do_exit;
    }

    CStdString strSubTitle = m_player_video.GetText();
    if(strSubTitle.length() && m_show_subtitle)
    {
      if(last_sub != strSubTitle)
      {
        last_sub = strSubTitle;
        printf("Text : %s\n", strSubTitle.c_str());
      }
    }

    if(m_stats)
    {
      printf("V : %8.02f %8d %8d A : %8.02f %8.02f Cv : %8d Ca : %8d                            \r",
             m_player_video.GetCurrentPTS() / DVD_TIME_BASE, m_player_video.GetDecoderBufferSize(),
             m_player_video.GetDecoderFreeSpace(), m_player_audio.GetCurrentPTS() / DVD_TIME_BASE, 
             m_player_audio.GetDelay(), m_player_video.GetCached(), m_player_audio.GetCached());
    }
    if(m_omx_reader.IsEof())
        break;

  }

do_exit:
  printf("\n");

  if(!m_stop)
  {
    if(m_has_audio)
      m_player_audio.WaitCompletion();
    else if(m_has_video)
      m_player_video.WaitCompletion();
  }

  if(m_refresh)
  {
    m_BcmHost.vc_tv_hdmi_power_on_best(tv_state.width, tv_state.height, tv_state.frame_rate, HDMI_NONINTERLACED,
                                       (EDID_MODE_MATCH_FLAG_T)(HDMI_MODE_MATCH_FRAMERATE|HDMI_MODE_MATCH_RESOLUTION|HDMI_MODE_MATCH_SCANMODE));
  }

  m_av_clock->OMXStop();
  m_av_clock->OMXStateIdle();

  m_player_video.Close();
  m_player_audio.Close();

  if(m_omx_pkt)
  {
    m_omx_reader.FreePacket(m_omx_pkt);
    m_omx_pkt = NULL;
  }

  m_omx_reader.Close();

  vc_tv_show_info(0);

  g_OMX.Deinitialize();
  g_RBP.Deinitialize();

  printf("have a nice day ;)\n");
  return 1;
}
Example #16
0
/* See if this is an IAX2 NEW.  If so, process */
bool TryIax2New(EthernetHeaderStruct* ethernetHeader, IpHeaderStruct* ipHeader,
		UdpHeaderStruct* udpHeader, u_char* udpPayload)
{
	struct Iax2FullHeader *fh = (struct Iax2FullHeader *)udpPayload;
	struct iax2_ies ies;
	int ies_len = 0, udp_act_payload_len = 0;
	Iax2NewInfoRef info(new Iax2NewInfo());
	//char source_ip[16], dest_ip[16];
	CStdString logmsg;

	if(!DLLCONFIG.m_iax2Support)
		return false;

	memset(&ies, 0, sizeof(ies));
	udp_act_payload_len = (ntohs(udpHeader->len)-sizeof(UdpHeaderStruct));
	if(udp_act_payload_len < (int)sizeof(*fh))
		return false; /* Frame too small */

        if(!(ntohs(fh->scallno) & 0x8000))
                return false; /* Not a full frame */

	ies_len = ((u_char*)ipHeader+ntohs(ipHeader->ip_len))-(udpPayload+sizeof(*fh));

#if 0  /* Debug headaches caused by udpHeader->len */
	/* Beware that udpHeader->len is not the length of the udpPayload
	 * but rather this includes the length of the UDP header as well.
	 * I.e watch out for the figure "8" as you debug ;-) */
	{
		char source_ip[16], dest_ip[16];

		ACE_OS::inet_ntop(AF_INET, (void*)&ipHeader->ip_src, source_ip, sizeof(source_ip));
		ACE_OS::inet_ntop(AF_INET, (void*)&ipHeader->ip_dest, dest_ip, sizeof(dest_ip));
	        iax2_dump_frame(fh, source_ip, dest_ip);
	}

        logmsg.Format("UDP_Payload=%p UDP+FH_Payload=%p FH->IEDATA=%p ies_len=%d "
                        "udpHeader->len-sizeof(fullhdr)=%d (ntohs(udpHeader->len)"
                        "-sizeof(UdpHeaderStruct))=%d", udpPayload, udpPayload+
                        sizeof(*fh), fh->ie_data, ies_len, (ntohs(udpHeader->len)-
                        sizeof(*fh)), (ntohs(udpHeader->len)-sizeof(UdpHeaderStruct)));
        LOG4CXX_INFO(s_iax2parsersLog, logmsg);
#endif

	if(fh->type != IAX2_FRAME_IAX)
		return false; /* Frame type must be IAX */

	if(get_uncompressed_subclass(fh->c_sub) != IAX2_COMMAND_NEW)
		return false; /* Subclass must be NEW */

	if(parse_iax2_ies(&ies, fh->ie_data, ies_len))
		return false; /* Invalid "full" frame received */

	if(!ies.callee)
		return false; /* According to the SPEC, a NEW MUST have a
			       * callee (Called Number) */

	if(!strlen(ies.callee))
		return false; /* According to the SPEC, a NEW MUST have a
                               * callee (Called Number) */

	if(!ies.caller) {
		ies.caller = (char*)"WITHELD";
	} else {
		if(!strlen(ies.caller)) {
			ies.caller = (char*)"WITHELD";
		}
	}

	/* Statistically this is most likely a NEW IAX2 frame. */

	info->m_senderIp = ipHeader->ip_src;
	info->m_receiverIp = ipHeader->ip_dest;
	info->m_caller = CStdString(ies.caller);
	info->m_callee = CStdString(ies.callee);
	info->m_callingName = CStdString(ies.calling_name ? ies.calling_name : "");
	info->m_callNo = IntToString(ntohs(fh->scallno) & ~0x8000);

	/* Report the packet */
	Iax2SessionsSingleton::instance()->ReportIax2New(info);

	LOG4CXX_INFO(s_iax2parsersLog, "Processed IAX2 NEW frame ts:" + IntToString(ntohl(fh->ts)));

	return true;
}
Example #17
0
/*----------------------------------------------------------------------
|   CUPnPDirectory::GetDirectory
+---------------------------------------------------------------------*/
bool
CUPnPDirectory::GetDirectory(const CStdString& strPath, CFileItemList &items)
{
    CUPnP* upnp = CUPnP::GetInstance();

    /* upnp should never be cached, it has internal cache */
    items.SetCacheToDisc(CFileItemList::CACHE_NEVER);

    // We accept upnp://devuuid/[item_id/]
    NPT_String path = strPath.c_str();
    if (!path.StartsWith("upnp://", true)) {
        return false;
    }

    if (path.Compare("upnp://", true) == 0) {
        upnp->StartClient();

        // root -> get list of devices
        const NPT_Lock<PLT_DeviceDataReferenceList>& devices = upnp->m_MediaBrowser->GetMediaServers();
        NPT_List<PLT_DeviceDataReference>::Iterator device = devices.GetFirstItem();
        while (device) {
            NPT_String name = (*device)->GetFriendlyName();
            NPT_String uuid = (*device)->GetUUID();

            CFileItemPtr pItem(new CFileItem((const char*)name));
            pItem->SetPath(CStdString((const char*) "upnp://" + uuid + "/"));
            pItem->m_bIsFolder = true;
            pItem->SetArt("thumb", (const char*)(*device)->GetIconUrl("image/png"));

            items.Add(pItem);

            ++device;
        }
    } else {
        if (!path.EndsWith("/")) path += "/";

        // look for nextslash
        int next_slash = path.Find('/', 7);

        NPT_String uuid = (next_slash==-1)?path.SubString(7):path.SubString(7, next_slash-7);
        NPT_String object_id = (next_slash==-1)?"":path.SubString(next_slash+1);
        object_id.TrimRight("/");
        if (object_id.GetLength()) {
            CStdString tmp = (char*) object_id;
            CURL::Decode(tmp);
            object_id = tmp;
        }

        // try to find the device with wait on startup
        PLT_DeviceDataReference device;
        if (!FindDeviceWait(upnp, uuid, device))
            goto failure;

        // issue a browse request with object_id
        // if object_id is empty use "0" for root
        object_id = object_id.IsEmpty()?"0":object_id;

        // remember a count of object classes
        std::map<NPT_String, int> classes;

        // just a guess as to what types of files we want
        bool video = true;
        bool audio = true;
        bool image = true;
        m_strFileMask.TrimLeft("/");
        if (!m_strFileMask.IsEmpty()) {
            video = m_strFileMask.Find(".wmv") >= 0;
            audio = m_strFileMask.Find(".wma") >= 0;
            image = m_strFileMask.Find(".jpg") >= 0;
        }

        // special case for Windows Media Connect and WMP11 when looking for root
        // We can target which root subfolder we want based on directory mask
        if (object_id == "0" && ((device->GetFriendlyName().Find("Windows Media Connect", 0, true) >= 0) ||
                                 (device->m_ModelName == "Windows Media Player Sharing"))) {

            // look for a specific type to differentiate which folder we want
            if (audio && !video && !image) {
                // music
                object_id = "1";
            } else if (!audio && video && !image) {
                // video
                object_id = "2";
            } else if (!audio && !video && image) {
                // pictures
                object_id = "3";
            }
        }

#ifdef DISABLE_SPECIALCASE
        // same thing but special case for XBMC
        if (object_id == "0" && ((device->m_ModelName.Find("XBMC", 0, true) >= 0) ||
                                 (device->m_ModelName.Find("Xbox Media Center", 0, true) >= 0))) {
            // look for a specific type to differentiate which folder we want
            if (audio && !video && !image) {
                // music
                object_id = "virtualpath://upnpmusic";
            } else if (!audio && video && !image) {
                // video
                object_id = "virtualpath://upnpvideo";
            } else if (!audio && !video && image) {
                // pictures
                object_id = "virtualpath://upnppictures";
            }
        }
#endif

        // if error, return now, the device could have gone away
        // this will make us go back to the sources list
        PLT_MediaObjectListReference list;
        NPT_Result res = upnp->m_MediaBrowser->BrowseSync(device, object_id, list);
        if (NPT_FAILED(res)) goto failure;

        // empty list is ok
        if (list.IsNull()) goto cleanup;

        PLT_MediaObjectList::Iterator entry = list->GetFirstItem();
        while (entry) {
            // disregard items with wrong class/type
            if( (!video && (*entry)->m_ObjectClass.type.CompareN("object.item.videoitem", 21,true) == 0)
             || (!audio && (*entry)->m_ObjectClass.type.CompareN("object.item.audioitem", 21,true) == 0)
             || (!image && (*entry)->m_ObjectClass.type.CompareN("object.item.imageitem", 21,true) == 0) )
            {
                ++entry;
                continue;
            }

            // never show empty containers in media views
            if((*entry)->IsContainer()) {
                if( (audio || video || image)
                 && ((PLT_MediaContainer*)(*entry))->m_ChildrenCount == 0) {
                    ++entry;
                    continue;
                }
            }


            // keep count of classes
            classes[(*entry)->m_ObjectClass.type]++;
            CFileItemPtr pItem = BuildObject(*entry);
            if(!pItem) {
                ++entry;
                continue;
            }

            CStdString id = (char*) (*entry)->m_ObjectID;
            CURL::Encode(id);
            URIUtils::AddSlashAtEnd(id);
            pItem->SetPath(CStdString((const char*) "upnp://" + uuid + "/" + id.c_str()));

            items.Add(pItem);

            ++entry;
        }

        NPT_String max_string = "";
        int        max_count  = 0;
        for(std::map<NPT_String, int>::iterator it = classes.begin(); it != classes.end(); it++)
        {
          if(it->second > max_count)
          {
            max_string = it->first;
            max_count  = it->second;
          }
        }
        std::string content = GetContentMapping(max_string);
        items.SetContent(content);
        if (content == "unknown")
        {
          items.AddSortMethod(SORT_METHOD_UNSORTED, 571, LABEL_MASKS("%L", "%I", "%L", ""));
          items.AddSortMethod(SORT_METHOD_LABEL_IGNORE_FOLDERS, 551, LABEL_MASKS("%L", "%I", "%L", ""));
          items.AddSortMethod(SORT_METHOD_SIZE, 553, LABEL_MASKS("%L", "%I", "%L", "%I"));
          items.AddSortMethod(SORT_METHOD_DATE, 552, LABEL_MASKS("%L", "%J", "%L", "%J"));
        }
    }

cleanup:
    return true;

failure:
    return false;
}
Example #18
0
CStdString RecordMsg::GetClassName()
{
	return  CStdString(RECORD_CLASS);
}
Example #19
0
/*----------------------------------------------------------------------
|   CUPnPDirectory::GetDirectory
+---------------------------------------------------------------------*/
bool
CUPnPDirectory::GetDirectory(const CStdString& strPath, CFileItemList &items)
{
    CUPnP* upnp = CUPnP::GetInstance();

    /* upnp should never be cached, it has internal cache */
    items.SetCacheToDisc(CFileItemList::CACHE_NEVER);

    // We accept upnp://devuuid/[item_id/]
    NPT_String path = strPath.c_str();
    if (!path.StartsWith("upnp://", true)) {
        return false;
    }

    if (path.Compare("upnp://", true) == 0) {
        upnp->StartClient();

        // root -> get list of devices
        const NPT_Lock<PLT_DeviceDataReferenceList>& devices = upnp->m_MediaBrowser->GetMediaServers();
        NPT_List<PLT_DeviceDataReference>::Iterator device = devices.GetFirstItem();
        while (device) {
            NPT_String name = (*device)->GetFriendlyName();
            NPT_String uuid = (*device)->GetUUID();

            CFileItemPtr pItem(new CFileItem((const char*)name));
            pItem->SetPath(CStdString((const char*) "upnp://" + uuid + "/"));
            pItem->m_bIsFolder = true;
            pItem->SetThumbnailImage((const char*)(*device)->GetIconUrl("image/jpeg"));

            items.Add(pItem);

            ++device;
        }
    } else {
        if (!path.EndsWith("/")) path += "/";

        // look for nextslash
        int next_slash = path.Find('/', 7);

        NPT_String uuid = (next_slash==-1)?path.SubString(7):path.SubString(7, next_slash-7);
        NPT_String object_id = (next_slash==-1)?"":path.SubString(next_slash+1);
        object_id.TrimRight("/");
        if (object_id.GetLength()) {
            CStdString tmp = (char*) object_id;
            CURL::Decode(tmp);
            object_id = tmp;
        }

        // try to find the device with wait on startup
        PLT_DeviceDataReference device;
        if (!FindDeviceWait(upnp, uuid, device))
            goto failure;

        // issue a browse request with object_id
        // if object_id is empty use "0" for root
        object_id = object_id.IsEmpty()?"0":object_id;

        // remember a count of object classes
        std::map<NPT_String, int> classes;

        // just a guess as to what types of files we want
        bool video = true;
        bool audio = true;
        bool image = true;
        m_strFileMask.TrimLeft("/");
        if (!m_strFileMask.IsEmpty()) {
            video = m_strFileMask.Find(".wmv") >= 0;
            audio = m_strFileMask.Find(".wma") >= 0;
            image = m_strFileMask.Find(".jpg") >= 0;
        }

        // special case for Windows Media Connect and WMP11 when looking for root
        // We can target which root subfolder we want based on directory mask
        if (object_id == "0" && ((device->GetFriendlyName().Find("Windows Media Connect", 0, true) >= 0) ||
                                 (device->m_ModelName == "Windows Media Player Sharing"))) {

            // look for a specific type to differentiate which folder we want
            if (audio && !video && !image) {
                // music
                object_id = "1";
            } else if (!audio && video && !image) {
                // video
                object_id = "2";
            } else if (!audio && !video && image) {
                // pictures
                object_id = "3";
            }
        }

#ifdef DISABLE_SPECIALCASE
        // same thing but special case for XBMC
        if (object_id == "0" && ((device->m_ModelName.Find("XBMC", 0, true) >= 0) ||
                                 (device->m_ModelName.Find("Xbox Media Center", 0, true) >= 0))) {
            // look for a specific type to differentiate which folder we want
            if (audio && !video && !image) {
                // music
                object_id = "virtualpath://upnpmusic";
            } else if (!audio && video && !image) {
                // video
                object_id = "virtualpath://upnpvideo";
            } else if (!audio && !video && image) {
                // pictures
                object_id = "virtualpath://upnppictures";
            }
        }
#endif

        // if error, return now, the device could have gone away
        // this will make us go back to the sources list
        PLT_MediaObjectListReference list;
        NPT_Result res = upnp->m_MediaBrowser->BrowseSync(device, object_id, list);
        if (NPT_FAILED(res)) goto failure;

        // empty list is ok
        if (list.IsNull()) goto cleanup;

        PLT_MediaObjectList::Iterator entry = list->GetFirstItem();
        while (entry) {
            // disregard items with wrong class/type
            if( (!video && (*entry)->m_ObjectClass.type.CompareN("object.item.videoitem", 21,true) == 0)
                    || (!audio && (*entry)->m_ObjectClass.type.CompareN("object.item.audioitem", 21,true) == 0)
                    || (!image && (*entry)->m_ObjectClass.type.CompareN("object.item.imageitem", 21,true) == 0) )
            {
                ++entry;
                continue;
            }

            // never show empty containers in media views
            if((*entry)->IsContainer()) {
                if( (audio || video || image)
                        && ((PLT_MediaContainer*)(*entry))->m_ChildrenCount == 0) {
                    ++entry;
                    continue;
                }
            }

            NPT_String ObjectClass = (*entry)->m_ObjectClass.type.ToLowercase();

            // keep count of classes
            classes[(*entry)->m_ObjectClass.type]++;

            CFileItemPtr pItem(new CFileItem((const char*)(*entry)->m_Title));
            pItem->SetLabelPreformated(true);
            pItem->m_strTitle = (const char*)(*entry)->m_Title;
            pItem->m_bIsFolder = (*entry)->IsContainer();

            CStdString id = (char*) (*entry)->m_ObjectID;
            CURL::Encode(id);
            pItem->SetPath(CStdString((const char*) "upnp://" + uuid + "/" + id.c_str()));

            // if it's a container, format a string as upnp://uuid/object_id
            if (pItem->m_bIsFolder) {
                pItem->SetPath(pItem->GetPath() + "/");

                // look for metadata
                if( ObjectClass.StartsWith("object.container.album.videoalbum") ) {
                    pItem->SetLabelPreformated(false);
                    CUPnP::PopulateTagFromObject(*pItem->GetVideoInfoTag(), *(*entry), NULL);

                } else if( ObjectClass.StartsWith("object.container.album.photoalbum")) {
                    //CPictureInfoTag* tag = pItem->GetPictureInfoTag();

                } else if( ObjectClass.StartsWith("object.container.album") ) {
                    pItem->SetLabelPreformated(false);
                    CUPnP::PopulateTagFromObject(*pItem->GetMusicInfoTag(), *(*entry), NULL);
                }

            } else {

                // set a general content type
                if (ObjectClass.StartsWith("object.item.videoitem"))
                    pItem->SetMimeType("video/octet-stream");
                else if(ObjectClass.StartsWith("object.item.audioitem"))
                    pItem->SetMimeType("audio/octet-stream");
                else if(ObjectClass.StartsWith("object.item.imageitem"))
                    pItem->SetMimeType("image/octet-stream");

                if ((*entry)->m_Resources.GetItemCount()) {
                    PLT_MediaItemResource& resource = (*entry)->m_Resources[0];

                    // set metadata
                    if (resource.m_Size != (NPT_LargeSize)-1) {
                        pItem->m_dwSize  = resource.m_Size;
                    }

                    // look for metadata
                    if( ObjectClass.StartsWith("object.item.videoitem") ) {
                        pItem->SetLabelPreformated(false);
                        CUPnP::PopulateTagFromObject(*pItem->GetVideoInfoTag(), *(*entry), &resource);

                    } else if( ObjectClass.StartsWith("object.item.audioitem") ) {
                        pItem->SetLabelPreformated(false);
                        CUPnP::PopulateTagFromObject(*pItem->GetMusicInfoTag(), *(*entry), &resource);

                    } else if( ObjectClass.StartsWith("object.item.imageitem") ) {
                        //CPictureInfoTag* tag = pItem->GetPictureInfoTag();

                    }
                }
            }

            // look for date?
            if((*entry)->m_Description.date.GetLength()) {
                SYSTEMTIME time = {};
                sscanf((*entry)->m_Description.date, "%hu-%hu-%huT%hu:%hu:%hu",
                       &time.wYear, &time.wMonth, &time.wDay, &time.wHour, &time.wMinute, &time.wSecond);
                pItem->m_dateTime = time;
            }

            // if there is a thumbnail available set it here
            if((*entry)->m_ExtraInfo.album_art_uri.GetLength())
                pItem->SetThumbnailImage((const char*) (*entry)->m_ExtraInfo.album_art_uri);
            else if((*entry)->m_Description.icon_uri.GetLength())
                pItem->SetThumbnailImage((const char*) (*entry)->m_Description.icon_uri);

            PLT_ProtocolInfo fanart_mask("xbmc.org", "*", "fanart", "*");
            for(unsigned i = 0; i < (*entry)->m_Resources.GetItemCount(); ++i) {
                PLT_MediaItemResource& res = (*entry)->m_Resources[i];
                if(res.m_ProtocolInfo.Match(fanart_mask)) {
                    pItem->SetProperty("fanart_image", (const char*)res.m_Uri);
                    break;
                }
            }
            items.Add(pItem);

            ++entry;
        }

        NPT_String max_string = "";
        int        max_count  = 0;
        for(std::map<NPT_String, int>::iterator it = classes.begin(); it != classes.end(); it++)
        {
            if(it->second > max_count)
            {
                max_string = it->first;
                max_count  = it->second;
            }
        }
        items.SetContent(GetContentMapping(max_string));
    }

cleanup:
    return true;

failure:
    return false;
}
Example #20
0
void BatchProcessing::ThreadHandler(void *args)
{
	SetThreadName("orka:batch");

	CStdString debug;
	CStdString logMsg;

	CStdString processorName("BatchProcessing");
	TapeProcessorRef batchProcessing = TapeProcessorRegistry::instance()->GetNewTapeProcessor(processorName);
	if(batchProcessing.get() == NULL)
	{
		LOG4CXX_ERROR(LOG.batchProcessingLog, "Could not instanciate BatchProcessing");
		return;
	}
	BatchProcessing* pBatchProcessing = (BatchProcessing*)(batchProcessing->Instanciate().get());

	pBatchProcessing->SetQueueSize(CONFIG.m_batchProcessingQueueSize);

	int threadId = 0;
	{
		MutexSentinel sentinel(pBatchProcessing->m_mutex);
		threadId = pBatchProcessing->m_threadCount++;
	}
	CStdString threadIdString = IntToString(threadId);
	debug.Format("thread Th%s starting - queue size:%d", threadIdString, CONFIG.m_batchProcessingQueueSize);
	LOG4CXX_INFO(LOG.batchProcessingLog, debug);

	bool stop = false;

	for(;stop == false;)
	{
		AudioFileRef fileRef;
		AudioFileRef outFileRef, outFileSecondaryRef;
		AudioTapeRef audioTapeRef;
		CStdString trackingId = "[no-trk]";

		try
		{
			audioTapeRef = pBatchProcessing->m_audioTapeQueue.pop();
			if(audioTapeRef.get() == NULL)
			{
				if(Daemon::Singleton()->IsStopping())
				{
					stop = true;
				}
				if(Daemon::Singleton()->GetShortLived())
				{
					Daemon::Singleton()->Stop();
				}
			}
			else
			{
				fileRef = audioTapeRef->GetAudioFileRef();
				trackingId = audioTapeRef->m_trackingId;

				audioTapeRef->m_audioOutputPath = CONFIG.m_audioOutputPath;

				// Let's work on the tape we have pulled
				//CStdString threadIdString = IntToString(threadId);
				LOG4CXX_INFO(LOG.batchProcessingLog, "[" + trackingId + "] Th" + threadIdString + " processing " + audioTapeRef->GetIdentifier() + " localside:" + CaptureEvent::LocalSideToString(audioTapeRef->m_localSide) + " audiokeepdirection:" + CaptureEvent::AudioKeepDirectionToString(audioTapeRef->m_audioKeepDirectionEnum));
				if(audioTapeRef->m_audioKeepDirectionEnum == CaptureEvent::AudioKeepDirectionInvalid)
				{
					LOG4CXX_WARN(LOG.batchProcessingLog, "[" + trackingId + 
						"] Th" + threadIdString + 
						" invalid audiokeepdirection:" + 
						IntToString(audioTapeRef->m_audioKeepDirectionEnum));
				}



				//fileRef->MoveOrig();	// #### could do this only when original and output file have the same extension. Irrelevant for now as everything is captured as mcf file
				fileRef->Open(AudioFile::READ);

				AudioChunkRef chunkRef;
				AudioChunkRef tmpChunkRef, tmpChunkSecondaryRef;
				unsigned int frameSleepCounter;

				frameSleepCounter = 0;

				switch(CONFIG.m_storageAudioFormat)
				{
				case FfUlaw:
					outFileRef.reset(new LibSndFileFile(SF_FORMAT_ULAW | SF_FORMAT_WAV));
					break;
				case FfAlaw:
					outFileRef.reset(new LibSndFileFile(SF_FORMAT_ALAW | SF_FORMAT_WAV));
					break;
				case FfGsm:
					outFileRef.reset(new LibSndFileFile(SF_FORMAT_GSM610 | SF_FORMAT_WAV));
					break;
				case FfPcmWav:
				default:
					outFileRef.reset(new LibSndFileFile(SF_FORMAT_PCM_16 | SF_FORMAT_WAV));
				}

				if(CONFIG.m_stereoRecording == true)
				{
					outFileRef->SetNumOutputChannels(2);
				}

				FilterRef rtpMixer, rtpMixerSecondary;
				FilterRef decoder1;
				FilterRef decoder2;
				FilterRef decoder;
				FilterRef audiogain;

				std::bitset<RTP_PAYLOAD_TYPE_MAX> seenRtpPayloadTypes;
				std::vector<FilterRef> decoders1;
				std::vector<FilterRef> decoders2;
				for(int pt=0; pt<RTP_PAYLOAD_TYPE_MAX; pt++)
				{
					decoder1 = FilterRegistry::instance()->GetNewFilter(pt);
					decoders1.push_back(decoder1);
					decoder2 = FilterRegistry::instance()->GetNewFilter(pt);
					decoders2.push_back(decoder2);
				}

				bool firstChunk = true;
				bool voIpSession = false;

				size_t numSamplesS1 = 0;
				size_t numSamplesS2 = 0;
				size_t numSamplesOut = 0;

				CStdString filterName("AudioGain");

				audiogain = FilterRegistry::instance()->GetNewFilter(filterName);
				if(audiogain.get() == NULL)
				{
					debug = "Could not instanciate AudioGain rtpMixer";
					throw(debug);
				}

				bool forceChannel1 = false;

				while(fileRef->ReadChunkMono(chunkRef))
				{
					// ############ HACK
					//ACE_Time_Value yield;
					//yield.set(0,1);
					//ACE_OS::sleep(yield);
					// ############ HACK

					AudioChunkDetails details = *chunkRef->GetDetails();
					int channelToSkip = 0;
					if(CONFIG.m_directionLookBack == true)					//if DirectionLookBack is not enable, DirectionSelector Tape should have taken care everything
					{
						if(BatchProcessing::SkipChunk(audioTapeRef, chunkRef, channelToSkip) == true)
						{
							LOG4CXX_DEBUG(LOG.batchProcessingLog, "[" + trackingId +
	                                                "] Th" + threadIdString +
	                                                " skipping chunk of channel:" +
							IntToString(details.m_channel));

							if(forceChannel1 == false)
							{
								if(channelToSkip == 1)
								{
									forceChannel1 = true;
								}
							}

							continue;
						}
					}

					if(forceChannel1 == true)
					{
						details.m_channel = 1;
						chunkRef->SetDetails(&details);
					}

					decoder.reset();

					if(details.m_rtpPayloadType < -1 || details.m_rtpPayloadType >= RTP_PAYLOAD_TYPE_MAX)
					{
						logMsg.Format("RTP payload type out of bound:%d", details.m_rtpPayloadType);
						LOG4CXX_DEBUG(LOG.batchProcessingLog, "[" + trackingId + "] Th" + threadIdString + " " + logMsg);
						continue;
					}

					// Instanciate any decoder we might need during a VoIP session
					if(details.m_rtpPayloadType != -1)
					{
						voIpSession = true;

						if(details.m_channel == 2)
						{
							decoder2 = decoders2.at(details.m_rtpPayloadType);
							decoder = decoder2;
						}
						else
						{
							decoder1 = decoders1.at(details.m_rtpPayloadType);
							decoder = decoder1;
						}

						bool ptAlreadySeen = seenRtpPayloadTypes.test(details.m_rtpPayloadType);
						seenRtpPayloadTypes.set(details.m_rtpPayloadType);

						if(decoder.get() == NULL)
						{
							if(ptAlreadySeen == false)
							{
								// First time we see a particular unsupported payload type in this session, log it
								CStdString rtpPayloadType = IntToString(details.m_rtpPayloadType);
								LOG4CXX_ERROR(LOG.batchProcessingLog, "[" + trackingId + "] Th" + threadIdString + " unsupported RTP payload type:" + rtpPayloadType);
							}
							// We cannot decode this chunk due to unknown codec, go to next chunk
							continue;
						}
						else if(ptAlreadySeen == false)
						{
							// First time we see a particular supported payload type in this session, log it
							CStdString rtpPayloadType = IntToString(details.m_rtpPayloadType);
							LOG4CXX_INFO(LOG.batchProcessingLog, "[" + trackingId + "] Th" + threadIdString + " RTP payload type:" + rtpPayloadType);
						}
					}
					if(!voIpSession || (firstChunk && decoder.get()))
					{
						firstChunk = false;

						// At this point, we know we have a working codec, create an RTP mixer and open the output file
						if(voIpSession)
						{
							CStdString filterName("RtpMixer");
							rtpMixer = FilterRegistry::instance()->GetNewFilter(filterName);
							if(rtpMixer.get() == NULL)
							{
								debug = "Could not instanciate RTP mixer";
								throw(debug);
							}
							if(CONFIG.m_stereoRecording == true)
							{
								rtpMixer->SetNumOutputChannels(2);
							}
							rtpMixer->SetSessionInfo(trackingId);

							//create another rtpmixer to store stereo audio
							if(CONFIG.m_audioOutputPathSecondary.length() > 3)
							{
								outFileSecondaryRef.reset(new LibSndFileFile(SF_FORMAT_PCM_16 | SF_FORMAT_WAV));
								outFileSecondaryRef->SetNumOutputChannels(2);
								rtpMixerSecondary = FilterRegistry::instance()->GetNewFilter(filterName);
								if(rtpMixerSecondary.get() == NULL)
								{
									debug = "Could not instanciate RTP mixer";
									throw(debug);
								}
								rtpMixerSecondary->SetNumOutputChannels(2);
								rtpMixerSecondary->SetSessionInfo(trackingId);

							}

						}

						CStdString path = audioTapeRef->m_audioOutputPath + "/" + audioTapeRef->GetPath();
						FileRecursiveMkdir(path, CONFIG.m_audioFilePermissions, CONFIG.m_audioFileOwner, CONFIG.m_audioFileGroup, audioTapeRef->m_audioOutputPath);

						CStdString file = path + "/" + audioTapeRef->GetIdentifier();
						outFileRef->Open(file, AudioFile::WRITE, false, fileRef->GetSampleRate());

						if(CONFIG.m_audioOutputPathSecondary.length() > 3)
						{
							path = CONFIG.m_audioOutputPathSecondary + "/" + audioTapeRef->GetPath();
							FileRecursiveMkdir(path, CONFIG.m_audioFilePermissions, CONFIG.m_audioFileOwner, CONFIG.m_audioFileGroup, CONFIG.m_audioOutputPathSecondary);
							CStdString storageFile = path + "/" + audioTapeRef->GetIdentifier();
							outFileSecondaryRef->Open(storageFile, AudioFile::WRITE, false, fileRef->GetSampleRate());
						}

					}
					if(voIpSession)
					{
						if(details.m_channel == 2)
						{
							decoder2->AudioChunkIn(chunkRef);
							decoder2->AudioChunkOut(tmpChunkRef);
							if(tmpChunkRef.get())
							{
								numSamplesS2 += tmpChunkRef->GetNumSamples();
							}

							if(rtpMixerSecondary.get() != NULL)
							{
								decoder2->AudioChunkOut(tmpChunkSecondaryRef);
							}
						}
						else
						{
							decoder1->AudioChunkIn(chunkRef);
							decoder1->AudioChunkOut(tmpChunkRef);
							if(tmpChunkRef.get())
							{
								numSamplesS1 += tmpChunkRef->GetNumSamples();
							}

							if(rtpMixerSecondary.get() != NULL)
							{
								decoder1->AudioChunkOut(tmpChunkSecondaryRef);
							}
						}

						audiogain->AudioChunkIn(tmpChunkRef);
						audiogain->AudioChunkOut(tmpChunkRef);
						rtpMixer->AudioChunkIn(tmpChunkRef);
						rtpMixer->AudioChunkOut(tmpChunkRef);
						if(rtpMixerSecondary.get() != NULL)
						{
							rtpMixerSecondary->AudioChunkIn(tmpChunkSecondaryRef);
							rtpMixerSecondary->AudioChunkOut(tmpChunkSecondaryRef);
						}

					} else {
						audiogain->AudioChunkIn(tmpChunkRef);
						audiogain->AudioChunkOut(tmpChunkRef);
					}

					outFileRef->WriteChunk(tmpChunkRef);
					if(rtpMixerSecondary.get() != NULL)
					{
						outFileSecondaryRef->WriteChunk(tmpChunkSecondaryRef);
					}

					if(tmpChunkRef.get())
					{
						numSamplesOut += tmpChunkRef->GetNumSamples();
					}

					if(CONFIG.m_batchProcessingEnhancePriority == false)
					{
						// Give up CPU between every audio buffer to make sure the actual recording always has priority
						//ACE_Time_Value yield;
						//yield.set(0,1);	// 1 us
						//ACE_OS::sleep(yield);

						// Use this instead, even if it still seems this holds the whole process under Linux instead of this thread only.
						struct timespec ts;
						ts.tv_sec = 0;
						ts.tv_nsec = 1;
						ACE_OS::nanosleep (&ts, NULL);
					}
					
					if(CONFIG.m_transcodingSleepEveryNumFrames > 0 && CONFIG.m_transcodingSleepUs > 0)
					{
						if(frameSleepCounter >= (unsigned int)CONFIG.m_transcodingSleepEveryNumFrames)
						{
							frameSleepCounter = 0;
							struct timespec ts;
							ts.tv_sec = 0;
							ts.tv_nsec = CONFIG.m_transcodingSleepUs*1000;
							ACE_OS::nanosleep (&ts, NULL);
						}
						else
						{
							frameSleepCounter += 1;
						}
					}
				}

				if(voIpSession && !firstChunk)
				{
					// Flush the RTP mixer
					AudioChunkRef stopChunk(new AudioChunk());
					stopChunk->GetDetails()->m_marker = MEDIA_CHUNK_EOS_MARKER;
					rtpMixer->AudioChunkIn(stopChunk);
					rtpMixer->AudioChunkOut(tmpChunkRef);
					if(rtpMixerSecondary.get() != NULL)
					{
						rtpMixerSecondary->AudioChunkOut(tmpChunkSecondaryRef);
					}

					while(tmpChunkRef.get())
					{
						outFileRef->WriteChunk(tmpChunkRef);
						numSamplesOut += tmpChunkRef->GetNumSamples();
						rtpMixer->AudioChunkOut(tmpChunkRef);
					}
					while(tmpChunkSecondaryRef.get())
					{
						outFileSecondaryRef->WriteChunk(tmpChunkSecondaryRef);
						rtpMixerSecondary->AudioChunkOut(tmpChunkSecondaryRef);
					}
				}

				fileRef->Close();
				outFileRef->Close();
				if(rtpMixerSecondary.get() != NULL)
				{
					outFileSecondaryRef->Close();
				}
				logMsg.Format("[%s] Th%s stop: num samples: s1:%u s2:%u out:%u queueSize:%d", trackingId, threadIdString, numSamplesS1, numSamplesS2, numSamplesOut, pBatchProcessing->m_audioTapeQueue.numElements());
				LOG4CXX_INFO(LOG.batchProcessingLog, logMsg);

				CStdString audioFilePath = audioTapeRef->m_audioOutputPath + "/" + audioTapeRef->GetPath();
				CStdString audioFileName;
				CStdString storageFilePath, storageFileName;
				if(CONFIG.m_audioOutputPathSecondary.length() > 3)
				{
					storageFilePath = CONFIG.m_audioOutputPathSecondary + "/" + audioTapeRef->GetPath();
					storageFileName = storageFilePath + "/" + audioTapeRef->GetIdentifier() + outFileRef->GetExtension();
				}

				audioFileName = audioFilePath + "/" + audioTapeRef->GetIdentifier() + outFileRef->GetExtension();
				if(CONFIG.m_audioFilePermissions) {
					if(FileSetPermissions(audioFileName, CONFIG.m_audioFilePermissions))
					{
						CStdString logMsg;

						logMsg.Format("Error setting permissions of %s to %o: %s", audioFileName.c_str(), CONFIG.m_audioFilePermissions, strerror(errno));
						LOG4CXX_ERROR(LOG.batchProcessingLog, "[" + trackingId + "] Th" + threadIdString + " " + logMsg);
					}
					if(storageFileName.length() > 5)
					{
						if(FileSetPermissions(storageFileName, CONFIG.m_audioFilePermissions))
						{
							CStdString logMsg;
							logMsg.Format("Error setting permissions of %s to %o: %s", storageFileName.c_str(), CONFIG.m_audioFilePermissions, strerror(errno));
							LOG4CXX_ERROR(LOG.batchProcessingLog, "[" + trackingId + "] Th" + threadIdString + " " + logMsg);
						}
					}
				}

				if(CONFIG.m_audioFileGroup.size() && CONFIG.m_audioFileOwner.size()) {
					if(FileSetOwnership(audioFileName, CONFIG.m_audioFileOwner, CONFIG.m_audioFileGroup))
					{
						logMsg.Format("Error setting ownership and group of %s to %s:%s: %s", audioFileName.c_str(), CONFIG.m_audioFileOwner, CONFIG.m_audioFileGroup, strerror(errno));
						LOG4CXX_ERROR(LOG.batchProcessingLog, "[" + trackingId + "] Th" + threadIdString + " " + logMsg);
					}
					if(storageFileName.length() > 5)
					{
						if(FileSetOwnership(storageFileName, CONFIG.m_audioFileOwner, CONFIG.m_audioFileGroup))
						{
							logMsg.Format("Error setting ownership and group of %s to %s:%s: %s", storageFileName.c_str(), CONFIG.m_audioFileOwner, CONFIG.m_audioFileGroup, strerror(errno));
							LOG4CXX_ERROR(LOG.batchProcessingLog, "[" + trackingId + "] Th" + threadIdString + " " + logMsg);
						}
					}
				}
				
				if(CONFIG.m_deleteNativeFile && numSamplesOut)
				{
					fileRef->Delete();
					LOG4CXX_INFO(LOG.batchProcessingLog, "[" + trackingId + "] Th" + threadIdString + " deleting native: " + audioTapeRef->GetIdentifier());
				}
				else if(CONFIG.m_deleteFailedCaptureFile)
				{
					fileRef->Delete();
					if(outFileRef.get()) 
					{
						outFileRef->Close();
						outFileRef->Delete();
					}
					LOG4CXX_INFO(LOG.batchProcessingLog, "[" + trackingId + "] Th" + threadIdString + " deleting native that could not be transcoded: " + audioTapeRef->GetIdentifier());
				}

				// Finished processing the tape, pass on to next processor
				if(numSamplesOut)
				{
					pBatchProcessing->RunNextProcessor(audioTapeRef);
				}
			}
		}
		catch (CStdString& e)
		{
			LOG4CXX_ERROR(LOG.batchProcessingLog, "[" + trackingId + "] Th" + threadIdString + " " + e);
			if(fileRef.get()) {fileRef->Close();}
			if(outFileRef.get()) {outFileRef->Close();}
			if(CONFIG.m_deleteFailedCaptureFile && fileRef.get() != NULL)
			{
				LOG4CXX_INFO(LOG.batchProcessingLog, "[" + trackingId + "] Th" + threadIdString + " deleting native and transcoded");
				if(fileRef.get()) {fileRef->Delete();}
				if(outFileRef.get()) {outFileRef->Delete();}
			}
		}
		//catch(...)
		//{
		//	LOG4CXX_ERROR(LOG.batchProcessingLog, CStdString("unknown exception"));
		//}
	}
	LOG4CXX_INFO(LOG.batchProcessingLog, CStdString("Exiting thread Th" + threadIdString));
}
Example #21
0
CStdString PauseMsg::GetClassName()
{
	return  CStdString(PAUSE_CLASS);
}
Example #22
0
HRESULT InputFileData::MapFileToMemory()
{
	CMemoryMappedFile* pMapFile = new CMemoryMappedFile();
	HRESULT hr = pMapFile->OpenRead(m_sFileName);
	if (FAILED(hr))
	{
		delete pMapFile;
		CStdStringW sTempCopy = CGeneral::GetTemporaryFileName();
		if (!CopyFileW(m_sFileName, sTempCopy, FALSE))
		{
			DWORD dwErr = GetLastError();
			CStdString sMsg;
			sMsg.Format(_T("The specified file (%s) could not be mapped to memory or copied. Error code %d"), CStdString(m_sFileName).c_str(), dwErr);
			LOG_WS_ERROR(sMsg);
			return E_FAIL;
		}
		pMapFile = new CMemoryMappedFile();
		hr = pMapFile->OpenRead(sTempCopy);
		if (FAILED(hr))
		{
			delete pMapFile;
			DWORD dwErr = GetLastError();
			CStdString sMsg;
			sMsg.Format(_T("The specified file (%s) was copied but the copy could not be mapped to memory. Error code %d"), CStdString(m_sFileName).c_str(), dwErr);
			LOG_WS_ERROR(sMsg);
			return hr;
		}
	}
	m_pBufferAsStream = pMapFile;
	m_pBuffer = m_pBufferAsStream->GetBase();
	m_iCharCount = m_pBufferAsStream->GetSize();

	m_bReadyToRead = true;
	ASSERT(m_pBuffer!=NULL);
	return S_OK;
}
Example #23
0
void VoIpConfig::Reset() {
	// Standard LAN internal IP range masks 
	m_asciiLanMasks.push_back("192.168.255.255");
	m_asciiLanMasks.push_back("10.255.255.255");
	m_asciiLanMasks.push_back("172.31.255.255");
	
	m_sipDropIndirectInvite = false;
	m_pcapRepeat = false;
	m_pcapSocketBufferSize = 67108864;
	m_pcapFastReplay = true;
	m_pcapFastReplaySleepUsPerSec = 0;
	m_rtpSessionTimeoutSec = 10;
	m_rtpSessionWithSignallingTimeoutSec = 10;
	m_rtpSessionWithSignallingInitialTimeoutSec = 5*60;
	m_rtpSessionOnHoldTimeOutSec = 1800;
	m_rtpReportDtmf = false;
	m_rtpTrackByUdpPortOnly = false;
	m_rtpAllowMultipleMappings = true;
	m_rtpSeqGapThreshold = 500;
	m_pcapTest= false;
	m_rtpDiscontinuityDetect = false;
	m_rtpDiscontinuityMinSeqDelta = 1000;
	m_iax2Support = false; // Disabled by default
	m_iax2TreatCallerIdNameAsXUniqueId = true;
	m_rtpDetectOnOddPorts = true;
	m_sipOverTcpSupport = true;
	m_sipLogFailedCalls = false;
	m_sipUse200OkMediaAddress = true;
	m_sipDetectSessionProgress = true; // Enabled by default
	m_sipReportFullAddress = false;
	m_sipDynamicMediaAddress = true;
	m_sipIgnoreBye = false;
	m_sipNotifySupport = false;
	m_sipReportNamesAsTags = false;
	m_sipRequestUriAsLocalParty = true;
	m_sipTreat200OkAsInvite = true;
	m_sipAllowMultipleMediaAddresses = false;	// deprecated
	m_sip302MovedTemporarilySupport = false;
	m_sipInviteCanPutOffHold = false;
	m_sipCallPickUpSupport = false;
	m_sipOnDemandFieldName = "X-record";
	m_sipDialedNumberFieldName = "";
	m_sipRemotePartyFieldName = "";
	m_sipGroupPickUpPattern = "";
	m_sipOnDemandFieldValue = "";
	m_sipOnDemandFieldValueOff = "";
	m_sipTrackMediaAddressOnSender = false;
	m_sipAllowMetadataUpdateOnRtpChange = false;
	m_sipAllowMediaAddressTransfer = false;

	m_rtcpDetect = false;
	m_inInMode = false;

	m_useMacIfNoLocalParty = false; // Uses IP address by default
	m_localPartyForceLocalIp = false;
	m_localPartyForceLocalMac = false;
	m_localPartyUseName = false;
	m_partiesUseName = false;

	m_skinnyIgnoreStopMediaTransmission = true;
	m_skinnyIgnoreOpenReceiveChannelAck = false;
	m_skinnyDynamicMediaAddress = true;
	m_skinnyAllowCallInfoUpdate = true;
	m_skinnyAllowLateCallInfo = false;
	m_skinnyNameAsLocalParty = false;
	m_skinnyCallInfoStopsPrevious = false;
	m_skinnyCallInfoStopsPreviousToleranceSec = 3;
	m_cucm7_1Mode = true;
	m_skinnyAllowMediaAddressTransfer = true;
	m_skinnyRtpSearchesForCallInfo = false;
	m_SkinnyTrackConferencesTransfers = false;
	m_skinnyBehindNat = false;
	m_skinnyIgnoreHold = false;

	m_sangomaEnable = false;
	m_sangomaRxTcpPortStart = 0;
	m_sangomaTxTcpPortStart = 0;
	m_skinnyTcpPort = 2000;

	// Initialize LAN IP ranges to standard values.
	m_lanIpRanges.m_asciiIpRanges.push_back(CStdString("10.0.0.0/8"));
	m_lanIpRanges.m_asciiIpRanges.push_back(CStdString("192.168.0.0/16"));
	m_lanIpRanges.m_asciiIpRanges.push_back(CStdString("172.16.0.0/20"));
	m_lanIpRanges.Compute();

	m_dahdiIntercept = false;
	m_holdReportStats = false;
	m_Iax2RewriteTimestamps = false;
	m_trackRawRtpSessionInNonLookBackMode = false;

	m_urlExtractorEnable = false;
	m_urlExtractorPort = 9080;
	m_urlExtractorEndpointIsSender =  true;
	m_rtpMinAmountOfPacketsBeforeStart = 50;
	m_rtpBreakupOnStreamPause = false;
	m_rtpS1S2MappingDeterministic = false;
	m_localPartyAddLocalIp = false;
	m_rtpLogAllSsrc = false;
	m_orekaEncapsulationMode = false;
	m_orekaEncapsulationPort = 10002;
	m_sipInfoDtmfRfc2976Detect = false;
	m_mediaAddressUseSecondRtpAddress = false;
	m_transferTimeOutInSec = 7200;
	m_rtpDtmfOnlyLocal = false;
	m_udpMinPort = 1024;
	m_localPartyNameMapEnable = false;
	m_ipFragmentsReassemble = false;
	m_rtpS1S2MappingDeterministicS1IsLocal = true;
	m_necNotifyDispLine = "Ind-DispLineN=3:Dsp:";

	m_necVoipGatewayNames.push_back("sipphd");
	m_necVoipGatewayNames.push_back("trk001");
	m_necVoipGatewayNames.push_back("trk002");

	m_sipMetadataUseLastInvite = false;

	m_necOnHoldMarker = "ffffff95ffffffdbffffff97ffffffaf"; 
	m_necOffHoldMarker = "ffffff89ffffff9effffff93ffffff9a"; 
	m_mtuMaxSize = 18000;
	m_sipLocalPartyFieldName = "x-Local-Extension:";
}
Example #24
0
HANDLE FindFirstFile(LPCSTR szPath,LPWIN32_FIND_DATA lpFindData)
{
  if (lpFindData == NULL || szPath == NULL)
    return NULL;

  CStdString strPath(szPath);

  if (IsAliasShortcut(strPath))
    TranslateAliasShortcut(strPath);

  if (strPath.empty())
    return INVALID_HANDLE_VALUE;

  strPath.Replace("\\","/");

  // if the file name is a directory then we add a * to look for all files in this directory
#if defined(__APPLE__) || defined(__FreeBSD__)
  DIR *testDir = opendir(strPath.c_str());
#else
  DIR *testDir = opendir(szPath);
#endif
  if (testDir)
  {
    strPath += "/*";
    closedir(testDir);
  }

  int nFilePos = strPath.ReverseFind(XBMC_FILE_SEP);

  CStdString strDir = ".";
  CStdString strFiles = strPath;

  if (nFilePos > 0)
  {
    strDir = strPath.substr(0,nFilePos);
    strFiles = strPath.substr(nFilePos + 1);
  }

  if (strFiles == "*.*")
     strFiles = "*";

  strFiles = CStdString("^") + strFiles + "$";
  strFiles.Replace(".","\\.");
  strFiles.Replace("*",".*");
  strFiles.Replace("?",".");

  strFiles.MakeLower();  // Do we really want this case insensitive?
  CRegExp re(true);

  if (re.RegComp(strFiles.c_str()) == NULL)
    return(INVALID_HANDLE_VALUE);

  struct dirent **namelist = NULL;
  int n = scandir(strDir, &namelist, 0, alphasort);

  CXHandle *pHandle = new CXHandle(CXHandle::HND_FIND_FILE);
    pHandle->m_FindFileDir = strDir;

  while (n-- > 0)
  {
    CStdString strComp(namelist[n]->d_name);
    strComp.MakeLower();

    if (re.RegFind(strComp.c_str()) >= 0)
      pHandle->m_FindFileResults.push_back(namelist[n]->d_name);
    free(namelist[n]);
  }
  free(namelist);

  if (pHandle->m_FindFileResults.size() == 0)
  {
    delete pHandle;
    return INVALID_HANDLE_VALUE;
  }

  FindNextFile(pHandle, lpFindData);

  return pHandle;
}
Example #25
0
CStdString StopMsg::GetClassName()
{
	return  CStdString(STOP_CLASS);
}
void CGUIWindowDebugInfo::Process(unsigned int currentTime, CDirtyRegionList &dirtyregions)
{
  g_graphicsContext.SetRenderingResolution(g_graphicsContext.GetResInfo(), false);

  g_cpuInfo.getUsedPercentage(); // must call it to recalculate pct values

  static int yShift = 20;
  static int xShift = 40;
  static unsigned int lastShift = time(NULL);
  time_t now = time(NULL);
  if (now - lastShift > 10)
  {
    yShift *= -1;
    if (now % 5 == 0)
      xShift *= -1;
    lastShift = now;
    MarkDirtyRegion();
  }

  if (!m_layout)
  {
    CGUIFont *font13 = g_fontManager.GetDefaultFont();
    CGUIFont *font13border = g_fontManager.GetDefaultFont(true);
    if (font13)
      m_layout = new CGUITextLayout(font13, true, 0, font13border);
  }
  if (!m_layout)
    return;

  CStdString info;
  if (LOG_LEVEL_DEBUG_FREEMEM <= g_advancedSettings.m_logLevel)
  {
    MEMORYSTATUSEX stat;
    stat.dwLength = sizeof(MEMORYSTATUSEX);
    GlobalMemoryStatusEx(&stat);
    CStdString profiling = CGUIControlProfiler::IsRunning() ? " (profiling)" : "";
    CStdString strCores = g_cpuInfo.GetCoresUsageString();
#if !defined(_LINUX)
    info.Format("LOG: %sxbmc.log\nMEM: %"PRIu64"/%"PRIu64" KB - FPS: %2.1f fps\nCPU: %s%s", g_settings.m_logFolder.c_str(),
                stat.ullAvailPhys/1024, stat.ullTotalPhys/1024, g_infoManager.GetFPS(), strCores.c_str(), profiling.c_str());
#else
    double dCPU = m_resourceCounter.GetCPUUsage();
    info.Format("LOG: %sxbmc.log\nMEM: %"PRIu64"/%"PRIu64" KB - FPS: %2.1f fps\nCPU: %s (CPU-XBMC %4.2f%%%s)", g_settings.m_logFolder.c_str(),
                stat.ullAvailPhys/1024, stat.ullTotalPhys/1024, g_infoManager.GetFPS(), strCores.c_str(), dCPU, profiling.c_str());
#endif
  }

  // render the skin debug info
  if (g_SkinInfo->IsDebugging())
  {
    if (!info.IsEmpty())
      info += "\n";
    CGUIWindow *window = g_windowManager.GetWindow(g_windowManager.GetFocusedWindow());
    CGUIWindow *pointer = g_windowManager.GetWindow(WINDOW_DIALOG_POINTER);
    CPoint point;
    if (pointer)
      point = CPoint(pointer->GetXPosition(), pointer->GetYPosition());
    if (window)
    {
      CStdString windowName = CButtonTranslator::TranslateWindow(window->GetID());
      if (!windowName.IsEmpty())
        windowName += " (" + CStdString(window->GetProperty("xmlfile").asString()) + ")";
      else
        windowName = window->GetProperty("xmlfile").asString();
      info += "Window: " + windowName + "  ";
      // transform the mouse coordinates to this window's coordinates
      g_graphicsContext.SetScalingResolution(window->GetCoordsRes(), true);
      point.x *= g_graphicsContext.GetGUIScaleX();
      point.y *= g_graphicsContext.GetGUIScaleY();
      g_graphicsContext.SetRenderingResolution(g_graphicsContext.GetResInfo(), false);
    }
    info.AppendFormat("Mouse: (%d,%d)  ", (int)point.x, (int)point.y);
    if (window)
    {
      CGUIControl *control = window->GetFocusedControl();
      if (control)
        info.AppendFormat("Focused: %i (%s)", control->GetID(), CGUIControlFactory::TranslateControlType(control->GetControlType()).c_str());
    }
  }

  float w, h;
  if (m_layout->Update(info))
    MarkDirtyRegion();
  m_layout->GetTextExtent(w, h);

  float x = xShift + 0.04f * g_graphicsContext.GetWidth();
  float y = yShift + 0.04f * g_graphicsContext.GetHeight();
  m_renderRegion.SetRect(x, y, x+w, y+h);
}
Example #27
0
void VoIpConfig::Validate()
{
	// iterate over ascii LAN masks and populate the binary LAN Masks list
	m_lanMasks.clear();
	std::list<CStdString>::iterator it;
	for(it = m_asciiLanMasks.begin(); it != m_asciiLanMasks.end(); it++)
	{
		struct in_addr a;
		if(ACE_OS::inet_aton((PCSTR)*it, &a))
		{
			m_lanMasks.push_back((unsigned int)a.s_addr);
		}
		else
		{
			throw (CStdString("VoIpConfig: invalid IP address in LanMasks:" + *it));
		}
	}

	// iterate over ascii Media gateway IP addresses and populate the binary Media gateway IP addresses list
	m_mediaGateways.clear();
	for(it = m_asciiMediaGateways.begin(); it != m_asciiMediaGateways.end(); it++)
	{
		struct in_addr a;
		if(ACE_OS::inet_aton((PCSTR)*it, &a))
		{
			m_mediaGateways.push_back((unsigned int)a.s_addr);
		}
		else
		{
			throw (CStdString("VoIpConfig: invalid IP address in MediaGateways:" + *it));
		}
	}

	// iterate over ascii RTP tracking IP addresses and populate the binary IP addresses list
	m_rtpTrackUsingIpAddresses.clear();
	for(it = m_asciiRtpTrackUsingIpAddresses.begin(); it != m_asciiRtpTrackUsingIpAddresses.end(); it++)
	{
		struct in_addr a;
		if(ACE_OS::inet_aton((PCSTR)*it, &a))
		{
			m_rtpTrackUsingIpAddresses.push_back((unsigned int)a.s_addr);
		}
		else
		{
			throw (CStdString("VoIpConfig: invalid IP address in RtpTrackUsingIpAddresses:" + *it));
		}
	}

	// Iterate over ascii allowed IP ranges and populate the bit width and prefix lists
	m_allowedIpRangePrefixes.clear();
	m_allowedIpRangeBitWidths.clear();
	for(it = m_asciiAllowedIpRanges.begin(); it != m_asciiAllowedIpRanges.end(); it++)
	{
		CStdString cidrPrefixLengthString;
		unsigned int cidrPrefixLength = 32;		// by default, x.x.x.x/32
		CStdString cidrIpAddressString;
		struct in_addr cidrIpAddress;
		
		CStdString entry = *it;
		int slashPosition = entry.Find('/');
		if(slashPosition > 0)
		{
			cidrIpAddressString = entry.Left(slashPosition);
			cidrPrefixLengthString = entry.Mid(slashPosition+1);

			bool notAnInt = false;
			try
			{
				cidrPrefixLength = StringToInt(cidrPrefixLengthString);
			}
			catch (...) {notAnInt = true;}
			if(cidrPrefixLength < 1 || cidrPrefixLength > 32 || notAnInt)
			{
				throw (CStdString("VoIpConfig: invalid CIDR prefix length in AllowedIpRanges:" + entry));
			}
		}
		else
		{
			cidrIpAddressString = entry;
		}

		if(ACE_OS::inet_aton((PCSTR)cidrIpAddressString, &cidrIpAddress))
		{
			unsigned int rangeBitWidth = 32-cidrPrefixLength;
			unsigned int prefix = ntohl((unsigned int)cidrIpAddress.s_addr) >> (rangeBitWidth);
			m_allowedIpRangePrefixes.push_back(prefix);
			m_allowedIpRangeBitWidths.push_back(rangeBitWidth);
		}
		else
		{
			throw (CStdString("VoIpConfig: invalid IP range in AllowedIpRanges:" + entry));
Example #28
0
HANDLE FindFirstFile(LPCSTR szPath,LPWIN32_FIND_DATA lpFindData) {
  if (lpFindData == NULL || szPath == NULL)
    return NULL;

  CStdString strPath(szPath);

  if (strPath.empty())
    return INVALID_HANDLE_VALUE;

   strPath.Replace("\\","/");

  // if the file name is a directory then we add a * to look for all files in this directory
  DIR *testDir = opendir(szPath);
  if (testDir) {
    strPath += "/*";
    closedir(testDir);
  }

  int nFilePos = strPath.ReverseFind(XBMC_FILE_SEP);

  CStdString strDir = ".";
  CStdString strFiles = strPath;

  if (nFilePos > 0) {
    strDir = strPath.substr(0,nFilePos);
    strFiles = strPath.substr(nFilePos + 1);
  }

        if (strFiles == "*.*")
           strFiles = "*";

  strFiles = CStdString("^") + strFiles + "$";
  strFiles.Replace(".","\\.");
  strFiles.Replace("*",".*");
  strFiles.Replace("?",".");

  strFiles.MakeLower();

  int status;
  regex_t re;
  if (regcomp(&re, strFiles, REG_EXTENDED|REG_NOSUB) != 0) {
    return(INVALID_HANDLE_VALUE);
  }

  struct dirent **namelist = NULL;
  int n = scandir(strDir, &namelist, 0, alphasort);

  CXHandle *pHandle = new CXHandle(CXHandle::HND_FIND_FILE);
    pHandle->m_FindFileDir = strDir;

  while (n-- > 0) {
    CStdString strComp(namelist[n]->d_name);
    strComp.MakeLower();

    status = regexec(&re, strComp.c_str(), (size_t) 0, NULL, 0);
    if (status == 0) {
      pHandle->m_FindFileResults.push_back(namelist[n]->d_name);
    }
    free(namelist[n]);
  }

  if (namelist)
    free(namelist);

  regfree(&re);

  if (pHandle->m_FindFileResults.size() == 0) {
    delete pHandle;
    return INVALID_HANDLE_VALUE;
  }

  FindNextFile(pHandle, lpFindData);

  return pHandle;
}
Example #29
0
CStdString CZeroconfBrowser::ZeroconfService::toPath(const ZeroconfService& fcr_service)
{
  return CStdString(fcr_service.m_type + "@" + fcr_service.m_domain + "@" + fcr_service.m_name);
}
Example #30
0
CStdString GetIPV6ShortForm(const CStdString& ip)
{
	// This could be optimized a lot.

	// First get the long form in a well-known format
	CStdString l = GetIPV6LongForm(ip);
	if (l.IsEmpty())
		return CStdString();

	LPCTSTR p = l;

	TCHAR outbuf[42];
	*outbuf = ':';
	TCHAR* out = outbuf + 1;

	bool segmentStart = true;
	bool readLeadingZero = false;
	while (*p)
	{
		switch (*p)
		{
		case ':':
			if (readLeadingZero)
				*(out++) = '0';
			*out++ = ':';
			readLeadingZero = false;
			segmentStart = true;
			break;
		case '0':
			if (segmentStart)
				readLeadingZero = true;
			else
			{
				*out++ = '0';
				readLeadingZero = false;
			}
			break;
		default:
			readLeadingZero = false;
			segmentStart = false;
			*out++ = *p;
			break;
		}

		++p;
	}
	*(out++) = ':';
	*out = 0;

	// Replace longest run of consecutive zeroes
	CStdString shortIp(outbuf);

	CStdString s = _T(":0:0:0:0:0:0:0:0:");
	while (s.GetLength() > 2)
	{
		int pos = shortIp.Find(s);
		if (pos != -1)
		{
			shortIp = shortIp.Left( pos + 1 ) + shortIp.Mid(pos + s.GetLength() -1);
			break;
		}

		s = s.Mid(2);
	}
	shortIp.Replace(_T(":::"), _T("::"));
	if (shortIp[0] == ':' && shortIp[1] != ':')
		shortIp = shortIp.Mid(1);
	if (shortIp.GetLength() >= 2 && shortIp[shortIp.GetLength()-1] == ':' && shortIp[shortIp.GetLength()-2] != ':')
		shortIp = shortIp.Left(shortIp.GetLength()-1);

	return shortIp;
}