// Called on the control thread.
nsresult
BackgroundFileSaver::Init()
{
  MOZ_ASSERT(NS_IsMainThread(), "This should be called on the main thread");

  nsresult rv;

  rv = NS_NewPipe2(getter_AddRefs(mPipeInputStream),
                   getter_AddRefs(mPipeOutputStream), true, true, 0,
                   HasInfiniteBuffer() ? UINT32_MAX : 0);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = NS_GetCurrentThread(getter_AddRefs(mControlThread));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = NS_NewThread(getter_AddRefs(mWorkerThread));
  NS_ENSURE_SUCCESS(rv, rv);

  sThreadCount++;
  if (sThreadCount > sTelemetryMaxThreadCount) {
    sTelemetryMaxThreadCount = sThreadCount;
  }

  return NS_OK;
}
Exemple #2
0
void
anp_audio_start(ANPAudioTrack* s)
{
  if (s == NULL || s->output_unit == NULL) {
    return;
  }

  if (s->keepGoing) {
    // we are already playing.  Ignore.
    return;
  }

  JNIEnv *jenv = GetJNIForThread();
  if (!jenv)
    return;

  mozilla::AutoLocalJNIFrame autoFrame(jenv, 0);
  jenv->CallVoidMethod(s->output_unit, at.play);

  if (autoFrame.CheckForException()) {
    jenv->DeleteGlobalRef(s->at_class);
    free(s);
    return;
  }

  s->isStopped = false;
  s->keepGoing = true;

  // AudioRunnable now owns the ANPAudioTrack
  nsRefPtr<AudioRunnable> runnable = new AudioRunnable(s);

  nsCOMPtr<nsIThread> thread;
  NS_NewThread(getter_AddRefs(thread), runnable);
}
// called from main thread only
NS_IMETHODIMP
nsSocketTransportService::Init()
{
    NS_ASSERTION(nsIThread::IsMainThread(), "wrong thread");

    if (mInitialized)
        return NS_OK;

    if (!mThreadEvent) {
        mThreadEvent = PR_NewPollableEvent();
        //
        // NOTE: per bug 190000, this failure could be caused by Zone-Alarm
        // or similar software.
        //
        // NOTE: per bug 191739, this failure could also be caused by lack
        // of a loopback device on Windows and OS/2 platforms (NSPR creates
        // a loopback socket pair on these platforms to implement a pollable
        // event object).  if we can't create a pollable event, then we'll
        // have to "busy wait" to implement the socket event queue :-(
        //
        if (!mThreadEvent) {
            NS_WARNING("running socket transport thread without a pollable event");
            LOG(("running socket transport thread without a pollable event"));
        }
    }

    nsresult rv = NS_NewThread(&mThread, this, 0, PR_JOINABLE_THREAD);
    if (NS_FAILED(rv)) return rv;

    mInitialized = PR_TRUE;
    return NS_OK;
}
nsresult
MediaManager::GetUserMediaDevices(nsPIDOMWindow* aWindow,
  nsIGetUserMediaDevicesSuccessCallback* aOnSuccess,
  nsIDOMGetUserMediaErrorCallback* aOnError)
{
  NS_ASSERTION(NS_IsMainThread(), "Only call on main thread");

  NS_ENSURE_TRUE(aOnError, NS_ERROR_NULL_POINTER);
  NS_ENSURE_TRUE(aOnSuccess, NS_ERROR_NULL_POINTER);

  nsCOMPtr<nsIGetUserMediaDevicesSuccessCallback> onSuccess(aOnSuccess);
  nsCOMPtr<nsIDOMGetUserMediaErrorCallback> onError(aOnError);

  nsCOMPtr<nsIRunnable> gUMDRunnable = new GetUserMediaDevicesRunnable(
    onSuccess.forget(), onError.forget()
  );

  nsCOMPtr<nsIThread> deviceThread;
  nsresult rv = NS_NewThread(getter_AddRefs(deviceThread));
  NS_ENSURE_SUCCESS(rv, rv);


  deviceThread->Dispatch(gUMDRunnable, NS_DISPATCH_NORMAL);
  return NS_OK;
}
Exemple #5
0
/* static */
nsresult
ImageEncoder::ExtractDataFromLayersImageAsync(nsAString& aType,
                                              const nsAString& aOptions,
                                              bool aUsingCustomOptions,
                                              layers::Image* aImage,
                                              EncodeCompleteCallback* aEncodeCallback)
{
  nsCOMPtr<imgIEncoder> encoder = ImageEncoder::GetImageEncoder(aType);
  if (!encoder) {
    return NS_IMAGELIB_ERROR_NO_ENCODER;
  }

  nsCOMPtr<nsIThread> encoderThread;
  nsresult rv = NS_NewThread(getter_AddRefs(encoderThread), nullptr);
  NS_ENSURE_SUCCESS(rv, rv);

  nsRefPtr<EncodingCompleteEvent> completeEvent =
    new EncodingCompleteEvent(encoderThread, aEncodeCallback);

  nsIntSize size(aImage->GetSize().width, aImage->GetSize().height);
  nsCOMPtr<nsIRunnable> event = new EncodingRunnable(aType,
                                                     aOptions,
                                                     nullptr,
                                                     aImage,
                                                     encoder,
                                                     completeEvent,
                                                     imgIEncoder::INPUT_FORMAT_HOSTARGB,
                                                     size,
                                                     aUsingCustomOptions);
  return encoderThread->Dispatch(event, NS_DISPATCH_NORMAL);
}
Exemple #6
0
TEST(Threads, Stress)
{
    const int loops = 1000;
    const int threads = 50;

    for (int i = 0; i < loops; i++) {
        printf("Loop %d of %d\n", i+1, loops);

        int k;
        nsIThread** array = new nsIThread*[threads];

        EXPECT_EQ(nsStressRunner::GetGlobalCount(), 0);

        for (k = 0; k < threads; k++) {
            nsCOMPtr<nsIThread> t;
            nsresult rv = NS_NewThread(getter_AddRefs(t), new nsStressRunner(k));
            EXPECT_TRUE(NS_SUCCEEDED(rv));
            NS_ADDREF(array[k] = t);
        }

        for (k = threads-1; k >= 0; k--) {
            array[k]->Shutdown();
            NS_RELEASE(array[k]);    
        }
        delete [] array;
    }
}
Exemple #7
0
/* static */
nsresult
ImageEncoder::ExtractDataAsync(nsAString& aType,
                               const nsAString& aOptions,
                               bool aUsingCustomOptions,
                               uint8_t* aImageBuffer,
                               int32_t aFormat,
                               const nsIntSize aSize,
                               EncodeCompleteCallback* aEncodeCallback)
{
  nsCOMPtr<imgIEncoder> encoder = ImageEncoder::GetImageEncoder(aType);
  if (!encoder) {
    return NS_IMAGELIB_ERROR_NO_ENCODER;
  }

  nsCOMPtr<nsIThread> encoderThread;
  nsresult rv = NS_NewThread(getter_AddRefs(encoderThread), nullptr);
  NS_ENSURE_SUCCESS(rv, rv);

  nsRefPtr<EncodingCompleteEvent> completeEvent =
    new EncodingCompleteEvent(encoderThread, aEncodeCallback);

  nsCOMPtr<nsIRunnable> event = new EncodingRunnable(aType,
                                                     aOptions,
                                                     aImageBuffer,
                                                     nullptr,
                                                     encoder,
                                                     completeEvent,
                                                     aFormat,
                                                     aSize,
                                                     aUsingCustomOptions);
  return encoderThread->Dispatch(event, NS_DISPATCH_NORMAL);
}
nsresult
nsNotifyAddrListener::Init(void)
{
    // XXX this call is very expensive (~650 milliseconds), so we
    //     don't want to call it synchronously.  Instead, we just
    //     start up assuming we have a network link, but we'll
    //     report that the status isn't known.
    //
    // CheckLinkStatus();

    // only start a thread on Windows 2000 or later
    if (mOSVerInfo.dwPlatformId != VER_PLATFORM_WIN32_NT ||
            mOSVerInfo.dwMajorVersion < 5)
        return NS_OK;

    nsresult rv;
    nsCOMPtr<nsIObserverService> observerService =
        do_GetService("@mozilla.org/observer-service;1", &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = observerService->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID,
                                      PR_FALSE);
    NS_ENSURE_SUCCESS(rv, rv);

    mShutdownEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
    NS_ENSURE_TRUE(mShutdownEvent, NS_ERROR_OUT_OF_MEMORY);

    rv = NS_NewThread(getter_AddRefs(mThread), this, 0,
                      PR_JOINABLE_THREAD);
    NS_ENSURE_SUCCESS(rv, rv);

    return NS_OK;
}
  void RunInBackground()
  {
    (void)NS_NewThread(getter_AddRefs(mThread));
    do_check_true(mThread);

    do_check_success(mThread->Dispatch(this, NS_DISPATCH_NORMAL));
  }
/**
 * Add an nsILDAPOperation to the list of operations pending on
 * this connection.  This is also mainly intended for use by the
 * nsLDAPOperation code.
 */
nsresult
nsLDAPConnection::AddPendingOperation(uint32_t aOperationID, nsILDAPOperation *aOperation)
{
  NS_ENSURE_ARG_POINTER(aOperation);

  nsIRunnable* runnable = new nsLDAPConnectionRunnable(aOperationID, aOperation,
                                                       this);
  mPendingOperations.Put((uint32_t)aOperationID, aOperation);

  nsresult rv;
  if (!mThread)
  {
    rv = NS_NewThread(getter_AddRefs(mThread), runnable);
    NS_ENSURE_SUCCESS(rv, rv);
  }
  else
  {
    rv = mThread->Dispatch(runnable, nsIEventTarget::DISPATCH_NORMAL);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  PR_LOG(gLDAPLogModule, PR_LOG_DEBUG,
         ("pending operation added; total pending operations now = %d\n",
          mPendingOperations.Count()));

  return NS_OK;
}
/* void initFifos (in string toserver, in string fromserver); */
NS_IMETHODIMP nsSynthesizer::InitFifos(const char *toserver, const char *fromserver, nsISynthSrvListener *svrListener)
{
    NS_PRECONDITION(toserver != nsnull && fromserver != nsnull, "null ptr");

  m_svrListener = svrListener;
  
  if (!toserver || !fromserver) {
    return NS_ERROR_NULL_POINTER;
  }

  m_toserver.reset(new std::ofstream(toserver));

  m_fromserver = fopen(fromserver, "r");

  if (!m_fromserver || !m_toserver->good()) {
    if (m_fromserver) {
      fclose(m_fromserver);
    }
    return NS_ERROR_FILE_NOT_FOUND;
  }
  
  nsCOMPtr<nsIThread> runner;
  nsresult rv = NS_NewThread(getter_AddRefs(runner), new nsListenRunner(*this));
    
  if (NS_FAILED(rv)) {
    printf("failed to create thread\n");
  }
  return rv;
}
NS_IMETHODIMP
sbWin32FileSystemWatcher::OnTreeReady(const nsAString & aTreeRootPath,
                                      sbStringArray & aDirPathArray)
{
  TRACE("%s: root path %s",
         __FUNCTION__, NS_ConvertUTF16toUTF8(aTreeRootPath).get());
  if (mWatchPath.Equals(EmptyString())) {
    // If the watch path is empty here, this means that the tree was loaded
    // from a previous session. Set the watch path now.
    mWatchPath.Assign(aTreeRootPath);
  }

  // Setup the timer callback
  nsresult rv;
  NS_ENSURE_STATE(!mRebuildThread);

  // Setup the timer callback, on a background thread
  nsCOMPtr<nsIRunnable> initRebuildEvent =
    NS_NEW_RUNNABLE_METHOD(sbWin32FileSystemWatcher, this, InitRebuildThread);
  NS_ENSURE_TRUE(initRebuildEvent, NS_ERROR_OUT_OF_MEMORY);

  rv = NS_NewThread(getter_AddRefs(mRebuildThread), initRebuildEvent);
  NS_ENSURE_SUCCESS(rv, rv);

  // Get a handle to the root directory.
  mRootDirHandle =
    CreateFileW(mWatchPath.get(),            // path
                GENERIC_READ,                // desired access
                FILE_SHARE_READ |            // shared mode
                FILE_SHARE_WRITE,
                NULL,                        // security attributes
                OPEN_EXISTING,               // creation disposition
                FILE_FLAG_BACKUP_SEMANTICS | // flags and attributes
                FILE_FLAG_OVERLAPPED,
                NULL);                       // template file

  NS_ENSURE_TRUE(mRootDirHandle != INVALID_HANDLE_VALUE, NS_ERROR_UNEXPECTED);

  memset(&mOverlapped, 0, sizeof(mOverlapped));
  mOverlapped.hEvent = (HANDLE)this;

  if (!mBuffer) {
    mBuffer = nsMemory::Alloc(BUFFER_LEN);
  }

  // Start the watcher thread.
  if (!mIsThreadRunning) {
    mShouldRunThread = PR_TRUE;
    mWatcherThread = CreateThread(NULL, 0, BackgroundThreadProc, this, 0, NULL);
    NS_ENSURE_TRUE(mWatcherThread != INVALID_HANDLE_VALUE, NS_ERROR_OUT_OF_MEMORY);
  }

  mIsWatching = PR_TRUE;

  rv = mListener->OnWatcherStarted();
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}
Exemple #13
0
nsresult TimerThread::Init()
{
  PR_LOG(gTimerLog, PR_LOG_DEBUG, ("TimerThread::Init [%d]\n", mInitialized));

  if (mInitialized) {
    if (!mThread)
      return NS_ERROR_FAILURE;

    return NS_OK;
  }

  if (PR_AtomicSet(&mInitInProgress, 1) == 0) {
    // We hold on to mThread to keep the thread alive.
    nsresult rv = NS_NewThread(getter_AddRefs(mThread), this);
    if (NS_FAILED(rv)) {
      mThread = nsnull;
    }
    else {
      nsCOMPtr<nsIObserverService> observerService =
          do_GetService("@mozilla.org/observer-service;1");
      // We must not use the observer service from a background thread!
      if (observerService && !NS_IsMainThread()) {
        nsCOMPtr<nsIObserverService> result = nsnull;
        NS_GetProxyForObject(NS_PROXY_TO_MAIN_THREAD,
                             NS_GET_IID(nsIObserverService),
                             observerService, NS_PROXY_ASYNC,
                             getter_AddRefs(result));
        observerService.swap(result);
      }
      // We'll be released at xpcom shutdown
      if (observerService) {
        observerService->AddObserver(this, "sleep_notification", PR_FALSE);
        observerService->AddObserver(this, "wake_notification", PR_FALSE);
      }
    }

    PR_Lock(mLock);
    mInitialized = PR_TRUE;
    PR_NotifyAllCondVar(mCondVar);
    PR_Unlock(mLock);
  }
  else {
    PR_Lock(mLock);
    while (!mInitialized) {
      PR_WaitCondVar(mCondVar, PR_INTERVAL_NO_TIMEOUT);
    }
    PR_Unlock(mLock);
  }

  if (!mThread)
    return NS_ERROR_FAILURE;

  return NS_OK;
}
void
InitGonkMemoryPressureMonitoring()
{
  // memoryPressureWatcher is held alive by the observer service.
  nsRefPtr<MemoryPressureWatcher> memoryPressureWatcher =
    new MemoryPressureWatcher();
  NS_ENSURE_SUCCESS_VOID(memoryPressureWatcher->Init());

  nsCOMPtr<nsIThread> thread;
  NS_NewThread(getter_AddRefs(thread), memoryPressureWatcher);
}
// called from main thread only
NS_IMETHODIMP
nsSocketTransportService::Init()
{
    NS_ENSURE_TRUE(mLock, NS_ERROR_OUT_OF_MEMORY);

    if (!NS_IsMainThread()) {
        NS_ERROR("wrong thread");
        return NS_ERROR_UNEXPECTED;
    }

    if (mInitialized)
        return NS_OK;

    if (mShuttingDown)
        return NS_ERROR_UNEXPECTED;

    if (!mThreadEvent) {
        mThreadEvent = PR_NewPollableEvent();
        //
        // NOTE: per bug 190000, this failure could be caused by Zone-Alarm
        // or similar software.
        //
        // NOTE: per bug 191739, this failure could also be caused by lack
        // of a loopback device on Windows and OS/2 platforms (NSPR creates
        // a loopback socket pair on these platforms to implement a pollable
        // event object).  if we can't create a pollable event, then we'll
        // have to "busy wait" to implement the socket event queue :-(
        //
        if (!mThreadEvent) {
            NS_WARNING("running socket transport thread without a pollable event");
            LOG(("running socket transport thread without a pollable event"));
        }
    }

    nsCOMPtr<nsIThread> thread;
    nsresult rv = NS_NewThread(getter_AddRefs(thread), this);
    if (NS_FAILED(rv)) return rv;
    
    {
        nsAutoLock lock(mLock);
        // Install our mThread, protecting against concurrent readers
        thread.swap(mThread);
    }

    nsCOMPtr<nsIPrefBranch2> tmpPrefService = do_GetService(NS_PREFSERVICE_CONTRACTID);
    if (tmpPrefService) 
        tmpPrefService->AddObserver(SEND_BUFFER_PREF, this, PR_FALSE);
    UpdatePrefs();

    mInitialized = PR_TRUE;
    return NS_OK;
}
nsresult
LazyIdleThread::EnsureThread()
{
  ASSERT_OWNING_THREAD();

  if (mShutdown) {
    return NS_ERROR_UNEXPECTED;
  }

  if (mThread) {
    return NS_OK;
  }

  MOZ_ASSERT(!mPendingEventCount, "Shouldn't have events yet!");
  MOZ_ASSERT(!mIdleNotificationCount, "Shouldn't have idle events yet!");
  MOZ_ASSERT(!mIdleTimer, "Should have killed this long ago!");
  MOZ_ASSERT(!mThreadIsShuttingDown, "Should have cleared that!");

  nsresult rv;

  if (mShutdownMethod == AutomaticShutdown && NS_IsMainThread()) {
    nsCOMPtr<nsIObserverService> obs =
      do_GetService(NS_OBSERVERSERVICE_CONTRACTID, &rv);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return rv;
    }

    rv = obs->AddObserver(this, "xpcom-shutdown-threads", false);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return rv;
    }
  }

  mIdleTimer = do_CreateInstance(NS_TIMER_CONTRACTID, &rv);
  if (NS_WARN_IF(!mIdleTimer)) {
    return NS_ERROR_UNEXPECTED;
  }

  nsCOMPtr<nsIRunnable> runnable =
    NewRunnableMethod(this, &LazyIdleThread::InitThread);
  if (NS_WARN_IF(!runnable)) {
    return NS_ERROR_UNEXPECTED;
  }

  rv = NS_NewThread(getter_AddRefs(mThread), runnable);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  return NS_OK;
}
Exemple #17
0
// HACK ALERT: this test fails if it runs after any of the other storage tests
// because the storage service will have been initialized and the
// do_GetService() call in ServiceInitializer::Run will succeed. So we need a
// way to force it to run before all the other storage gtests. As it happens,
// gtest has a concept of "death tests" that, among other things, run before
// all non-death tests. By merely using a "DeathTest" suffix here this becomes
// a death test -- even though it doesn't use any of the normal death test
// features -- which ensures this is the first storage test to run.
TEST(storage_service_init_background_thread_DeathTest, Test)
{
  nsCOMPtr<nsIRunnable> event = new ServiceInitializer();
  do_check_true(event);

  nsCOMPtr<nsIThread> thread;
  do_check_success(NS_NewThread(getter_AddRefs(thread)));

  do_check_success(thread->Dispatch(event, NS_DISPATCH_NORMAL));

  // Shutting down the thread will spin the event loop until all work in its
  // event queue is completed.  This will act as our thread synchronization.
  do_check_success(thread->Shutdown());
}
nsresult FileBlockCache::Open(PRFileDesc* aFD)
{
  NS_ASSERTION(NS_IsMainThread(), "Only call on main thread");
  NS_ENSURE_TRUE(aFD != nullptr, NS_ERROR_FAILURE);
  {
    MonitorAutoLock mon(mFileMonitor);
    mFD = aFD;
  }
  {
    MonitorAutoLock mon(mDataMonitor);
    nsresult res = NS_NewThread(getter_AddRefs(mThread),
                                nullptr,
                                MEDIA_THREAD_STACK_SIZE);
    mIsOpen = NS_SUCCEEDED(res);
    return res;
  }
}
Exemple #19
0
nsresult
TestPipe(nsIInputStream* in, nsIOutputStream* out)
{
    nsresult rv;
    nsIThread* thread;
    nsReceiver* receiver = new nsReceiver(in);
    if (receiver == nsnull) return NS_ERROR_OUT_OF_MEMORY;
    NS_ADDREF(receiver);

    rv = NS_NewThread(&thread, receiver);
    if (NS_FAILED(rv)) return rv;

    PRUint32 total = 0;
    PRIntervalTime start = PR_IntervalNow();
    for (PRUint32 i = 0; i < ITERATIONS; i++) {
        PRUint32 writeCount;
        char *buf = PR_smprintf("%d %s", i, kTestPattern);
        PRUint32 len = strlen(buf);
        rv = WriteAll(out, buf, len, &writeCount);
        if (gTrace) {
            printf("wrote: ");
            for (PRUint32 j = 0; j < writeCount; j++) {
                putc(buf[j], stdout);
            }
            printf("\n");
        }
        PR_smprintf_free(buf);
        if (NS_FAILED(rv)) return rv;
        total += writeCount;
    }
    rv = out->Close();
    if (NS_FAILED(rv)) return rv;

    PRIntervalTime end = PR_IntervalNow();

    thread->Shutdown();

    printf("wrote %d bytes, time = %dms\n", total,
           PR_IntervalToMilliseconds(end - start));
    NS_ASSERTION(receiver->GetBytesRead() == total, "didn't read everything");

    NS_RELEASE(thread);
    NS_RELEASE(receiver);

    return NS_OK;
}
Exemple #20
0
nsresult
TestShortWrites(nsIInputStream* in, nsIOutputStream* out)
{
    nsresult rv;
    nsIThread* thread;
    nsShortReader* receiver = new nsShortReader(in);
    if (receiver == nsnull) return NS_ERROR_OUT_OF_MEMORY;
    NS_ADDREF(receiver);

    rv = NS_NewThread(&thread, receiver);
    if (NS_FAILED(rv)) return rv;

    PRUint32 total = 0;
    for (PRUint32 i = 0; i < ITERATIONS; i++) {
        PRUint32 writeCount;
        char* buf = PR_smprintf("%d %s", i, kTestPattern);
        PRUint32 len = strlen(buf);
        len = len * rand() / RAND_MAX;
        len = PR_MAX(1, len);
        rv = WriteAll(out, buf, len, &writeCount);
        if (NS_FAILED(rv)) return rv;
        NS_ASSERTION(writeCount == len, "didn't write enough");
        total += writeCount;

        if (gTrace)
            printf("wrote %d bytes: %s\n", writeCount, buf);
        PR_smprintf_free(buf);
        //printf("calling Flush\n");
        out->Flush();
        //printf("calling WaitForReceipt\n");
        PRUint32 received = receiver->WaitForReceipt();
        NS_ASSERTION(received == writeCount, "received wrong amount");
    }
    rv = out->Close();
    if (NS_FAILED(rv)) return rv;

    thread->Shutdown();
    printf("wrote %d bytes\n", total);

    NS_RELEASE(thread);
    NS_RELEASE(receiver);

    return NS_OK;
}
Exemple #21
0
void
EnableBatteryNotifications()
{
  if (!sUEventInitialized)
    sUEventInitialized = uevent_init();
  if (!sUEventInitialized) {
    NS_WARNING("uevent_init() failed!");
    return;
  }

  if (!sWatcher)
    sWatcher = new UEventWatcher();
  NS_ADDREF(sWatcher);

  sWatcher->mRunning = true;
  nsresult rv = NS_NewThread(&sWatcherThread, sWatcher);
  if (NS_FAILED(rv))
    NS_WARNING("Failed to get new thread for uevent watching");
}
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);

    nsCOMPtr<nsIRunnable> worker = new ParserWorker(currentThread, serialized, tzProvider, listener);
    NS_ENSURE_TRUE(worker, NS_ERROR_OUT_OF_MEMORY);
    rv = NS_NewThread(getter_AddRefs(workerThread), worker);
    NS_ENSURE_SUCCESS(rv, rv);
    return NS_OK;
}
nsresult
MediaEngineWebrtcVideoSource::Start(SourceMediaStream* aStream, TrackID aID)
{
  if (false == mInitDone || mState != kAllocated) {
    return NULL;
  }

  if(!aStream)
  	return NULL;

  if(mState == kStarted)
    return NS_OK;

  mSource = aStream;
  mTrackID = aID;

  //setup  a blank track
  mImageContainer = layers::LayerManager::CreateImageContainer();
  mSource->AddTrack(aID, mFps, 0, new VideoSegment());
  mSource->AdvanceKnownTracksTime(STREAM_TIME_MAX);
  
  //let's start the rendering
  if (!mVideoRenderingThread)
  {
    NS_NewThread(getter_AddRefs(mVideoRenderingThread),
                        nsnull,
                        MEDIA_THREAD_STACK_SIZE);
  }
  // no point in proceeding
  if(!mVideoRenderingThread)
	return NS_ERROR_FAILURE;

  int error = mViERender->AddRenderer(mCapIndex, webrtc::kVideoI420, (webrtc::ExternalRenderer*) this);
  error = mViERender->StartRender(mCapIndex);
  if (-1 == error)
  {
        printf( "ERROR in ViERender::StartRender %d ", mViEBase->LastError());
        return NS_ERROR_FAILURE;
  }

  mState = kStarted;
  return NS_OK;
}
static nsresult
RunApartmentTest()
{
    LOG(("RunApartmentTest: start\n"));

    const PRUint32 numDispatched = 160;

    PRUint32 numCompleted = 0;
    nsCOMPtr<nsIRunnable> obj = new MainThreadOnly(&numCompleted);

    nsCOMPtr<nsIProxyObjectManager> manager =
            do_GetService(NS_XPCOMPROXY_CONTRACTID);

    nsCOMPtr<nsIRunnable> objProxy;
    manager->GetProxyForObject(NS_PROXY_TO_CURRENT_THREAD,
                               NS_GET_IID(nsIRunnable),
                               obj,
                               NS_PROXY_ASYNC,
                               getter_AddRefs(objProxy));
    nsCOMPtr<nsIThread> thread;
    NS_NewThread(getter_AddRefs(thread));

    obj = nsnull;

    nsCOMPtr<nsIThreadPool> pool = do_CreateInstance(NS_THREADPOOL_CONTRACTID);

    pool->SetThreadLimit(8);
    for (PRUint32 i = 0; i < numDispatched; ++i)
        pool->Dispatch(objProxy, NS_DISPATCH_NORMAL);

    objProxy = nsnull;

    nsCOMPtr<nsIThread> curThread = do_GetCurrentThread();
    while (numCompleted < numDispatched) {
        NS_ProcessNextEvent(curThread);
    }

    pool->Shutdown();

    LOG(("RunApartmentTest: end\n"));
    return NS_OK;
}
Exemple #25
0
TEST(Threads, Main)
{
    nsresult rv;

    nsCOMPtr<nsIRunnable> event = new nsRunner(0);
    EXPECT_TRUE(event);

    nsCOMPtr<nsIThread> runner;
    rv = NS_NewThread(getter_AddRefs(runner), event);
    EXPECT_TRUE(NS_SUCCEEDED(rv));

    nsCOMPtr<nsIThread> thread;
    rv = NS_GetCurrentThread(getter_AddRefs(thread));
    EXPECT_TRUE(NS_SUCCEEDED(rv));

    rv = runner->Shutdown();     // wait for the runner to die before quitting
    EXPECT_TRUE(NS_SUCCEEDED(rv));

    PR_Sleep(PR_MillisecondsToInterval(100));       // hopefully the runner will quit here
}
nsresult
nsNotifyAddrListener::Init(void)
{
    nsCOMPtr<nsIObserverService> observerService =
        mozilla::services::GetObserverService();
    if (!observerService)
        return NS_ERROR_FAILURE;

    nsresult rv = observerService->AddObserver(this, "xpcom-shutdown-threads",
                                               false);
    NS_ENSURE_SUCCESS(rv, rv);

    mShutdownEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
    NS_ENSURE_TRUE(mShutdownEvent, NS_ERROR_OUT_OF_MEMORY);

    rv = NS_NewThread(getter_AddRefs(mThread), this);
    NS_ENSURE_SUCCESS(rv, rv);

    return NS_OK;
}
nsresult sbRequestThreadQueue::Start()
{
  TRACE_FUNCTION("");
  // Ensure we've allocated our lock and monitor
  NS_ENSURE_TRUE(mLock, NS_ERROR_OUT_OF_MEMORY);
  NS_ENSURE_TRUE(mStopWaitMonitor, NS_ERROR_OUT_OF_MEMORY);

  nsresult rv;

  // No need to lock since Start should not be called while the request thread
  // is running or from multiple threads.
  // Start should not be called more than once before Stop is called.
  NS_ENSURE_FALSE(mThreadStarted, NS_ERROR_FAILURE);

  // Clear the stop request processing flag. No need to lock since this is
  // the only live thread with access to the object.
  mStopProcessing = false;

  // Create the request added event object.
  rv = sbRTQAddedEvent::New(this, getter_AddRefs(mReqAddedEvent));
  NS_ENSURE_SUCCESS(rv, rv);


  rv = sbRunnableMethod(*this,
                        &sbRequestThreadQueue::ThreadShutdownAction,
                        NS_ERROR_FAILURE,
                        0,
                        getter_AddRefs(mShutdownAction));
  NS_ENSURE_SUCCESS(rv, rv);

  mThreadStarted = true;

  // Create the request processing thread.
  rv = NS_NewThread(getter_AddRefs(mThread), nsnull);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = PushRequest(sbRequestItem::New(REQUEST_THREAD_START));
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}
Exemple #28
0
nsresult
DataStorage::Init(bool& aDataWillPersist)
{
  // Don't access the observer service or preferences off the main thread.
  if (!NS_IsMainThread()) {
    NS_NOTREACHED("DataStorage::Init called off main thread");
    return NS_ERROR_NOT_SAME_THREAD;
  }

  MutexAutoLock lock(mMutex);

  nsresult rv;
  rv = NS_NewThread(getter_AddRefs(mWorkerThread));
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  rv = AsyncReadData(aDataWillPersist, lock);
  if (NS_FAILED(rv)) {
    return rv;
  }

  nsCOMPtr<nsIObserverService> os = services::GetObserverService();
  if (NS_WARN_IF(!os)) {
    return NS_ERROR_FAILURE;
  }
  // Clear private data as appropriate.
  os->AddObserver(this, "last-pb-context-exited", false);
  // Observe shutdown; save data and prevent any further writes.
  os->AddObserver(this, "profile-before-change", false);

  // For test purposes, we can set the write timer to be very fast.
  mTimerDelay = Preferences::GetInt("test.datastorage.write_timer_ms",
                                    sDataStorageDefaultTimerDelay);
  rv = Preferences::AddStrongObserver(this, "test.datastorage.write_timer_ms");
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return rv;
  }

  return NS_OK;
}
already_AddRefed<nsDOMMediaStream>
MediaEngineWebrtcVideoSource::Allocate()
{
  if (mState != kReleased) {
    return NULL;
  }

  //let's allocate the device
  char deviceName[KMaxDeviceNameLength];
  char uniqueId[KMaxUniqueIdLength];
  memset(deviceName, 0, KMaxDeviceNameLength);
  memset(uniqueId, 0, KMaxUniqueIdLength);
  mViECapture->GetCaptureDevice(
 				mCapIndex, deviceName, KMaxDeviceNameLength, uniqueId, KMaxUniqueIdLength
  	);

  if(0 == mViECapture->AllocateCaptureDevice(
    					uniqueId, KMaxUniqueIdLength, mCapIndex)) 
  {
  	mState = kAllocated;
    // start the capture on the device
  	if (!mVideoCaptureThread)
  	{
   	 NS_NewThread(getter_AddRefs(mVideoCaptureThread),
   	                     nsnull,
   	                     MEDIA_THREAD_STACK_SIZE);
  	}
    //no point in proceeding
    if(!mVideoCaptureThread)
    	return NULL;

   	nsCOMPtr<nsIRunnable> event = new VideoStartCaptureEvent(this);
  	mVideoCaptureThread->Dispatch(event,0);
   	return nsDOMMediaStream::CreateInputStream();
  }

  return NULL; 
}
Exemple #30
0
void
Test(CreateFun create, PRUint32 count,
     nsIFile* inDirSpec, nsIFile* outDirSpec, PRUint32 bufSize)
{
    nsresult rv;
    PRUint32 i;

    nsCAutoString inDir;
    nsCAutoString outDir;
    (void)inDirSpec->GetNativePath(inDir);
    (void)outDirSpec->GetNativePath(outDir);
    printf("###########\nTest: from %s to %s, bufSize = %d\n",
           inDir.get(), outDir.get(), bufSize);
    gTimeSampler.Reset();
    nsTimeSampler testTime;
    testTime.StartTime();

    nsCOMArray<nsIThread> threads;

    nsCOMPtr<nsISimpleEnumerator> entries;
    rv = inDirSpec->GetDirectoryEntries(getter_AddRefs(entries));
    NS_ASSERTION(NS_SUCCEEDED(rv), "GetDirectoryEntries failed");

    i = 0;
    bool hasMore;
    while (i < count && NS_SUCCEEDED(entries->HasMoreElements(&hasMore)) && hasMore) {
        nsCOMPtr<nsISupports> next;
        rv = entries->GetNext(getter_AddRefs(next));
        if (NS_FAILED(rv)) goto done;

        nsCOMPtr<nsIFile> inSpec = do_QueryInterface(next, &rv);
        if (NS_FAILED(rv)) goto done;

        nsCOMPtr<nsIFile> outSpec;
        rv = outDirSpec->Clone(getter_AddRefs(outSpec)); // don't munge the original
        if (NS_FAILED(rv)) goto done;

        nsCAutoString leafName;
        rv = inSpec->GetNativeLeafName(leafName);
        if (NS_FAILED(rv)) goto done;

        rv = outSpec->AppendNative(leafName);
        if (NS_FAILED(rv)) goto done;

        bool exists;
        rv = outSpec->Exists(&exists);
        if (NS_FAILED(rv)) goto done;

        if (exists) {
            rv = outSpec->Remove(PR_FALSE);
            if (NS_FAILED(rv)) goto done;
        }

        nsCOMPtr<nsIThread> thread;
        nsCOMPtr<nsIRunnable> worker;
        rv = create(getter_AddRefs(worker), 
                    inSpec,
                    outSpec,
                    bufSize);
        if (NS_FAILED(rv)) goto done;

        rv = NS_NewThread(getter_AddRefs(thread), worker, 0, PR_JOINABLE_THREAD);
        if (NS_FAILED(rv)) goto done;

        bool inserted = threads.InsertObjectAt(thread, i);
        NS_ASSERTION(inserted, "not inserted");

        i++;
    }

    PRUint32 j;
    for (j = 0; j < i; j++) {
        nsIThread* thread = threads.ObjectAt(j);
        thread->Join();
    }

  done:
    NS_ASSERTION(rv == NS_OK, "failed");

    testTime.EndTime();
    char* testStats = testTime.PrintStats();
    char* workerStats = gTimeSampler.PrintStats();
    printf("  threads = %d\n  work time = %s,\n  test time = %s\n",
           i, workerStats, testStats);
    PR_smprintf_free(workerStats);
    PR_smprintf_free(testStats);
}