void Session::pause( const RTSP::PlayRequest & rq ) throw() { OwnThread::Lock lk( _th ); if ( _status.bag[ Status::STOPPED ] ) { Log::warning( "%s: session is stopped", getLogName() ); } else if ( _status.bag[ Status::PAUSED ] ) { Log::warning( "%s: already paused", getLogName() ); } else { _status.bag[ Status::PAUSED ] = true; _frame.time->pause( rq.time ); Log::message( "%s: start pause at media time %lf", getLogName(), _frame.time->getPresentationTime() ); this->logTimes(); _pause.sync = true; { OwnThread::UnLock ulk( lk ); _th.interrupt(); _pause.asleep.wait(); } Log::debug( "%s: effectively paused", getLogName() ); } }
void Session::teardown( const RTSP::PlayRequest & rq ) throw() { OwnThread::Lock lk(_th); Log::debug( "%s: tearing down", getLogName() ); if ( !_status.bag[ Status::STOPPED ] ) { _status.bag[ Status::STOPPED ] = true; if ( _status.bag[ Status::PAUSED ] ) { Log::verbose( "%s: awaking paused send loop", getLogName() ); _status.bag[ Status::PAUSED ] = false; { OwnThread::UnLock ulk( lk ); _pause.wakeup.notify_all(); } } _frame.buf->stop(); } if ( _th ) { Log::verbose( "%s: waiting loop termination", getLogName() ); OwnThread::UnLock ulk( lk ); _th.reset(); Log::verbose( "%s: loop joined terminate", getLogName() ); } _frame.time->stop( rq.time ); this->logTimes(); Log::debug( "%s: teardown completed", getLogName() ); }
void Container::mediaContainerLoop( AVFormatContext *fctx ) { { OwnThread::Lock lk( _th ); double storedFramesDuration = 0; bool live = this->isLiveCast(); while( _th.running ) { AVPacket pkt; av_init_packet( &pkt ); // load frame int rdRes = av_read_frame( fctx, &pkt ); // err if ( rdRes < 0 ) { // break cycle if ( rdRes == AVERROR_EOF ) _th.running = false; else Log::warning( "%s: av_read_frame error %d", getLogName(), rdRes ); } else { MediaMap::iterator medium = _media.find( pkt.stream_index ); if ( medium != _media.end() && pkt.size > 0 ) { Medium::Base & m = *medium->second; Frame::MediaFile * f = new Frame::MediaFile( pkt, m.getTimeBase() ); m.addFrame( f ); if (live) storedFramesDuration = m.getStoredDuration(); } else Log::warning( "%s: skipping frame stream %d sz %d", getLogName(), pkt.stream_index, pkt.size ); } av_free_packet( &pkt ); // suspend if (storedFramesDuration > Container::SIZE_FULL) { _th.requestMore.wait( lk ); Log::debug("%s: more frames requested", getLogName()); } else _th.yield( lk ); } // finalize sizes BOOST_FOREACH( MediaMap::iterator::reference medium, _media ) medium->second->finalizeFrameCount(); } av_close_input_file( fctx ); // sync termination Log::verbose( "%s: sync loop termination", getLogName() ); _th.wait(); }
/*! *\~english * Inits log system. *\~russian * Инициализирует систему логирования. Выполняется один раз при запуске програмы, если параметры не указаны, осуществляется попытка прочитать из из конфигурационного файла. Если это не удается, используются параметры по умолчанию. *\~ * \param log_name - \~english logfile name. Default ~/.ananas.ananas.log \~russian Путь к логу. Значение по умолчанию ~/.ananas/ananas.log \~ * \param status - \~english showing status \~russian статус скрытия сообщений. Все сообщения, имеющие больший статус, не попадут в лог ( ERROR= 0, INFO= 1, DEBUG= 2 ). Значение по умолчанию DEBUG \~ */ void aLog::init(const QString &log_name, int show_up) { bool ok; QString log; if(log_name =="" || logName==QString::null) { log = aService::readConfigVariable("log", &ok); if(!ok) log = QDir::homeDirPath()+"/.ananas/ananas.log"; } else { log = log_name; } aLog::logLevel = show_up; const QString logLev = aService::readConfigVariable("logLevel", &ok); if(logLev=="ERROR") aLog::logLevel = aLog::Error; if(logLev=="INFO") aLog::logLevel = aLog::Info; if(logLev=="DEBUG") aLog::logLevel = aLog::Debug; aLog::logName = log; if (aLog::f.isOpen()) f.close(); aLog::f.setName(getLogName()); aLog::f.open( IO_WriteOnly | IO_Append ); }
/* * SpyLogOpen - open the log file */ BOOL SpyLogOpen( void ) { int f; WORD flags; FARPROC fp; INT_PTR ret; char *msgtitle; flags = 0; if( !LogCurInfo.init ) { SetLogDef(); } if( LogCurInfo.config.query_for_name ) { if( !getLogName( LogCurInfo.config.name, LogCurInfo.hwnd ) ) { return( FALSE ); } } strcpy( LogCurInfo.config.curname, LogCurInfo.config.name ); switch( LogCurInfo.config.def_action ) { case LOG_ACTION_TRUNC: flags = O_TRUNC; break; case LOG_ACTION_APPEND: flags = O_APPEND; break; case LOG_ACTION_QUERY: if( !access( LogCurInfo.config.curname, F_OK ) ) { fp = MakeDlgProcInstance( LogExistsDlgProc, LogCurInfo.instance ); ret = DialogBox( LogCurInfo.instance, "LOG_EXISTS_DLG", LogCurInfo.hwnd, (DLGPROC)fp ); FreeProcInstance( fp ); switch( ret ) { case LOG_APPEND: flags = O_APPEND; break; case LOG_REPLACE: flags = O_TRUNC; break; case LOG_CANCEL: return( FALSE ); } } break; } f = open( LogCurInfo.config.curname, O_TEXT | O_WRONLY | O_CREAT | flags, S_IREAD | S_IWRITE ); if( f < 0 ) { msgtitle = AllocRCString( LOG_LOG_ERROR ); RCMessageBox( LogCurInfo.hwnd, LOG_CANT_OPEN_LOG, msgtitle, MB_OK | MB_ICONEXCLAMATION ); FreeRCString( msgtitle ); return( FALSE ); } if( LogCurInfo.writefn != NULL ) { LogCurInfo.writefn( f ); } close( f ); LogCurInfo.config.logging = TRUE; LogCurInfo.config.paused = FALSE; return( TRUE ); } /* SpyLogOpen */
FILE *openLog(char *filename, char *tname, struct timeval tv) { FILE *fp = NULL; char tdir[128], tfile[128], tchar[256]; extern double TB_RATE_AVG_INTERVAL; int ret = 0; memset(filename, '\0', 256); if(getLogName(tdir, tfile, tname, 128, 128, strlen(tname)) != -1) { sprintf(filename, "%s/%s", tdir, tfile); sprintf(tchar, "/bin/mkdir -p %s", tdir); ret = system(tchar); fp = fopen(filename, "w"); } if(fp == NULL) //revert back to old "flat" files { sprintf(filename, "%s_%d_%fdelta.txt", tname, (int)tv.tv_sec, TB_RATE_AVG_INTERVAL); fp = fopen(filename, "w"); } return fp; }
Iterator::Base * Base::newFrameIterator() throw() { It::Lock lk( _it ); Iterator::Base * rt = _it.model->getClone(); _it.instances.push_back( rt ); Log::verbose( "%s: new iterator %p", getLogName(), rt ); return rt; }
Base::FrameList Base::getFrames( double from, double to ) const throw( ) { FrameData::Lock lk( _frame ); size_t fromPos = 0, toPos = this->getFrameCount() - 1; // guess exact start try { fromPos = this->getFramePos( from ); } catch( const KGD::Exception::OutOfBounds & e ) { Log::warning( "%s: %s during getFrames, cropping start to 0", getLogName(), e.what() ); } // guess exact stop if ( to < HUGE_VAL ) { try { toPos = this->getFramePos( to ); // stop before the last key frame if video if ( _type == SDP::MediaType::Video && toPos > 0 ) -- toPos; } catch( const KGD::Exception::OutOfBounds & e ) { Log::warning( "%s: %s during getFrames, cropping stop to frame count", getLogName(), e.what() ); } } // copy FrameList rt; rt.reserve( toPos - fromPos + 1 ); for( size_t i = fromPos; i <= toPos; ++i ) { if ( ! _frame.list.is_null( i ) ) { auto_ptr< Frame::Base > f( _frame.list[i].getClone() ); f->addTime( -from ); rt.push_back( f ); } } return rt; }
void Base::finalizeFrameCount( ) throw() { { FrameData::Lock lk( _frame ); _frame.count = _frame.list.size(); Log::debug("%s: %lld frames", getLogName(), _frame.count ); } _frame.available.notify_all(); }
void Base::releaseIterator( Iterator::Base & i ) throw() { Log::debug( "%s: releasing iterator %p", getLogName(), &i ); _it.lock(); IteratorList::iterator toRemove = find( _it.instances.begin(), _it.instances.end(), &i ); if ( toRemove != _it.instances.end() ) { Log::verbose( "%s: iterator %p found", getLogName(), &i ); _it.instances.erase( toRemove ); if ( _it.instances.empty() ) { _it.unlock(); _it.released.notify_all(); return; } } _it.unlock(); }
~VerboseLog() { typedef LogLvl<(logLvl & LogParent::log_level), LogParent> LogClass; /* check if a bit in the mask is set * If you get an linker error in the next two lines you have not used * DEFINE_LOGLVL makro to define a named logLvl */ if (logLvl & LogParent::log_level) /*compiletime check*/ { std::cout << LogParent::getName() << " " << getLogName(LogClass()) << "(" << (logLvl & LogParent::log_level) << ")" << " | " << fmt << std::endl; } }
void Session::unpause( const RTSP::PlayRequest & rq ) throw() { _th.lock(); if ( _status.bag[ Status::PAUSED ] ) { Log::message( "%s: unpause", getLogName() ); _status.bag[ Status::PAUSED ] = false; _frame.time->unpause( rq.time, _frame.time->getSpeed() ); _th.unlock(); Log::verbose( "%s: wakeup", getLogName() ); _pause.wakeup.notify_all(); } else { Log::warning( "%s: already playing", getLogName() ); _th.unlock(); } }
PlayRequest Session::play( const PlayRequest & rq ) throw( RTSP::Exception::ManagedError ) { try { Session::Lock lk( *this ); Log::debug( "%s: pre-play", getLogName() ); // guess common parameters PlayRequest rt( rq ); BOOST_FOREACH( SessionMap::iterator::reference sess, _sessions ) { rt.merge( sess->second->eval( rq ) ); Log::debug("%s: merge: %s", getLogName(), rt.toString().c_str() ); } Log::debug( "%s: play setup with %s", getLogName(), rt.toString().c_str() ); // set it up BOOST_FOREACH( SessionMap::iterator::reference sess, _sessions ) sess->second->play( rt ); _playIssued = true; return rt; }
RTSP::PlayRequest Session::doSeekScale( const RTSP::PlayRequest & rq ) throw( KGD::Exception::OutOfBounds ) { RTSP::PlayRequest ret( rq ); if ( !rq.hasScale ) ret.speed = _frame.time->getSpeed(); if ( rq.from == HUGE_VAL ) ret.from = _frame.time->getPresentationTime(); _status.bag[ Status::SEEKED ] = ret.hasRange; // pause if ( _status.bag[ Status::PAUSED ] ) { Log::message( "%s: unpause medium after %f s", getLogName(), _frame.time->getLastPause() ); } // seek if ( ret.hasRange ) { Log::message( "%s: seek medium at %f", getLogName(), ret.from ); } // scale if ( ret.hasScale ) { Log::message( "%s: scale medium at %0.2f x", getLogName(), ret.speed ); } if ( _status.bag[ Status::PAUSED ] || ret.hasRange || ret.hasScale ) { _frame.next.reset(); _frame.buf->seek( ret.from, ret.speed ); _seqStart = _seqCur + 1; _frame.time->seek( rq.time, ret.from, ret.speed ); } else Log::warning( "%s: no changes in play status", getLogName() ); return ret; }
Base::~Base() { FrameData::Lock lk( _frame ); _it.model.reset(); while( ! _it.instances.empty() ) { Log::debug( "%s: waiting for %u iterators", getLogName(), _it.instances.size() ); _it.released.wait( lk ); } _frame.list.clear(); }
void Sender::releaseRTP( OwnThread::Lock & lk ) { if ( _syncRTP ) { Log::verbose( "%s: release barrier", getLogName() ); { OwnThread::UnLock ulk( lk ); bool done = false; do NO_INTERRUPT( _syncRTP.wait(); done = true; ) while( ! done ); } _syncRTP = false; }
void Base::insert( double duration, double start ) throw( KGD::Exception::OutOfBounds ) { FrameData::Lock lk( _frame ); // guess pos size_t pos = this->getFramePos( start ); Log::debug( "%s: media insert: found insert position %lu", getLogName(), pos ); // shift successive frames by new medium duration FrameList::iterator insIt = _frame.list.begin() + pos; { FrameList::iterator it = insIt, ed = _frame.list.end(); for( ; it != ed; ++it ) it->addTime( duration ); } _duration += duration; _frame.timeShift += duration; }
void Session::play() throw() { { OwnThread::Lock lk( _th ); Log::message( "%s: start play", getLogName() ); _status.bag[ Status::PAUSED ] = false; if ( ! _th ) { _rtcp.receiver->start(); _rtcp.sender->reset(); _th.reset( new boost::thread(boost::bind(&RTP::Session::run, this)) ); } } _pause.wakeup.notify_all(); }
void InitLog(const wchar_t *wzLogFile) { ZeroMemory(g_wzLogFile,sizeof(g_wzLogFile)); if(wcslen(wzLogFile)<MAX_PATH) { swprintf_s(g_wzLogFile,MAX_PATH,L"%s",wzLogFile); } FILE *f=NULL; _wfopen_s(&f, getLogName(), L"w"); if (f) { fclose(f); f=NULL; } }
void LOG(const wchar_t *format, ...) { va_list args; va_start(args, format); FILE *f=NULL; _wfopen_s(&f, getLogName(), L"a"); if (f) { vfwprintf_s(f, format, args); fclose(f); f=NULL; } else { vwprintf_s(format, args); } va_end(args); }
RTSP::PlayRequest Session::doFirstPlay( const RTSP::PlayRequest & rq ) throw( KGD::Exception::OutOfBounds ) { RTSP::PlayRequest ret( rq ); if ( !rq.hasScale ) ret.speed = RTSP::PlayRequest::LINEAR_SCALE; if ( rq.from == HUGE_VAL ) ret.from = signedMin( 0.0, _medium.getIterationDuration(), sign( ret.speed ) ); Log::message( "%s: play %s", getLogName(), ret.toString().c_str() ); _seqStart = _seqCur + 1; _frame.time->restartRTPtime(); _status.bag[ Status::STOPPED ] = false; _status.bag[ Status::PAUSED ] = true; _frame.time->seek( ret.time, ret.from, ret.speed ); _frame.buf->seek( ret.from, ret.speed ); return ret; }
void Base::insert( FrameList::iterator at, double offset, double shift, Iterator::Base & otherFrames ) { FrameList toInsert; try { // clone and shift by offset time for(;;) { auto_ptr< Frame::Base > newFrame( otherFrames.next().getClone() ); newFrame->addTime( offset ); toInsert.push_back( newFrame ); } } catch( KGD::Exception::OutOfBounds ) { // insert and adjust internal state Log::debug( "%s: media append: append %lu new frames", getLogName(), toInsert.size() ); _frame.list.insert( at, toInsert.begin(), toInsert.end() ); _frame.count += toInsert.size(); _duration += otherFrames.duration(); _frame.timeShift += shift; } }
Sender::~Sender() { Log::verbose( "%s: destroying", getLogName() ); }
/* * ConfigLogDlgProc - handle the configure log dialog */ WINEXPORT INT_PTR CALLBACK ConfigLogDlgProc( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam ) { char *buf; lparam = lparam; switch( msg ) { case WM_INITDIALOG: if( LogCurInfo.config.query_for_name ) { CheckDlgButton( hwnd, LOG_CFG_QUERY_NAME, TRUE ); } else { CheckDlgButton( hwnd, LOG_CFG_USE_NAME, TRUE ); } if( LogCurInfo.config.type == LOG_TYPE_BUFFER ) { CheckDlgButton( hwnd, LOG_CFG_PERIODIC, TRUE ); } else { CheckDlgButton( hwnd, LOG_CFG_CONT, TRUE ); } if( LogCurInfo.config.def_action == LOG_ACTION_APPEND ) { CheckDlgButton( hwnd, LOG_CFG_APPEND, TRUE ); } else if( LogCurInfo.config.def_action == LOG_ACTION_TRUNC ) { CheckDlgButton( hwnd, LOG_CFG_REPLACE, TRUE ); } else if( LogCurInfo.config.def_action == LOG_ACTION_QUERY ) { CheckDlgButton( hwnd, LOG_CFG_QUERY, TRUE ); } SetDlgItemText( hwnd, LOG_CFG_NAME_EDIT, LogCurInfo.config.name ); break; #ifndef NOUSE3D case WM_SYSCOLORCHANGE: CvrCtl3dColorChange(); break; #endif case WM_COMMAND: switch( wparam ) { case LOG_CFG_BROWSE: buf = MemAlloc( LOG_MAX_FNAME ); if( getLogName( buf, hwnd ) ) { strlwr( buf ); SetDlgItemText( hwnd, LOG_CFG_NAME_EDIT, buf ); } MemFree( buf ); break; case LOG_CFG_OK: if( IsDlgButtonChecked( hwnd, LOG_CFG_QUERY_NAME ) ) { LogCurInfo.config.query_for_name = TRUE; } else if( IsDlgButtonChecked( hwnd, LOG_CFG_USE_NAME ) ) { LogCurInfo.config.query_for_name = FALSE; } if( IsDlgButtonChecked( hwnd, LOG_CFG_PERIODIC ) ) { LogCurInfo.config.type = LOG_TYPE_BUFFER; } else if( IsDlgButtonChecked( hwnd, LOG_CFG_CONT ) ) { LogCurInfo.config.type = LOG_TYPE_CONTINUOUS; } if( IsDlgButtonChecked( hwnd, LOG_CFG_APPEND ) ) { LogCurInfo.config.def_action = LOG_ACTION_APPEND; } else if( IsDlgButtonChecked( hwnd, LOG_CFG_REPLACE ) ) { LogCurInfo.config.def_action = LOG_ACTION_TRUNC; } else if( IsDlgButtonChecked( hwnd, LOG_CFG_QUERY ) ) { LogCurInfo.config.def_action = LOG_ACTION_QUERY; } GetDlgItemText( hwnd, LOG_CFG_NAME_EDIT, LogCurInfo.config.name, LOG_MAX_FNAME ); EndDialog( hwnd, TRUE ); break; case LOG_CFG_CANCEL: EndDialog( hwnd, FALSE ); break; default: return( FALSE ); } break; default: return( FALSE ); } return( TRUE ); } /* ConfigLogDlgProc */
void Container::loadMediaContainer() throw( SDP::Exception::Generic ) { AVFormatContext *fctx = 0; // ff open file if ( av_open_input_file(&fctx, this->getFilePath().c_str(), NULL, 0, NULL) != 0 ) throw SDP::Exception::Generic( "unable to open " + _fileName + " in " + BASE_DIR ); // ff load stream info if( av_find_stream_info(fctx) < 0 ) { av_close_input_file( fctx ); throw SDP::Exception::Generic( "unable to find streams in " + _fileName ); } // other info _bitRate = fctx->bit_rate; _duration = double(fctx->duration) / AV_TIME_BASE; // load media size_t i = 0; for( i = 0; i < fctx->nb_streams; i++) { AVStream *str = fctx->streams[i]; AVCodecContext *cdc = str->codec; AVRational tBase = str->time_base; try { auto_ptr< Medium::Base > m( Factory::ClassRegistry< Medium::Base >::newInstance( cdc->codec_id ) ); m->setContainer( *this ); m->setIndex( i ); m->setExtraData( cdc->extradata, cdc->extradata_size ); m->setFileName( this->getFileName() ); m->setDuration( _duration ); m->setTimeBase( double(tBase.num) / tBase.den ); // set specific data if ( Medium::Audio::AAC * ma = m->asPtrUnsafe< Medium::Audio::AAC >() ) { ma->setRate( cdc->sample_rate ); ma->setChannels( cdc->channels ); } _media.insert( i, m ); } catch( const KGD::Exception::NotFound & e ) { Log::error( "%s: %s", getLogName(), e.what() ); _media.clear(); av_close_input_file( fctx ); throw SDP::Exception::Generic( "unsupported codec " + string(cdc->codec_name) ); } } { OwnThread::Lock lk( _th ); _th.running = true; _th.reset( new boost::thread( boost::bind( &Container::mediaContainerLoop, this, fctx ) )); } }
void Base::insert( Iterator::Base & otherFrames, double start ) throw( KGD::Exception::OutOfBounds ) { FrameData::Lock lk( _frame ); double otherDuration = otherFrames.duration(); // guess pos size_t pos = this->getFramePos( start ); Log::debug( "%s: media insert: found insert position %lu for time %lf, shifting next frames by %lf", getLogName(), pos, start, otherDuration ); // shift successive frames by new medium duration FrameList::iterator insIt = _frame.list.begin() + pos; Log::debug( "%s: media insert: first frame to shift at time %lf (previous at %lf)", getLogName(), insIt->getTime(), (insIt - 1)->getTime() ); { FrameList::iterator it = insIt, ed = _frame.list.end(); for( ; it != ed; ++it ) it->addTime( otherDuration ); } this->insert( insIt, start, otherDuration, otherFrames ); }
int Layout::format(Event *evt) { int ptr = 0; int ret = 0; int bufsiz = evt->_render_msgbuf_size; char *buf = evt->_render_msgbuf; if(bufsiz < 2) { return -1; } if (evt->_log_version >= 0 && *evt->_log_type != 0) { ret = snprintf(buf+ptr, bufsiz-ptr, "%d", evt->_log_version); CHECKTAIL; ptr += ret; buf[ptr++] = ' '; ret = snprintf(buf+ptr, bufsiz-ptr, "%s", evt->_log_type); CHECKTAIL; ptr += ret; buf[ptr++] = ' '; } //_com_debug("patterns[%s] ndc[%s]", _pattern, _ndc_pattern); for (int i=0; _pattern[i]!=0; ++i) { if (ptr >= bufsiz) { break; } if (_pattern[i] == '%') { ++i; if (_pattern[i] == 0) { break; } switch (_pattern[i]) { case 'L': ret = snprintf(buf+ptr, bufsiz-ptr, "%s", getLogName(evt->_log_level)); CHECKTAIL; ptr += ret; break; case 'A': ret = xfmtime(buf+ptr, bufsiz-ptr, evt->_print_time); CHECKTAIL; ptr += ret; break; case 'T': ret = snprintf(buf+ptr, bufsiz-ptr, "%u", (u_int)evt->_thread_id); CHECKTAIL; ptr += ret; break; case 'D': ret = xfmtime(buf+ptr, bufsiz-ptr, evt->_print_time.tv_sec); CHECKTAIL; ptr += ret; break; case 'Y': struct tm ftm; localtime_r(&evt->_print_time.tv_sec, &ftm); ret = strftime(buf+ptr, bufsiz-ptr, comlog_time_format, &ftm); CHECKTAIL; ptr += ret; break; case 'U': ret = snprintf(buf+ptr, bufsiz-ptr, "%lu", evt->_print_time.tv_usec/1000); CHECKTAIL; ptr += ret; break; case 'P': ret = snprintf(buf+ptr, bufsiz-ptr, "%s", evt->_proc_name); CHECKTAIL; ptr += ret; break; case 'N': //_com_debug("check ndc %d", evt->_ndc_num); ret = fmtpattern(evt, buf+ptr, bufsiz-ptr); CHECKTAIL; ptr += ret; break; /* Add hostname by wangshaoyan, 2012-08-20*/ case 'H': char hostname[128]; gethostname(hostname, 128); ret = xstrcpy(buf+ptr, bufsiz-ptr, hostname, strlen(hostname)); CHECKTAIL; ptr += ret; break; case 'R': /* ret = snprintf(buf+ptr, bufsiz-ptr, "%s", evt->_msgbuf); CHECKTAIL; ptr += ret; */ ret = xstrcpy(buf+ptr, bufsiz-ptr, evt->_msgbuf, evt->_msgbuf_len); CHECKTAIL; ptr += ret; break; case '%': //buf[ptr++] = '%'; break; default: break; } } else { buf[ptr++] = _pattern[i]; } } end: if (ptr >= bufsiz-1) { //bufsiz must be >= 2 !!! ptr = bufsiz - 2; } buf[ptr++] = '\n'; buf[ptr] = 0; evt->_render_msgbuf_len = ptr; //_com_debug("render msgbuf[%s] len=%d", buf, ptr); return 0; }
void Base::setTimeBase( double x ) throw() { _timeBase = x; _freqBase = 1 / x; Log::debug( "%s: Tbase %lf Fbase %lf", getLogName(), _timeBase, _freqBase ); }
RTP::Session & Session::createSession(const Url &url, const Channel::Description & remote, const boost::optional< TSSrc > & ssrc ) throw( RTSP::Exception::ManagedError ) { try { Session::Lock lk( *this ); // setup channel boost::shared_ptr< Channel::Bi > rtpChan, rtcpChan; TPortPair local; // udp if ( remote.type == Channel::Owned ) { local = Port::Udp::getInstance()->getPair(); Log::debug("%s: creating udp socket locally bound to %d / %d", getLogName(), local.first, local.second ); auto_ptr< KGD::Socket::Udp > rtp( new KGD::Socket::Udp( local.first, url.host ) ), rtcp( new KGD::Socket::Udp( local.second, url.host ) ); Log::debug("%s: connecting udp socket to remote %d / %d", getLogName(), remote.ports.first, remote.ports.second); try { rtp->connectTo( remote.ports.first, url.remoteHost ); rtcp->connectTo( remote.ports.second, url.remoteHost ); } catch( const KGD::Socket::Exception & e ) { Log::debug( "%s: socket error: %s", getLogName(), e.what() ); throw RTSP::Exception::ManagedError( Error::UnsupportedTransport ); } rtp->setWriteTimeout( KGD::Socket::WRITE_TIMEOUT ); rtcp->setWriteTimeout( KGD::Socket::WRITE_TIMEOUT ); rtcp->setReadBlock( true ); rtcp->setReadTimeout( RTCP::Receiver::POLL_INTERVAL ); rtpChan = rtp; rtcpChan = rtcp; } // tcp interleaved else { Socket & rtsp = _conn.getSocket(); local = rtsp.addInterleavePair( remote.ports, _id ); rtpChan = rtsp.getInterleave( local.first ); rtcpChan = rtsp.getInterleave( local.second ); rtcpChan->setReadTimeout( RTCP::Receiver::POLL_INTERVAL ); } // get description int mediumIndex = fromString< int >( url.track ); SDP::Medium::Base & med = _conn.getDescription( url.file ).getMedium( mediumIndex ); // create session auto_ptr< RTP::Session > s( new RTP::Session( *this, url, med, rtpChan, rtcpChan, _conn.getUserAgent() ) ); if ( ssrc ) s->setSsrc( *ssrc ); // temp to return RTP::Session * sPtr = s.get(); // add to basket { string tmpTrack( url.track ); _sessions.insert( tmpTrack, s ); } Log::debug("%s: RTP session created / track: %s / ports: RTP %d %d - RTCP %d %d" , getLogName() , url.track.c_str() , local.first , remote.ports.first , local.second , remote.ports.second ); return *sPtr; } catch( const KGD::Socket::Exception & e ) { Log::debug( "%s: socket error: %s", getLogName(), e.what() ); throw RTSP::Exception::ManagedError( Error::InternalServerError ); } // no more ports catch( const KGD::Exception::NotFound & e ) { Log::debug( "%s: %s", getLogName(), e.what() ); throw RTSP::Exception::ManagedError( Error::NotEnoughBandwidth ); } }
//写日志,newline=true为行模式,自动加前导字符和回行符 bool LogUtil::Write(int level, string message, bool newline) { //异常情况,无法打开log目录或文件 if (logEnable == false) { return false; } //取当前时间 time_t nowTime = time(NULL); //是否重加载log level if (nowTime - lastTime > reloadConfigTime) { lastTime = nowTime; //重新加载日志级别 basePath/level string levelFile = basePath + "/level.conf"; FILE * tmpFp; char tmpLevel[50]; tmpLevel[0] = '\0'; tmpFp = fopen(levelFile.c_str(), "r"); if (tmpFp != NULL) { fgets(tmpLevel, 50, tmpFp); fclose(tmpFp); setLogLevel(tmpLevel); } } //判断是否需要记日志 if (level > curLevel) { return true; } //取到文件名 string curLogName = getLogName(nowTime); if (curLogName != lastLogName) { lastLogName = curLogName; //关闭上次打开的log文件。 if (fp != NULL) { fclose(fp); fp = NULL; } } //取得log文件名 string fullName = basePath + "/" + fileName + lastLogName + "." + fileExtName; //打开文件 if (fp == NULL) { fp = fopen(fullName.c_str(), "a"); if (fp == NULL) { return false; } } //注意多进程情况 //写日志 [TIME] [LEVEL] [PID] message if (newline) { string header=getLineHeader(level); fprintf(fp, "%s", header.c_str()); //换行退格处理 replace("\n", "\n "); message = StringUtil::ReplaceAll(message, "\n", "\n "); } fprintf(fp, "%s", message.c_str()); if (newline) { //行模式,加回车并flush到文件 fprintf(fp,"%s", "\n"); fflush(fp); } return true; }