Exemplo n.º 1
0
void
GMPDecryptorParent::Shutdown()
{
  LOGD(("GMPDecryptorParent[%p]::Shutdown()", this));
  MOZ_ASSERT(mGMPThread == NS_GetCurrentThread());

  if (mShuttingDown) {
    return;
  }
  mShuttingDown = true;

  // Notify client we're gone!  Won't occur after Close()
  if (mCallback) {
    mCallback->Terminated();
    mCallback = nullptr;
  }

  mIsOpen = false;
  if (!mActorDestroyed) {
    Unused << SendDecryptingComplete();
  }
}
NS_IMETHODIMP nsEmbedFilePicker::Show(int16_t* _retval)
{
  DoSendPrompt();

  nsresult rv;

  mService->EnterSecureJSContext();

  nsCOMPtr<nsIDOMWindowUtils> utils = do_GetInterface(mWin);
  NS_ENSURE_TRUE(utils, NS_ERROR_FAILURE);

  rv = utils->EnterModalState();

  mModalDepth++;
  int origModalDepth = mModalDepth;
  nsCOMPtr<nsIThread> thread;
  NS_GetCurrentThread(getter_AddRefs(thread));
  while (mModalDepth == origModalDepth && NS_SUCCEEDED(rv)) {
    bool processedEvent;
    rv = thread->ProcessNextEvent(true, &processedEvent);
    if (NS_SUCCEEDED(rv) && !processedEvent) {
      rv = NS_ERROR_UNEXPECTED;
    }
  }
  mService->RemoveMessageListener("promptresponse", this);

  uint32_t winid;
  mService->GetIDByWindow(mWin, &winid);

  std::map<uint32_t, EmbedFilePickerResponse>::iterator it = mResponseMap.find(winid);
  if (it == mResponseMap.end()) {
    return NS_ERROR_UNEXPECTED;
  }

  rv = utils->LeaveModalState();
  mService->LeaveSecureJSContext();

  return rv;
}
Exemplo n.º 3
0
// Note: Consider keeping ActorDestroy sync'd up when making changes here.
nsresult
GMPAudioDecoderParent::Shutdown()
{
  LOGD(("%s: %p", __FUNCTION__, this));
  MOZ_ASSERT(mPlugin->GMPThread() == NS_GetCurrentThread());

  if (mShuttingDown) {
    return NS_OK;
  }
  mShuttingDown = true;

  // Notify client we're gone!  Won't occur after Close()
  if (mCallback) {
    mCallback->Terminated();
    mCallback = nullptr;
  }

  mIsOpen = false;
  unused << SendDecodingComplete();

  return NS_OK;
}
Exemplo n.º 4
0
NS_IMETHODIMP
GeckoMediaPluginService::GetGMPVideoEncoder(nsTArray<nsCString>* aTags,
                                            const nsACString& aNodeId,
                                            UniquePtr<GetGMPVideoEncoderCallback>&& aCallback)
{
  MOZ_ASSERT(NS_GetCurrentThread() == mGMPThread);
  NS_ENSURE_ARG(aTags && aTags->Length() > 0);
  NS_ENSURE_ARG(aCallback);

  if (mShuttingDownOnGMPThread) {
    return NS_ERROR_FAILURE;
  }

  UniquePtr<GetGMPContentParentCallback> callback(
    new GetGMPContentParentForVideoEncoderDone(Move(aCallback)));
  if (!GetContentParentFrom(aNodeId, NS_LITERAL_CSTRING(GMP_API_VIDEO_ENCODER),
                            *aTags, Move(callback))) {
    return NS_ERROR_FAILURE;
  }

  return NS_OK;
}
Exemplo n.º 5
0
void
nsBaseAppShell::ScheduleSyncSection(already_AddRefed<nsIRunnable> aRunnable,
                                    bool aStable)
{
  NS_ASSERTION(NS_IsMainThread(), "Should be on main thread.");

  nsIThread* thread = NS_GetCurrentThread();

  // Add this runnable to our list of synchronous sections.
  SyncSection* section = mSyncSections.AppendElement();
  section->mStable = aStable;
  section->mRunnable = aRunnable;

  // If aStable is false then this synchronous section is supposed to run before
  // the next event at the current nesting level. Record the event loop nesting
  // level and the thread recursion level so that the synchronous section will
  // run at the proper time.
  if (!aStable) {
    section->mEventloopNestingLevel = mEventloopNestingLevel;

    nsCOMPtr<nsIThreadInternal> threadInternal = do_QueryInterface(thread);
    NS_ASSERTION(threadInternal, "This should never fail!");

    uint32_t recursionLevel;
    if (NS_FAILED(threadInternal->GetRecursionDepth(&recursionLevel))) {
      NS_ERROR("This should never fail!");
    }

    // Due to the weird way that the thread recursion counter is implemented we
    // subtract one from the recursion level if we have one.
    section->mThreadRecursionLevel = recursionLevel ? recursionLevel - 1 : 0;
  }

  // Ensure we've got a pending event, else the callbacks will never run.
  if (!NS_HasPendingEvents(thread) && !DispatchDummyEvent(thread)) {
    RunSyncSections(true, 0);
  }
}
nsresult
GMPVideoDecoderParent::Decode(GMPVideoEncodedFrame* aInputFrame,
                              bool aMissingFrames,
                              const nsTArray<uint8_t>& aCodecSpecificInfo,
                              int64_t aRenderTimeMs)
{
  nsAutoRef<GMPVideoEncodedFrame> autoDestroy(aInputFrame);

  if (!mCanSendMessages) {
    NS_WARNING("Trying to use an invalid GMP video decoder!");
    return NS_ERROR_FAILURE;
  }

  MOZ_ASSERT(mPlugin->GMPThread() == NS_GetCurrentThread());

  auto inputFrameImpl = static_cast<GMPVideoEncodedFrameImpl*>(aInputFrame);

  GMPVideoEncodedFrameData frameData;
  inputFrameImpl->RelinquishFrameData(frameData);

  // Very rough kill-switch if the plugin stops processing.  If it's merely
  // hung and continues, we'll come back to life eventually.
  // 3* is because we're using 3 buffers per frame for i420 data for now.
  if (NumInUse(kGMPFrameData) > 3*GMPSharedMemManager::kGMPBufLimit ||
      NumInUse(kGMPEncodedData) > GMPSharedMemManager::kGMPBufLimit) {
    return NS_ERROR_FAILURE;
  }

  if (!SendDecode(frameData,
                  aMissingFrames,
                  aCodecSpecificInfo,
                  aRenderTimeMs)) {
    return NS_ERROR_FAILURE;
  }

  // Async IPC, we don't have access to a return value.
  return NS_OK;
}
Exemplo n.º 7
0
NS_IMETHODIMP
GeckoMediaPluginService::GetDecryptingGMPVideoDecoder(GMPCrashHelper* aHelper,
                                                      nsTArray<nsCString>* aTags,
                                                      const nsACString& aNodeId,
                                                      UniquePtr<GetGMPVideoDecoderCallback>&& aCallback,
                                                      uint32_t aDecryptorId)
{
  MOZ_ASSERT(NS_GetCurrentThread() == mGMPThread);
  NS_ENSURE_ARG(aTags && aTags->Length() > 0);
  NS_ENSURE_ARG(aCallback);

  if (mShuttingDownOnGMPThread) {
    return NS_ERROR_FAILURE;
  }

  GetGMPVideoDecoderCallback* rawCallback = aCallback.release();
  RefPtr<AbstractThread> thread(GetAbstractGMPThread());
  RefPtr<GMPCrashHelper> helper(aHelper);
  GetContentParent(aHelper, aNodeId, NS_LITERAL_CSTRING(GMP_API_VIDEO_DECODER), *aTags)
    ->Then(thread, __func__,
      [rawCallback, helper, aDecryptorId](RefPtr<GMPContentParent::CloseBlocker> wrapper) {
        RefPtr<GMPContentParent> parent = wrapper->mParent;
        UniquePtr<GetGMPVideoDecoderCallback> callback(rawCallback);
        GMPVideoDecoderParent* actor = nullptr;
        GMPVideoHostImpl* host = nullptr;
        if (parent && NS_SUCCEEDED(parent->GetGMPVideoDecoder(&actor, aDecryptorId))) {
          host = &(actor->Host());
          actor->SetCrashHelper(helper);
        }
        callback->Done(actor, host);
      },
      [rawCallback] {
        UniquePtr<GetGMPVideoDecoderCallback> callback(rawCallback);
        callback->Done(nullptr, nullptr);
      });

  return NS_OK;
}
Exemplo n.º 8
0
ThreadInfo::ThreadInfo(const char* aName, int aThreadId,
                       bool aIsMainThread, PseudoStack* aPseudoStack,
                       void* aStackTop)
  : mName(strdup(aName))
  , mThreadId(aThreadId)
  , mIsMainThread(aIsMainThread)
  , mPseudoStack(aPseudoStack)
  , mPlatformData(Sampler::AllocPlatformData(aThreadId))
  , mProfile(nullptr)
  , mStackTop(aStackTop)
  , mPendingDelete(false)
{
  MOZ_COUNT_CTOR(ThreadInfo);
#ifndef SPS_STANDALONE
  mThread = NS_GetCurrentThread();
#endif

  // We don't have to guess on mac
#ifdef XP_MACOSX
  pthread_t self = pthread_self();
  mStackTop = pthread_get_stackaddr_np(self);
#endif
}
Exemplo n.º 9
0
void
CacheFileChunk::WaitForUpdate(CacheFileChunkListener *aCallback)
{
  mFile->AssertOwnsLock();

  LOG(("CacheFileChunk::WaitForUpdate() [this=%p, listener=%p]",
       this, aCallback));

  MOZ_ASSERT(mFile->mOutput);
  MOZ_ASSERT(IsReady());

#ifdef DEBUG
  for (uint32_t i = 0 ; i < mUpdateListeners.Length() ; i++) {
    MOZ_ASSERT(mUpdateListeners[i]->mCallback != aCallback);
  }
#endif

  ChunkListenerItem *item = new ChunkListenerItem();
  item->mTarget = NS_GetCurrentThread();
  item->mCallback = aCallback;

  mUpdateListeners.AppendElement(item);
}
Exemplo n.º 10
0
nsresult
GMPParent::Init(GeckoMediaPluginService *aService, nsIFile* aPluginDir)
{
  MOZ_ASSERT(aPluginDir);
  MOZ_ASSERT(aService);
  MOZ_ASSERT(GMPThread() == NS_GetCurrentThread());

  mService = aService;
  mDirectory = aPluginDir;

  nsAutoString leafname;
  nsresult rv = aPluginDir->GetLeafName(leafname);
  if (NS_FAILED(rv)) {
    return rv;
  }
  LOGD(("%s::%s: %p for %s", __CLASS__, __FUNCTION__, this, 
       NS_LossyConvertUTF16toASCII(leafname).get()));

  MOZ_ASSERT(leafname.Length() > 4);
  mName = Substring(leafname, 4);

  return ReadGMPMetaData();
}
Exemplo n.º 11
0
  NS_IMETHOD Run()
  {
    MOZ_ASSERT(!NS_IsMainThread());

    bool continueThread;

    do {
      continueThread = mDBusWatcher->Poll();
    } while (continueThread);

    mDBusWatcher->CleanUp();

    nsIThread* thread;
    nsresult rv = NS_GetCurrentThread(&thread);
    NS_ENSURE_SUCCESS(rv, rv);

    nsRefPtr<nsIRunnable> runnable =
      NS_NewRunnableMethod(thread, &nsIThread::Shutdown);
    rv = NS_DispatchToMainThread(runnable);
    NS_ENSURE_SUCCESS(rv, rv);

    return NS_OK;
  }
Exemplo n.º 12
0
nsresult
GMPParent::GetGMPVideoEncoder(GMPVideoEncoderParent** aGMPVE)
{
  MOZ_ASSERT(GMPThread() == NS_GetCurrentThread());

  if (!EnsureProcessLoaded()) {
    return NS_ERROR_FAILURE;
  }

  // returned with one anonymous AddRef that locks it until Destroy
  PGMPVideoEncoderParent* pvep = SendPGMPVideoEncoderConstructor();
  if (!pvep) {
    return NS_ERROR_FAILURE;
  }
  GMPVideoEncoderParent *vep = static_cast<GMPVideoEncoderParent*>(pvep);
  // This addref corresponds to the Proxy pointer the consumer is returned.
  // It's dropped by calling Close() on the interface.
  NS_ADDREF(vep);
  *aGMPVE = vep;
  mVideoEncoders.AppendElement(vep);

  return NS_OK;
}
Exemplo n.º 13
0
nsresult
GMPAudioDecoder::Init()
{
  MOZ_ASSERT(IsOnGMPThread());

  mMPS = do_GetService("@mozilla.org/gecko-media-plugin-service;1");
  MOZ_ASSERT(mMPS);

  nsCOMPtr<nsIThread> gmpThread = NS_GetCurrentThread();

  nsRefPtr<GMPInitDoneRunnable> initDone(new GMPInitDoneRunnable());
  gmpThread->Dispatch(
    NS_NewRunnableMethodWithArg<GMPInitDoneRunnable*>(this,
                                                      &GMPAudioDecoder::GetGMPAPI,
                                                      initDone),
    NS_DISPATCH_NORMAL);

  while (!initDone->IsDone()) {
    NS_ProcessNextEvent(gmpThread, true);
  }

  return mGMP ? NS_OK : NS_ERROR_FAILURE;
}
Exemplo n.º 14
0
void*
WebRTCCall::State::WorkFunc(void* ptr)
{
  nsRefPtr<State> self = static_cast<State*>(ptr);

  NS_InitXPCOM2(nullptr, nullptr, nullptr);
  NSS_NoDB_Init(nullptr);
  NSS_SetDomesticPolicy();
  nsresult rv;

  rv = NS_GetCurrentThread(getter_AddRefs(self->mThread));
  if (NS_FAILED(rv)) {
    LOG("failed to get current thread\n");
    return 0;
  }

  sipcc::IceConfiguration cfg;

  self->mPeerConnection = sipcc::PeerConnectionImpl::CreatePeerConnection();
  self->mPeerConnectionObserver = new PCObserver(self);
  self->mPeerConnection->Initialize(*(self->mPeerConnectionObserver), nullptr, cfg, self->mThread.get());

  self->mTimer = do_CreateInstance(NS_TIMER_CONTRACTID, &rv);
  if (NS_FAILED(rv)) {
    LOG("failed to create timer\n");
    return 0;
  }

  self->mTimer->InitWithCallback(
      self->mPeerConnectionObserver,
      PR_MillisecondsToInterval(30),
      nsITimer::TYPE_REPEATING_PRECISE);

  while (self->mRunThread) { NS_ProcessNextEvent(nullptr, true); }

  return nullptr;
}
void
RegisterOperator::Reply(DNSServiceRef aSdRef,
                        DNSServiceFlags aFlags,
                        DNSServiceErrorType aErrorCode,
                        const nsACString& aName,
                        const nsACString& aRegType,
                        const nsACString& aDomain)
{
  MOZ_ASSERT(GetThread() == NS_GetCurrentThread());

  if (kDNSServiceErr_NoError != aErrorCode) {
    LOG_E("RegisterOperator::Reply (%d)", aErrorCode);
  }

  if (!mListener) { return; }
  nsCOMPtr<nsIDNSServiceInfo> info = new nsDNSServiceInfo(mServiceInfo);
  if (NS_WARN_IF(NS_FAILED(info->SetServiceName(aName)))) { return; }
  if (NS_WARN_IF(NS_FAILED(info->SetServiceType(aRegType)))) { return; }
  if (NS_WARN_IF(NS_FAILED(info->SetDomainName(aDomain)))) { return; }

  if (kDNSServiceErr_NoError == aErrorCode) {
    if (aFlags & kDNSServiceFlagsAdd) {
      mListener->OnServiceRegistered(info);
    } else {
      // If a successfully-registered name later suffers a name conflict
      // or similar problem and has to be deregistered, the callback will
      // be invoked with the kDNSServiceFlagsAdd flag not set.
      LOG_E("RegisterOperator::Reply: deregister");
      if (NS_WARN_IF(NS_FAILED(Stop()))) {
        return;
      }
    }
  } else {
    mListener->OnRegistrationFailed(info, aErrorCode);
  }
}
Exemplo n.º 16
0
NS_IMETHODIMP
calICSService::ParseICSAsync(const nsACString& serialized,
                             calITimezoneProvider *tzProvider,
                             calIIcsComponentParsingListener *listener)
{
    nsresult rv;
    NS_ENSURE_ARG_POINTER(listener);

    nsCOMPtr<nsIThread> workerThread;
    nsCOMPtr<nsIThread> currentThread;
    rv = NS_GetCurrentThread(getter_AddRefs(currentThread));
    NS_ENSURE_SUCCESS(rv, rv);
    rv = NS_NewThread(getter_AddRefs(workerThread));
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIRunnable> worker = new ParserWorker(currentThread, workerThread,
                                                    serialized, tzProvider, listener);
    NS_ENSURE_TRUE(worker, NS_ERROR_OUT_OF_MEMORY);

    rv = workerThread->Dispatch(worker, NS_DISPATCH_NORMAL);
    NS_ENSURE_SUCCESS(rv, rv);

    return NS_OK;
}
Exemplo n.º 17
0
PRStatus
nsSOCKSSocketInfo::StartDNS(PRFileDesc *fd)
{
    NS_ABORT_IF_FALSE(!mDnsRec && mState == SOCKS_INITIAL,
                      "Must be in initial state to make DNS Lookup");

    nsCOMPtr<nsIDNSService> dns = do_GetService(NS_DNSSERVICE_CONTRACTID);
    if (!dns)
        return PR_FAILURE;

    mFD  = fd;
    nsresult rv = dns->AsyncResolve(mProxyHost, 0, this,
                                    NS_GetCurrentThread(),
                                    getter_AddRefs(mLookup));

    if (NS_FAILED(rv)) {
        LOGERROR(("socks: DNS lookup for SOCKS proxy %s failed",
                  mProxyHost.get()));
        return PR_FAILURE;
    }
    mState = SOCKS_DNS_IN_PROGRESS;
    PR_SetError(PR_IN_PROGRESS_ERROR, 0);
    return PR_FAILURE;
}
Exemplo n.º 18
0
nsRefPtr<MediaDataDecoder::InitPromise>
GMPVideoDecoder::Init()
{
  MOZ_ASSERT(IsOnGMPThread());

  mMPS = do_GetService("@mozilla.org/gecko-media-plugin-service;1");
  MOZ_ASSERT(mMPS);

  nsCOMPtr<nsIThread> gmpThread = NS_GetCurrentThread();

  nsRefPtr<GMPInitDoneRunnable> initDone(new GMPInitDoneRunnable());
  gmpThread->Dispatch(
    NS_NewRunnableMethodWithArg<GMPInitDoneRunnable*>(this,
                                                      &GMPVideoDecoder::GetGMPAPI,
                                                      initDone),
    NS_DISPATCH_NORMAL);

  while (!initDone->IsDone()) {
    NS_ProcessNextEvent(gmpThread, true);
  }

  return mGMP ? InitPromise::CreateAndResolve(TrackInfo::kVideoTrack, __func__)
              : InitPromise::CreateAndReject(DecoderFailureReason::INIT_ERROR, __func__);
}
Exemplo n.º 19
0
void
GetAddrInfoOperator::Reply(DNSServiceRef aSdRef,
                           DNSServiceFlags aFlags,
                           uint32_t aInterfaceIndex,
                           DNSServiceErrorType aErrorCode,
                           const nsACString& aHostName,
                           const NetAddr& aAddress,
                           uint32_t aTTL)
{
  MOZ_ASSERT(GetThread() == NS_GetCurrentThread());

  mDeleteProtector = nullptr;

  if (NS_WARN_IF(kDNSServiceErr_NoError != aErrorCode)) {
    LOG_E("GetAddrInfoOperator::Reply (%d)", aErrorCode);
    return;
  }

  if (!mListener) { return; }

  NetAddr addr = aAddress;
  nsCOMPtr<nsINetAddr> address = new nsNetAddr(&addr);
  nsCString addressStr;
  if (NS_WARN_IF(NS_FAILED(address->GetAddress(addressStr)))) { return; }

  nsCOMPtr<nsIDNSServiceInfo> info = new nsDNSServiceInfo(mServiceInfo);
  if (NS_WARN_IF(NS_FAILED(info->SetAddress(addressStr)))) { return; }

  if (kDNSServiceErr_NoError == aErrorCode) {
    mListener->OnServiceResolved(info);
  } else {
    mListener->OnResolveFailed(info, aErrorCode);
  }

  NS_WARN_IF(NS_FAILED(Stop()));
}
Exemplo n.º 20
0
GMPErr
GMPVideoEncoderParent::Encode(GMPVideoi420Frame* aInputFrame,
                              const nsTArray<uint8_t>& aCodecSpecificInfo,
                              const nsTArray<GMPVideoFrameType>& aFrameTypes)
{
  nsAutoRef<GMPVideoi420Frame> frameRef(aInputFrame);

  if (!mIsOpen) {
    NS_WARNING("Trying to use an dead GMP video encoder");
    return GMPGenericErr;
  }

  MOZ_ASSERT(mPlugin->GMPThread() == NS_GetCurrentThread());

  auto inputFrameImpl = static_cast<GMPVideoi420FrameImpl*>(aInputFrame);

  // Very rough kill-switch if the plugin stops processing.  If it's merely
  // hung and continues, we'll come back to life eventually.
  // 3* is because we're using 3 buffers per frame for i420 data for now.
  if ((NumInUse(GMPSharedMem::kGMPFrameData) > 3*GMPSharedMem::kGMPBufLimit) ||
      (NumInUse(GMPSharedMem::kGMPEncodedData) > GMPSharedMem::kGMPBufLimit)) {
    return GMPGenericErr;
  }

  GMPVideoi420FrameData frameData;
  inputFrameImpl->InitFrameData(frameData);

  if (!SendEncode(frameData,
                  aCodecSpecificInfo,
                  aFrameTypes)) {
    return GMPGenericErr;
  }

  // Async IPC, we don't have access to a return value.
  return GMPNoErr;
}
Exemplo n.º 21
0
nsresult
CacheFile::QueueChunkListener(uint32_t aIndex,
                              CacheFileChunkListener *aCallback)
{
  LOG(("CacheFile::QueueChunkListener() [this=%p, idx=%d, listener=%p]",
       this, aIndex, aCallback));

  AssertOwnsLock();

  MOZ_ASSERT(aCallback);

  ChunkListenerItem *item = new ChunkListenerItem();
  item->mTarget = NS_GetCurrentThread();
  item->mCallback = aCallback;

  ChunkListeners *listeners;
  if (!mChunkListeners.Get(aIndex, &listeners)) {
    listeners = new ChunkListeners();
    mChunkListeners.Put(aIndex, listeners);
  }

  listeners->mItems.AppendElement(item);
  return NS_OK;
}
Exemplo n.º 22
0
void CacheIOThread::ThreadFunc()
{
  nsCOMPtr<nsIThreadInternal> threadInternal;

  {
    MonitorAutoLock lock(mMonitor);

    // This creates nsThread for this PRThread
    nsCOMPtr<nsIThread> xpcomThread = NS_GetCurrentThread();

    threadInternal = do_QueryInterface(xpcomThread);
    if (threadInternal)
      threadInternal->SetObserver(this);

    mXPCOMThread = xpcomThread.forget().take();

    lock.NotifyAll();

    do {
loopStart:
      // Reset the lowest level now, so that we can detect a new event on
      // a lower level (i.e. higher priority) has been scheduled while
      // executing any previously scheduled event.
      mLowestLevelWaiting = LAST_LEVEL;

      // Process xpcom events first
      while (mHasXPCOMEvents) {
        mHasXPCOMEvents = false;
        mCurrentlyExecutingLevel = XPCOM_LEVEL;

        MonitorAutoUnlock unlock(mMonitor);

        bool processedEvent;
        nsresult rv;
        do {
          nsIThread *thread = mXPCOMThread;
          rv = thread->ProcessNextEvent(false, &processedEvent);
        } while (NS_SUCCEEDED(rv) && processedEvent);
      }

      uint32_t level;
      for (level = 0; level < LAST_LEVEL; ++level) {
        if (!mEventQueue[level].Length()) {
          // no events on this level, go to the next level
          continue;
        }

        LoopOneLevel(level);

        // Go to the first (lowest) level again
        goto loopStart;
      }

      if (EventsPending())
        continue;

      if (mShutdown)
        break;

      lock.Wait(PR_INTERVAL_NO_TIMEOUT);

      if (EventsPending())
        continue;

    } while (true);

    MOZ_ASSERT(!EventsPending());

    // This is for correct assertion on XPCOM events dispatch.
    mInsideLoop = false;
  } // lock

  if (threadInternal)
    threadInternal->SetObserver(nullptr);
}
Exemplo n.º 23
0
// this is used for Send without UI
nsresult nsMapiHook::BlindSendMail (unsigned long aSession, nsIMsgCompFields * aCompFields)
{
  nsresult rv = NS_OK ;

  if (!IsBlindSendAllowed())
    return NS_ERROR_FAILURE;

  /** create nsIMsgComposeParams obj and other fields to populate it **/

  nsCOMPtr<nsIDOMWindowInternal>  hiddenWindow;
  // get parent window
  nsCOMPtr<nsIAppShellService> appService = do_GetService( "@mozilla.org/appshell/appShellService;1", &rv);
  if (NS_FAILED(rv)|| (!appService) ) return rv ;

  rv = appService->GetHiddenDOMWindow(getter_AddRefs(hiddenWindow));
  if ( NS_FAILED(rv) ) return rv ;
  // smtp password and Logged in used IdKey from MapiConfig (session obj)
  nsMAPIConfiguration * pMapiConfig = nsMAPIConfiguration::GetMAPIConfiguration() ;
  if (!pMapiConfig) return NS_ERROR_FAILURE ;  // get the singelton obj
  PRUnichar * password = pMapiConfig->GetPassword(aSession) ;
  // password
  nsCAutoString smtpPassword;
  LossyCopyUTF16toASCII(password, smtpPassword);

  // Id key
  nsCString MsgIdKey;
  pMapiConfig->GetIdKey(aSession, MsgIdKey);

  // get the MsgIdentity for the above key using AccountManager
  nsCOMPtr <nsIMsgAccountManager> accountManager = do_GetService (NS_MSGACCOUNTMANAGER_CONTRACTID) ;
  if (NS_FAILED(rv) || (!accountManager) ) return rv ;

  nsCOMPtr <nsIMsgIdentity> pMsgId ;
  rv = accountManager->GetIdentity (MsgIdKey, getter_AddRefs(pMsgId)) ;
  if (NS_FAILED(rv) ) return rv ;

  // create a send listener to get back the send status
  nsCOMPtr <nsIMsgSendListener> sendListener ;
  rv = nsMAPISendListener::CreateMAPISendListener(getter_AddRefs(sendListener)) ;
  if (NS_FAILED(rv) || (!sendListener) ) return rv;

  // create the compose params object
  nsCOMPtr<nsIMsgComposeParams> pMsgComposeParams (do_CreateInstance(NS_MSGCOMPOSEPARAMS_CONTRACTID, &rv));
  if (NS_FAILED(rv) || (!pMsgComposeParams) ) return rv ;

  // populate the compose params
  PRBool forcePlainText;
  aCompFields->GetForcePlainText(&forcePlainText);
  pMsgComposeParams->SetType(nsIMsgCompType::New);
  pMsgComposeParams->SetFormat(forcePlainText ? nsIMsgCompFormat::PlainText : nsIMsgCompFormat::HTML);
  pMsgComposeParams->SetIdentity(pMsgId);
  pMsgComposeParams->SetComposeFields(aCompFields);
  pMsgComposeParams->SetSendListener(sendListener) ;
  pMsgComposeParams->SetSmtpPassword(smtpPassword.get());

  // create the nsIMsgCompose object to send the object
  nsCOMPtr<nsIMsgCompose> pMsgCompose (do_CreateInstance(NS_MSGCOMPOSE_CONTRACTID, &rv));
  if (NS_FAILED(rv) || (!pMsgCompose) ) return rv ;

  /** initialize nsIMsgCompose, Send the message, wait for send completion response **/

  rv = pMsgCompose->Initialize(hiddenWindow, pMsgComposeParams) ;
  if (NS_FAILED(rv)) return rv ;

  return pMsgCompose->SendMsg(nsIMsgSend::nsMsgDeliverNow, pMsgId, nsnull, nsnull, nsnull) ;
  if (NS_FAILED(rv)) return rv ;

  // assign to interface pointer from nsCOMPtr to facilitate typecast below
  nsIMsgSendListener * pSendListener = sendListener ;

  // we need to wait here to make sure that we return only after send is completed
  // so we will have a event loop here which will process the events till the Send IsDone.
  nsIThread *thread = NS_GetCurrentThread();
  while ( !((nsMAPISendListener *) pSendListener)->IsDone() )
  {
    PR_CEnterMonitor(pSendListener);
    PR_CWait(pSendListener, PR_MicrosecondsToInterval(1000UL));
    PR_CExitMonitor(pSendListener);
    NS_ProcessPendingEvents(thread);
  }

  return rv ;
}
Exemplo n.º 24
0
bool
ReadStream::Inner::MatchId(const nsID& aId) const
{
  MOZ_ASSERT(NS_GetCurrentThread() == mOwningThread);
  return mId.Equals(aId);
}
Exemplo n.º 25
0
bool
ReadStream::Inner::HasEverBeenRead() const
{
  MOZ_ASSERT(NS_GetCurrentThread() == mOwningThread);
  return mHasEverBeenRead;
}
Exemplo n.º 26
0
void
ReadStream::Inner::CloseStreamWithoutReporting()
{
  MOZ_ASSERT(NS_GetCurrentThread() == mOwningThread);
  Forget();
}
Exemplo n.º 27
0
void
ReadStream::Inner::CloseStream()
{
  MOZ_ASSERT(NS_GetCurrentThread() == mOwningThread);
  Close();
}
Exemplo n.º 28
0
void
MediaDecodeTask::Decode()
{
  MOZ_ASSERT(!mThreadPool == NS_IsMainThread(),
             "We should be on the main thread only if we don't have a thread pool");

  mBufferDecoder->BeginDecoding(NS_GetCurrentThread());

  // Tell the decoder reader that we are not going to play the data directly,
  // and that we should not reject files with more channels than the audio
  // bakend support.
  mDecoderReader->SetIgnoreAudioOutputFormat();

  mDecoderReader->OnDecodeThreadStart();

  MediaInfo mediaInfo;
  nsAutoPtr<MetadataTags> tags;
  nsresult rv = mDecoderReader->ReadMetadata(&mediaInfo, getter_Transfers(tags));
  if (NS_FAILED(rv)) {
    ReportFailureOnMainThread(WebAudioDecodeJob::InvalidContent);
    return;
  }

  if (!mDecoderReader->HasAudio()) {
    ReportFailureOnMainThread(WebAudioDecodeJob::NoAudio);
    return;
  }

  while (mDecoderReader->DecodeAudioData()) {
    // consume all of the buffer
    continue;
  }

  mDecoderReader->OnDecodeThreadFinish();

  MediaQueue<AudioData>& audioQueue = mDecoderReader->AudioQueue();
  uint32_t frameCount = audioQueue.FrameCount();
  uint32_t channelCount = mediaInfo.mAudio.mChannels;
  uint32_t sampleRate = mediaInfo.mAudio.mRate;

  if (!frameCount || !channelCount || !sampleRate) {
    ReportFailureOnMainThread(WebAudioDecodeJob::InvalidContent);
    return;
  }

  const uint32_t destSampleRate = mDecodeJob.mContext->SampleRate();
  AutoResampler resampler;

  uint32_t resampledFrames = frameCount;
  if (sampleRate != destSampleRate) {
    resampledFrames = static_cast<uint32_t>(
        static_cast<uint64_t>(destSampleRate) *
        static_cast<uint64_t>(frameCount) /
        static_cast<uint64_t>(sampleRate)
      );

    resampler = speex_resampler_init(channelCount,
                                     sampleRate,
                                     destSampleRate,
                                     SPEEX_RESAMPLER_QUALITY_DEFAULT, nullptr);
    speex_resampler_skip_zeros(resampler);
    resampledFrames += speex_resampler_get_output_latency(resampler);
  }

  // Allocate the channel buffers.  Note that if we end up resampling, we may
  // write fewer bytes than mResampledFrames to the output buffer, in which
  // case mWriteIndex will tell us how many valid samples we have.
  static const fallible_t fallible = fallible_t();
  bool memoryAllocationSuccess = true;
  if (!mDecodeJob.mChannelBuffers.SetLength(channelCount)) {
    memoryAllocationSuccess = false;
  } else {
    for (uint32_t i = 0; i < channelCount; ++i) {
      mDecodeJob.mChannelBuffers[i] = new(fallible) float[resampledFrames];
      if (!mDecodeJob.mChannelBuffers[i]) {
        memoryAllocationSuccess = false;
        break;
      }
    }
  }
  if (!memoryAllocationSuccess) {
    ReportFailureOnMainThread(WebAudioDecodeJob::UnknownError);
    return;
  }

  nsAutoPtr<AudioData> audioData;
  while ((audioData = audioQueue.PopFront())) {
    audioData->EnsureAudioBuffer(); // could lead to a copy :(
    AudioDataValue* bufferData = static_cast<AudioDataValue*>
      (audioData->mAudioBuffer->Data());

    if (sampleRate != destSampleRate) {
      const uint32_t maxOutSamples = resampledFrames - mDecodeJob.mWriteIndex;

      for (uint32_t i = 0; i < audioData->mChannels; ++i) {
        uint32_t inSamples = audioData->mFrames;
        uint32_t outSamples = maxOutSamples;

        WebAudioUtils::SpeexResamplerProcess(
            resampler, i, &bufferData[i * audioData->mFrames], &inSamples,
            mDecodeJob.mChannelBuffers[i] + mDecodeJob.mWriteIndex,
            &outSamples);

        if (i == audioData->mChannels - 1) {
          mDecodeJob.mWriteIndex += outSamples;
          MOZ_ASSERT(mDecodeJob.mWriteIndex <= resampledFrames);
          MOZ_ASSERT(inSamples == audioData->mFrames);
        }
      }
    } else {
      for (uint32_t i = 0; i < audioData->mChannels; ++i) {
        ConvertAudioSamples(&bufferData[i * audioData->mFrames],
                            mDecodeJob.mChannelBuffers[i] + mDecodeJob.mWriteIndex,
                            audioData->mFrames);

        if (i == audioData->mChannels - 1) {
          mDecodeJob.mWriteIndex += audioData->mFrames;
        }
      }
    }
  }

  if (sampleRate != destSampleRate) {
    uint32_t inputLatency = speex_resampler_get_input_latency(resampler);
    const uint32_t maxOutSamples = resampledFrames - mDecodeJob.mWriteIndex;
    for (uint32_t i = 0; i < channelCount; ++i) {
      uint32_t inSamples = inputLatency;
      uint32_t outSamples = maxOutSamples;

      WebAudioUtils::SpeexResamplerProcess(
          resampler, i, (AudioDataValue*)nullptr, &inSamples,
          mDecodeJob.mChannelBuffers[i] + mDecodeJob.mWriteIndex,
          &outSamples);

      if (i == channelCount - 1) {
        mDecodeJob.mWriteIndex += outSamples;
        MOZ_ASSERT(mDecodeJob.mWriteIndex <= resampledFrames);
        MOZ_ASSERT(inSamples == inputLatency);
      }
    }
  }

  mPhase = PhaseEnum::AllocateBuffer;
  RunNextPhase();
}
Exemplo n.º 29
0
void
DOMStorageDBThread::ThreadFunc()
{
  nsresult rv = InitDatabase();

  MonitorAutoLock lockMonitor(mThreadObserver->GetMonitor());

  if (NS_FAILED(rv)) {
    mStatus = rv;
    mStopIOThread = true;
    return;
  }

  // Create an nsIThread for the current PRThread, so we can observe runnables
  // dispatched to it.
  nsCOMPtr<nsIThread> thread = NS_GetCurrentThread();
  nsCOMPtr<nsIThreadInternal> threadInternal = do_QueryInterface(thread);
  MOZ_ASSERT(threadInternal); // Should always succeed.
  threadInternal->SetObserver(mThreadObserver);

  while (MOZ_LIKELY(!mStopIOThread || mPreloads.Length() ||
                    mPendingTasks.HasTasks() ||
                    mThreadObserver->HasPendingEvents())) {
    // Process xpcom events first.
    while (MOZ_UNLIKELY(mThreadObserver->HasPendingEvents())) {
      mThreadObserver->ClearPendingEvents();
      MonitorAutoUnlock unlock(mThreadObserver->GetMonitor());
      bool processedEvent;
      do {
        rv = thread->ProcessNextEvent(false, &processedEvent);
      } while (NS_SUCCEEDED(rv) && processedEvent);
    }

    if (MOZ_UNLIKELY(TimeUntilFlush() == 0)) {
      // Flush time is up or flush has been forced, do it now.
      UnscheduleFlush();
      if (mPendingTasks.Prepare()) {
        {
          MonitorAutoUnlock unlockMonitor(mThreadObserver->GetMonitor());
          rv = mPendingTasks.Execute(this);
        }

        if (!mPendingTasks.Finalize(rv)) {
          mStatus = rv;
          NS_WARNING("localStorage DB access broken");
        }
      }
      NotifyFlushCompletion();
    } else if (MOZ_LIKELY(mPreloads.Length())) {
      nsAutoPtr<DBOperation> op(mPreloads[0]);
      mPreloads.RemoveElementAt(0);
      {
        MonitorAutoUnlock unlockMonitor(mThreadObserver->GetMonitor());
        op->PerformAndFinalize(this);
      }

      if (op->Type() == DBOperation::opPreloadUrgent) {
        SetDefaultPriority(); // urgent preload unscheduled
      }
    } else if (MOZ_UNLIKELY(!mStopIOThread)) {
      lockMonitor.Wait(TimeUntilFlush());
    }
  } // thread loop

  mStatus = ShutdownDatabase();

  if (threadInternal) {
    threadInternal->SetObserver(nullptr);
  }
}
Exemplo n.º 30
0
NS_IMETHODIMP
NamedPipeService::Run()
{
  MOZ_ASSERT(NS_GetCurrentThread() == mThread);
  MOZ_ASSERT(mIocp && mIocp != INVALID_HANDLE_VALUE);

  while (!mIsShutdown) {
    {
      MutexAutoLock lock(mLock);
      if (mObservers.IsEmpty()) {
        LOG_NPS_DEBUG("no observer, stop loop");
        break;
      }

      RemoveRetiredObjects();
    }

    DWORD bytesTransferred = 0;
    ULONG_PTR key = 0;
    LPOVERLAPPED overlapped = nullptr;
    BOOL success = GetQueuedCompletionStatus(mIocp,
                                             &bytesTransferred,
                                             &key,
                                             &overlapped,
                                             1000); // timeout, 1s
    auto err = GetLastError();
    if (!success) {
      if (err == WAIT_TIMEOUT) {
        continue;
      } else if (err == ERROR_ABANDONED_WAIT_0) { // mIocp was closed
        break;
      } else if (!overlapped) {
        /**
         * Did not dequeue a completion packet from the completion port, and
         * bytesTransferred/key are meaningless.
         * See remarks of |GetQueuedCompletionStatus| API.
         */

        LOG_NPS_ERROR("invalid overlapped (%d)", err);
        continue;
      }

      MOZ_ASSERT(key);
    }

    /**
     * Windows doesn't provide a method to remove created I/O Completion Port,
     * all we can do is just close the handle we monitored before.
     * In some cases, there's race condition that the monitored handle has an
     * I/O status after the observer is being removed and destroyed.
     * To avoid changing the ref-count of a dangling pointer, don't use nsCOMPtr
     * here.
     */
    nsINamedPipeDataObserver* target =
      reinterpret_cast<nsINamedPipeDataObserver*>(key);

    nsCOMPtr<nsINamedPipeDataObserver> obs;
    {
      MutexAutoLock lock(mLock);

      auto idx = mObservers.IndexOf(target);
      if (idx == decltype(mObservers)::NoIndex) {
        LOG_NPS_ERROR("observer %p not found", target);
        continue;
      }
      obs = target;
    }

    MOZ_ASSERT(obs.get());

    if (success) {
      LOG_NPS_DEBUG("OnDataAvailable: obs=%p, bytes=%d",
                    obs.get(),
                    bytesTransferred);
      obs->OnDataAvailable(bytesTransferred, overlapped);
    } else {
      LOG_NPS_ERROR("GetQueuedCompletionStatus %p failed, error=%d",
                    obs.get(),
                    err);
      obs->OnError(err, overlapped);
    }

  }

  {
    MutexAutoLock lock(mLock);
    RemoveRetiredObjects();
  }

  return NS_OK;
}