Esempio n. 1
0
        void schedule_frame(IDeckLinkMutableVideoFrame *frame) {
            RawFrame *input = NULL;
            void *data;

            if (in_pipe.data_ready( )) {
                input = in_pipe.get( );
            } else if (last_frame != NULL) {
                /* use the stale frame */
                fprintf(stderr, "DeckLink: stale frame\n");
                input = last_frame;
            } else {
                /* this should likewise be a black frame */
                input = NULL;
            }
            
            if (input != NULL) {
                frame->GetBytes(&data);
                input->unpack->CbYCrY8422((uint8_t *) data);
            } else {
                fprintf(stderr, "DeckLink: on fire\n");
            }
            
            deckLinkOutput->ScheduleVideoFrame(frame, 
                frame_counter * frame_duration, frame_duration, time_base);

            frame_counter++;

            if (last_frame != input) {
                delete last_frame;
                last_frame = input;
            }
        }
bool SshEncryptionFacility::createAuthenticationKeyFromPKCS8(const QByteArray &privKeyFileContents,
    QList<BigInt> &pubKeyParams, QList<BigInt> &allKeyParams, QString &error)
{
    try {
        Pipe pipe;
        pipe.process_msg(convertByteArray(privKeyFileContents), privKeyFileContents.size());
        Private_Key * const key = PKCS8::load_key(pipe, m_rng, SshKeyPasswordRetriever());
        if (DSA_PrivateKey * const dsaKey = dynamic_cast<DSA_PrivateKey *>(key)) {
            m_authKeyAlgoName = SshCapabilities::PubKeyDss;
            m_authKey.reset(dsaKey);
            pubKeyParams << dsaKey->group_p() << dsaKey->group_q()
                         << dsaKey->group_g() << dsaKey->get_y();
            allKeyParams << pubKeyParams << dsaKey->get_x();
        } else if (RSA_PrivateKey * const rsaKey = dynamic_cast<RSA_PrivateKey *>(key)) {
            m_authKeyAlgoName = SshCapabilities::PubKeyRsa;
            m_authKey.reset(rsaKey);
            pubKeyParams << rsaKey->get_e() << rsaKey->get_n();
            allKeyParams << pubKeyParams << rsaKey->get_p() << rsaKey->get_q()
                         << rsaKey->get_d();
        } else {
            qWarning("%s: Unexpected code flow, expected success or exception.", Q_FUNC_INFO);
            return false;
        }
    } catch (const Botan::Exception &ex) {
        error = QLatin1String(ex.what());
        return false;
    } catch (const Botan::Decoding_Error &ex) {
        error = QLatin1String(ex.what());
        return false;
    }

    return true;
}
Esempio n. 3
0
void ComposerEngine::playWaveForAnim(uint16 id, uint16 priority, bool bufferingOnly) {
	if (_audioStream && _audioStream->numQueuedStreams() != 0) {
		if (_currSoundPriority < priority)
			return;
		if (_currSoundPriority > priority) {
			_mixer->stopAll();
			_audioStream = NULL;
		}
	}
	Common::SeekableReadStream *stream = NULL;
	if (!bufferingOnly && hasResource(ID_WAVE, id)) {
		stream = getResource(ID_WAVE, id);
	} else {
		for (Common::List<Pipe *>::iterator k = _pipes.begin(); k != _pipes.end(); k++) {
			Pipe *pipe = *k;
			if (!pipe->hasResource(ID_WAVE, id))
				continue;
			stream = pipe->getResource(ID_WAVE, id, true);
			break;
		}
	}
	if (!stream)
		return;
	// FIXME: non-pipe buffers have fixed wav header (data at +44, size at +40)
	byte *buffer = (byte *)malloc(stream->size());
	stream->read(buffer, stream->size());
	if (!_audioStream)
		_audioStream = Audio::makeQueuingAudioStream(22050, false);
	_audioStream->queueBuffer(buffer, stream->size(), DisposeAfterUse::YES, Audio::FLAG_UNSIGNED);
	_currSoundPriority = priority;
	delete stream;
	if (!_mixer->isSoundHandleActive(_soundHandle))
		_mixer->playStream(Audio::Mixer::kSFXSoundType, &_soundHandle, _audioStream);
}
void test_pipeEvent_given_pipe_with_AND_and_OR_module_data_should_register_event_for_all_pipe_data(void)
{
    Module *AND, *OR;
    ModuleAndPin *andData, *orData;
    Pipe *pipe;
    Node *andRootNode, *orNode;
    int inputType = QUAD_2_INPUT;

    AND = createdAndModule(inputType);
    OR = createdOrModule(inputType);
    pipe = createdPipeModule();
    pipe->stateToFire = HIGH;
    andData = createdModuleAndPin(AND, (AND->pin[0]).pinNumber);
    orData = createdModuleAndPin(OR, (OR->pin[1]).pinNumber);

    andRootNode = createdNewPipeDataNode(andData);
    orNode = createdNewPipeDataNode(orData);
    setNode(andRootNode, orNode, NULL, 'b');
    pipe->data = andRootNode;

    registerEvent_Expect(orData, NULL, ONE_NANO_SEC + OR_PROPAGATION_DELAY);
    registerEvent_Expect(andData, NULL, ONE_NANO_SEC + AND_PROPAGATION_DELAY);

    pipe->event((void *)pipe, (void *)pipe->data, ONE_NANO_SEC);

    TEST_ASSERT_EQUAL(HIGH, (AND->pin[0]).state);
    TEST_ASSERT_EQUAL(HIGH, (OR->pin[1]).state);

    destroyModule(OR);
    destroyModule(AND);
    destroyPipeData(pipe);
}
void test_pipeEvent_given_pipe_with_AND_module_data_should_register_event_for_pipe_data(void)
{
    Module *AND;
    ModuleAndPin *pipeData;
    Pipe *pipe;
    Node *newNode;
    int inputType = QUAD_2_INPUT;

    AND = createdAndModule(inputType);
    pipe = createdPipeModule();
    pipe->stateToFire = HIGH;
    pipeData = createdModuleAndPin(AND, (AND->pin[0]).pinNumber);

    newNode = createdNewPipeDataNode(pipeData);
    pipe->data = newNode;

    registerEvent_Expect(pipeData, NULL, ONE_NANO_SEC + AND_PROPAGATION_DELAY);

    pipe->event((void *)pipe, (void *)pipe->data, ONE_NANO_SEC);

    TEST_ASSERT_EQUAL(HIGH, (AND->pin[0]).state);

    destroyModule(AND);
    destroyPipeData(pipe);
}
Esempio n. 6
0
  void testWriteRead ()
  {
    char outBuff[256];
    char inBuff[256];
    size_t nbw;
    size_t nbr;

    strcpy (outBuff, "MyServer is a powerful and easy to configure web server");

    int ret = pipe->create ();

    CPPUNIT_ASSERT_EQUAL (ret, 0);

    ret = pipe->write (outBuff, 256, &nbw);

    CPPUNIT_ASSERT_EQUAL (ret, 0);

    ret = pipe->read (inBuff, 256, &nbr);

    CPPUNIT_ASSERT_EQUAL (ret, 0);


    CPPUNIT_ASSERT_EQUAL (nbr, nbw);
    CPPUNIT_ASSERT (strcmp (outBuff, inBuff) == 0);

    pipe->close ();
  }
Esempio n. 7
0
//-----------------------------------------------------------------------------------------------
// adds the rates from the well to the direct upstream connections
//-----------------------------------------------------------------------------------------------
void DecoupledModel::addToMaterialBalanceStreamsUpstream(ProductionWell *w)
{

    // looping through the pipes connected to the well
    for(int i = 0; i < w->numberOfPipeConnections(); ++i)
    {

        Pipe *p = w->pipeConnection(i)->pipe();     // pointer to the pipe


        // finding the flow fraction from this well to the pipe
        double frac = w->pipeConnection(i)->variable()->value();

        // calculating the rate from this well to the pipe vs. time
        for(int j = 0; j < w->numberOfStreams(); ++j)
        {
            Stream s = *w->stream(j) * frac;

            // finding the material balance constraint that corresponds to this pipe and time
            MaterialBalanceConstraint *mbc = find(p->stream(j));

            // adding the rate contribution from this well to what is allready in the mbc
            mbc->setStream(s + mbc->stream());

        }

    }

}
Esempio n. 8
0
    void initializePipelineProcessors()
    {
        const Window* sharedWindow = static_cast< const Window* >(
                                         _window->getSharedContextWindow( ));

        // share upload processors for windows which also share the GL context
        if( sharedWindow && sharedWindow != _window )
        {
            _glContext = sharedWindow->_impl->_glContext;
            _dashProcessor = sharedWindow->_impl->_dashProcessor;
            _textureUploader = sharedWindow->_impl->_textureUploader;
            _dataUploader = sharedWindow->_impl->_dataUploader;
            return;
        }

        // First one in group: setup
        Node* node = static_cast< Node* >( _window->getNode( ));
        DashTree& dashTree = node->getDashTree();
        _dashProcessor->setDashContext( dashTree.createContext( ));
        _dataUploader.reset( new DataUploadProcessor( dashTree, _glContext,
                                                      node->getTextureDataCache( )));

        Config* config = static_cast< Config* >( _window->getConfig( ));
        Pipe* pipe = static_cast< Pipe* >( _window->getPipe( ));

        _textureUploader.reset(
            new EqTextureUploadProcessor( *config, dashTree, _glContext,
                                          node->getTextureDataCache(),
                                          pipe->getFrameData()->getVRParameters( )));
    }
Esempio n. 9
0
void Window::addTasks( const uint32_t tasks )
{
    Pipe* pipe = getPipe();
    EQASSERT( pipe );
    setTasks( getTasks() | tasks );
    pipe->addTasks( tasks );
}
Esempio n. 10
0
int main(int argc, const char* argv[])
{
	if (argc == 4) {
		port = atoi(argv[1]);
		ipaddr = argv[2];
		bindaddr = argv[3];
	}

	ev::loop_ref loop = ev::default_loop(0);

	InetServer server(loop);
	server.open(IPAddress(bindaddr), port);
	if (!server.isOpen()) {
		perror("server.open()");
		return 1;
	}

	pthread_t client_thread;
	int rv = pthread_create(&client_thread, NULL, client_run, NULL);
	if (rv < 0) {
		perror("pthread_create");
		return 1;
	}

	pthread_t proxy_thread;
	for (int i = 0; i < 2; ++i) {
		Socket* cs = server.acceptOne();
		if (!cs) {
			perror("accept");
			return 1;
		}

		if (i == 0) {
			// first client gets proxied
			pthread_create(&proxy_thread, NULL, proxy_run, cs);
		} else {
			// second client gets dumped to terminal (partly reading into buf, remaining data via pipe)
			Buffer buf;
			cs->read(buf, 39);
			write(STDOUT_FILENO, buf.data(), buf.size());

			Pipe pipe;
			for (;;) {
				if (cs->read(&pipe, 1024) > 0) {
					pipe.read(STDOUT_FILENO, pipe.size());
				} else {
					break;
				}
			}
			// TODO: cs->read(chunkedBuffer, Stream::MOVE);
			delete cs;
		}
	}

	pthread_join(client_thread, NULL);
	pthread_join(proxy_thread, NULL);

	return 0;
}
Esempio n. 11
0
void View::notifyAttach()
{
    eq::View::notifyAttach();
    Pipe* pipe = getPipe();

    if (pipe) // render client view
        setUserData(pipe->getRenderer()->createViewData(*this));
}
Esempio n. 12
0
/*
* Return a BER encoded X.509 object
*/
SecureVector<byte> EAC_Signed_Object::BER_encode() const
   {
   Pipe ber;
   ber.start_msg();
   encode(ber, RAW_BER);
   ber.end_msg();
   return ber.read_all();
   }
Esempio n. 13
0
/*
* Return a PEM encoded X.509 object
*/
std::string EAC_Signed_Object::PEM_encode() const
   {
   Pipe pem;
   pem.start_msg();
   encode(pem, PEM);
   pem.end_msg();
   return pem.read_all_as_string();
   }
Esempio n. 14
0
void View::notifyAttach()
{
    eq::View::notifyAttach();
    Pipe* pipe = getPipe();

    if( pipe ) // render client view
        setUserData( pipe->getRenderer()->createViewData( ));
    else // application view
        setUserData( getConfig()->getApplication()->createViewData( ));
}
Esempio n. 15
0
void Window::activate()
{   
    Pipe* pipe = getPipe();
    EQASSERT( pipe );

    ++_active;
    pipe->activate();

    EQLOG( LOG_VIEW ) << "activate: " << _active << std::endl;
}
Esempio n. 16
0
void tester_util::redirect(const ProcessPointer &from, const int from_fd,
                           const ProcessPointer &to, const int to_fd) {
  try {
    const Pipe pipe = create_pipe();
    from->setStream(from_fd, pipe.writeEnd());
    to->setStream(to_fd, pipe.readEnd());
  } catch (std::exception &) {
    BOOST_THROW_EXCEPTION(redirect_error() << bunsan::enable_nested_current());
  }
}
Esempio n. 17
0
status_t
OHCI::_SubmitTransfer(Transfer *transfer)
{
	Pipe *pipe = transfer->TransferPipe();
	bool directionIn = (pipe->Direction() == Pipe::In);

	ohci_general_td *firstDescriptor = NULL;
	ohci_general_td *lastDescriptor = NULL;
	status_t result = _CreateDescriptorChain(&firstDescriptor, &lastDescriptor,
		directionIn ? OHCI_TD_DIRECTION_PID_IN : OHCI_TD_DIRECTION_PID_OUT,
		transfer->VectorLength());

	if (result < B_OK)
		return result;

	// Apply data toggle to the first descriptor (the others will use the carry)
	firstDescriptor->flags &= ~OHCI_TD_TOGGLE_CARRY;
	firstDescriptor->flags |= pipe->DataToggle() ? OHCI_TD_TOGGLE_1
		: OHCI_TD_TOGGLE_0;

	// Set the last descriptor to generate an interrupt
	lastDescriptor->flags &= ~OHCI_TD_INTERRUPT_MASK;
	lastDescriptor->flags |=
		OHCI_TD_SET_DELAY_INTERRUPT(OHCI_TD_INTERRUPT_IMMEDIATE);

	if (!directionIn) {
		_WriteDescriptorChain(firstDescriptor, transfer->Vector(),
			transfer->VectorCount());
	}

	// Add to the transfer list
	ohci_endpoint_descriptor *endpoint
		= (ohci_endpoint_descriptor *)pipe->ControllerCookie();

	MutexLocker endpointLocker(endpoint->lock);
	result = _AddPendingTransfer(transfer, endpoint, firstDescriptor,
		firstDescriptor, lastDescriptor, directionIn);
	if (result < B_OK) {
		TRACE_ERROR("failed to add pending transfer\n");
		_FreeDescriptorChain(firstDescriptor);
		return result;
	}

	// Add the descriptor chain to the endpoint
	_SwitchEndpointTail(endpoint, firstDescriptor, lastDescriptor);
	endpointLocker.Unlock();

	endpoint->flags &= ~OHCI_ENDPOINT_SKIP;
	if (pipe->Type() & USB_OBJECT_BULK_PIPE) {
		// Tell the controller to process the bulk list
		_WriteReg(OHCI_COMMAND_STATUS, OHCI_BULK_LIST_FILLED);
	}

	return B_OK;
}
Esempio n. 18
0
void Display::discoverLocal( Config* config )
{
    Node* node = config->findAppNode();
    EQASSERT( node );
    if( !node )
        return;

    const Pipes& pipes = node->getPipes();
    EQASSERT( !pipes.empty( ));
    if( pipes.empty( ))
        return;

    Pipe* pipe = pipes.front();
    Window* window = new Window( pipe );
    window->setViewport( Viewport( .25f, .2f, .5f, .5f ));
    window->setName( pipe->getName() + " window" );
    window->setIAttribute( Window::IATTR_PLANES_STENCIL, 1 );

    Channel* channel = new Channel( window );
    channel->setName( pipe->getName() + " channel" );
    Observer* observer = new Observer( config );

    const PixelViewport& pvp = pipe->getPixelViewport();
    Wall wall;
    if( pvp.isValid( ))
        wall.resizeHorizontalToAR( float( pvp.w ) / float( pvp.h ));

    Canvas* canvas = new Canvas( config );
    canvas->setWall( wall );

    Segment* segment = new Segment( canvas );
    segment->setChannel( channel );

    Strings names;
    names.push_back( EQ_SERVER_CONFIG_LAYOUT_2D_DYNAMIC  );
    names.push_back( EQ_SERVER_CONFIG_LAYOUT_SIMPLE );
    names.push_back( EQ_SERVER_CONFIG_LAYOUT_DB_DS );
    names.push_back( EQ_SERVER_CONFIG_LAYOUT_DB_STATIC );
    names.push_back( EQ_SERVER_CONFIG_LAYOUT_DB_DYNAMIC );
    names.push_back( EQ_SERVER_CONFIG_LAYOUT_2D_STATIC );

    for( StringsCIter i = names.begin(); i != names.end(); ++i )
    {
        Layout* layout = new Layout( config );
        layout->setName( *i );

        View* view = new View( layout );
        view->setObserver( observer );
        view->setWall( wall );

        canvas->addLayout( layout );
    }

    config->activateCanvas( canvas );
}
Esempio n. 19
0
Common::SeekableReadStream *ComposerEngine::getStreamForSprite(uint16 id) {
	for (Common::List<Pipe *>::iterator k = _pipes.begin(); k != _pipes.end(); k++) {
		Pipe *pipe = *k;
		if (!pipe->hasResource(ID_BMAP, id))
			continue;
		return pipe->getResource(ID_BMAP, id, true);
	}
	if (hasResource(ID_BMAP, id))
		return getResource(ID_BMAP, id);
	return NULL;
}
Esempio n. 20
0
void Node::dirtyClientExit()
{
    const Pipes& pipes = getPipes();
    for( PipesCIter i = pipes.begin(); i != pipes.end(); ++i )
    {
        Pipe* pipe = *i;
        pipe->cancelThread();
    }
    transmitter.getQueue().wakeup();
    transmitter.join();
}
Esempio n. 21
0
bool Channel::configInit( const uint32_t initID )
{
    if( !eq::Channel::configInit( initID )) return false;
	
	const eq::Viewport& viewport = getViewport();
	Pipe *pipe = static_cast<Pipe*>( getPipe() );
    osg::ref_ptr<EqViewer> viewer = pipe->getViewer();
	_window = viewer->setUpViewerAsEmbeddedInWindow(viewport.x,viewport.y,viewport.w,viewport.h);
     
    return true;
}
Esempio n. 22
0
void Node::dirtyClientExit()
{
    const Pipes& pipes = getPipes();
    for( PipesCIter i = pipes.begin(); i != pipes.end(); ++i )
    {
        Pipe* pipe = *i;
        pipe->cancelThread();
    }
    getTransmitterQueue()->push( co::ICommand( )); // wake up to exit
    _impl->transmitter.join();
}
Esempio n. 23
0
std::string Row_Encryptor::decrypt(const std::string& input,
                                   const MemoryRegion<byte>& salt)
   {
   eax_dec->set_iv(salt);

   dec_pipe.start_msg();
   dec_pipe.write(input);
   dec_pipe.end_msg();

   return dec_pipe.read_all_as_string(Pipe::LAST_MESSAGE);
   }
Esempio n. 24
0
void Window::deactivate()
{ 
    EQASSERT( _active != 0 );
    Pipe* pipe = getPipe();
    EQASSERT( pipe );

    --_active; 
    pipe->deactivate(); 

    EQLOG( LOG_VIEW ) << "deactivate: " << _active << std::endl;
};
Esempio n. 25
0
  void testCreateClose ()
  {
    int ret = pipe->create ();

    CPPUNIT_ASSERT_EQUAL (pipe->pipeTerminated (), false);

    CPPUNIT_ASSERT_EQUAL (ret, 0);

    pipe->close ();

    CPPUNIT_ASSERT_EQUAL (pipe->pipeTerminated (), true);
  }
Esempio n. 26
0
void Pipe_Client()
{
	Pipe* pipe = new Pipe();
	string input;
	cout<<"id:";
	cin>>input;
	if(!pipe->Connect(input.c_str()))
	{
		cout<<"[pause] <fail to connect pipe>"<<endl;
		cin>>input;
		return;
	}
Esempio n. 27
0
void Node::_finishFrame( const uint32_t frameNumber ) const
{
    const Pipes& pipes = getPipes();
    for( Pipes::const_iterator i = pipes.begin(); i != pipes.end(); ++i )
    {
        Pipe* pipe = *i;
        LBASSERT( pipe->isThreaded() || pipe->getFinishedFrame()>=frameNumber );

        pipe->waitFrameLocal( frameNumber );
        pipe->waitFrameFinished( frameNumber );
    }
}
Esempio n. 28
0
void
Device::InitEndpoints(int32 interfaceIndex)
{
	for (size_t j = 0; j < fCurrentConfiguration->interface_count; j++) {
		if (interfaceIndex >= 0 && j != (size_t)interfaceIndex)
			continue;

		usb_interface_info* interfaceInfo
			= fCurrentConfiguration->interface[j].active;
		if (interfaceInfo == NULL)
			continue;

		for (size_t i = 0; i < interfaceInfo->endpoint_count; i++) {
			usb_endpoint_info* endpoint = &interfaceInfo->endpoint[i];
			Pipe* pipe = NULL;

			Pipe::pipeDirection direction = Pipe::Out;
			if ((endpoint->descr->endpoint_address & 0x80) != 0)
				direction = Pipe::In;

			switch (endpoint->descr->attributes & 0x03) {
				case USB_ENDPOINT_ATTR_CONTROL:		// Control Endpoint
					pipe = new(std::nothrow) ControlPipe(this);
					direction = Pipe::Default;
					break;

				case USB_ENDPOINT_ATTR_ISOCHRONOUS:	// Isochronous Endpoint
					pipe = new(std::nothrow) IsochronousPipe(this);
					break;

				case USB_ENDPOINT_ATTR_BULK:		// Bulk Endpoint
					pipe = new(std::nothrow) BulkPipe(this);
					break;

				case USB_ENDPOINT_ATTR_INTERRUPT:	// Interrupt Endpoint
					pipe = new(std::nothrow) InterruptPipe(this);
					break;
			}

			if (pipe == NULL) {
				TRACE_ERROR("failed to allocate pipe\n");
				endpoint->handle = 0;
				continue;
			}

			pipe->InitCommon(fDeviceAddress,
				endpoint->descr->endpoint_address & 0x0f,
				fSpeed, direction, endpoint->descr->max_packet_size,
				endpoint->descr->interval, fHubAddress, fHubPort);
			endpoint->handle = pipe->USBID();
		}
	}
}
Esempio n. 29
0
void ComposerEngine::playAnimation(uint16 animId, int16 x, int16 y, int16 eventParam) {
	// First, we check if this animation is already playing,
	// and if it is, we sabotage that running one first.
	for (Common::List<Animation *>::iterator i = _anims.begin(); i != _anims.end(); i++) {
		Animation *anim = *i;
		if (anim->_id != animId)
			continue;

		stopAnimation(*i);
	}

	Common::SeekableReadStream *stream = NULL;
	Pipe *newPipe = NULL;

	// First, check the existing pipes.
	for (Common::List<Pipe *>::iterator j = _pipes.begin(); j != _pipes.end(); j++) {
		Pipe *pipe = *j;
		if (!pipe->hasResource(ID_ANIM, animId))
			continue;
		stream = pipe->getResource(ID_ANIM, animId, false);
		break;
	}

	// If we didn't find it, try the libraries.
	if (!stream) {
		if (!hasResource(ID_ANIM, animId)) {
			warning("ignoring attempt to play invalid anim %d", animId);
			return;
		}
		stream = getResource(ID_ANIM, animId);

		uint32 type = 0;
		for (Common::List<Library>::iterator i = _libraries.begin(); i != _libraries.end(); i++)
			if (i->_archive->hasResource(ID_ANIM, animId)) {
				type = i->_archive->getResourceFlags(ID_ANIM, animId);
				break;
			}

		// If the resource is a pipe itself, then load the pipe
		// and then fish the requested animation out of it.
		if (type != 1) {
			newPipe = new Pipe(stream);
			_pipes.push_front(newPipe);
			stream = newPipe->getResource(ID_ANIM, animId, false);
		}
	}

	Animation *anim = new Animation(stream, animId, Common::Point(x, y), eventParam);
	_anims.push_back(anim);
	runEvent(kEventAnimStarted, animId, eventParam, 0);
	if (newPipe)
		newPipe->_anim = anim;
}
Esempio n. 30
0
//-----------------------------------------------------------------------------------------------
// adds the rates from the pipe to all upstream connections
//-----------------------------------------------------------------------------------------------
void DecoupledModel::addToMaterialBalanceStreamsUpstream(Separator *s, Well *from_well, double flow_frac)
{
    // pointer to the upstream connected pipe
    Pipe *upstream = s->outletConnection()->pipe();

    // looping through the streams, adding the contribution from the separator
    for(int i = 0; i < s->numberOfStreams(); ++i)
    {
        Stream str = *from_well->stream(i) * flow_frac;

        // checking if the separator is installed
        if(i >= s->installTime()->value())
        {
            // checking if this is a water or gas separator
            if(s->type() == Separator::WATER)
            {
                // how much water should be removed
                double qw_remove = str.waterRate(true) * s->removeFraction()->value();
                if(qw_remove > s->removeCapacity()->value()) qw_remove = s->removeCapacity()->value();

                // subtracting the removed water
                str.setWaterRate(str.waterRate(true) - qw_remove);
            }
            else if(s->type() == Separator::GAS)
            {
                // how much gas should be removed
                double qg_remove = str.gasRate(true) * s->removeFraction()->value();
                if(qg_remove > s->removeCapacity()->value()) qg_remove = s->removeCapacity()->value();

                // subtracting the removed gas
                str.setGasRate(str.gasRate(true) - qg_remove);
            }

        }

        // finding the material balance constraint that corresponds to this pipe and time
        MaterialBalanceConstraint *mbc = find(upstream->stream(i));

        // adding the rate contribution from this well to what is allready in the mbc
        mbc->setStream(str + mbc->stream());


    }

    // then checking if the upstream pipe is a midpipe or separator
    MidPipe *p_mid = dynamic_cast<MidPipe*>(upstream);
    Separator *p_sep = dynamic_cast<Separator*>(upstream);

    if(p_mid != 0) addToMaterialBalanceStreamsUpstream(p_mid, from_well, flow_frac);
    else if(p_sep != 0) addToMaterialBalanceStreamsUpstream(p_sep, from_well, flow_frac);

}