static bool Init() { g_LogMod = PR_NewLogModule("xpclog"); g_Spaces = new char[SPACE_COUNT+1]; if (!g_LogMod || !g_Spaces || !PR_LOG_TEST(g_LogMod,1)) { g_InitState = 1; XPC_Log_Finish(); return false; } memset(g_Spaces, ' ', SPACE_COUNT); g_Spaces[SPACE_COUNT] = 0; g_InitState = 1; return true; }
PRBool nsRDFConInstanceTestNode::CanPropagate(nsIRDFResource* aSource, nsIRDFResource* aProperty, nsIRDFNode* aTarget, Instantiation& aInitialBindings) const { nsresult rv; PRBool canpropagate = PR_FALSE; nsCOMPtr<nsIRDFContainerUtils> rdfc = do_GetService("@mozilla.org/rdf/container-utils;1"); if (! rdfc) return PR_FALSE; // We can certainly propagate ordinal properties rv = rdfc->IsOrdinalProperty(aProperty, &canpropagate); if (NS_FAILED(rv)) return PR_FALSE; if (! canpropagate) { canpropagate = mProcessor->ContainmentProperties().Contains(aProperty); } #ifdef PR_LOGGING if (PR_LOG_TEST(gXULTemplateLog, PR_LOG_DEBUG)) { const char* source; aSource->GetValueConst(&source); const char* property; aProperty->GetValueConst(&property); nsAutoString target; nsXULContentUtils::GetTextForNode(aTarget, target); PR_LOG(gXULTemplateLog, PR_LOG_DEBUG, ("nsRDFConInstanceTestNode[%p]: CanPropagate([%s]==[%s]=>[%s]) => %s", this, source, property, NS_ConvertUTF16toUTF8(target).get(), canpropagate ? "true" : "false")); } #endif if (canpropagate) { aInitialBindings.AddAssignment(mContainerVariable, aSource); return PR_TRUE; } return PR_FALSE; }
nsresult nsMsgCopyService::DoCopy(nsCopyRequest* aRequest) { NS_ENSURE_ARG(aRequest); bool copyImmediately; QueueRequest(aRequest, ©Immediately); m_copyRequests.AppendElement(aRequest); if (PR_LOG_TEST(gCopyServiceLog, PR_LOG_ALWAYS)) LogCopyRequest(copyImmediately ? "DoCopy" : "QueueRequest", aRequest); // if no active request for this dest folder then we can copy immediately if (copyImmediately) return DoNextCopy(); return NS_OK; }
NS_IMETHODIMP nsResProtocolHandler::ResolveURI(nsIURI *uri, nsACString &result) { nsresult rv; nsCAutoString host; nsCAutoString path; rv = uri->GetAsciiHost(host); if (NS_FAILED(rv)) return rv; rv = uri->GetPath(path); if (NS_FAILED(rv)) return rv; // Unescape the path so we can perform some checks on it. nsCAutoString unescapedPath(path); NS_UnescapeURL(unescapedPath); // Don't misinterpret the filepath as an absolute URI. if (unescapedPath.FindChar(':') != -1) return NS_ERROR_MALFORMED_URI; if (unescapedPath.FindChar('\\') != -1) return NS_ERROR_MALFORMED_URI; const char *p = path.get() + 1; // path always starts with a slash NS_ASSERTION(*(p-1) == '/', "Path did not begin with a slash!"); if (*p == '/') return NS_ERROR_MALFORMED_URI; nsCOMPtr<nsIURI> baseURI; rv = GetSubstitution(host, getter_AddRefs(baseURI)); if (NS_FAILED(rv)) return rv; rv = baseURI->Resolve(nsDependentCString(p, path.Length()-1), result); #if defined(PR_LOGGING) if (PR_LOG_TEST(gResLog, PR_LOG_DEBUG)) { nsCAutoString spec; uri->GetAsciiSpec(spec); PR_LOG(gResLog, PR_LOG_DEBUG, ("%s\n -> %s\n", spec.get(), PromiseFlatCString(result).get())); } #endif return rv; }
nsRDFConMemberTestNode::nsRDFConMemberTestNode(TestNode* aParent, nsXULTemplateQueryProcessorRDF* aProcessor, nsIAtom *aContainerVariable, nsIAtom *aMemberVariable) : nsRDFTestNode(aParent), mProcessor(aProcessor), mContainerVariable(aContainerVariable), mMemberVariable(aMemberVariable) { #ifdef PR_LOGGING if (PR_LOG_TEST(gXULTemplateLog, PR_LOG_DEBUG)) { nsCAutoString props; nsResourceSet& containmentProps = aProcessor->ContainmentProperties(); nsResourceSet::ConstIterator last = containmentProps.Last(); nsResourceSet::ConstIterator first = containmentProps.First(); nsResourceSet::ConstIterator iter; for (iter = first; iter != last; ++iter) { if (iter != first) props += " "; const char* str; iter->GetValueConst(&str); props += str; } nsAutoString cvar(NS_LITERAL_STRING("(none)")); if (mContainerVariable) mContainerVariable->ToString(cvar); nsAutoString mvar(NS_LITERAL_STRING("(none)")); if (mMemberVariable) mMemberVariable->ToString(mvar); PR_LOG(gXULTemplateLog, PR_LOG_DEBUG, ("nsRDFConMemberTestNode[%p]: parent=%p member-props=(%s) container-var=%s member-var=%s", this, aParent, props.get(), NS_ConvertUTF16toUTF8(cvar).get(), NS_ConvertUTF16toUTF8(mvar).get())); } #endif }
nsresult nsMsgCopyService::ClearRequest(nsCopyRequest* aRequest, nsresult rv) { if (aRequest) { if (PR_LOG_TEST(gCopyServiceLog, PR_LOG_ALWAYS)) LogCopyRequest(NS_SUCCEEDED(rv) ? "Clearing OK request" : "Clearing failed request", aRequest); // Send notifications to nsIMsgFolderListeners if (NS_SUCCEEDED(rv) && aRequest->m_requestType == nsCopyFoldersType) { nsCOMPtr<nsIMsgFolderNotificationService> notifier(do_GetService(NS_MSGNOTIFICATIONSERVICE_CONTRACTID)); if (notifier) { bool hasListeners; notifier->GetHasListeners(&hasListeners); if (hasListeners) { // Iterate over the copy sources and append their message arrays to this mutable array // or in the case of folders, the source folder. int32_t cnt, i; cnt = aRequest->m_copySourceArray.Length(); for (i = 0; i < cnt; i++) { nsCopySource *copySource = aRequest->m_copySourceArray.ElementAt(i); notifier->NotifyFolderMoveCopyCompleted(aRequest->m_isMoveOrDraftOrTemplate, copySource->m_msgFolder, aRequest->m_dstFolder); } } } } // undo stuff if (aRequest->m_allowUndo && aRequest->m_copySourceArray.Length() > 1 && aRequest->m_txnMgr) aRequest->m_txnMgr->EndBatch(); m_copyRequests.RemoveElement(aRequest); if (aRequest->m_listener) aRequest->m_listener->OnStopCopy(rv); delete aRequest; } return rv; }
NS_IMETHODIMP nsMailDatabase::ListAllOfflineOpIds(nsTArray<nsMsgKey> *offlineOpIds) { NS_ENSURE_ARG(offlineOpIds); nsresult rv = GetAllOfflineOpsTable(); NS_ENSURE_SUCCESS(rv, rv); nsIMdbTableRowCursor *rowCursor; if (!IMAPOffline) IMAPOffline = PR_NewLogModule("IMAPOFFLINE"); if (m_mdbAllOfflineOpsTable) { nsresult err = m_mdbAllOfflineOpsTable->GetTableRowCursor(GetEnv(), -1, &rowCursor); while (NS_SUCCEEDED(err) && rowCursor) { mdbOid outOid; mdb_pos outPos; err = rowCursor->NextRowOid(GetEnv(), &outOid, &outPos); // is this right? Mork is returning a 0 id, but that should valid. if (outPos < 0 || outOid.mOid_Id == (mdb_id) -1) break; if (NS_SUCCEEDED(err)) { offlineOpIds->AppendElement(outOid.mOid_Id); if (PR_LOG_TEST(IMAPOffline, PR_LOG_ALWAYS)) { nsCOMPtr <nsIMsgOfflineImapOperation> offlineOp; GetOfflineOpForKey(outOid.mOid_Id, false, getter_AddRefs(offlineOp)); if (offlineOp) { nsMsgOfflineImapOperation *logOp = static_cast<nsMsgOfflineImapOperation *>(static_cast<nsIMsgOfflineImapOperation *>(offlineOp.get())); if (logOp) logOp->Log(IMAPOffline); } } } } // TODO: would it cause a problem to replace this with "rv = err;" ? rv = (NS_SUCCEEDED(err)) ? NS_OK : NS_ERROR_FAILURE; rowCursor->Release(); } offlineOpIds->Sort(); return rv; }
/* void clearOperation (in nsOfflineImapOperationType operation); */ NS_IMETHODIMP nsMsgOfflineImapOperation::ClearOperation(nsOfflineImapOperationType aOperation) { if (PR_LOG_TEST(IMAPOffline, PR_LOG_ALWAYS)) PR_LOG(IMAPOffline, PR_LOG_ALWAYS, ("msg id %x clearOperation was %x clear %x", m_messageKey, m_operation, aOperation)); m_operation &= ~aOperation; switch (aOperation) { case kMsgMoved: case kAppendTemplate: case kAppendDraft: m_moveDestination.Truncate(); break; case kMsgCopy: m_copyDestinations.RemoveCStringAt(0); break; } return m_mdb->SetUint32Property(m_mdbRow, PROP_OPERATION, m_operation); }
void nsTimerImpl::Shutdown() { #ifdef DEBUG_TIMERS if (PR_LOG_TEST(gTimerLog, PR_LOG_DEBUG)) { double mean = 0, stddev = 0; myNS_MeanAndStdDev(sDeltaNum, sDeltaSum, sDeltaSumSquared, &mean, &stddev); PR_LOG(gTimerLog, PR_LOG_DEBUG, ("sDeltaNum = %f, sDeltaSum = %f, sDeltaSumSquared = %f\n", sDeltaNum, sDeltaSum, sDeltaSumSquared)); PR_LOG(gTimerLog, PR_LOG_DEBUG, ("mean: %fms, stddev: %fms\n", mean, stddev)); } #endif if (!gThread) return; gThread->Shutdown(); NS_RELEASE(gThread); }
bool nsRDFPropertyTestNode::CanPropagate(nsIRDFResource* aSource, nsIRDFResource* aProperty, nsIRDFNode* aTarget, Instantiation& aInitialBindings) const { bool result; if ((mProperty.get() != aProperty) || (mSource && mSource.get() != aSource) || (mTarget && mTarget.get() != aTarget)) { result = false; } else { if (mSourceVariable) aInitialBindings.AddAssignment(mSourceVariable, aSource); if (mTargetVariable) aInitialBindings.AddAssignment(mTargetVariable, aTarget); result = true; } #ifdef PR_LOGGING if (PR_LOG_TEST(gXULTemplateLog, PR_LOG_DEBUG)) { const char* source; aSource->GetValueConst(&source); const char* property; aProperty->GetValueConst(&property); nsAutoString target; nsXULContentUtils::GetTextForNode(aTarget, target); PR_LOG(gXULTemplateLog, PR_LOG_DEBUG, ("nsRDFPropertyTestNode[%p]: CanPropagate([%s]==[%s]=>[%s]) => %s", this, source, property, NS_ConvertUTF16toUTF8(target).get(), result ? "true" : "false")); } #endif return result; }
NS_IMETHODIMP nsTimerEvent::Run() { nsRefPtr<nsTimerImpl> timer; timer.swap(mTimer); if (mGeneration != timer->GetGeneration()) return NS_OK; #ifdef DEBUG_TIMERS if (PR_LOG_TEST(gTimerLog, PR_LOG_DEBUG)) { PRIntervalTime now = PR_IntervalNow(); PR_LOG(gTimerLog, PR_LOG_DEBUG, ("[this=%p] time between PostTimerEvent() and Fire(): %dms\n", this, PR_IntervalToMilliseconds(now - mInitTime))); } #endif timer->Fire(); return NS_OK; }
nsContentTestNode::nsContentTestNode(nsXULTemplateQueryProcessorRDF* aProcessor, nsIAtom* aRefVariable) : TestNode(nullptr), mProcessor(aProcessor), mDocument(nullptr), mRefVariable(aRefVariable), mTag(nullptr) { if (PR_LOG_TEST(gXULTemplateLog, PR_LOG_DEBUG)) { nsAutoString tag(NS_LITERAL_STRING("(none)")); if (mTag) mTag->ToString(tag); nsAutoString refvar(NS_LITERAL_STRING("(none)")); if (aRefVariable) aRefVariable->ToString(refvar); MOZ_LOG(gXULTemplateLog, PR_LOG_DEBUG, ("nsContentTestNode[%p]: ref-var=%s tag=%s", this, NS_ConvertUTF16toUTF8(refvar).get(), NS_ConvertUTF16toUTF8(tag).get())); } }
//WebRTC::RTP Callback Implementation int WebrtcAudioConduit::SendPacket(int channel, const void* data, int len) { CSFLogDebug(logTag, "%s : channel %d %s", __FUNCTION__, channel, (mEngineReceiving && mOtherDirection) ? "(using mOtherDirection)" : ""); if (mEngineReceiving) { if (mOtherDirection) { return mOtherDirection->SendPacket(channel, data, len); } CSFLogDebug(logTag, "%s : Asked to send RTP without an RTP sender on channel %d", __FUNCTION__, channel); return -1; } else { #ifdef MOZILLA_INTERNAL_API if (PR_LOG_TEST(GetLatencyLog(), PR_LOG_DEBUG)) { if (mProcessing.Length() > 0) { TimeStamp started = mProcessing[0].mTimeStamp; mProcessing.RemoveElementAt(0); mProcessing.RemoveElementAt(0); // 20ms packetization! Could automate this by watching sizes TimeDuration t = TimeStamp::Now() - started; int64_t delta = t.ToMilliseconds(); LogTime(AsyncLatencyLogger::AudioSendRTP, ((uint64_t) this), delta); } } #endif if(mTransport && (mTransport->SendRtpPacket(data, len) == NS_OK)) { CSFLogDebug(logTag, "%s Sent RTP Packet ", __FUNCTION__); return len; } else { CSFLogError(logTag, "%s RTP Packet Send Failed ", __FUNCTION__); return -1; } } }
// aTime is the time in ms the samples were inserted into MediaStreamGraph nsresult AudioStream::Write(const AudioDataValue* aBuf, uint32_t aFrames, TimeStamp *aTime) { MonitorAutoLock mon(mMonitor); if (!mCubebStream || mState == ERRORED) { return NS_ERROR_FAILURE; } NS_ASSERTION(mState == INITIALIZED || mState == STARTED, "Stream write in unexpected state."); // Downmix to Stereo. if (mChannels > 2 && mChannels <= 8) { DownmixAudioToStereo(const_cast<AudioDataValue*> (aBuf), mChannels, aFrames); } else if (mChannels > 8) { return NS_ERROR_FAILURE; } const uint8_t* src = reinterpret_cast<const uint8_t*>(aBuf); uint32_t bytesToCopy = FramesToBytes(aFrames); // XXX this will need to change if we want to enable this on-the-fly! if (PR_LOG_TEST(GetLatencyLog(), PR_LOG_DEBUG)) { // Record the position and time this data was inserted int64_t timeMs; if (aTime && !aTime->IsNull()) { if (mStartTime.IsNull()) { AsyncLatencyLogger::Get(true)->GetStartTime(mStartTime); } timeMs = (*aTime - mStartTime).ToMilliseconds(); } else { timeMs = 0; } struct Inserts insert = { timeMs, aFrames}; mInserts.AppendElement(insert); } while (bytesToCopy > 0) { uint32_t available = std::min(bytesToCopy, mBuffer.Available()); NS_ABORT_IF_FALSE(available % mBytesPerFrame == 0, "Must copy complete frames."); mBuffer.AppendElements(src, available); src += available; bytesToCopy -= available; if (bytesToCopy > 0) { // If we are not playing, but our buffer is full, start playing to make // room for soon-to-be-decoded data. if (mState != STARTED) { StartUnlocked(); if (mState != STARTED) { return NS_ERROR_FAILURE; } } mon.Wait(); } } mWritten += aFrames; return NS_OK; }
nsresult nsNSSCertificate::hasValidEVOidTag(SECOidTag &resultOidTag, PRBool &validEV) { nsNSSShutDownPreventionLock locker; if (isAlreadyShutDown()) return NS_ERROR_NOT_AVAILABLE; nsresult nrv; nsCOMPtr<nsINSSComponent> nssComponent = do_GetService(PSM_COMPONENT_CONTRACTID, &nrv); if (NS_FAILED(nrv)) return nrv; nssComponent->EnsureIdentityInfoLoaded(); validEV = PR_FALSE; resultOidTag = SEC_OID_UNKNOWN; PRBool isOCSPEnabled = PR_FALSE; nsCOMPtr<nsIX509CertDB> certdb; certdb = do_GetService(NS_X509CERTDB_CONTRACTID); if (certdb) certdb->GetIsOcspOn(&isOCSPEnabled); // No OCSP, no EV if (!isOCSPEnabled) return NS_OK; SECOidTag oid_tag; SECStatus rv = getFirstEVPolicy(mCert, oid_tag); if (rv != SECSuccess) return NS_OK; if (oid_tag == SEC_OID_UNKNOWN) // not in our list of OIDs accepted for EV return NS_OK; CERTCertList *rootList = getRootsForOid(oid_tag); CERTCertListCleaner rootListCleaner(); CERTRevocationMethodIndex preferedRevMethods[1] = { cert_revocation_method_ocsp }; PRUint64 revMethodFlags = CERT_REV_M_TEST_USING_THIS_METHOD | CERT_REV_M_ALLOW_NETWORK_FETCHING | CERT_REV_M_ALLOW_IMPLICIT_DEFAULT_SOURCE | CERT_REV_M_REQUIRE_INFO_ON_MISSING_SOURCE | CERT_REV_M_STOP_TESTING_ON_FRESH_INFO; PRUint64 revMethodIndependentFlags = CERT_REV_MI_TEST_ALL_LOCAL_INFORMATION_FIRST | CERT_REV_MI_REQUIRE_SOME_FRESH_INFO_AVAILABLE; PRUint64 methodFlags[2]; methodFlags[cert_revocation_method_crl] = revMethodFlags; methodFlags[cert_revocation_method_ocsp] = revMethodFlags; CERTRevocationFlags rev; rev.leafTests.number_of_defined_methods = cert_revocation_method_ocsp +1; rev.leafTests.cert_rev_flags_per_method = methodFlags; rev.leafTests.number_of_preferred_methods = 1; rev.leafTests.preferred_methods = preferedRevMethods; rev.leafTests.cert_rev_method_independent_flags = revMethodIndependentFlags; rev.chainTests.number_of_defined_methods = cert_revocation_method_ocsp +1; rev.chainTests.cert_rev_flags_per_method = methodFlags; rev.chainTests.number_of_preferred_methods = 1; rev.chainTests.preferred_methods = preferedRevMethods; rev.chainTests.cert_rev_method_independent_flags = revMethodIndependentFlags; CERTValInParam cvin[3]; cvin[0].type = cert_pi_policyOID; cvin[0].value.arraySize = 1; cvin[0].value.array.oids = &oid_tag; cvin[1].type = cert_pi_revocationFlags; cvin[1].value.pointer.revocation = &rev; cvin[2].type = cert_pi_trustAnchors; cvin[2].value.pointer.chain = rootList; cvin[3].type = cert_pi_end; CERTValOutParam cvout[2]; cvout[0].type = cert_po_trustAnchor; cvout[0].value.pointer.cert = nsnull; cvout[1].type = cert_po_end; PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("calling CERT_PKIXVerifyCert nss cert %p\n", mCert)); rv = CERT_PKIXVerifyCert(mCert, certificateUsageSSLServer, cvin, cvout, nsnull); if (rv != SECSuccess) return NS_OK; CERTCertificate *issuerCert = cvout[0].value.pointer.cert; CERTCertificateCleaner issuerCleaner(issuerCert); #ifdef PR_LOGGING if (PR_LOG_TEST(gPIPNSSLog, PR_LOG_DEBUG)) { nsNSSCertificate ic(issuerCert); nsAutoString fingerprint; ic.GetSha1Fingerprint(fingerprint); NS_LossyConvertUTF16toASCII fpa(fingerprint); PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("CERT_PKIXVerifyCert returned success, issuer: %s, SHA1: %s\n", issuerCert->subjectName, fpa.get())); } #endif validEV = isApprovedForEV(oid_tag, issuerCert); if (validEV) resultOidTag = oid_tag; return NS_OK; }
/* void Run(); */ NS_IMETHODIMP TimerThread::Run() { nsAutoLock lock(mLock); while (!mShutdown) { PRIntervalTime waitFor; if (mSleeping) { // Sleep for 0.1 seconds while not firing timers. waitFor = PR_MillisecondsToInterval(100); } else { waitFor = PR_INTERVAL_NO_TIMEOUT; PRIntervalTime now = PR_IntervalNow(); nsTimerImpl *timer = nsnull; if (mTimers.Count() > 0) { timer = static_cast<nsTimerImpl*>(mTimers[0]); if (!TIMER_LESS_THAN(now, timer->mTimeout + mTimeoutAdjustment)) { next: // NB: AddRef before the Release under RemoveTimerInternal to avoid // mRefCnt passing through zero, in case all other refs than the one // from mTimers have gone away (the last non-mTimers[i]-ref's Release // must be racing with us, blocked in gThread->RemoveTimer waiting // for TimerThread::mLock, under nsTimerImpl::Release. NS_ADDREF(timer); RemoveTimerInternal(timer); // We release mLock around the Fire call to avoid deadlock. lock.unlock(); #ifdef DEBUG_TIMERS if (PR_LOG_TEST(gTimerLog, PR_LOG_DEBUG)) { PR_LOG(gTimerLog, PR_LOG_DEBUG, ("Timer thread woke up %dms from when it was supposed to\n", (now >= timer->mTimeout) ? PR_IntervalToMilliseconds(now - timer->mTimeout) : -(PRInt32)PR_IntervalToMilliseconds(timer->mTimeout-now)) ); } #endif // We are going to let the call to PostTimerEvent here handle the // release of the timer so that we don't end up releasing the timer // on the TimerThread instead of on the thread it targets. if (NS_FAILED(timer->PostTimerEvent())) { nsrefcnt rc; NS_RELEASE2(timer, rc); // The nsITimer interface requires that its users keep a reference // to the timers they use while those timers are initialized but // have not yet fired. If this ever happens, it is a bug in the // code that created and used the timer. // // Further, note that this should never happen even with a // misbehaving user, because nsTimerImpl::Release checks for a // refcount of 1 with an armed timer (a timer whose only reference // is from the timer thread) and when it hits this will remove the // timer from the timer thread and thus destroy the last reference, // preventing this situation from occurring. NS_ASSERTION(rc != 0, "destroyed timer off its target thread!"); } timer = nsnull; lock.lock(); if (mShutdown) break; // Update now, as PostTimerEvent plus the locking may have taken a // tick or two, and we may goto next below. now = PR_IntervalNow(); } } if (mTimers.Count() > 0) { timer = static_cast<nsTimerImpl *>(mTimers[0]); PRIntervalTime timeout = timer->mTimeout + mTimeoutAdjustment; // Don't wait at all (even for PR_INTERVAL_NO_WAIT) if the next timer // is due now or overdue. if (!TIMER_LESS_THAN(now, timeout)) goto next; waitFor = timeout - now; } #ifdef DEBUG_TIMERS if (PR_LOG_TEST(gTimerLog, PR_LOG_DEBUG)) { if (waitFor == PR_INTERVAL_NO_TIMEOUT) PR_LOG(gTimerLog, PR_LOG_DEBUG, ("waiting for PR_INTERVAL_NO_TIMEOUT\n")); else PR_LOG(gTimerLog, PR_LOG_DEBUG, ("waiting for %u\n", PR_IntervalToMilliseconds(waitFor))); } #endif } mWaiting = PR_TRUE; PR_WaitCondVar(mCondVar, waitFor); mWaiting = PR_FALSE; } return NS_OK; }
nsresult nsDirectoryIndexStream::Init(nsIFile* aDir) { nsresult rv; bool isDir; rv = aDir->IsDirectory(&isDir); if (NS_FAILED(rv)) return rv; NS_PRECONDITION(isDir, "not a directory"); if (!isDir) return NS_ERROR_ILLEGAL_VALUE; #ifdef PR_LOGGING if (PR_LOG_TEST(gLog, PR_LOG_DEBUG)) { nsCAutoString path; aDir->GetNativePath(path); PR_LOG(gLog, PR_LOG_DEBUG, ("nsDirectoryIndexStream[%p]: initialized on %s", this, path.get())); } #endif // Sigh. We have to allocate on the heap because there are no // assignment operators defined. nsCOMPtr<nsISimpleEnumerator> iter; rv = aDir->GetDirectoryEntries(getter_AddRefs(iter)); if (NS_FAILED(rv)) return rv; // Now lets sort, because clients expect it that way // XXX - should we do so here, or when the first item is requested? // XXX - use insertion sort instead? bool more; nsCOMPtr<nsISupports> elem; while (NS_SUCCEEDED(iter->HasMoreElements(&more)) && more) { rv = iter->GetNext(getter_AddRefs(elem)); if (NS_SUCCEEDED(rv)) { nsCOMPtr<nsIFile> file = do_QueryInterface(elem); if (file) mArray.AppendObject(file); // addrefs } } #ifdef THREADSAFE_I18N nsCOMPtr<nsILocaleService> ls = do_GetService(NS_LOCALESERVICE_CONTRACTID, &rv); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsILocale> locale; rv = ls->GetApplicationLocale(getter_AddRefs(locale)); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsICollationFactory> cf = do_CreateInstance(NS_COLLATIONFACTORY_CONTRACTID, &rv); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsICollation> coll; rv = cf->CreateCollation(locale, getter_AddRefs(coll)); if (NS_FAILED(rv)) return rv; mArray.Sort(compare, coll); #else mArray.Sort(compare, nsnull); #endif mBuf.AppendLiteral("300: "); nsCAutoString url; rv = net_GetURLSpecFromFile(aDir, url); if (NS_FAILED(rv)) return rv; mBuf.Append(url); mBuf.Append('\n'); mBuf.AppendLiteral("200: filename content-length last-modified file-type\n"); return NS_OK; }
NS_IMETHODIMP nsDirectoryIndexStream::Read(char* aBuf, PRUint32 aCount, PRUint32* aReadCount) { if (mStatus == NS_BASE_STREAM_CLOSED) { *aReadCount = 0; return NS_OK; } if (NS_FAILED(mStatus)) return mStatus; PRUint32 nread = 0; // If anything is enqueued (or left-over) in mBuf, then feed it to // the reader first. while (mOffset < (PRInt32)mBuf.Length() && aCount != 0) { *(aBuf++) = char(mBuf.CharAt(mOffset++)); --aCount; ++nread; } // Room left? if (aCount > 0) { mOffset = 0; mBuf.Truncate(); // Okay, now we'll suck stuff off of our iterator into the mBuf... while (PRUint32(mBuf.Length()) < aCount) { bool more = mPos < mArray.Count(); if (!more) break; // don't addref, for speed - an addref happened when it // was placed in the array, so it's not going to go stale nsIFile* current = mArray.ObjectAt(mPos); ++mPos; #ifdef PR_LOGGING if (PR_LOG_TEST(gLog, PR_LOG_DEBUG)) { nsCAutoString path; current->GetNativePath(path); PR_LOG(gLog, PR_LOG_DEBUG, ("nsDirectoryIndexStream[%p]: iterated %s", this, path.get())); } #endif // rjc: don't return hidden files/directories! // bbaetz: why not? nsresult rv; #ifndef XP_UNIX bool hidden = false; current->IsHidden(&hidden); if (hidden) { PR_LOG(gLog, PR_LOG_DEBUG, ("nsDirectoryIndexStream[%p]: skipping hidden file/directory", this)); continue; } #endif PRInt64 fileSize = 0; current->GetFileSize( &fileSize ); PRInt64 fileInfoModifyTime = 0; current->GetLastModifiedTime( &fileInfoModifyTime ); fileInfoModifyTime *= PR_USEC_PER_MSEC; mBuf.AppendLiteral("201: "); // The "filename" field char* escaped = nsnull; if (!NS_IsNativeUTF8()) { nsAutoString leafname; rv = current->GetLeafName(leafname); if (NS_FAILED(rv)) return rv; if (!leafname.IsEmpty()) escaped = nsEscape(NS_ConvertUTF16toUTF8(leafname).get(), url_Path); } else { nsCAutoString leafname; rv = current->GetNativeLeafName(leafname); if (NS_FAILED(rv)) return rv; if (!leafname.IsEmpty()) escaped = nsEscape(leafname.get(), url_Path); } if (escaped) { mBuf += escaped; mBuf.Append(' '); nsMemory::Free(escaped); } // The "content-length" field mBuf.AppendInt(fileSize, 10); mBuf.Append(' '); // The "last-modified" field PRExplodedTime tm; PR_ExplodeTime(fileInfoModifyTime, PR_GMTParameters, &tm); { char buf[64]; PR_FormatTimeUSEnglish(buf, sizeof(buf), "%a,%%20%d%%20%b%%20%Y%%20%H:%M:%S%%20GMT ", &tm); mBuf.Append(buf); } // The "file-type" field bool isFile = true; current->IsFile(&isFile); if (isFile) { mBuf.AppendLiteral("FILE "); } else { bool isDir; rv = current->IsDirectory(&isDir); if (NS_FAILED(rv)) return rv; if (isDir) { mBuf.AppendLiteral("DIRECTORY "); } else { bool isLink; rv = current->IsSymlink(&isLink); if (NS_FAILED(rv)) return rv; if (isLink) { mBuf.AppendLiteral("SYMBOLIC-LINK "); } } } mBuf.Append('\n'); } // ...and once we've either run out of directory entries, or // filled up the buffer, then we'll push it to the reader. while (mOffset < (PRInt32)mBuf.Length() && aCount != 0) { *(aBuf++) = char(mBuf.CharAt(mOffset++)); --aCount; ++nread; } } *aReadCount = nread; return NS_OK; }
MediaConduitErrorCode WebrtcAudioConduit::SendAudioFrame(const int16_t audio_data[], int32_t lengthSamples, int32_t samplingFreqHz, int32_t capture_delay) { CSFLogDebug(logTag, "%s ", __FUNCTION__); // Following checks need to be performed // 1. Non null audio buffer pointer, // 2. invalid sampling frequency - less than 0 or unsupported ones // 3. Appropriate Sample Length for 10 ms audio-frame. This represents // block size the VoiceEngine feeds into encoder for passed in audio-frame // Ex: for 16000 sampling rate , valid block-length is 160 // Similarly for 32000 sampling rate, valid block length is 320 // We do the check by the verify modular operator below to be zero if(!audio_data || (lengthSamples <= 0) || (IsSamplingFreqSupported(samplingFreqHz) == false) || ((lengthSamples % (samplingFreqHz / 100) != 0)) ) { CSFLogError(logTag, "%s Invalid Parameters ",__FUNCTION__); MOZ_ASSERT(PR_FALSE); return kMediaConduitMalformedArgument; } //validate capture time if(capture_delay < 0 ) { CSFLogError(logTag,"%s Invalid Capture Delay ", __FUNCTION__); MOZ_ASSERT(PR_FALSE); return kMediaConduitMalformedArgument; } // if transmission is not started .. conduit cannot insert frames if(!mEngineTransmitting) { CSFLogError(logTag, "%s Engine not transmitting ", __FUNCTION__); return kMediaConduitSessionNotInited; } #ifdef MOZILLA_INTERNAL_API if (PR_LOG_TEST(GetLatencyLog(), PR_LOG_DEBUG)) { struct Processing insert = { TimeStamp::Now(), 0 }; mProcessing.AppendElement(insert); } #endif capture_delay = mCaptureDelay; //Insert the samples if(mPtrVoEXmedia->ExternalRecordingInsertData(audio_data, lengthSamples, samplingFreqHz, capture_delay) == -1) { int error = mPtrVoEBase->LastError(); CSFLogError(logTag, "%s Inserting audio data Failed %d", __FUNCTION__, error); if(error == VE_RUNTIME_REC_ERROR) { return kMediaConduitRecordingError; } return kMediaConduitUnknownError; } // we should be good here return kMediaConduitNoError; }
nsresult nsRDFConInstanceTestNode::FilterInstantiations(InstantiationSet& aInstantiations, PRBool* aCantHandleYet) const { nsresult rv; if (aCantHandleYet) *aCantHandleYet = PR_FALSE; nsCOMPtr<nsIRDFContainerUtils> rdfc = do_GetService("@mozilla.org/rdf/container-utils;1"); if (! rdfc) return NS_ERROR_FAILURE; nsIRDFDataSource* ds = mProcessor->GetDataSource(); InstantiationSet::Iterator last = aInstantiations.Last(); for (InstantiationSet::Iterator inst = aInstantiations.First(); inst != last; ++inst) { nsCOMPtr<nsIRDFNode> value; if (! inst->mAssignments.GetAssignmentFor(mContainerVariable, getter_AddRefs(value))) { NS_ERROR("can't do unbounded container testing"); return NS_ERROR_UNEXPECTED; } nsCOMPtr<nsIRDFResource> valueres = do_QueryInterface(value); if (! valueres) { aInstantiations.Erase(inst--); continue; } #ifdef PR_LOGGING if (PR_LOG_TEST(gXULTemplateLog, PR_LOG_DEBUG)) { const char* container = "(unbound)"; valueres->GetValueConst(&container); PR_LOG(gXULTemplateLog, PR_LOG_DEBUG, ("nsRDFConInstanceTestNode[%p]::FilterInstantiations() container=[%s]", this, container)); } #endif nsCOMPtr<nsIRDFContainer> rdfcontainer; PRBool isRDFContainer; rv = rdfc->IsContainer(ds, valueres, &isRDFContainer); if (NS_FAILED(rv)) return rv; if (mEmpty != eDontCare || mContainer != eDontCare) { Test empty = eDontCare; Test container = eDontCare; if (isRDFContainer) { // It's an RDF container. Use the container utilities // to deduce what's in it. container = eTrue; // XXX should cache the factory rdfcontainer = do_CreateInstance("@mozilla.org/rdf/container;1", &rv); if (NS_FAILED(rv)) return rv; rv = rdfcontainer->Init(ds, valueres); if (NS_FAILED(rv)) return rv; PRInt32 count; rv = rdfcontainer->GetCount(&count); if (NS_FAILED(rv)) return rv; empty = (count == 0) ? eTrue : eFalse; } else { empty = eTrue; container = eFalse; // First do the simple check of finding some outward // arcs; there should be only a few containment arcs, so this can // save us time from dealing with an iterator later on nsResourceSet& containmentProps = mProcessor->ContainmentProperties(); for (nsResourceSet::ConstIterator property = containmentProps.First(); property != containmentProps.Last(); ++property) { nsCOMPtr<nsIRDFNode> target; rv = ds->GetTarget(valueres, *property, PR_TRUE, getter_AddRefs(target)); if (NS_FAILED(rv)) return rv; if (target != nsnull) { // bingo. we found one. empty = eFalse; container = eTrue; break; } } // if we still don't think its a container, but we // want to know for sure whether it is or not, we need // to check ArcLabelsOut for potential container arcs. if (container == eFalse && mContainer != eDontCare) { nsCOMPtr<nsISimpleEnumerator> arcsout; rv = ds->ArcLabelsOut(valueres, getter_AddRefs(arcsout)); if (NS_FAILED(rv)) return rv; while (1) { PRBool hasmore; rv = arcsout->HasMoreElements(&hasmore); if (NS_FAILED(rv)) return rv; if (! hasmore) break; nsCOMPtr<nsISupports> isupports; rv = arcsout->GetNext(getter_AddRefs(isupports)); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsIRDFResource> property = do_QueryInterface(isupports); NS_ASSERTION(property != nsnull, "not a property"); if (! property) return NS_ERROR_UNEXPECTED; if (mProcessor->ContainmentProperties().Contains(property)) { container = eTrue; break; } } } } PR_LOG(gXULTemplateLog, PR_LOG_DEBUG, (" empty => %s", (empty == mEmpty) ? "consistent" : "inconsistent")); PR_LOG(gXULTemplateLog, PR_LOG_DEBUG, (" container => %s", (container == mContainer) ? "consistent" : "inconsistent")); if (((mEmpty == empty) && (mContainer == container)) || ((mEmpty == eDontCare) && (mContainer == container)) || ((mContainer == eDontCare) && (mEmpty == empty))) { Element* element = nsRDFConInstanceTestNode::Element::Create(valueres, container, empty); if (! element) return NS_ERROR_OUT_OF_MEMORY; inst->AddSupportingElement(element); } else { aInstantiations.Erase(inst--); } } } return NS_OK; }
long AudioStream::DataCallback(void* aBuffer, long aFrames) { MonitorAutoLock mon(mMonitor); uint32_t available = std::min(static_cast<uint32_t>(FramesToBytes(aFrames)), mBuffer.Length()); NS_ABORT_IF_FALSE(available % mBytesPerFrame == 0, "Must copy complete frames"); AudioDataValue* output = reinterpret_cast<AudioDataValue*>(aBuffer); uint32_t underrunFrames = 0; uint32_t servicedFrames = 0; int64_t insertTime; if (available) { // When we are playing a low latency stream, and it is the first time we are // getting data from the buffer, we prefer to add the silence for an // underrun at the beginning of the buffer, so the first buffer is not cut // in half by the silence inserted to compensate for the underrun. if (mInRate == mOutRate) { if (mLatencyRequest == LowLatency && !mWritten) { servicedFrames = GetUnprocessedWithSilencePadding(output, aFrames, insertTime); } else { servicedFrames = GetUnprocessed(output, aFrames, insertTime); } } else { servicedFrames = GetTimeStretched(output, aFrames, insertTime); } float scaled_volume = float(GetVolumeScale() * mVolume); ScaleAudioSamples(output, aFrames * mOutChannels, scaled_volume); NS_ABORT_IF_FALSE(mBuffer.Length() % mBytesPerFrame == 0, "Must copy complete frames"); // Notify any blocked Write() call that more space is available in mBuffer. mon.NotifyAll(); } else { GetBufferInsertTime(insertTime); } underrunFrames = aFrames - servicedFrames; if (mState != DRAINING) { uint8_t* rpos = static_cast<uint8_t*>(aBuffer) + FramesToBytes(aFrames - underrunFrames); memset(rpos, 0, FramesToBytes(underrunFrames)); if (underrunFrames) { PR_LOG(gAudioStreamLog, PR_LOG_WARNING, ("AudioStream %p lost %d frames", this, underrunFrames)); } mLostFrames += underrunFrames; servicedFrames += underrunFrames; } WriteDumpFile(mDumpFile, this, aFrames, aBuffer); // Don't log if we're not interested or if the stream is inactive if (PR_LOG_TEST(GetLatencyLog(), PR_LOG_DEBUG) && insertTime != INT64_MAX && servicedFrames > underrunFrames) { uint32_t latency = UINT32_MAX; if (cubeb_stream_get_latency(mCubebStream, &latency)) { NS_WARNING("Could not get latency from cubeb."); } TimeStamp now = TimeStamp::Now(); mLatencyLog->Log(AsyncLatencyLogger::AudioStream, reinterpret_cast<uint64_t>(this), insertTime, now); mLatencyLog->Log(AsyncLatencyLogger::Cubeb, reinterpret_cast<uint64_t>(mCubebStream.get()), (latency * 1000) / mOutRate, now); } mAudioClock.UpdateWritePosition(servicedFrames); return servicedFrames; }
nsresult nsRDFConMemberTestNode::FilterInstantiations(InstantiationSet& aInstantiations, bool* aCantHandleYet) const { // XXX Uh, factor me, please! nsresult rv; if (aCantHandleYet) *aCantHandleYet = false; nsCOMPtr<nsIRDFContainerUtils> rdfc = do_GetService("@mozilla.org/rdf/container-utils;1"); if (! rdfc) return NS_ERROR_FAILURE; nsIRDFDataSource* ds = mProcessor->GetDataSource(); InstantiationSet::Iterator last = aInstantiations.Last(); for (InstantiationSet::Iterator inst = aInstantiations.First(); inst != last; ++inst) { bool hasContainerBinding; nsCOMPtr<nsIRDFNode> containerValue; hasContainerBinding = inst->mAssignments.GetAssignmentFor(mContainerVariable, getter_AddRefs(containerValue)); nsCOMPtr<nsIRDFResource> containerRes = do_QueryInterface(containerValue); nsCOMPtr<nsIRDFContainer> rdfcontainer; if (hasContainerBinding && containerRes) { // If we have a container assignment, then see if the // container is an RDF container (bag, seq, alt), and if // so, wrap it. bool isRDFContainer; rv = rdfc->IsContainer(ds, containerRes, &isRDFContainer); if (NS_FAILED(rv)) return rv; if (isRDFContainer) { rdfcontainer = do_CreateInstance("@mozilla.org/rdf/container;1", &rv); if (NS_FAILED(rv)) return rv; rv = rdfcontainer->Init(ds, containerRes); if (NS_FAILED(rv)) return rv; } } bool hasMemberBinding; nsCOMPtr<nsIRDFNode> memberValue; hasMemberBinding = inst->mAssignments.GetAssignmentFor(mMemberVariable, getter_AddRefs(memberValue)); #ifdef PR_LOGGING if (PR_LOG_TEST(gXULTemplateLog, PR_LOG_DEBUG)) { const char* container = "(unbound)"; if (hasContainerBinding) containerRes->GetValueConst(&container); nsAutoString member(NS_LITERAL_STRING("(unbound)")); if (hasMemberBinding) nsXULContentUtils::GetTextForNode(memberValue, member); PR_LOG(gXULTemplateLog, PR_LOG_DEBUG, ("nsRDFConMemberTestNode[%p]: FilterInstantiations() container=[%s] member=[%s]", this, container, NS_ConvertUTF16toUTF8(member).get())); } #endif if (hasContainerBinding && hasMemberBinding) { // it's a consistency check. see if we have a assignment that is consistent bool isconsistent = false; if (rdfcontainer) { // RDF containers are easy. Just use the container API. PRInt32 index; rv = rdfcontainer->IndexOf(memberValue, &index); if (NS_FAILED(rv)) return rv; if (index >= 0) isconsistent = true; } // XXXwaterson oof. if we *are* an RDF container, why do // we still need to grovel through all the containment // properties if the thing we're looking for wasn't there? if (! isconsistent) { // Othewise, we'll need to grovel through the // membership properties to see if we have an // assertion that indicates membership. nsResourceSet& containmentProps = mProcessor->ContainmentProperties(); for (nsResourceSet::ConstIterator property = containmentProps.First(); property != containmentProps.Last(); ++property) { bool hasAssertion; rv = ds->HasAssertion(containerRes, *property, memberValue, true, &hasAssertion); if (NS_FAILED(rv)) return rv; if (hasAssertion) { // it's consistent. leave it in the set and we'll // run it up to our parent. isconsistent = true; break; } } } PR_LOG(gXULTemplateLog, PR_LOG_DEBUG, (" consistency check => %s", isconsistent ? "passed" : "failed")); if (isconsistent) { // Add a memory element to our set-of-support. Element* element = nsRDFConMemberTestNode::Element::Create(containerRes, memberValue); if (! element) return NS_ERROR_OUT_OF_MEMORY; inst->AddSupportingElement(element); } else { // it's inconsistent. remove it. aInstantiations.Erase(inst--); } // We're done, go on to the next instantiation continue; } if (hasContainerBinding && rdfcontainer) { // We've got a container assignment, and the container is // bound to an RDF container. Add each member as a new // instantiation. nsCOMPtr<nsISimpleEnumerator> elements; rv = rdfcontainer->GetElements(getter_AddRefs(elements)); if (NS_FAILED(rv)) return rv; while (1) { bool hasmore; rv = elements->HasMoreElements(&hasmore); if (NS_FAILED(rv)) return rv; if (! hasmore) break; nsCOMPtr<nsISupports> isupports; rv = elements->GetNext(getter_AddRefs(isupports)); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsIRDFNode> node = do_QueryInterface(isupports); if (! node) return NS_ERROR_UNEXPECTED; #ifdef PR_LOGGING if (PR_LOG_TEST(gXULTemplateLog, PR_LOG_DEBUG)) { nsAutoString member; nsXULContentUtils::GetTextForNode(node, member); PR_LOG(gXULTemplateLog, PR_LOG_DEBUG, (" member => %s", NS_ConvertUTF16toUTF8(member).get())); } #endif Instantiation newinst = *inst; newinst.AddAssignment(mMemberVariable, node); Element* element = nsRDFConMemberTestNode::Element::Create(containerRes, node); if (! element) return NS_ERROR_OUT_OF_MEMORY; newinst.AddSupportingElement(element); aInstantiations.Insert(inst, newinst); } } if (hasMemberBinding) { // Oh, this is so nasty. If we have a member assignment, then // grovel through each one of our inbound arcs to see if // any of them are ordinal properties (like an RDF // container might have). If so, walk it backwards to get // the container we're in. nsCOMPtr<nsISimpleEnumerator> arcsin; rv = ds->ArcLabelsIn(memberValue, getter_AddRefs(arcsin)); if (NS_FAILED(rv)) return rv; while (1) { nsCOMPtr<nsIRDFResource> property; { bool hasmore; rv = arcsin->HasMoreElements(&hasmore); if (NS_FAILED(rv)) return rv; if (! hasmore) break; nsCOMPtr<nsISupports> isupports; rv = arcsin->GetNext(getter_AddRefs(isupports)); if (NS_FAILED(rv)) return rv; property = do_QueryInterface(isupports); if (! property) return NS_ERROR_UNEXPECTED; } // Ordinal properties automagically indicate container // membership as far as we're concerned. Note that // we're *only* concerned with ordinal properties // here: the next block will worry about the other // membership properties. bool isordinal; rv = rdfc->IsOrdinalProperty(property, &isordinal); if (NS_FAILED(rv)) return rv; if (isordinal) { // If we get here, we've found a property that // indicates container membership leading *into* a // member node. Find all the people that point to // it, and call them containers. nsCOMPtr<nsISimpleEnumerator> sources; rv = ds->GetSources(property, memberValue, true, getter_AddRefs(sources)); if (NS_FAILED(rv)) return rv; while (1) { bool hasmore; rv = sources->HasMoreElements(&hasmore); if (NS_FAILED(rv)) return rv; if (! hasmore) break; nsCOMPtr<nsISupports> isupports; rv = sources->GetNext(getter_AddRefs(isupports)); if (NS_FAILED(rv)) return rv; nsCOMPtr<nsIRDFResource> source = do_QueryInterface(isupports); if (! source) return NS_ERROR_UNEXPECTED; #ifdef PR_LOGGING if (PR_LOG_TEST(gXULTemplateLog, PR_LOG_DEBUG)) { const char* container; source->GetValueConst(&container); PR_LOG(gXULTemplateLog, PR_LOG_DEBUG, (" container => %s", container)); } #endif // Add a new instantiation Instantiation newinst = *inst; newinst.AddAssignment(mContainerVariable, source); Element* element = nsRDFConMemberTestNode::Element::Create(source, memberValue); if (! element) return NS_ERROR_OUT_OF_MEMORY; newinst.AddSupportingElement(element); aInstantiations.Insert(inst, newinst); } } } } if ((hasContainerBinding && ! hasMemberBinding) || (! hasContainerBinding && hasMemberBinding)) { // it's an open ended query on the container or member. go // through our containment properties to see if anything // applies. nsResourceSet& containmentProps = mProcessor->ContainmentProperties(); for (nsResourceSet::ConstIterator property = containmentProps.First(); property != containmentProps.Last(); ++property) { nsCOMPtr<nsISimpleEnumerator> results; if (hasContainerBinding) { rv = ds->GetTargets(containerRes, *property, true, getter_AddRefs(results)); } else { rv = ds->GetSources(*property, memberValue, true, getter_AddRefs(results)); } if (NS_FAILED(rv)) return rv; while (1) { bool hasmore; rv = results->HasMoreElements(&hasmore); if (NS_FAILED(rv)) return rv; if (! hasmore) break; nsCOMPtr<nsISupports> isupports; rv = results->GetNext(getter_AddRefs(isupports)); if (NS_FAILED(rv)) return rv; nsIAtom* variable; nsCOMPtr<nsIRDFNode> value; nsCOMPtr<nsIRDFResource> valueRes; if (hasContainerBinding) { variable = mMemberVariable; value = do_QueryInterface(isupports); NS_ASSERTION(value != nsnull, "member is not an nsIRDFNode"); if (! value) continue; #ifdef PR_LOGGING if (PR_LOG_TEST(gXULTemplateLog, PR_LOG_DEBUG)) { nsAutoString s; nsXULContentUtils::GetTextForNode(value, s); PR_LOG(gXULTemplateLog, PR_LOG_DEBUG, (" member => %s", NS_ConvertUTF16toUTF8(s).get())); } #endif } else { variable = mContainerVariable; valueRes = do_QueryInterface(isupports); NS_ASSERTION(valueRes != nsnull, "container is not an nsIRDFResource"); if (! valueRes) continue; value = valueRes; #ifdef PR_LOGGING if (PR_LOG_TEST(gXULTemplateLog, PR_LOG_DEBUG)) { const char* s; valueRes->GetValueConst(&s); PR_LOG(gXULTemplateLog, PR_LOG_DEBUG, (" container => %s", s)); } #endif } // Copy the original instantiation, and add it to the // instantiation set with the new assignment that we've // introduced. Ownership will be transferred to the Instantiation newinst = *inst; newinst.AddAssignment(variable, value); Element* element; if (hasContainerBinding) { element = nsRDFConMemberTestNode::Element::Create(containerRes, value); } else { element = nsRDFConMemberTestNode::Element::Create(valueRes, memberValue); } if (! element) return NS_ERROR_OUT_OF_MEMORY; newinst.AddSupportingElement(element); aInstantiations.Insert(inst, newinst); } } } if (! hasContainerBinding && ! hasMemberBinding) { // Neither container nor member assignment! if (!aCantHandleYet) { nsXULContentUtils::LogTemplateError(ERROR_TEMPLATE_MEMBER_UNBOUND); return NS_ERROR_UNEXPECTED; } *aCantHandleYet = true; return NS_OK; } // finally, remove the "under specified" instantiation. aInstantiations.Erase(inst--); } return NS_OK; }
nsresult CVE_2013_1709_thunderbird6_0_2_nsDocShell::AddToSessionHistory(nsIURI * aURI, nsIChannel * aChannel, nsISupports* aOwner, PRBool aCloneChildren, nsISHEntry ** aNewEntry) { NS_PRECONDITION(aURI, "uri is null"); NS_PRECONDITION(!aChannel || !aOwner, "Shouldn't have both set"); #if defined(PR_LOGGING) && defined(DEBUG) if (PR_LOG_TEST(gDocShellLog, PR_LOG_DEBUG)) { nsCAutoString spec; aURI->GetSpec(spec); nsCAutoString chanName; if (aChannel) aChannel->GetName(chanName); else chanName.AssignLiteral("<no channel>"); PR_LOG(gDocShellLog, PR_LOG_DEBUG, ("nsDocShell[%p]::AddToSessionHistory(\"%s\", [%s])\n", this, spec.get(), chanName.get())); } #endif nsresult rv = NS_OK; nsCOMPtr<nsISHEntry> entry; PRBool shouldPersist; shouldPersist = ShouldAddToSessionHistory(aURI); // Get a handle to the root docshell nsCOMPtr<nsIDocShellTreeItem> root; GetSameTypeRootTreeItem(getter_AddRefs(root)); /* * If this is a LOAD_FLAGS_REPLACE_HISTORY in a subframe, we use * the existing SH entry in the page and replace the url and * other vitalities. */ if (LOAD_TYPE_HAS_FLAGS(mLoadType, LOAD_FLAGS_REPLACE_HISTORY) && root != static_cast<nsIDocShellTreeItem *>(this)) { // This is a subframe entry = mOSHE; nsCOMPtr<nsISHContainer> shContainer(do_QueryInterface(entry)); if (shContainer) { PRInt32 childCount = 0; shContainer->GetChildCount(&childCount); // Remove all children of this entry for (PRInt32 i = childCount - 1; i >= 0; i--) { nsCOMPtr<nsISHEntry> child; shContainer->GetChildAt(i, getter_AddRefs(child)); shContainer->RemoveChild(child); } // for } // shContainer } // Create a new entry if necessary. if (!entry) { entry = do_CreateInstance(NS_SHENTRY_CONTRACTID); if (!entry) { return NS_ERROR_OUT_OF_MEMORY; } } // Get the post data & referrer nsCOMPtr<nsIInputStream> inputStream; nsCOMPtr<nsIURI> referrerURI; nsCOMPtr<nsISupports> cacheKey; nsCOMPtr<nsISupports> owner = aOwner; PRBool expired = PR_FALSE; PRBool discardLayoutState = PR_FALSE; nsCOMPtr<nsICachingChannel> cacheChannel; if (aChannel) { cacheChannel = do_QueryInterface(aChannel); /* If there is a caching channel, get the Cache Key and store it * in SH. */ if (cacheChannel) { cacheChannel->GetCacheKey(getter_AddRefs(cacheKey)); } nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(aChannel)); // Check if the httpChannel is hiding under a multipartChannel if (!httpChannel) { GetHttpChannel(aChannel, getter_AddRefs(httpChannel)); } if (httpChannel) { nsCOMPtr<nsIUploadChannel> uploadChannel(do_QueryInterface(httpChannel)); if (uploadChannel) { uploadChannel->GetUploadStream(getter_AddRefs(inputStream)); } httpChannel->GetReferrer(getter_AddRefs(referrerURI)); discardLayoutState = ShouldDiscardLayoutState(httpChannel); } aChannel->GetOwner(getter_AddRefs(owner)); } //Title is set in nsDocShell::SetTitle() entry->Create(aURI, // uri EmptyString(), // Title inputStream, // Post data stream nsnull, // LayoutHistory state cacheKey, // CacheKey mContentTypeHint, // Content-type owner, // Channel or provided owner mHistoryID, mDynamicallyCreated); entry->SetReferrerURI(referrerURI); /* If cache got a 'no-store', ask SH not to store * HistoryLayoutState. By default, SH will set this * flag to PR_TRUE and save HistoryLayoutState. */ if (discardLayoutState) { entry->SetSaveLayoutStateFlag(PR_FALSE); } if (cacheChannel) { // Check if the page has expired from cache PRUint32 expTime = 0; cacheChannel->GetCacheTokenExpirationTime(&expTime); PRUint32 now = PRTimeToSeconds(PR_Now()); if (expTime <= now) expired = PR_TRUE; } if (expired) entry->SetExpirationStatus(PR_TRUE); if (root == static_cast<nsIDocShellTreeItem *>(this) && mSessionHistory) { // If we need to clone our children onto the new session // history entry, do so now. if (aCloneChildren && mOSHE) { PRUint32 cloneID; mOSHE->GetID(&cloneID); nsCOMPtr<nsISHEntry> newEntry; CloneAndReplace(mOSHE, this, cloneID, entry, PR_TRUE, getter_AddRefs(newEntry)); NS_ASSERTION(entry == newEntry, "The new session history should be in the new entry"); } // This is the root docshell if (LOAD_TYPE_HAS_FLAGS(mLoadType, LOAD_FLAGS_REPLACE_HISTORY)) { // Replace current entry in session history. PRInt32 index = 0; mSessionHistory->GetIndex(&index); nsCOMPtr<nsISHistoryInternal> shPrivate(do_QueryInterface(mSessionHistory)); // Replace the current entry with the new entry if (shPrivate) rv = shPrivate->ReplaceEntry(index, entry); } else { // Add to session history nsCOMPtr<nsISHistoryInternal> shPrivate(do_QueryInterface(mSessionHistory)); NS_ENSURE_TRUE(shPrivate, NS_ERROR_FAILURE); mSessionHistory->GetIndex(&mPreviousTransIndex); rv = shPrivate->AddEntry(entry, shouldPersist); mSessionHistory->GetIndex(&mLoadedTransIndex); #ifdef DEBUG_PAGE_CACHE printf("Previous index: %d, Loaded index: %d\n\n", mPreviousTransIndex, mLoadedTransIndex); #endif } } else { // This is a subframe. if (!mOSHE || !LOAD_TYPE_HAS_FLAGS(mLoadType, LOAD_FLAGS_REPLACE_HISTORY)) rv = DoAddChildSHEntry(entry, mChildOffset, aCloneChildren); } // Return the new SH entry... if (aNewEntry) { *aNewEntry = nsnull; if (NS_SUCCEEDED(rv)) { *aNewEntry = entry; NS_ADDREF(*aNewEntry); } } return rv; }
nsresult nsWebDAVService::SendDocumentToChannel(nsIDocument *doc, nsIHttpChannel *channel, const char *const method, nsIStreamListener *listener, PRBool withDepth) { // Why do I have to pick values for these? I just want to store some data // for stream access! (And how would script set these?) nsresult rv; nsCOMPtr<nsIStorageStream> const storageStream( do_CreateInstance("@mozilla.org/storagestream;1", &rv)); NS_ENSURE_SUCCESS(rv, rv); rv = storageStream->Init(4096, PR_UINT32_MAX, nsnull); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIOutputStream> storageOutputStream; rv = storageStream->GetOutputStream(0, getter_AddRefs(storageOutputStream)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIDocumentEncoder> encoder = do_CreateInstance(NS_DOC_ENCODER_CONTRACTID_BASE "text/xml", &rv); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIDOMDocument> domDoc = do_QueryInterface(doc); NS_ASSERTION(domDoc, "Need a document"); rv = encoder->Init(domDoc, NS_LITERAL_STRING("text/xml"), nsIDocumentEncoder::OutputEncodeBasicEntities); NS_ENSURE_SUCCESS(rv, rv); encoder->SetCharset(NS_LITERAL_CSTRING("UTF-8")); rv = encoder->EncodeToStream(storageOutputStream); NS_ENSURE_SUCCESS(rv, rv); storageOutputStream->Close(); // You gotta really want it. #ifdef PR_LOGGING if (PR_LOG_TEST(gDAVLog, 5)) { nsCOMPtr<nsIInputStream> logInputStream; rv = storageStream->NewInputStream(0, getter_AddRefs(logInputStream)); NS_ENSURE_SUCCESS(rv, rv); PRUint32 len, read; logInputStream->Available(&len); char *buf = new char[len+1]; memset(buf, 0, len+1); logInputStream->Read(buf, len, &read); NS_ASSERTION(len == read, "short read on closed storage stream?"); LOG(("XML:\n\n%*s\n\n", len, buf)); delete [] buf; } #endif nsCOMPtr<nsIInputStream> inputStream; rv = storageStream->NewInputStream(0, getter_AddRefs(inputStream)); NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsIUploadChannel> uploadChannel = do_QueryInterface(channel, &rv); NS_ENSURE_SUCCESS(rv, rv); rv = uploadChannel->SetUploadStream(inputStream, NS_LITERAL_CSTRING("text/xml"), -1); NS_ENSURE_SUCCESS(rv, rv); channel->SetRequestMethod(nsDependentCString(method)); channel->SetRequestHeader(NS_LITERAL_CSTRING("Content-Type"), NS_LITERAL_CSTRING("text/xml; charset=utf-8"), PR_FALSE); channel->SetRequestHeader(NS_LITERAL_CSTRING("Accept"), NS_LITERAL_CSTRING("text/xml"), PR_FALSE); channel->SetRequestHeader(NS_LITERAL_CSTRING("Accept-Charset"), NS_LITERAL_CSTRING("utf-8,*;q=0.1"), PR_FALSE); if (withDepth) { channel->SetRequestHeader(NS_LITERAL_CSTRING("Depth"), NS_LITERAL_CSTRING("1"), PR_FALSE); } else { channel->SetRequestHeader(NS_LITERAL_CSTRING("Depth"), NS_LITERAL_CSTRING("0"), PR_FALSE); } #ifdef PR_LOGGING if (LOG_ENABLED()) { nsCOMPtr<nsIURI> uri; channel->GetURI(getter_AddRefs(uri)); nsCAutoString spec; uri->GetSpec(spec); LOG(("%s starting for %s", method, spec.get())); } #endif return channel->AsyncOpen(listener, channel); }
void nsTimerImpl::Fire() { if (mCanceled) return; PRIntervalTime now = PR_IntervalNow(); #ifdef DEBUG_TIMERS if (PR_LOG_TEST(gTimerLog, PR_LOG_DEBUG)) { PRIntervalTime a = now - mStart; // actual delay in intervals PRUint32 b = PR_MillisecondsToInterval(mDelay); // expected delay in intervals PRUint32 d = PR_IntervalToMilliseconds((a > b) ? a - b : b - a); // delta in ms sDeltaSum += d; sDeltaSumSquared += double(d) * double(d); sDeltaNum++; PR_LOG(gTimerLog, PR_LOG_DEBUG, ("[this=%p] expected delay time %4dms\n", this, mDelay)); PR_LOG(gTimerLog, PR_LOG_DEBUG, ("[this=%p] actual delay time %4dms\n", this, PR_IntervalToMilliseconds(a))); PR_LOG(gTimerLog, PR_LOG_DEBUG, ("[this=%p] (mType is %d) -------\n", this, mType)); PR_LOG(gTimerLog, PR_LOG_DEBUG, ("[this=%p] delta %4dms\n", this, (a > b) ? (PRInt32)d : -(PRInt32)d)); mStart = mStart2; mStart2 = 0; } #endif PRIntervalTime timeout = mTimeout; if (mType == TYPE_REPEATING_PRECISE) { // Precise repeating timers advance mTimeout by mDelay without fail before // calling Fire(). timeout -= PR_MillisecondsToInterval(mDelay); } if (gThread) gThread->UpdateFilter(mDelay, timeout, now); if (mCallbackType == CALLBACK_TYPE_INTERFACE) mTimerCallbackWhileFiring = mCallback.i; mFiring = PR_TRUE; // Handle callbacks that re-init the timer, but avoid leaking. // See bug 330128. CallbackUnion callback = mCallback; PRUintn callbackType = mCallbackType; if (callbackType == CALLBACK_TYPE_INTERFACE) NS_ADDREF(callback.i); else if (callbackType == CALLBACK_TYPE_OBSERVER) NS_ADDREF(callback.o); ReleaseCallback(); switch (callbackType) { case CALLBACK_TYPE_FUNC: callback.c(this, mClosure); break; case CALLBACK_TYPE_INTERFACE: callback.i->Notify(this); break; case CALLBACK_TYPE_OBSERVER: callback.o->Observe(static_cast<nsITimer*>(this), NS_TIMER_CALLBACK_TOPIC, nsnull); break; default:; } // If the callback didn't re-init the timer, and it's not a one-shot timer, // restore the callback state. if (mCallbackType == CALLBACK_TYPE_UNKNOWN && mType != TYPE_ONE_SHOT && !mCanceled) { mCallback = callback; mCallbackType = callbackType; } else { // The timer was a one-shot, or the callback was reinitialized. if (callbackType == CALLBACK_TYPE_INTERFACE) NS_RELEASE(callback.i); else if (callbackType == CALLBACK_TYPE_OBSERVER) NS_RELEASE(callback.o); } mFiring = PR_FALSE; mTimerCallbackWhileFiring = nsnull; #ifdef DEBUG_TIMERS if (PR_LOG_TEST(gTimerLog, PR_LOG_DEBUG)) { PR_LOG(gTimerLog, PR_LOG_DEBUG, ("[this=%p] Took %dms to fire timer callback\n", this, PR_IntervalToMilliseconds(PR_IntervalNow() - now))); } #endif if (mType == TYPE_REPEATING_SLACK) { SetDelayInternal(mDelay); // force mTimeout to be recomputed. if (gThread) gThread->AddTimer(this); } }
MediaConduitErrorCode WebrtcAudioConduit::GetAudioFrame(int16_t speechData[], int32_t samplingFreqHz, int32_t capture_delay, int& lengthSamples) { CSFLogDebug(logTag, "%s ", __FUNCTION__); unsigned int numSamples = 0; //validate params if(!speechData ) { CSFLogError(logTag,"%s Null Audio Buffer Pointer", __FUNCTION__); MOZ_ASSERT(PR_FALSE); return kMediaConduitMalformedArgument; } // Validate sample length if((numSamples = GetNum10msSamplesForFrequency(samplingFreqHz)) == 0 ) { CSFLogError(logTag,"%s Invalid Sampling Frequency ", __FUNCTION__); MOZ_ASSERT(PR_FALSE); return kMediaConduitMalformedArgument; } //validate capture time if(capture_delay < 0 ) { CSFLogError(logTag,"%s Invalid Capture Delay ", __FUNCTION__); MOZ_ASSERT(PR_FALSE); return kMediaConduitMalformedArgument; } //Conduit should have reception enabled before we ask for decoded // samples if(!mEngineReceiving) { CSFLogError(logTag, "%s Engine not Receiving ", __FUNCTION__); return kMediaConduitSessionNotInited; } lengthSamples = 0; //output paramter if(mPtrVoEXmedia->ExternalPlayoutGetData( speechData, samplingFreqHz, capture_delay, lengthSamples) == -1) { int error = mPtrVoEBase->LastError(); CSFLogError(logTag, "%s Getting audio data Failed %d", __FUNCTION__, error); if(error == VE_RUNTIME_PLAY_ERROR) { return kMediaConduitPlayoutError; } return kMediaConduitUnknownError; } // Not #ifdef DEBUG or on a log module so we can use it for about:webrtc/etc mSamples += lengthSamples; if (mSamples >= mLastSyncLog + samplingFreqHz) { int jitter_buffer_delay_ms; int playout_buffer_delay_ms; int avsync_offset_ms; if (GetAVStats(&jitter_buffer_delay_ms, &playout_buffer_delay_ms, &avsync_offset_ms)) { #ifdef MOZILLA_INTERNAL_API if (avsync_offset_ms < 0) { Telemetry::Accumulate(Telemetry::WEBRTC_AVSYNC_WHEN_VIDEO_LAGS_AUDIO_MS, -avsync_offset_ms); } else { Telemetry::Accumulate(Telemetry::WEBRTC_AVSYNC_WHEN_AUDIO_LAGS_VIDEO_MS, avsync_offset_ms); } #endif CSFLogError(logTag, "A/V sync: sync delta: %dms, audio jitter delay %dms, playout delay %dms", avsync_offset_ms, jitter_buffer_delay_ms, playout_buffer_delay_ms); } else { CSFLogError(logTag, "A/V sync: GetAVStats failed"); } mLastSyncLog = mSamples; } #ifdef MOZILLA_INTERNAL_API if (PR_LOG_TEST(GetLatencyLog(), PR_LOG_DEBUG)) { if (mProcessing.Length() > 0) { unsigned int now; mPtrVoEVideoSync->GetPlayoutTimestamp(mChannel, now); if (static_cast<uint32_t>(now) != mLastTimestamp) { mLastTimestamp = static_cast<uint32_t>(now); // Find the block that includes this timestamp in the network input while (mProcessing.Length() > 0) { // FIX! assumes 20ms @ 48000Hz // FIX handle wrap-around if (mProcessing[0].mRTPTimeStamp + 20*(48000/1000) >= now) { TimeDuration t = TimeStamp::Now() - mProcessing[0].mTimeStamp; // Wrap-around? int64_t delta = t.ToMilliseconds() + (now - mProcessing[0].mRTPTimeStamp)/(48000/1000); LogTime(AsyncLatencyLogger::AudioRecvRTP, ((uint64_t) this), delta); break; } mProcessing.RemoveElementAt(0); } } } } #endif CSFLogDebug(logTag,"%s GetAudioFrame:Got samples: length %d ",__FUNCTION__, lengthSamples); return kMediaConduitNoError; }
long AudioStream::DataCallback(void* aBuffer, long aFrames) { MonitorAutoLock mon(mMonitor); MOZ_ASSERT(mState != SHUTDOWN, "No data callback after shutdown"); uint32_t available = std::min(static_cast<uint32_t>(FramesToBytes(aFrames)), mBuffer.Length()); NS_ABORT_IF_FALSE(available % mBytesPerFrame == 0, "Must copy complete frames"); AudioDataValue* output = reinterpret_cast<AudioDataValue*>(aBuffer); uint32_t underrunFrames = 0; uint32_t servicedFrames = 0; int64_t insertTime; // NOTE: wasapi (others?) can call us back *after* stop()/Shutdown() (mState == SHUTDOWN) // Bug 996162 // callback tells us cubeb succeeded initializing if (mState == STARTED) { // For low-latency streams, we want to minimize any built-up data when // we start getting callbacks. // Simple version - contract on first callback only. if (mLatencyRequest == LowLatency) { #ifdef PR_LOGGING uint32_t old_len = mBuffer.Length(); #endif available = mBuffer.ContractTo(FramesToBytes(aFrames)); #ifdef PR_LOGGING TimeStamp now = TimeStamp::Now(); if (!mStartTime.IsNull()) { int64_t timeMs = (now - mStartTime).ToMilliseconds(); PR_LOG(gAudioStreamLog, PR_LOG_WARNING, ("Stream took %lldms to start after first Write() @ %u", timeMs, mOutRate)); } else { PR_LOG(gAudioStreamLog, PR_LOG_WARNING, ("Stream started before Write() @ %u", mOutRate)); } if (old_len != available) { // Note that we may have dropped samples in Write() as well! PR_LOG(gAudioStreamLog, PR_LOG_WARNING, ("AudioStream %p dropped %u + %u initial frames @ %u", this, mReadPoint, BytesToFrames(old_len - available), mOutRate)); mReadPoint += BytesToFrames(old_len - available); } #endif } mState = RUNNING; } if (available) { // When we are playing a low latency stream, and it is the first time we are // getting data from the buffer, we prefer to add the silence for an // underrun at the beginning of the buffer, so the first buffer is not cut // in half by the silence inserted to compensate for the underrun. if (mInRate == mOutRate) { if (mLatencyRequest == LowLatency && !mWritten) { servicedFrames = GetUnprocessedWithSilencePadding(output, aFrames, insertTime); } else { servicedFrames = GetUnprocessed(output, aFrames, insertTime); } } else { servicedFrames = GetTimeStretched(output, aFrames, insertTime); } float scaled_volume = float(GetVolumeScale() * mVolume); ScaleAudioSamples(output, aFrames * mOutChannels, scaled_volume); NS_ABORT_IF_FALSE(mBuffer.Length() % mBytesPerFrame == 0, "Must copy complete frames"); // Notify any blocked Write() call that more space is available in mBuffer. mon.NotifyAll(); } else { GetBufferInsertTime(insertTime); } underrunFrames = aFrames - servicedFrames; // Always send audible frames first, and silent frames later. // Otherwise it will break the assumption of FrameHistory. if (mState != DRAINING) { mAudioClock.UpdateFrameHistory(servicedFrames, underrunFrames); uint8_t* rpos = static_cast<uint8_t*>(aBuffer) + FramesToBytes(aFrames - underrunFrames); memset(rpos, 0, FramesToBytes(underrunFrames)); if (underrunFrames) { PR_LOG(gAudioStreamLog, PR_LOG_WARNING, ("AudioStream %p lost %d frames", this, underrunFrames)); } servicedFrames += underrunFrames; } else { mAudioClock.UpdateFrameHistory(servicedFrames, 0); } WriteDumpFile(mDumpFile, this, aFrames, aBuffer); // Don't log if we're not interested or if the stream is inactive if (PR_LOG_TEST(GetLatencyLog(), PR_LOG_DEBUG) && mState != SHUTDOWN && insertTime != INT64_MAX && servicedFrames > underrunFrames) { uint32_t latency = UINT32_MAX; if (cubeb_stream_get_latency(mCubebStream, &latency)) { NS_WARNING("Could not get latency from cubeb."); } TimeStamp now = TimeStamp::Now(); mLatencyLog->Log(AsyncLatencyLogger::AudioStream, reinterpret_cast<uint64_t>(this), insertTime, now); mLatencyLog->Log(AsyncLatencyLogger::Cubeb, reinterpret_cast<uint64_t>(mCubebStream.get()), (latency * 1000) / mOutRate, now); } return servicedFrames; }
nsresult nsRDFPropertyTestNode::FilterInstantiations(InstantiationSet& aInstantiations, bool* aCantHandleYet) const { nsresult rv; if (aCantHandleYet) *aCantHandleYet = false; nsIRDFDataSource* ds = mProcessor->GetDataSource(); InstantiationSet::Iterator last = aInstantiations.Last(); for (InstantiationSet::Iterator inst = aInstantiations.First(); inst != last; ++inst) { bool hasSourceBinding; nsCOMPtr<nsIRDFResource> sourceRes; if (mSource) { hasSourceBinding = true; sourceRes = mSource; } else { nsCOMPtr<nsIRDFNode> sourceValue; hasSourceBinding = inst->mAssignments.GetAssignmentFor(mSourceVariable, getter_AddRefs(sourceValue)); sourceRes = do_QueryInterface(sourceValue); } bool hasTargetBinding; nsCOMPtr<nsIRDFNode> targetValue; if (mTarget) { hasTargetBinding = true; targetValue = mTarget; } else { hasTargetBinding = inst->mAssignments.GetAssignmentFor(mTargetVariable, getter_AddRefs(targetValue)); } #ifdef PR_LOGGING if (PR_LOG_TEST(gXULTemplateLog, PR_LOG_DEBUG)) { const char* source = "(unbound)"; if (hasSourceBinding) sourceRes->GetValueConst(&source); nsAutoString target(NS_LITERAL_STRING("(unbound)")); if (hasTargetBinding) nsXULContentUtils::GetTextForNode(targetValue, target); PR_LOG(gXULTemplateLog, PR_LOG_DEBUG, ("nsRDFPropertyTestNode[%p]: FilterInstantiations() source=[%s] target=[%s]", this, source, NS_ConvertUTF16toUTF8(target).get())); } #endif if (hasSourceBinding && hasTargetBinding) { // it's a consistency check. see if we have a assignment that is consistent bool hasAssertion; rv = ds->HasAssertion(sourceRes, mProperty, targetValue, true, &hasAssertion); if (NS_FAILED(rv)) return rv; #ifdef PR_LOGGING PR_LOG(gXULTemplateLog, PR_LOG_DEBUG, (" consistency check => %s", hasAssertion ? "passed" : "failed")); #endif if (hasAssertion) { // it's consistent. Element* element = new nsRDFPropertyTestNode::Element(sourceRes, mProperty, targetValue); if (! element) return NS_ERROR_OUT_OF_MEMORY; inst->AddSupportingElement(element); } else { // it's inconsistent. remove it. aInstantiations.Erase(inst--); } } else if ((hasSourceBinding && ! hasTargetBinding) || (! hasSourceBinding && hasTargetBinding)) { // it's an open ended query on the source or // target. figure out what matches and add as a // cross-product. nsCOMPtr<nsISimpleEnumerator> results; if (hasSourceBinding) { rv = ds->GetTargets(sourceRes, mProperty, true, getter_AddRefs(results)); } else { rv = ds->GetSources(mProperty, targetValue, true, getter_AddRefs(results)); if (NS_FAILED(rv)) return rv; } while (1) { bool hasMore; rv = results->HasMoreElements(&hasMore); if (NS_FAILED(rv)) return rv; if (! hasMore) break; nsCOMPtr<nsISupports> isupports; rv = results->GetNext(getter_AddRefs(isupports)); if (NS_FAILED(rv)) return rv; nsIAtom* variable; nsCOMPtr<nsIRDFNode> value; if (hasSourceBinding) { variable = mTargetVariable; value = do_QueryInterface(isupports); NS_ASSERTION(value != nullptr, "target is not an nsIRDFNode"); #ifdef PR_LOGGING if (PR_LOG_TEST(gXULTemplateLog, PR_LOG_DEBUG)) { nsAutoString s(NS_LITERAL_STRING("(none found)")); if (value) nsXULContentUtils::GetTextForNode(value, s); PR_LOG(gXULTemplateLog, PR_LOG_DEBUG, (" target => %s", NS_ConvertUTF16toUTF8(s).get())); } #endif if (! value) continue; targetValue = value; } else { variable = mSourceVariable; nsCOMPtr<nsIRDFResource> source = do_QueryInterface(isupports); NS_ASSERTION(source != nullptr, "source is not an nsIRDFResource"); #ifdef PR_LOGGING if (PR_LOG_TEST(gXULTemplateLog, PR_LOG_DEBUG)) { const char* s = "(none found)"; if (source) source->GetValueConst(&s); PR_LOG(gXULTemplateLog, PR_LOG_DEBUG, (" source => %s", s)); } #endif if (! source) continue; value = sourceRes = source; } // Copy the original instantiation, and add it to the // instantiation set with the new assignment that we've // introduced. Ownership will be transferred to the Instantiation newinst = *inst; newinst.AddAssignment(variable, value); Element* element = new nsRDFPropertyTestNode::Element(sourceRes, mProperty, targetValue); if (! element) return NS_ERROR_OUT_OF_MEMORY; newinst.AddSupportingElement(element); aInstantiations.Insert(inst, newinst); } // finally, remove the "under specified" instantiation. aInstantiations.Erase(inst--); } else { if (!aCantHandleYet) { nsXULContentUtils::LogTemplateError(ERROR_TEMPLATE_TRIPLE_UNBOUND); // Neither source nor target assignment! return NS_ERROR_UNEXPECTED; } *aCantHandleYet = true; return NS_OK; } } return NS_OK; }
nsresult XULContentSinkImpl::OpenTag(const PRUnichar** aAttributes, const PRUint32 aAttrLen, const PRUint32 aLineNumber, nsINodeInfo *aNodeInfo) { nsresult rv; // Create the element nsXULPrototypeElement* element; rv = CreateElement(aNodeInfo, &element); if (NS_FAILED(rv)) { #ifdef PR_LOGGING if (PR_LOG_TEST(gLog, PR_LOG_ERROR)) { nsAutoString anodeC; aNodeInfo->GetName(anodeC); PR_LOG(gLog, PR_LOG_ERROR, ("xul: unable to create element '%s' at line %d", NS_ConvertUTF16toUTF8(anodeC).get(), aLineNumber)); } #endif return rv; } // Link this element to its parent. nsPrototypeArray* children = nsnull; rv = mContextStack.GetTopChildren(&children); if (NS_FAILED(rv)) { delete element; return rv; } // Add the attributes rv = AddAttributes(aAttributes, aAttrLen, element); if (NS_FAILED(rv)) return rv; children->AppendElement(element); if (aNodeInfo->Equals(nsGkAtoms::script, kNameSpaceID_XHTML) || aNodeInfo->Equals(nsGkAtoms::script, kNameSpaceID_XUL)) { // Do scripty things now rv = OpenScript(aAttributes, aLineNumber); NS_ENSURE_SUCCESS(rv, rv); NS_ASSERTION(mState == eInScript || mState == eInDocumentElement, "Unexpected state"); if (mState == eInScript) { // OpenScript has pushed the nsPrototypeScriptElement onto the // stack, so we're done. return NS_OK; } } // Push the element onto the context stack, so that child // containers will hook up to us as their parent. rv = mContextStack.Push(element, mState); if (NS_FAILED(rv)) return rv; mState = eInDocumentElement; return NS_OK; }
// aTime is the time in ms the samples were inserted into MediaStreamGraph nsresult AudioStream::Write(const AudioDataValue* aBuf, uint32_t aFrames, TimeStamp *aTime) { MonitorAutoLock mon(mMonitor); if (mState == ERRORED) { return NS_ERROR_FAILURE; } NS_ASSERTION(mState == INITIALIZED || mState == STARTED || mState == RUNNING, "Stream write in unexpected state."); // See if we need to start() the stream, since we must do that from this thread CheckForStart(); // Downmix to Stereo. if (mChannels > 2 && mChannels <= 8) { DownmixAudioToStereo(const_cast<AudioDataValue*> (aBuf), mChannels, aFrames); } else if (mChannels > 8) { return NS_ERROR_FAILURE; } const uint8_t* src = reinterpret_cast<const uint8_t*>(aBuf); uint32_t bytesToCopy = FramesToBytes(aFrames); // XXX this will need to change if we want to enable this on-the-fly! if (PR_LOG_TEST(GetLatencyLog(), PR_LOG_DEBUG)) { // Record the position and time this data was inserted int64_t timeMs; if (aTime && !aTime->IsNull()) { if (mStartTime.IsNull()) { AsyncLatencyLogger::Get(true)->GetStartTime(mStartTime); } timeMs = (*aTime - mStartTime).ToMilliseconds(); } else { timeMs = 0; } struct Inserts insert = { timeMs, aFrames}; mInserts.AppendElement(insert); } while (bytesToCopy > 0) { uint32_t available = std::min(bytesToCopy, mBuffer.Available()); NS_ABORT_IF_FALSE(available % mBytesPerFrame == 0, "Must copy complete frames."); mBuffer.AppendElements(src, available); src += available; bytesToCopy -= available; if (bytesToCopy > 0) { // Careful - the CubebInit thread may not have gotten to STARTED yet if ((mState == INITIALIZED || mState == STARTED) && mLatencyRequest == LowLatency) { // don't ever block MediaStreamGraph low-latency streams uint32_t remains = 0; // we presume the buffer is full if (mBuffer.Length() > bytesToCopy) { remains = mBuffer.Length() - bytesToCopy; // Free up just enough space } // account for dropping samples PR_LOG(gAudioStreamLog, PR_LOG_WARNING, ("Stream %p dropping %u bytes (%u frames)in Write()", this, mBuffer.Length() - remains, BytesToFrames(mBuffer.Length() - remains))); mReadPoint += BytesToFrames(mBuffer.Length() - remains); mBuffer.ContractTo(remains); } else { // RUNNING or high latency // If we are not playing, but our buffer is full, start playing to make // room for soon-to-be-decoded data. if (mState != STARTED && mState != RUNNING) { PR_LOG(gAudioStreamLog, PR_LOG_WARNING, ("Starting stream %p in Write (%u waiting)", this, bytesToCopy)); StartUnlocked(); if (mState == ERRORED) { return NS_ERROR_FAILURE; } } PR_LOG(gAudioStreamLog, PR_LOG_WARNING, ("Stream %p waiting in Write() (%u waiting)", this, bytesToCopy)); mon.Wait(); } } } mWritten += aFrames; return NS_OK; }