Esempio n. 1
0
// Create a file and dump the event information
void EventList::dumpEvents(char* path, char * ip_filename)
{
    FILE* fp =  NULL;
    char * filename;
    // Construct a filename based on the current time
    if (ip_filename == NULL)
    	filename = this->createFilenameWithTimestamp();
    else
    {
    	filename =  (char *)malloc(strlen(ip_filename)*sizeof(char));
    	strcpy(filename, ip_filename);
    }

    // Create string to hold the path + filename
    char* fullpath = new char[strlen(path)+strlen(filename)+1];
 
    // Concat the path and filename into the destination string
    strcpy(fullpath, path);
    strcat(fullpath, filename);

    // Try to open the file for writing
    fp = fopen(fullpath, "w");
    if(fp == NULL) {
        printf("Error opening %s\n", fullpath);
        exit(-1);
    }

    // Write some information out about the environment
 
    cl_int status;
    size_t devInfoSize;
    char* devInfoStr = NULL;

    // Get the device name
    status = clGetDeviceInfo(this->device, CL_DEVICE_NAME, 0, NULL, 
        &devInfoSize);
    if(status != CL_SUCCESS) {
        printf("Device info failed\n");
        exit(-1);
    }
                
    devInfoStr = new char[devInfoSize];

    status = clGetDeviceInfo(this->device, CL_DEVICE_NAME, devInfoSize, 
        devInfoStr, NULL);
    if(status != CL_SUCCESS) {
        printf("Device info failed\n");
        exit(-1);
    }

    // Write the device name
    fprintf(fp, "Info;\t%s\n", devInfoStr);
    delete devInfoStr;
    devInfoStr = NULL;

    // Get the device driver version
    status = clGetDeviceInfo(this->device, CL_DRIVER_VERSION, 0, NULL, 
        &devInfoSize);	
    if(status != CL_SUCCESS) {
        printf("Device info failed\n");
        exit(-1);
    }

    devInfoStr = new char[devInfoSize];

    status = clGetDeviceInfo(this->device, CL_DRIVER_VERSION, devInfoSize, 			
        devInfoStr, NULL);		
    if(status != CL_SUCCESS) {
        printf("Device info failed\n");
        exit(-1);
    }

    // Write the device driver version
    fprintf(fp, "Info;\tDriver version %s\n", devInfoStr);
    delete devInfoStr;

    // Write the hostname
#ifndef _WIN32
    char hostname[50];
    if(gethostname(hostname, 50) != 0) {
        printf("Error getting hostname\n");
    }
    else {
        fprintf(fp, "Info;\tHost %s\n", hostname);
    }
#endif
printf("Timer start %lu \n",this->gpu_timer_start) ;
    // Write the events to file with each field separated by semicolons
    for(int i = 0; i < (int)this->event_list.size(); i++) {
//        fprintf(fp, "%s;\t%s;\t%f;\t%f;\t%f;\t%f\n",
	    fprintf(fp, "%s;\t%s;\t%llu;\t%llu;\t%llu;\t%llu\n",
            this->event_list[i]->type,
            this->event_list[i]->name, 
            long( getEventValue(this->event_list[i]->event,
                	CL_PROFILING_COMMAND_QUEUED) - this->gpu_timer_start ),
	    long( getEventValue(this->event_list[i]->event,
	                CL_PROFILING_COMMAND_SUBMIT) - this->gpu_timer_start ),
            long( getEventValue(this->event_list[i]->event,
        	        CL_PROFILING_COMMAND_START) - this->gpu_timer_start ),
            long( getEventValue(this->event_list[i]->event,
        	        CL_PROFILING_COMMAND_END) - this->gpu_timer_start )  
	);
/*
        printf("%s;\t%s;\t%lu;\t%lu;\t%lu;\t%lu\n", 
            this->event_list[i]->type,
            this->event_list[i]->name, 
            ulong(	getEventValue(this->event_list[i]->event, 
	                CL_PROFILING_COMMAND_QUEUED) - this->gpu_timer_start ),
            ulong(	getEventValue(this->event_list[i]->event, 
                	CL_PROFILING_COMMAND_SUBMIT) - this->gpu_timer_start ),
            ulong(	getEventValue(this->event_list[i]->event, 
	                CL_PROFILING_COMMAND_START) - this->gpu_timer_start ),
	    ulong(	getEventValue(this->event_list[i]->event, 
	                CL_PROFILING_COMMAND_END) - this->gpu_timer_start) );
*/
    }
    for(int i = 0; i < (int)this->user_event_list.size(); i++) {
        fprintf(fp, "%s;\t%s;\t%lu;\t%lu;\t%lu;\t%lu\n", 
            this->user_event_list[i]->type,
            this->user_event_list[i]->name, 
	    ulong(     getUserEventValue(this->user_event_list[i]->event, 
                CL_PROFILING_COMMAND_QUEUED) - this->cpu_timer_start ),
            ulong(	getUserEventValue(this->user_event_list[i]->event, 
                CL_PROFILING_COMMAND_SUBMIT) - this->cpu_timer_start ),
            ulong(	getUserEventValue(this->user_event_list[i]->event, 
                CL_PROFILING_COMMAND_START) - this->cpu_timer_start  ),
            ulong(	getUserEventValue(this->user_event_list[i]->event, 
                CL_PROFILING_COMMAND_END) - this->cpu_timer_start )
	);
    }
    //!Bound check
    if(event_list.size() > 0)
    {
    	long long start_t = getEventValue(this->event_list[0]->event, CL_PROFILING_COMMAND_QUEUED) - this->gpu_timer_start ;
    	long long end_t = getEventValue(this->event_list[event_list.size() - 1]->event,CL_PROFILING_COMMAND_END)	- this->gpu_timer_start;
		printf("Time first %llu \t last %llu \t Diff %f \n",start_t, end_t, float((end_t - start_t))/(1000.0f*1000.0f) );
    }
    else
    	printf("WARNING - No events Detected\n ");

    fclose(fp);

    delete filename;
    delete fullpath;
}
Esempio n. 2
0
/*
 *TODO:
 * if output is null or dummy, the use duration to wait
 */
void AudioThread::run()
{
    DPTR_D(AudioThread);
    //No decoder or output. No audio output is ok, just display picture
    if (!d.dec || !d.dec->isAvailable() || !d.outputSet)
        return;
    resetState();
    Q_ASSERT(d.clock != 0);
    AudioDecoder *dec = static_cast<AudioDecoder*>(d.dec);
    AudioOutput *ao = 0;
    // first() is not null even if list empty
    if (!d.outputSet->outputs().isEmpty())
        ao = static_cast<AudioOutput*>(d.outputSet->outputs().first()); //TODO: not here
    static const double max_len = 0.02; //TODO: how to choose?
    d.init();
    //TODO: bool need_sync in private class
    bool is_external_clock = d.clock->clockType() == AVClock::ExternalClock;
    Packet pkt;
    while (!d.stop) {
        processNextTask();
        //TODO: why put it at the end of loop then playNextFrame() not work?
        if (tryPause()) { //DO NOT continue, or playNextFrame() will fail
            if (d.stop)
                break; //the queue is empty and may block. should setBlocking(false) wake up cond empty?
        } else {
            if (isPaused())
                continue;
        }
        if (d.packets.isEmpty() && !d.stop) {
            d.stop = d.demux_end;
        }
        if (d.stop) {
            qDebug("audio thread stop before take packet");
            break;
        }
        if (!pkt.isValid()) {
            pkt = d.packets.take(); //wait to dequeue
        }
        if (!pkt.isValid()) {
            qDebug("Invalid packet! flush audio codec context!!!!!!!! audio queue size=%d", d.packets.size());
            dec->flush();
            continue;
        }
        bool skip_render = pkt.pts < d.render_pts0;
        // audio has no key frame, skip rendering equals to skip decoding
        if (skip_render) {
            d.clock->updateValue(pkt.pts);
            /*
             * audio may be too fast than video if skip without sleep
             * a frame is about 20ms. sleep time must be << frame time
             */
            qreal a_v = pkt.pts - d.clock->videoPts();

            //qDebug("skip audio decode at %f/%f v=%f a-v=%f", pkt.pts, d.render_pts0, d.clock->videoPts(), a_v);
            if (a_v > 0)
                msleep(qMin((ulong)300, ulong(a_v*1000.0)));
            else
                msleep(2);
            pkt = Packet(); //mark invalid to take next
            continue;
        }
        d.render_pts0 = 0;
        if (is_external_clock) {
            d.delay = pkt.pts - d.clock->value();
            /*
             *after seeking forward, a packet may be the old, v packet may be
             *the new packet, then the d.delay is very large, omit it.
             *TODO: 1. how to choose the value
             * 2. use last delay when seeking
            */
            if (qAbs(d.delay) < 2.718) {
                if (d.delay < -kSyncThreshold) { //Speed up. drop frame?
                    //continue;
                }
                while (d.delay > kSyncThreshold) { //Slow down
                    //d.delay_cond.wait(&d.mutex, d.delay*1000); //replay may fail. why?
                    //qDebug("~~~~~wating for %f msecs", d.delay*1000);
                    usleep(kSyncThreshold * 1000000UL);
                    if (d.stop)
                        d.delay = 0;
                    else
                        d.delay -= kSyncThreshold;
                }
                if (d.delay > 0)
                    usleep(d.delay * 1000000UL);
            } else { //when to drop off?
                if (d.delay > 0) {
                    msleep(64);
                } else {
                    //audio packet not cleaned up?
                    continue;
                }
            }
        } else {
            d.clock->updateValue(pkt.pts);
        }
        //DO NOT decode and convert if ao is not available or mute!
        bool has_ao = ao && ao->isAvailable();
        //if (!has_ao) {//do not decode?
        // TODO: move resampler to AudioFrame, like VideoFrame does
        if (has_ao && dec->resampler()) {
            if (dec->resampler()->speed() != ao->speed()
                    || dec->resampler()->outAudioFormat() != ao->audioFormat()) {
                //resample later to ensure thread safe. TODO: test
                if (d.resample) {
                    qDebug("decoder set speed: %.2f", ao->speed());
                    dec->resampler()->setOutAudioFormat(ao->audioFormat());
                    dec->resampler()->setSpeed(ao->speed());
                    dec->resampler()->prepare();
                    d.resample = false;
                } else {
                    d.resample = true;
                }
            }
        } else {
            if (dec->resampler() && dec->resampler()->speed() != d.clock->speed()) {
                if (d.resample) {
                    qDebug("decoder set speed: %.2f", d.clock->speed());
                    dec->resampler()->setSpeed(d.clock->speed());
                    dec->resampler()->prepare();
                    d.resample = false;
                } else {
                    d.resample = true;
                }
            }
        }
        if (d.stop) {
            qDebug("audio thread stop before decode()");
            break;
        }
        QMutexLocker locker(&d.mutex);
        Q_UNUSED(locker);
        if (!dec->decode(pkt.data)) {
            qWarning("Decode audio failed");
            qreal dt = pkt.pts - d.last_pts;
            if (dt > 0.618 || dt < 0) {
                dt = 0;
            }
            //qDebug("sleep %f", dt);
            //TODO: avoid acummulative error. External clock?
            msleep((unsigned long)(dt*1000.0));
            pkt = Packet();
            d.last_pts = d.clock->value(); //not pkt.pts! the delay is updated!
            continue;
        }
        QByteArray decoded(dec->data());
        int decodedSize = decoded.size();
        int decodedPos = 0;
        qreal delay =0;
        //AudioFormat.durationForBytes() calculates int type internally. not accurate
        AudioFormat &af = dec->resampler()->inAudioFormat();
        qreal byte_rate = af.bytesPerSecond();
        while (decodedSize > 0) {
            if (d.stop) {
                qDebug("audio thread stop after decode()");
                break;
            }
            int chunk = qMin(decodedSize, 1024*4);//int(max_len*byte_rate));
            //AudioFormat.bytesForDuration
            qreal chunk_delay = (qreal)chunk/(qreal)byte_rate;
            pkt.pts += chunk_delay;
            QByteArray decodedChunk(chunk, 0); //volume == 0 || mute
            if (has_ao) {
                //TODO: volume filter and other filters!!!
                if (!ao->isMute()) {
                    decodedChunk = QByteArray::fromRawData(decoded.constData() + decodedPos, chunk);
                    qreal vol = ao->volume();
                    if (vol != 1.0) {
                        int len = decodedChunk.size()/ao->audioFormat().bytesPerSample();
                        switch (ao->audioFormat().sampleFormat()) {
                        case AudioFormat::SampleFormat_Unsigned8:
                        case AudioFormat::SampleFormat_Unsigned8Planar: {
                            quint8 *data = (quint8*)decodedChunk.data(); //TODO: other format?
                            for (int i = 0; i < len; data[i++] *= vol) {}
                        }
                            break;
                        case AudioFormat::SampleFormat_Signed16:
                        case AudioFormat::SampleFormat_Signed16Planar: {
                            qint16 *data = (qint16*)decodedChunk.data(); //TODO: other format?
                            for (int i = 0; i < len; data[i++] *= vol) {}
                        }
                            break;
                        case AudioFormat::SampleFormat_Signed32:
                        case AudioFormat::SampleFormat_Signed32Planar: {
                            qint32 *data = (qint32*)decodedChunk.data(); //TODO: other format?
                            for (int i = 0; i < len; data[i++] *= vol) {}
                        }
                            break;
                        case AudioFormat::SampleFormat_Float:
                        case AudioFormat::SampleFormat_FloatPlanar: {
                            float *data = (float*)decodedChunk.data(); //TODO: other format?
                            for (int i = 0; i < len; data[i++] *= vol) {}
                        }
                            break;
                        case AudioFormat::SampleFormat_Double:
                        case AudioFormat::SampleFormat_DoublePlanar: {
                            double *data = (double*)decodedChunk.data(); //TODO: other format?
                            for (int i = 0; i < len; data[i++] *= vol) {}
                        }
                            break;
                        default:
                            break;
                        }
                    }
                }
                ao->waitForNextBuffer();
                ao->receiveData(decodedChunk, pkt.pts);
                d.clock->updateValue(ao->timestamp());
            } else {
                d.clock->updateDelay(delay += chunk_delay);

            /*
             * why need this even if we add delay? and usleep sounds weird
             * the advantage is if no audio device, the play speed is ok too
             * So is portaudio blocking the thread when playing?
             */
                static bool sWarn_no_ao = true; //FIXME: no warning when replay. warn only once
                if (sWarn_no_ao) {
                    qDebug("Audio output not available! msleep(%lu)", (unsigned long)((qreal)chunk/(qreal)byte_rate * 1000));
                    sWarn_no_ao = false;
                }
                //TODO: avoid acummulative error. External clock?
                msleep((unsigned long)(chunk_delay * 1000.0));
            }
            decodedPos += chunk;
            decodedSize -= chunk;
        }
        int undecoded = dec->undecodedSize();
        if (undecoded > 0) {
            pkt.data.remove(0, pkt.data.size() - undecoded);
        } else {
            pkt = Packet();
        }

        d.last_pts = d.clock->value(); //not pkt.pts! the delay is updated!
    }
    qDebug("Audio thread stops running...");
}
Esempio n. 3
0
void AbstractPort::updatePacketListInterleaved()
{
    int numStreams = 0;
    quint64 minGap = ULLONG_MAX;
    quint64 duration = quint64(1e9);
    QList<quint64> ibg1, ibg2;
    QList<quint64> nb1, nb2;
    QList<quint64> ipg1, ipg2;
    QList<quint64> np1, np2;
    QList<ulong> schedSec, schedNsec;
    QList<ulong> pktCount, burstCount;
    QList<ulong> burstSize;
    QList<bool> isVariable;
    QList<QByteArray> pktBuf;
    QList<ulong> pktLen;

    qDebug("In %s", __FUNCTION__);

    // First sort the streams by ordinalValue
    qSort(streamList_.begin(), streamList_.end(), StreamBase::StreamLessThan);

    clearPacketList();

    for (int i = 0; i < streamList_.size(); i++)
    {
        if (!streamList_[i]->isEnabled())
            continue;

        double numBursts = 0;
        double numPackets = 0;

        quint64 _burstSize = 0;
        double ibg = 0;
        quint64 _ibg1 = 0, _ibg2 = 0;
        quint64 _nb1 = 0, _nb2 = 0;
        double ipg = 0;
        quint64 _ipg1 = 0, _ipg2 = 0;
        quint64 _np1 = 0, _np2 = 0;

        switch (streamList_[i]->sendUnit())
        {
        case OstProto::StreamControl::e_su_bursts:
            numBursts = streamList_[i]->burstRate();
            if (streamList_[i]->burstRate() > 0)
            {
                ibg = 1e9/double(streamList_[i]->burstRate());
                _ibg1 = quint64(ceil(ibg));
                _ibg2 = quint64(floor(ibg));
                _nb1 = quint64((ibg - double(_ibg2)) * double(numBursts));
                _nb2 = quint64(numBursts) - _nb1;
                _burstSize = streamList_[i]->burstSize();
            }
            break;
        case OstProto::StreamControl::e_su_packets:
            numPackets = streamList_[i]->packetRate();
            if (streamList_[i]->packetRate() > 0)
            {
                ipg = 1e9/double(streamList_[i]->packetRate());
                _ipg1 = llrint(ceil(ipg));
                _ipg2 = quint64(floor(ipg));
                _np1 = quint64((ipg - double(_ipg2)) * double(numPackets));
                _np2 = quint64(numPackets) - _np1;
                _burstSize = 1;
            }
            break;
        default:
            qWarning("Unhandled stream control unit %d",
                streamList_[i]->sendUnit());
            continue;
        }
        qDebug("numBursts = %g, numPackets = %g\n", numBursts, numPackets);

        qDebug("ibg  = %g", ibg);
        qDebug("ibg1 = %" PRIu64, _ibg1);
        qDebug("nb1  = %" PRIu64, _nb1);
        qDebug("ibg2 = %" PRIu64, _ibg2);
        qDebug("nb2  = %" PRIu64 "\n", _nb2);

        qDebug("ipg  = %g", ipg);
        qDebug("ipg1 = %" PRIu64, _ipg1);
        qDebug("np1  = %" PRIu64, _np1);
        qDebug("ipg2 = %" PRIu64, _ipg2);
        qDebug("np2  = %" PRIu64 "\n", _np2);


        if (_ibg2 && (_ibg2 < minGap))
            minGap = _ibg2;

        if (_ibg1 && (_ibg1 > duration))
            duration = _ibg1;

        ibg1.append(_ibg1);
        ibg2.append(_ibg2);

        nb1.append(_nb1);
        nb2.append(_nb1);

        burstSize.append(_burstSize);

        if (_ipg2 && (_ipg2 < minGap))
            minGap = _ipg2;

        if (_np1)
        {
            if (_ipg1 && (_ipg1 > duration))
                duration = _ipg1;
        }
        else
        {
            if (_ipg2 && (_ipg2 > duration))
                duration = _ipg2;
        }

        ipg1.append(_ipg1);
        ipg2.append(_ipg2);

        np1.append(_np1);
        np2.append(_np1);

        schedSec.append(0);
        schedNsec.append(0);

        pktCount.append(0);
        burstCount.append(0);

        if (streamList_[i]->isFrameVariable())
        {
            isVariable.append(true);
            pktBuf.append(QByteArray());
            pktLen.append(0);
        }
        else
        {
            isVariable.append(false);
            pktBuf.append(QByteArray());
            pktBuf.last().resize(kMaxPktSize);
            pktLen.append(streamList_[i]->frameValue(
                    (uchar*)pktBuf.last().data(), pktBuf.last().size(), 0));
        }

        numStreams++;
    } // for i

    qDebug("minGap   = %" PRIu64, minGap);
    qDebug("duration = %" PRIu64, duration);

    uchar* buf;
    int len;
    quint64 durSec = duration/ulong(1e9);
    quint64 durNsec = duration % ulong(1e9);
    quint64 sec = 0; 
    quint64 nsec = 0;
    quint64 lastPktTxSec = 0;
    quint64 lastPktTxNsec = 0;
    do
    {
        for (int i = 0; i < numStreams; i++)
        {
            // If a packet is not scheduled yet, look at the next stream
            if ((schedSec.at(i) > sec) || (schedNsec.at(i) > nsec))
                continue;

            for (uint j = 0; j < burstSize[i]; j++)
            {
                if (isVariable.at(i))
                {
                    buf = pktBuf_;
                    len = streamList_[i]->frameValue(pktBuf_, sizeof(pktBuf_), 
                            pktCount[i]);
                }
                else
                {
                    buf = (uchar*) pktBuf.at(i).data();
                    len = pktLen.at(i);
                }

                if (len <= 0)
                    continue;

                qDebug("q(%d) sec = %" PRIu64 " nsec = %" PRIu64, i, sec, nsec);
                appendToPacketList(sec, nsec, buf, len); 
                lastPktTxSec = sec;
                lastPktTxNsec = nsec;

                pktCount[i]++;
                schedNsec[i] += (pktCount.at(i) < np1.at(i)) ? 
                    ipg1.at(i) : ipg2.at(i);
                while (schedNsec.at(i) >= 1e9)
                {
                    schedSec[i]++;
                    schedNsec[i] -= long(1e9);
                }
            }

            burstCount[i]++;
            schedNsec[i] += (burstCount.at(i) < nb1.at(i)) ? 
                    ibg1.at(i) : ibg2.at(i);
            while (schedNsec.at(i) >= 1e9)
            {
                schedSec[i]++;
                schedNsec[i] -= long(1e9);
            }
        } 

        nsec += minGap;
        while (nsec >= 1e9)
        {
            sec++;
            nsec -= long(1e9);
        }
    } while ((sec < durSec) || (nsec < durNsec));

    qint64 delaySec = durSec - lastPktTxSec;
    qint64 delayNsec = durNsec - lastPktTxNsec;
    while (delayNsec < 0)
    {
        delayNsec += long(1e9);
        delaySec--;
    }
    qDebug("loop Delay = %" PRId64 "/%" PRId64, delaySec, delayNsec);
    setPacketListLoopMode(true, delaySec, delayNsec); 
    isSendQueueDirty_ = false;
}
Esempio n. 4
0
			{
				/**
				* Don't trigger callback (default).
				*/
				DONT_ASK_PROFILE,
				/**
				* Trigger callback.
				*/
				ASK_PROFILE
			};

			enum
			{
				CLK_NTSC_DOT   = Core::CLK_NTSC,
				CLK_NTSC_DIV   = Core::CLK_NTSC_DIV,
				CLK_NTSC_VSYNC = Core::PPU_RP2C02_HVSYNC * ulong(Core::CLK_NTSC_DIV),
				CLK_PAL_DOT    = Core::CLK_PAL,
				CLK_PAL_DIV    = Core::CLK_PAL_DIV,
				CLK_PAL_VSYNC  = Core::PPU_RP2C07_HVSYNC * ulong(Core::CLK_PAL_DIV)
			};

			/**
			* Soft-patching context object.
			*
			* Used as input parameter to some of the image loading methods.
			*/
			struct Patch
			{
				/**
				* Input stream containing the patch in UPS or IPS format.
				*/
Esempio n. 5
0
/*
 * ELF64 binaries.
 */
static int
elf64dotout(int fd, Fhdr *fp, ExecHdr *hp)
{
	E64hdr *ep;
	P64hdr *ph;
	ushort (*swab)(ushort);
	ulong (*swal)(ulong);
	uvlong (*swav)(uvlong);
	int i, it, id, is, phsz;
	uvlong uvl;

	ep = &hp->e;
	if(ep->ident[DATA] == ELFDATA2LSB) {
		swab = leswab;
		swal = leswal;
		swav = leswav;
	} else if(ep->ident[DATA] == ELFDATA2MSB) {
		swab = beswab;
		swal = beswal;
		swav = beswav;
	} else {
		werrstr("bad ELF64 encoding - not big or little endian");
		return 0;
	}

	ep->type = swab(ep->type);
	ep->machine = swab(ep->machine);
	ep->version = swal(ep->version);
	if(ep->type != EXEC || ep->version != CURRENT)
		return 0;
	ep->elfentry = swav(ep->elfentry);
	ep->phoff = swav(ep->phoff);
	ep->shoff = swav(ep->shoff);
	ep->flags = swal(ep->flags);
	ep->ehsize = swab(ep->ehsize);
	ep->phentsize = swab(ep->phentsize);
	ep->phnum = swab(ep->phnum);
	ep->shentsize = swab(ep->shentsize);
	ep->shnum = swab(ep->shnum);
	ep->shstrndx = swab(ep->shstrndx);

	fp->magic = ELF_MAG;
	fp->hdrsz = (ep->ehsize+ep->phnum*ep->phentsize+16)&~15;
	switch(ep->machine) {
	default:
		return 0;
	case AMD64:
		mach = &mamd64;
		fp->type = FAMD64;
		fp->name = "amd64 ELF64 executable";
		break;
	case POWER64:
		mach = &mpower64;
		fp->type = FPOWER64;
		fp->name = "power64 ELF64 executable";
		break;
	}

	if(ep->phentsize != sizeof(P64hdr)) {
		werrstr("bad ELF64 header size");
		return 0;
	}
	phsz = sizeof(P64hdr)*ep->phnum;
	ph = malloc(phsz);
	if(!ph)
		return 0;
	seek(fd, ep->phoff, 0);
	if(read(fd, ph, phsz) < 0) {
		free(ph);
		return 0;
	}
	for(i = 0; i < ep->phnum; i++) {
		ph[i].type = swal(ph[i].type);
		ph[i].flags = swal(ph[i].flags);
		ph[i].offset = swav(ph[i].offset);
		ph[i].vaddr = swav(ph[i].vaddr);
		ph[i].paddr = swav(ph[i].paddr);
		ph[i].filesz = swav(ph[i].filesz);
		ph[i].memsz = swav(ph[i].memsz);
		ph[i].align = swav(ph[i].align);
	}

	/* find text, data and symbols and install them */
	it = id = is = -1;
	for(i = 0; i < ep->phnum; i++) {
		if(ph[i].type == LOAD
		&& (ph[i].flags & (R|X)) == (R|X) && it == -1)
			it = i;
		else if(ph[i].type == LOAD
		&& (ph[i].flags & (R|W)) == (R|W) && id == -1)
			id = i;
		else if(ph[i].type == NOPTYPE && is == -1)
			is = i;
	}
	if(it == -1 || id == -1) {
		werrstr("No ELF64 TEXT or DATA sections");
		free(ph);
		return 0;
	}

	settext(fp, ep->elfentry, ph[it].vaddr, ph[it].memsz, ph[it].offset);
	/* 8c: out of fixed registers */
	uvl = ph[id].memsz - ph[id].filesz;
	setdata(fp, ph[id].vaddr, ph[id].filesz, ph[id].offset, uvl);
	if(is != -1)
		setsym(fp, ph[is].filesz, 0, ph[is].memsz, ph[is].offset);
	free(ph);
	return 1;
}
Esempio n. 6
0
bool CGoods::Serialize(vector<uchar>* pStream, bool b)
{
	CShape::AddToByteArray( pStream, b==false?false:true );

	_AddToByteArray( pStream, m_dwBasePropertiesIndex );
	_AddToByteArray( pStream, m_dwAmount );
	_AddToByteArray( pStream, const_cast<char*>( m_strMakerName.c_str() ) );		

	CGoodsBaseProperties* pBaseProperty=GoodsSetup::QueryGoodsBaseProperties(m_dwBasePropertiesIndex);
	if(!pBaseProperty)
		return false;
	ulong dwAddonNum=0;
	ulong dwPropertyId=0;
	vector<uchar> vecAddonData;
	for( size_t i = 0; i < m_vAddonProperties.size(); i ++ )
	{		
		if(pBaseProperty->IsHasAddonPropertie(m_vAddonProperties[i].gapType))	
		{			
			dwPropertyId=m_vAddonProperties[i].gapType;
			if(GoodsSetup::s_GoodsAttrDBSetup[dwPropertyId][0]==1)
			{
				dwAddonNum++;
				m_vAddonProperties[i].Serialize(&vecAddonData);
			}
		}
	}
	_AddToByteArray( pStream,dwAddonNum);
	if(dwAddonNum>0)
	{
		_AddToByteArray(pStream,&vecAddonData[0],(long)vecAddonData.size());
	}
	

	EnchaseArrange();
	//enchase data	
	
	_AddToByteArray(pStream,m_dwMaxHoleNum);
	//激活孔数量
	_AddToByteArray( pStream, GetActivedHoleNum());
	_AddToByteArray( pStream, m_dwActivedKitCardId);
	for(int i=0;i<(int)m_dwMaxHoleNum;i++)
	{
		//状态
		//王晓轩:所有镶嵌孔设置为开启
		_AddToByteArray(pStream,uchar(1));
		//if(m_pEnchaseHoleArray[i]->GetState())
		//{
		//	_AddToByteArray(pStream,uchar(1));
		//}
		//else
		//{
		//	_AddToByteArray(pStream,uchar(0));
		//}
		//CARD ID
		CGoods* pCard=m_pEnchaseHoleArray[i]->GetCard();
		if(pCard)
		{
			_AddToByteArray(pStream,pCard->GetBasePropertiesIndex());
			pCard->Serialize(pStream);
		}
		else
		{
			_AddToByteArray(pStream,ulong(0));
		}
	}
	return true;
}
Esempio n. 7
0
void AudioFileWriter::run() {
	QFile file(outFileName);
	bool waveMode = false;
	if (outFileName.endsWith(".wav")) waveMode = true;
	if (!file.open(QIODevice::WriteOnly)) {
		qDebug() << "AudioFileWriter: Can't open file for writing:" << outFileName;
		synth->close();
		if (!realtimeMode) {
			Master::getInstance()->setAudioFileWriterSynth(NULL);
		}
		return;
	}
	if (waveMode) file.seek(44);
	MasterClockNanos startNanos = MasterClock::getClockNanos();
	MasterClockNanos firstSampleNanos = 0;
	MasterClockNanos midiTick = 0;
	MasterClockNanos midiNanos = 0;
	QMidiEventList midiEvents;
	int midiEventIx = 0;
	uint parserIx = 0;
	bool skipSilence = false;
	if (realtimeMode) {
		firstSampleNanos = startNanos;
	} else {
		midiEvents = parsers[parserIx].getMIDIEvents();
		midiTick = parsers[parserIx].getMidiTick();
		skipSilence = true;
	}
	qDebug() << "AudioFileWriter: Rendering started";
	while (!stopProcessing) {
		uint frameCount = 0;
		if (realtimeMode) {
			frameCount = uint((sampleRate * (MasterClock::getClockNanos() - firstSampleNanos)) / MasterClock::NANOS_PER_SECOND);
			if (frameCount < bufferSize) {
				usleep(ulong((MasterClock::MICROS_PER_SECOND * (bufferSize - frameCount)) / sampleRate));
				continue;
			} else {
				frameCount = bufferSize;
			}
		} else {
			while (midiEventIx < midiEvents.count()) {
				const QMidiEvent &e = midiEvents.at(midiEventIx);
				bool eventPushed = true;
				MasterClockNanos nextEventNanos = midiNanos + e.getTimestamp() * midiTick;
				quint32 nextEventFrames = quint32(((double)sampleRate * nextEventNanos) / MasterClock::NANOS_PER_SECOND);
				frameCount = uint((sampleRate * (nextEventNanos - firstSampleNanos)) / MasterClock::NANOS_PER_SECOND);
				if (bufferSize < frameCount) {
					frameCount = bufferSize;
					break;
				}
				switch (e.getType()) {
					case SHORT_MESSAGE:
						eventPushed = synth->playMIDIShortMessage(e.getShortMessage(), nextEventFrames);
						break;
					case SYSEX:
						eventPushed = synth->playMIDISysex(e.getSysexData(), e.getSysexLen(), nextEventFrames);
						break;
					case SET_TEMPO:
						midiTick = parsers[parserIx].getMidiTick(e.getShortMessage());
						break;
					default:
						break;
				}
				if (!eventPushed) {
					qDebug() << "AudioFileWriter: MIDI buffer overflow, midiNanos:" << midiNanos;
					break;
				}
				midiNanos = nextEventNanos;
				midiEventIx++;
				emit midiEventProcessed(midiEventIx, midiEvents.count());
			}
			if (midiEvents.count() <= midiEventIx) {
				if (parserIx < parsersCount - 1) {
					++parserIx;
					midiEventIx = 0;
					midiEvents = parsers[parserIx].getMIDIEvents();
					midiTick = parsers[parserIx].getMidiTick();
					continue;
				}
				if (!synth->isActive() && frameCount == 0) break;
				frameCount += bufferSize;
				qDebug() << "AudioFileWriter: Rendering after the end of MIDI file, time:" << (double)midiNanos / MasterClock::NANOS_PER_SECOND;
			}
		}
		while (frameCount > 0) {
			uint framesToRender = qMin(bufferSize, frameCount);
			synth->render(buffer, framesToRender);
			// libmt32emu produces samples in native byte order
			QSynth::convertSamplesFromNativeEndian(buffer, framesToRender << 1, waveMode ? QSysInfo::LittleEndian : QSysInfo::BigEndian);
			qint64 bytesToWrite = framesToRender * FRAME_SIZE;
			char *bufferPos = (char *)buffer;
			if (skipSilence) {
				qint32 *startPos = (qint32 *)buffer;
				qint32 *endPos = startPos + framesToRender;
				bytesToWrite = 0;
				for (qint32 *p = startPos; p < endPos; p++) {
					if (*p != 0) {
						skipSilence = false;
						bufferPos = (char *)p;
						bytesToWrite = (char *)endPos - bufferPos;
						break;
					}
				}
			}
			while (bytesToWrite > 0) {
				qint64 bytesWritten = file.write(bufferPos, bytesToWrite);
				if (bytesWritten == -1) {
					qDebug() << "AudioFileWriter: error writing into the audio file:" << file.errorString();
					file.close();
					return;
				}
				bytesToWrite -= bytesWritten;
				bufferPos += bytesWritten;
			}
			firstSampleNanos += MasterClock::NANOS_PER_SECOND * framesToRender / sampleRate;
			frameCount -= framesToRender;
			if (!realtimeMode) qDebug() << "AudioFileWriter: Rendering time:" << (double)firstSampleNanos / MasterClock::NANOS_PER_SECOND;
		}
	}
	qDebug() << "AudioFileWriter: Rendering finished";
	if (!realtimeMode) qDebug() << "AudioFileWriter: Elapsed seconds: " << 1e-9 * (MasterClock::getClockNanos() - startNanos);
	if (waveMode) {
		unsigned char *charBuffer = (unsigned char *)buffer;
		memcpy(charBuffer, WAVE_HEADER, 44);
		quint32 fileSize = (quint32)file.size();
		qToLittleEndian(fileSize - 8, charBuffer + 4);
		qToLittleEndian(fileSize - 44, charBuffer + 40);
		qToLittleEndian(sampleRate, charBuffer + 24);
		qToLittleEndian(sampleRate * FRAME_SIZE, charBuffer + 28);
		file.seek(0);
		file.write((char *)charBuffer, 44);
	}
	file.close();
	synth->close();
	if (!realtimeMode) {
		Master::getInstance()->setAudioFileWriterSynth(NULL);
	}
	if (!stopProcessing) emit conversionFinished();
}
Esempio n. 8
0
int main(int argc, char* argv[])
{
    // Parse command-line arguments
    Parameters parameters;
    bool bParsed = parseCommandLine(argc, argv, parameters);

    if(!bParsed || parameters.bShowHelp || argc == 1)
    {
        help();
        return 0;
    }
    else if(parameters.bShowVersion)
    {
        std::cout << "Naive Bayes Classify v1.0.5 by Donovan Parks, Norm MacDonald, and Rob Beiko." << std::endl;
        return 0;
    }
    else if(parameters.bShowContactInfo)
    {
        std::cout << "Comments, suggestions, and bug reports can be sent to Donovan Parks ([email protected])." << std::endl;
        return 0;
    }
    else if(parameters.queryFile.empty() || parameters.modelFile.empty() || parameters.resultsFile.empty())
    {
        std::cout << "Must specify query (-q), model (-m), and result (-r) file." << std::endl << std::endl;
        help();
        return 0;
    }

    bool bRecordAllModels = false;
    if(parameters.topModels <= 0)
    {
        bRecordAllModels = true;
        parameters.topModels = 0;
    }

    // Get model k-mer length
    if(parameters.verbose >= 1)
        std::cout << "Determining n-mer length..." << std::endl;

    std::ifstream tempStream(parameters.modelFile.c_str(), std::ios::in);
    if(tempStream.fail())
    {
        std::cout << "Failed to open model file: " << parameters.modelFile << std::endl << std::endl;
        return -1;
    }
    std::string line;
    std::getline(tempStream, line);
    KmerModel tempModel(line);
    uint kmerLength = tempModel.kmerLength();
    if(parameters.verbose >= 1)
        std::cout << "  n-mer length: " << kmerLength << std::endl << std::endl;

    // Read query fragments

    if(parameters.verbose >= 1)
        std::cout << "Reading query fragments..." << std::endl;

    char* buffer = NULL;
    std::vector<SeqInfo> querySeqs;
    FastaIO fastaIO;
    bool bSuccess = fastaIO.readSeqs(parameters.queryFile, querySeqs, buffer, parameters.verbose);
    if(!bSuccess)
    {
        std::cout << "Failed to open query fragment file: " << parameters.queryFile << std::endl;
        return -1;
    }
    if(parameters.verbose >= 1)
        std::cout << "  Number of query fragments: " << querySeqs.size() << std::endl << std::endl;

    // Classify query fragments in batches in order to keep memory requirements within reason (~ 1GB)
    if(parameters.verbose >= 1)
        std::cout << "Processing query fragments in batches of " << parameters.batchSize << "." << std::endl << std::endl;

    KmerCalculator kmerCalculator(kmerLength);
    for(uint batchNum = 0; batchNum < ceil(double(querySeqs.size()) / parameters.batchSize); ++batchNum)
    {
        if(parameters.verbose >= 1)
            std::cout << "Batch #" << (batchNum+1) << std::endl;

        // get k-mers for each query fragment
        if(parameters.verbose >= 1)
            std::cout << "  Calculating n-mers in query fragment: " << std::endl;

        std::vector< std::vector<uint> > queryKmerProfiles;
        queryKmerProfiles.reserve(parameters.batchSize);
        for(uint seqIndex = batchNum*parameters.batchSize;
                seqIndex < std::min(ulong(querySeqs.size()), ulong(batchNum+1)*parameters.batchSize);
                ++seqIndex)
        {
            if(parameters.verbose >= 3)
                std::cout << querySeqs.at(seqIndex).seqId << std::endl;
            else if (seqIndex % 5000 == 0 && parameters.verbose >= 1)
                std::cout << "." << std::flush;

            std::vector<uint> profile;
            kmerCalculator.extractForwardKmers(querySeqs.at(seqIndex), profile);
            queryKmerProfiles.push_back(profile);
        }
        if(parameters.verbose >= 1)
            std::cout << std::endl;

        // apply each model to each query sequence
        if(parameters.verbose >= 1)
            std::cout << "  Applying models to query sequences: " << std::endl;

        std::ifstream modelStream(parameters.modelFile.c_str(), std::ios::in);

        uint modelNum = 0;

        std::vector<std::string> modelNames;
        std::vector< std::list<TopModel> > topModelsPerFragment(queryKmerProfiles.size());
        std::vector< std::vector<float> > modelLogLikelihoods;
        while(!modelStream.eof())
        {
            std::string line;
            std::getline(modelStream, line);

            if(line.empty())
                break;

            if(modelNum % 200 == 0 && parameters.verbose >= 1)
                std::cout << " " << modelNum << std::flush;

            KmerModel kmerModel(line);
            modelNames.push_back(kmerModel.name());
            if(parameters.verbose >= 2)
            {
                kmerModel.printModelInfo(std::cout);
                std::cout << std::endl;
            }

            ulong size = 0;
            if(bRecordAllModels)
                size = queryKmerProfiles.size();
            std::vector<float> logLikelihoods(size);
            for(uint seqIndex = 0; seqIndex < queryKmerProfiles.size(); ++seqIndex)
            {
                SeqInfo querySeqInfo = querySeqs[seqIndex + batchNum*parameters.batchSize];
                float logLikelihood = kmerModel.classify(querySeqInfo, queryKmerProfiles[seqIndex]);

                // record models with highest log likelihood
                if(bRecordAllModels)
                {
                    logLikelihoods[seqIndex] = logLikelihood;
                }
                else
                {
                    std::list<TopModel> topModels = topModelsPerFragment.at(seqIndex);

                    if(topModels.size() == 0)
                        topModels.push_front(TopModel(modelNum, logLikelihood));

                    std::list<TopModel>::iterator it;
                    bool bInserted = false;
                    for(it = topModels.begin(); it != topModels.end(); it++)
                    {
                        if(logLikelihood > it->logLikelihood)
                        {
                            topModels.insert(it, TopModel(modelNum, logLikelihood));
                            bInserted = true;
                            break;
                        }
                    }

                    if((int)topModels.size() < parameters.topModels && !bInserted)
                        topModels.push_back(TopModel(modelNum, logLikelihood));
                    else if((int)topModels.size() > parameters.topModels)
                        topModels.pop_back();

                    topModelsPerFragment.at(seqIndex) = topModels;
                }
            }

            if(bRecordAllModels)
                modelLogLikelihoods.push_back(logLikelihoods);

            modelNum++;
        }
        if(parameters.verbose >= 1)
            std::cout << std::endl;

        // write out classification
        if(parameters.verbose >= 1)
            std::cout << "  Writing out classification results." << std::endl << std::endl;

        std::stringstream outputTempResults;
        outputTempResults << "./batch_" << batchNum << "." << parameters.tempExtension;
        std::ofstream fout(outputTempResults.str().c_str(), std::ios::out);
        if(fout.fail())
        {
            std::cout << "Failed to write temporary results file: " << outputTempResults.str() << std::endl;
            return -1;
        }

        // check if all model results are to be written out
        if(bRecordAllModels)
        {
            if(batchNum == 0)
            {
                fout << "Fragment Id" << "\t" << "Length" << "\t" << "Valid n-mers";
                for(uint modelIndex = 0; modelIndex < modelNames.size(); ++modelIndex)
                    fout << "\t" << modelNames[modelIndex];
                fout << std::endl;
            }

            for(uint seqIndex = 0; seqIndex < queryKmerProfiles.size(); ++seqIndex)
            {
                SeqInfo querySeqInfo = querySeqs.at(seqIndex + batchNum*parameters.batchSize);

                fout << querySeqInfo.seqId << "\t" << querySeqInfo.length << "\t" << querySeqInfo.validKmers;

                for(uint modelIndex = 0; modelIndex < modelNames.size(); ++modelIndex)
                    fout << "\t" << modelLogLikelihoods[modelIndex][seqIndex];
                fout << std::endl;
            }
        }
        else
        {
            for(uint seqIndex = 0; seqIndex < queryKmerProfiles.size(); ++seqIndex)
            {
                SeqInfo querySeqInfo = querySeqs.at(seqIndex + batchNum*parameters.batchSize);

                fout << querySeqInfo.seqId << "\t" << querySeqInfo.length << "\t" << querySeqInfo.validKmers;

                std::list<TopModel>::iterator it;
                for(it = topModelsPerFragment.at(seqIndex).begin(); it != topModelsPerFragment.at(seqIndex).end(); it++)
                    fout << "\t" << modelNames[it->modelNum] << "\t" << it->logLikelihood;

                fout << std::endl;
            }
        }

        fout.close();
    }

    // free memory allocated to hold query fragment data
    delete[] buffer;

    // Concatenate result files
    if(parameters.verbose >= 1)
        std::cout << "Building results file: ";

    std::ofstream resultsStream(parameters.resultsFile.c_str(), std::ios::out | std::ios::binary);
    for(uint batchNum = 0; batchNum < ceil(double(querySeqs.size()) / parameters.batchSize); ++batchNum)
    {
        if(parameters.verbose >= 1)
            std::cout << "." << std::flush;

        std::stringstream tempResultFile;
        tempResultFile << "./batch_" << batchNum  << "." << parameters.tempExtension;
        std::ifstream tempStream(tempResultFile.str().c_str(), std::ios::binary);
        if(tempStream.fail() || tempStream.bad())
        {
            std::cout << "Failed to open file: " << tempResultFile.str() << std::endl;
            return -1;
        }

        // calculate size of file
        tempStream.seekg(0, std::ios::end);
        ulong fileSize = tempStream.tellg();
        tempStream.seekg(0, std::ios::beg);

        // write out data in reasonable sized chunks
        ulong chunkSize = 64*1024*1024;

        // allocate memory for reading file
        char* tempBuffer = new char[chunkSize];
        if(tempBuffer == NULL)
        {
            std::cout << std::endl << "Failed to allocate memory required by file: " << tempResultFile.str() << std::endl;
            return -1;
        }

        for(uint chunk = 0; chunk < ceil(float(fileSize) / chunkSize); ++chunk)
        {
            ulong currentChunkSize = std::min(chunkSize, fileSize - chunk*chunkSize);

            // read file into buffer
            tempStream.read(tempBuffer, currentChunkSize);
            if(tempStream.fail() || tempStream.bad())
            {
                std::cout << std::endl << "Failed to read data from " << tempResultFile.str() << std::endl;
                return -1;
            }

            resultsStream.write(tempBuffer, currentChunkSize);
            resultsStream.flush();
        }

        tempStream.close();
        delete[] tempBuffer;
    }
    resultsStream.close();

    if(parameters.verbose >= 1)
    {
        std::cout << std::endl;
        std::cout << "Done." << std::endl;
    }

    for(uint batchNum = 0; batchNum < ceil(double(querySeqs.size()) / parameters.batchSize); ++batchNum)
    {
        std::stringstream filename;
        filename << "./batch_" << batchNum  << "." << parameters.tempExtension;
        std::remove(filename.str().c_str());
    }

    return 0;
}
Esempio n. 9
0
void AudioFileRenderer::run() {
	AudioFileWriter writer(sampleRate, outFileName);
	if (!writer.open(!realtimeMode)) {
		synth->close();
		if (!realtimeMode) Master::getInstance()->setAudioFileWriterSynth(NULL);
		emit conversionFinished();
		return;
	}
	MasterClockNanos startNanos = MasterClock::getClockNanos();
	MasterClockNanos firstSampleNanos = 0;
	MasterClockNanos midiTick = 0;
	MasterClockNanos midiNanos = 0;
	QMidiEventList midiEvents;
	int midiEventIx = 0;
	uint parserIx = 0;
	if (realtimeMode) {
		firstSampleNanos = startNanos;
	} else {
		midiEvents = parsers[parserIx].getMIDIEvents();
		midiTick = parsers[parserIx].getMidiTick();
	}
	qDebug() << "AudioFileRenderer: Rendering started";
	while (!stopProcessing) {
		uint frameCount = 0;
		if (realtimeMode) {
			frameCount = uint((sampleRate * (MasterClock::getClockNanos() - firstSampleNanos)) / MasterClock::NANOS_PER_SECOND);
			if (frameCount < bufferSize) {
				usleep(ulong((MasterClock::MICROS_PER_SECOND * (bufferSize - frameCount)) / sampleRate));
				continue;
			} else {
				frameCount = bufferSize;
			}
		} else {
			while (midiEventIx < midiEvents.count()) {
				const QMidiEvent &e = midiEvents.at(midiEventIx);
				bool eventPushed = true;
				MasterClockNanos nextEventNanos = midiNanos + e.getTimestamp() * midiTick;
				quint32 nextEventFrames = quint32(((double)sampleRate * nextEventNanos) / MasterClock::NANOS_PER_SECOND);
				frameCount = uint((sampleRate * (nextEventNanos - firstSampleNanos)) / MasterClock::NANOS_PER_SECOND);
				if (bufferSize < frameCount) {
					frameCount = bufferSize;
					break;
				}
				switch (e.getType()) {
					case SHORT_MESSAGE:
						eventPushed = synth->playMIDIShortMessage(e.getShortMessage(), nextEventFrames);
						break;
					case SYSEX:
						eventPushed = synth->playMIDISysex(e.getSysexData(), e.getSysexLen(), nextEventFrames);
						break;
					case SET_TEMPO:
						midiTick = parsers[parserIx].getMidiTick(e.getShortMessage());
						break;
					default:
						break;
				}
				if (!eventPushed) {
					qDebug() << "AudioFileRenderer: MIDI buffer overflow, midiNanos:" << midiNanos;
					break;
				}
				midiNanos = nextEventNanos;
				midiEventIx++;
				emit midiEventProcessed(midiEventIx, midiEvents.count());
			}
			if (midiEvents.count() <= midiEventIx) {
				if (parserIx < parsersCount - 1) {
					++parserIx;
					midiEventIx = 0;
					midiEvents = parsers[parserIx].getMIDIEvents();
					midiTick = parsers[parserIx].getMidiTick();
					continue;
				}
				if (!synth->isActive() && frameCount == 0) break;
				frameCount += bufferSize;
				qDebug() << "AudioFileRenderer: Rendering after the end of MIDI file, time:" << (double)midiNanos / MasterClock::NANOS_PER_SECOND;
			}
		}
		while (frameCount > 0) {
			uint framesToRender = qMin(bufferSize, frameCount);
			synth->render(buffer, framesToRender);
			if (!writer.write(buffer, framesToRender)) {
				synth->close();
				if (!realtimeMode) Master::getInstance()->setAudioFileWriterSynth(NULL);
				emit conversionFinished();
				return;
			}
			firstSampleNanos += MasterClock::NANOS_PER_SECOND * framesToRender / sampleRate;
			frameCount -= framesToRender;
			if (!realtimeMode) qDebug() << "AudioFileWriter: Rendering time:" << (double)firstSampleNanos / MasterClock::NANOS_PER_SECOND;
		}
	}
	qDebug() << "AudioFileRenderer: Rendering finished";
	if (!realtimeMode) qDebug() << "AudioFileRenderer: Elapsed seconds: " << 1e-9 * (MasterClock::getClockNanos() - startNanos);
	writer.close();
	synth->close();
	if (!realtimeMode) Master::getInstance()->setAudioFileWriterSynth(NULL);
	if (!stopProcessing) emit conversionFinished();
}
Esempio n. 10
0
ulong ext2::FindAddressByBlockNumber(ulong blockNumber, ulong blockPointers[])
{
	ulong	addr = 0;
	ulong	*addrs = NULL;
	
	// make sure the request isn't larger then the largest block number
	if(blockNumber >= ulong(DIRECT_BLOCK_PTRS) + (addrPerBlock * addrPerBlock * addrPerBlock))
		return(0);
	
	// direct data block
	if(blockNumber <= ulong(DIRECT_BLOCK_PTRS))
		addr = blockPointers[blockNumber];
	
	// single indirection
	else if(blockNumber < ulong(INDIRECT_BLOCK_PTR + addrPerBlock))
	{
// 		printf("\nSINGLE INDIRECT\n");
// 		printf("BLOCK NUM: %d\n", blockNumber);
		
		// make space for our inodes
		addrs = new ulong[blockSize/sizeof(ulong)];
		
		// read in the indirect blocks
		ReadBlocks(blockPointers[INDIRECT_BLOCK_PTR], 1, reinterpret_cast<uchar*>(addrs));
		
		// update the block number
		blockNumber -= INDIRECT_BLOCK_PTR;
		
// 		printf("ASKING FOR: %d\n", addrs[blockNumber % addrPerBlock]);
		
		addr = addrs[blockNumber % addrPerBlock];
	}
	
	// double indirection
	else if(blockNumber < ulong(INDIRECT_BLOCK_PTR + (addrPerBlock * addrPerBlock)))
	{
// 		printf("\nDOUBLE INDIRECT\n");
// 		printf("BLOCK NUM: %d\n", blockNumber);
		
		// make space for our inodes
		addrs = new ulong[blockSize/sizeof(ulong)];
		
		// read in the indirect blocks
		ReadBlocks(blockPointers[DOUBLE_INDIRECT_BLOCK_PTR], 1, reinterpret_cast<uchar*>(addrs));
		
		// update the block number
		blockNumber = blockNumber - INDIRECT_BLOCK_PTR - addrPerBlock;
		 
		// read in the double indirect blocks
		ReadBlocks(addrs[blockNumber / addrPerBlock], 1, reinterpret_cast<uchar*>(addrs));
		
// 		printf("ASKING FOR: %d\n", addrs[blockNumber % addrPerBlock]);
		
		addr = addrs[blockNumber % addrPerBlock];
	}
	
	// tripple indirection
	else
	{
// 		printf("\nTRIPPLE INDIRECT\n");
// 		printf("BLOCK NUM: %d\n", blockNumber);
		
		// make space for our inodes
		addrs = new ulong[blockSize/sizeof(ulong)];
		
		// read in the indirect blocks
		ReadBlocks(blockPointers[TRIPPLE_INDIRECT_BLOCK_PTR], 1, reinterpret_cast<uchar*>(addrs));
		
		// update the block number
		blockNumber = blockNumber - INDIRECT_BLOCK_PTR - addrPerBlock - (addrPerBlock * addrPerBlock);
		 
		// read in the double indirect blocks
		ReadBlocks(addrs[blockNumber / (addrPerBlock * addrPerBlock)], 1, reinterpret_cast<uchar*>(addrs));
		
		// read in the tripple indirect blocks
		ReadBlocks(addrs[blockNumber / addrPerBlock], 1, reinterpret_cast<uchar*>(addrs));
		
// 		printf("ASKING FOR: %d\n", addrs[blockNumber % addrPerBlock]);
		
		addr = addrs[blockNumber % addrPerBlock];
	}
	
	// cleanup any memory we might have made
	if(addrs != NULL)
		delete [] addrs;

	return(addr);
}
Esempio n. 11
0
bool CGoods::SerializeForOldClient(DBWriteSet& setWriteDB, bool b)
{
	bool bResult = false;
	CGoodsBaseProperties* pProperties = GoodsSetup::QueryGoodsBaseProperties(
		GetBasePropertiesIndex() );
	if( pProperties )
	{
		setWriteDB.AddToByteArray( GetBasePropertiesIndex() );
		setWriteDB.AddToByteArray( GetExID() );
		setWriteDB.AddToByteArray( GetAmount() );
		setWriteDB.AddToByteArray( const_cast<char*>( GetMakerName() ) );		
		setWriteDB.AddToByteArray( GetPrice() );	
		setWriteDB.AddToByteArray( GetSilverPrice());
		setWriteDB.AddToByteArray( m_dwBuyPrice);
		setWriteDB.AddToByteArray( (ulong)GetGoodsBaseType());		

		long lAddonNum=0;
		ulong dwPropertyId=0;

		vector<uchar> vecAddonData;
		for( size_t i = 0; i < m_vAddonProperties.size(); i ++ )
		{		
			if(pProperties->IsHasAddonPropertie(m_vAddonProperties[i].gapType))	
			{
				dwPropertyId=m_vAddonProperties[i].gapType;				
				lAddonNum++;
				_AddToByteArray( &vecAddonData, static_cast<WORD>(m_vAddonProperties[i].gapType) );
				_AddToByteArray( &vecAddonData, m_vAddonProperties[i].lValues[0]);
				_AddToByteArray( &vecAddonData, m_vAddonProperties[i].lValues[1]);
			}
			else
			{
				lAddonNum++;
				_AddToByteArray( &vecAddonData, static_cast<WORD>(m_vAddonProperties[i].gapType) );
				_AddToByteArray( &vecAddonData, m_vAddonProperties[i].lValues[0]);
				_AddToByteArray( &vecAddonData, m_vAddonProperties[i].lValues[1]);
			}
		}
		setWriteDB.AddToByteArray(lAddonNum);
		if(lAddonNum>0)
		{
			setWriteDB.AddToByteArray( &vecAddonData[0],(long)vecAddonData.size());
		}
		/////////////////
		
		setWriteDB.AddToByteArray( GetTileX() );
		setWriteDB.AddToByteArray( GetTileY() );

		EnchaseArrange();
		//enchase data	
		ulong dwMaxHoleNum=GetMaxEnchaseHoleNum();
		if(dwMaxHoleNum>0)
		{
			//最大孔数
			setWriteDB.AddToByteArray( dwMaxHoleNum);
			//激活孔数量
			//王晓轩:默认所有孔都开启,所以删除此项数据
			//setWriteDB.AddToByteArray( GetActivedHoleNum());
			for(int i=0;i<(int)dwMaxHoleNum;i++)
			{		
				//CARD ID
				CGoods* pCard=m_pEnchaseHoleArray[i]->GetCard();
				if(pCard)
				{
					setWriteDB.AddToByteArray( pCard->GetBasePropertiesIndex());
					pCard->SerializeForOldClient(setWriteDB);
				}
				else
				{
					setWriteDB.AddToByteArray(ulong(0));
				}
			}
		}

		bResult = true;
	}
	return bResult;
}
Esempio n. 12
0
bool CGoods::Serialize(DBWriteSet& setWriteDB, bool b)
{
	CShape::CodeToDataBlock( setWriteDB, b==false?false:true );

	setWriteDB.AddToByteArray( m_dwBasePropertiesIndex );
	setWriteDB.AddToByteArray( m_dwAmount );
	//setWriteDB.AddToByteArray( m_dwPrice );
	//setWriteDB.AddToByteArray( m_dwBuyPrice);
	//setWriteDB.AddToByteArray( (ulong)m_GoodsBaseType);
	//专业制造者名字
	setWriteDB.AddToByteArray( const_cast<char*>( m_strMakerName.c_str()));		

	CGoodsBaseProperties* pBaseProperty=GoodsSetup::QueryGoodsBaseProperties(m_dwBasePropertiesIndex);
	if(!pBaseProperty)
		return false;
	ulong dwAddonNum=0;
	ulong dwPropertyId=0;
	vector<uchar> vecAddonData;
	for( size_t i = 0; i < m_vAddonProperties.size(); i ++ )
	{		
		if(pBaseProperty->IsHasAddonPropertie(m_vAddonProperties[i].gapType))	
		{			
			dwPropertyId=m_vAddonProperties[i].gapType;
			if(GoodsSetup::s_GoodsAttrDBSetup[dwPropertyId][0]==1)
			{
				dwAddonNum++;
				m_vAddonProperties[i].Serialize(&vecAddonData);
			}
		}
	}
	setWriteDB.AddToByteArray(dwAddonNum);
	if(dwAddonNum>0)
	{
		setWriteDB.AddToByteArray(&vecAddonData[0],(long)vecAddonData.size());
	}

	EnchaseArrange();
	//enchase data	
	
	setWriteDB.AddToByteArray(m_dwMaxHoleNum);
	//激活孔数量
	setWriteDB.AddToByteArray( GetActivedHoleNum());
	setWriteDB.AddToByteArray( m_dwActivedKitCardId);
	for(int i=0;i< (int)m_dwMaxHoleNum;i++)
	{
		//状态
		//王晓轩:所有镶嵌孔设置为开启
		setWriteDB.AddToByteArray(uchar(1));
		//if(m_pEnchaseHoleArray[i]->GetState())
		//{
		//	setWriteDB.AddToByteArray(uchar(1));
		//}
		//else
		//{
		//	setWriteDB.AddToByteArray(uchar(0));
		//}
		//CARD ID
		CGoods* pCard=m_pEnchaseHoleArray[i]->GetCard();
		if(pCard)
		{
			setWriteDB.AddToByteArray(pCard->GetBasePropertiesIndex());
			pCard->Serialize(setWriteDB);
		}
		else
		{
			setWriteDB.AddToByteArray(ulong(0));
		}
	}
	return true;
}
Esempio n. 13
0
bool CGoods::SerializeForOldClient(vector<uchar>* pStream, bool b)
{
	bool bResult = false;
	CGoodsBaseProperties* pProperties = GoodsSetup::QueryGoodsBaseProperties(
		GetBasePropertiesIndex() );
	if( pProperties )
	{
		_AddToByteArray( pStream, GetBasePropertiesIndex() );
		_AddToByteArray( pStream, GetExID() );
		_AddToByteArray( pStream, GetAmount() );
		_AddToByteArray( pStream, const_cast<char*>( GetMakerName() ) );		
		_AddToByteArray( pStream, GetPrice() );	
		_AddToByteArray(pStream,GetSilverPrice());
		_AddToByteArray(pStream,m_dwBuyPrice);
		_AddToByteArray(pStream,(ulong)GetGoodsBaseType());
		

		CGoodsBaseProperties* pBaseProperty=GoodsSetup::QueryGoodsBaseProperties(m_dwBasePropertiesIndex);
		if(!pBaseProperty)
			return false;
		long lAddonNum=0;
		ulong dwPropertyId=0;

		vector<uchar> vecAddonData;
		for( size_t i = 0; i < m_vAddonProperties.size(); i ++ )
		{		
			if(pBaseProperty->IsHasAddonPropertie(m_vAddonProperties[i].gapType))	
			{
				dwPropertyId=m_vAddonProperties[i].gapType;
				//if(GoodsSetup::s_GoodsAttrDBSetup[dwPropertyId][1]==1)
				//{
					lAddonNum++;
					_AddToByteArray( &vecAddonData, static_cast<WORD>(m_vAddonProperties[i].gapType) );
					_AddToByteArray( &vecAddonData, m_vAddonProperties[i].lValues[0] );
					_AddToByteArray( &vecAddonData, m_vAddonProperties[i].lValues[1] );
				//}
			}
			else
			{
				lAddonNum++;
				_AddToByteArray( &vecAddonData, static_cast<WORD>(m_vAddonProperties[i].gapType) );
				_AddToByteArray( &vecAddonData, m_vAddonProperties[i].lValues[0] );
				_AddToByteArray( &vecAddonData, m_vAddonProperties[i].lValues[1] );
			}
		}
		_AddToByteArray( pStream,lAddonNum);
		if(lAddonNum>0)
		{
			_AddToByteArray(pStream,&vecAddonData[0],(long)vecAddonData.size());
		}
		/////////////////
		
		_AddToByteArray( pStream, GetTileX() );
		_AddToByteArray( pStream, GetTileY() );

		EnchaseArrange();

		//enchase data	
		ulong dwMaxHoleNum=GetMaxEnchaseHoleNum();
		if(dwMaxHoleNum>0)
		{
			//最大孔数
			_AddToByteArray(pStream,dwMaxHoleNum);
			//激活孔数量
			//王晓轩:默认所有孔都开启,所以删除此项数据
			//_AddToByteArray( pStream, GetActivedHoleNum());
			for(int i=0;i<(int)dwMaxHoleNum;i++)
			{		
				//CARD ID
				CGoods* pCard=m_pEnchaseHoleArray[i]->GetCard();
				if(pCard)
				{
					_AddToByteArray(pStream,pCard->GetBasePropertiesIndex());
					pCard->SerializeForOldClient(pStream);
				}
				else
				{
					_AddToByteArray(pStream,ulong(0));
				}
			}
		}

		bResult = true;
	}
	return bResult;
}
Esempio n. 14
0
void L3DS::ReadFaceList(const LChunk &chunk, LMesh &mesh)
{
    // variables
    unsigned short count, t;
    uint i;
    LTri tri;
    LChunk ch;
    char str[20];
    //uint mat;

    // consistency checks
    if (chunk.id != TRI_FACELIST)
    {
        fprintf(stderr, "L3DS::ReadFaceList - internal error: wrong chunk passed as parameter");
        return;
    }
    GotoChunk(chunk);
    tri.smoothingGroups = 1;
    // read the number of faces
    count = ReadShort();
    mesh.SetTriangleArraySize(count);
    for (i=0; i<count; i++)
    {
        tri.a = ReadShort();
        tri.b = ReadShort();
        tri.c = ReadShort();
        ReadShort();
        mesh.SetTri(tri, i);
    }
    // now read the optional chunks
    ch = ReadChunk();
    int mat_id;
    while (ch.end <= chunk.end)
    {
        switch (ch.id)
        {
            case TRI_MAT_GROUP:
            {
                ReadASCIIZ(str, 20);
                
                LMaterial *pMat = FindMaterial(str);

                if(pMat != NULL)
                {
                    mat_id = pMat->GetID();
                    
                    mesh.AddMaterial(mat_id);
                }

                count = ReadShort();
                for (i=0; i<count; i++)
                {
                    t = ReadShort();
                    if(pMat != NULL)
                        mesh.GetTri(t).materialId = mat_id;
                }
            }
            break;

            case TRI_SMOOTH_GROUP:
                for (i=0; i<mesh.GetTriangleCount(); i++)
                    mesh.GetTri(i).smoothingGroups = ulong(ReadInt());
                break;
        }
        SkipChunk(ch);
        ch = ReadChunk();
    }
}
Esempio n. 15
0
		bool Pins::ConstPinsProxy::ComponentProxy::operator == (wcstring s) const
		{
			return ulong(end - component) == wcslen(s) && Core::StringCompare( component, s, end - component ) == 0;
		}
Esempio n. 16
0
static int *align16(int *lock)
{
    ulong off = (((ulong) lock) % 16);
    return off ? (int *)(ulong(lock) + 16 - off) : lock;
}
Esempio n. 17
0
/*!
    Reads the object of the specified \a type from the given \a
    stream into \a data. Returns true if the object is loaded
    successfully; otherwise returns false.

    The type must have been registered with qRegisterMetaType() and
    qRegisterMetaTypeStreamOperators() beforehand.

    Normally, you should not need to call this function directly.
    Instead, use QVariant's \c operator>>(), which relies on load()
    to stream custom types.

    \sa save(), qRegisterMetaTypeStreamOperators()
*/
bool QMetaType::load(QDataStream &stream, int type, void *data)
{
    if (!data || !isRegistered(type))
        return false;

    switch(type) {
    case QMetaType::Void:
    case QMetaType::VoidStar:
    case QMetaType::QObjectStar:
    case QMetaType::QWidgetStar:
        return false;
    case QMetaType::Long: {
        qlonglong l;
        stream >> l;
        *static_cast<long *>(data) = long(l);
        break; }
    case QMetaType::Int:
        stream >> *static_cast<int *>(data);
        break;
    case QMetaType::Short:
        stream >> *static_cast<short *>(data);
        break;
    case QMetaType::Char:
        // force a char to be signed
        stream >> *static_cast<signed char *>(data);
        break;
    case QMetaType::ULong: {
        qulonglong ul;
        stream >> ul;
        *static_cast<ulong *>(data) = ulong(ul);
        break; }
    case QMetaType::UInt:
        stream >> *static_cast<uint *>(data);
        break;
    case QMetaType::LongLong:
        stream >> *static_cast<qlonglong *>(data);
        break;
    case QMetaType::ULongLong:
        stream >> *static_cast<qulonglong *>(data);
        break;
    case QMetaType::UShort:
        stream >> *static_cast<ushort *>(data);
        break;
    case QMetaType::UChar:
        stream >> *static_cast<uchar *>(data);
        break;
    case QMetaType::Bool: {
        qint8 b;
        stream >> b;
        *static_cast<bool *>(data) = b;
        break; }
    case QMetaType::Float:
        stream >> *static_cast<float *>(data);
        break;
    case QMetaType::Double:
        stream >> *static_cast<double *>(data);
        break;
    case QMetaType::QChar:
        stream >> *static_cast< ::QChar *>(data);
        break;
#ifndef QT_BOOTSTRAPPED
    case QMetaType::QVariantMap:
        stream >> *static_cast< ::QVariantMap *>(data);
        break;
    case QMetaType::QVariantList:
        stream >> *static_cast< ::QVariantList *>(data);
        break;
#endif
    case QMetaType::QByteArray:
        stream >> *static_cast< ::QByteArray *>(data);
        break;
    case QMetaType::QString:
        stream >> *static_cast< ::QString *>(data);
        break;
    case QMetaType::QStringList:
        stream >> *static_cast< ::QStringList *>(data);
        break;
#ifndef QT_BOOTSTRAPPED
    case QMetaType::QBitArray:
        stream >> *static_cast< ::QBitArray *>(data);
        break;
#endif
    case QMetaType::QDate:
        stream >> *static_cast< ::QDate *>(data);
        break;
    case QMetaType::QTime:
        stream >> *static_cast< ::QTime *>(data);
        break;
    case QMetaType::QDateTime:
        stream >> *static_cast< ::QDateTime *>(data);
        break;
#ifndef QT_BOOTSTRAPPED
    case QMetaType::QUrl:
        stream >> *static_cast< ::QUrl *>(data);
        break;
#endif
    case QMetaType::QLocale:
        stream >> *static_cast< ::QLocale *>(data);
        break;
#ifndef QT_NO_GEOM_VARIANT
    case QMetaType::QRect:
        stream >> *static_cast< ::QRect *>(data);
        break;
    case QMetaType::QRectF:
        stream >> *static_cast< ::QRectF *>(data);
        break;
    case QMetaType::QSize:
        stream >> *static_cast< ::QSize *>(data);
        break;
    case QMetaType::QSizeF:
        stream >> *static_cast< ::QSizeF *>(data);
        break;
    case QMetaType::QLine:
        stream >> *static_cast< ::QLine *>(data);
        break;
    case QMetaType::QLineF:
        stream >> *static_cast< ::QLineF *>(data);
        break;
    case QMetaType::QPoint:
        stream >> *static_cast< ::QPoint *>(data);
        break;
    case QMetaType::QPointF:
        stream >> *static_cast< ::QPointF *>(data);
        break;
#endif
#ifndef QT_NO_REGEXP
    case QMetaType::QRegExp:
        stream >> *static_cast< ::QRegExp *>(data);
        break;
#endif
#ifdef QT3_SUPPORT
    case QMetaType::QColorGroup:
#endif
    case QMetaType::QFont:
    case QMetaType::QPixmap:
    case QMetaType::QBrush:
    case QMetaType::QColor:
    case QMetaType::QPalette:
    case QMetaType::QIcon:
    case QMetaType::QImage:
    case QMetaType::QPolygon:
    case QMetaType::QRegion:
    case QMetaType::QBitmap:
    case QMetaType::QCursor:
    case QMetaType::QSizePolicy:
    case QMetaType::QKeySequence:
    case QMetaType::QPen:
    case QMetaType::QTextLength:
    case QMetaType::QTextFormat:
    case QMetaType::QMatrix:
    case QMetaType::QTransform:
        if (!qMetaTypeGuiHelper)
            return false;
        qMetaTypeGuiHelper[type - FirstGuiType].loadOp(stream, data);
        break;
    default: {
        const QVector<QCustomTypeInfo> * const ct = customTypes();
        if (!ct)
            return false;

        LoadOperator loadOp = 0;
        {
            QReadLocker locker(customTypesLock());
            loadOp = ct->at(type - User).loadOp;
        }

        if (!loadOp)
            return false;
        loadOp(stream, data);
        break; }
    }
    return true;
}
Esempio n. 18
0
static QString osc_label ( qtractorDssiPlugin *pDssiPlugin )
{
	return (pDssiPlugin->type())->label()
		+ '.' + QString::number(ulong(pDssiPlugin), 16);
}
Esempio n. 19
0
void AbstractPort::updatePacketListSequential()
{
    long    sec = 0; 
    long    nsec = 0;

    qDebug("In %s", __FUNCTION__);

    // First sort the streams by ordinalValue
    qSort(streamList_.begin(), streamList_.end(), StreamBase::StreamLessThan);

    clearPacketList();

    for (int i = 0; i < streamList_.size(); i++)
    {
        if (streamList_[i]->isEnabled())
        {
            int len = 0;
            ulong n, x, y;
            ulong burstSize;
            double ibg = 0;
            quint64 ibg1 = 0, ibg2 = 0;
            quint64 nb1 = 0, nb2 = 0;
            double ipg = 0;
            quint64 ipg1 = 0, ipg2 = 0;
            quint64 npx1 = 0, npx2 = 0;
            quint64 npy1 = 0, npy2 = 0;
            quint64 loopDelay;
            ulong frameVariableCount = streamList_[i]->frameVariableCount();

            // We derive n, x, y such that
            // n * x + y = total number of packets to be sent

            switch (streamList_[i]->sendUnit())
            {
            case OstProto::StreamControl::e_su_bursts:
                burstSize = streamList_[i]->burstSize();
                x = AbstractProtocol::lcm(frameVariableCount, burstSize);
                n = ulong(burstSize * streamList_[i]->numBursts()) / x;
                y = ulong(burstSize * streamList_[i]->numBursts()) % x;
                if (streamList_[i]->burstRate() > 0)
                {
                    ibg = 1e9/double(streamList_[i]->burstRate());
                    ibg1 = quint64(ceil(ibg));
                    ibg2 = quint64(floor(ibg));
                    nb1  = quint64((ibg - double(ibg2)) * double(x));
                    nb2  = x - nb1;
                }
                loopDelay = ibg2;
                break;
            case OstProto::StreamControl::e_su_packets:
                x = frameVariableCount;
                n = 2;
                while (x < minPacketSetSize_) 
                    x = frameVariableCount*n++;
                n = streamList_[i]->numPackets() / x;
                y = streamList_[i]->numPackets() % x;
                burstSize = x + y;
                if (streamList_[i]->packetRate() > 0)
                {
                    ipg = 1e9/double(streamList_[i]->packetRate());
                    ipg1 = quint64(ceil(ipg));
                    ipg2 = quint64(floor(ipg));
                    npx1  = quint64((ipg - double(ipg2)) * double(x));
                    npx2  = x - npx1;
                    npy1  = quint64((ipg - double(ipg2)) * double(y));
                    npy2  = y - npy1;
                }
                loopDelay = ipg2;
                break;
            default:
                qWarning("Unhandled stream control unit %d",
                    streamList_[i]->sendUnit());
                continue;
            }

            qDebug("\nframeVariableCount = %lu", frameVariableCount);
            qDebug("n = %lu, x = %lu, y = %lu, burstSize = %lu",
                    n, x, y, burstSize);

            qDebug("ibg  = %g", ibg);
            qDebug("ibg1 = %" PRIu64, ibg1);
            qDebug("nb1  = %" PRIu64, nb1);
            qDebug("ibg2 = %" PRIu64, ibg2);
            qDebug("nb2  = %" PRIu64 "\n", nb2);

            qDebug("ipg  = %g", ipg);
            qDebug("ipg1 = %" PRIu64, ipg1);
            qDebug("npx1 = %" PRIu64, npx1);
            qDebug("npy1 = %" PRIu64, npy1);
            qDebug("ipg2 = %" PRIu64, ipg2);
            qDebug("npx2 = %" PRIu64, npx2);
            qDebug("npy2 = %" PRIu64 "\n", npy2);

            if (n > 1)
                loopNextPacketSet(x, n, 0, loopDelay);
            else if (n == 0)
                x = 0;

            for (uint j = 0; j < (x+y); j++)
            {
                
                if (j == 0 || frameVariableCount > 1)
                {
                    len = streamList_[i]->frameValue(
                            pktBuf_, sizeof(pktBuf_), j);
                }
                if (len <= 0)
                    continue;

                qDebug("q(%d, %d) sec = %lu nsec = %lu",
                        i, j, sec, nsec);

                appendToPacketList(sec, nsec, pktBuf_, len); 

                if ((j > 0) && (((j+1) % burstSize) == 0))
                {
                    nsec += (j < nb1) ? ibg1 : ibg2;
                    while (nsec >= long(1e9))
                    {
                        sec++;
                        nsec -= long(1e9);
                    }
                }
                else
                {
                    if (j < x)
                        nsec += (j < npx1) ? ipg1 : ipg2;
                    else
                        nsec += ((j-x) < npy1) ? ipg1 : ipg2;

                    while (nsec >= long(1e9))
                    {
                        sec++;
                        nsec -= long(1e9);
                    }
                }
            }

            switch(streamList_[i]->nextWhat())
            {
                case ::OstProto::StreamControl::e_nw_stop:
                    goto _stop_no_more_pkts;

                case ::OstProto::StreamControl::e_nw_goto_id:
                    /*! \todo (MED): define and use 
                    streamList_[i].d.control().goto_stream_id(); */

                    /*! \todo (MED): assumes goto Id is less than current!!!! 
                     To support goto to any id, do
                     if goto_id > curr_id then 
                         i = goto_id;
                         goto restart;
                     else
                         returnToQIdx = 0;
                     */

                    setPacketListLoopMode(true, 0, 
                            streamList_[i]->sendUnit() == 
                                StreamBase::e_su_bursts ? ibg1 : ipg1);
                    goto _stop_no_more_pkts;

                case ::OstProto::StreamControl::e_nw_goto_next:
                    break;

                default:
                    qFatal("---------- %s: Unhandled case (%d) -----------",
                            __FUNCTION__, streamList_[i]->nextWhat() );
                    break;
            }

        } // if (stream is enabled)
    } // for (numStreams)

_stop_no_more_pkts:
    isSendQueueDirty_ = false;
}
Esempio n. 20
0
/*
 * Elf32 binaries.
 */
static int
elfdotout(int fd, Fhdr *fp, ExecHdr *hp)
{

	ulong (*swal)(ulong);
	ushort (*swab)(ushort);
	Ehdr *ep;
	Phdr *ph;
	int i, it, id, is, phsz;

	/* bitswap the header according to the DATA format */
	ep = &hp->e.elfhdr32;
	if(ep->ident[CLASS] != ELFCLASS32) {
		werrstr("bad ELF class - not 32 bit");
		return 0;
	}
	if(ep->ident[DATA] == ELFDATA2LSB) {
		swab = leswab;
		swal = leswal;
	} else if(ep->ident[DATA] == ELFDATA2MSB) {
		swab = beswab;
		swal = beswal;
	} else {
		werrstr("bad ELF encoding - not big or little endian");
		return 0;
	}

	ep->type = swab(ep->type);
	ep->machine = swab(ep->machine);
	ep->version = swal(ep->version);
	ep->elfentry = swal(ep->elfentry);
	ep->phoff = swal(ep->phoff);
	ep->shoff = swal(ep->shoff);
	ep->flags = swal(ep->flags);
	ep->ehsize = swab(ep->ehsize);
	ep->phentsize = swab(ep->phentsize);
	ep->phnum = swab(ep->phnum);
	ep->shentsize = swab(ep->shentsize);
	ep->shnum = swab(ep->shnum);
	ep->shstrndx = swab(ep->shstrndx);
	if(ep->type != EXEC || ep->version != CURRENT)
		return 0;

	/* we could definitely support a lot more machines here */
	fp->magic = ELF_MAG;
	fp->hdrsz = (ep->ehsize+ep->phnum*ep->phentsize+16)&~15;
	switch(ep->machine) {
	case I386:
		mach = &mi386;
		fp->type = FI386;
		break;
	case MIPS:
		mach = &mmips;
		fp->type = FMIPS;
		break;
	case SPARC64:
		return 0;
	case POWER:
		mach = &mpower;
		fp->type = FPOWER;
		break;
	case AMD64:
		mach = &mamd64;
		fp->type = FAMD64;
		break;
	case ARM:
		mach = &marm;
		fp->type = FARM;
		break;
	default:
		return 0;
	}

	if(ep->phentsize != sizeof(Phdr)) {
		werrstr("bad ELF header size");
		return 0;
	}
	phsz = sizeof(Phdr)*ep->phnum;
	ph = malloc(phsz);
	if(!ph)
		return 0;
	seek(fd, ep->phoff, 0);
	if(read(fd, ph, phsz) < 0) {
		free(ph);
		return 0;
	}
	hswal(ph, phsz/sizeof(ulong), swal);

	/* find text, data and symbols and install them */
	it = id = is = -1;
	for(i = 0; i < ep->phnum; i++) {
		if(ph[i].type == LOAD
		&& (ph[i].flags & (R|X)) == (R|X) && it == -1)
			it = i;
		else if(ph[i].type == LOAD
		&& (ph[i].flags & (R|W)) == (R|W) && id == -1)
			id = i;
		else if(ph[i].type == NOPTYPE && is == -1)
			is = i;
	}
	if(it == -1 || id == -1) {
		/*
		 * The SPARC64 boot image is something of an ELF hack.
		 * Text+Data+BSS are represented by ph[0].  Symbols
		 * are represented by ph[1]:
		 *
		 *		filesz, memsz, vaddr, paddr, off
		 * ph[0] : txtsz+datsz, txtsz+datsz+bsssz, txtaddr-KZERO, datasize, txtoff
		 * ph[1] : symsz, lcsz, 0, 0, symoff
		 */
		if(ep->machine == SPARC64 && ep->phnum == 2) {
			ulong txtaddr, txtsz, dataddr, bsssz;

			txtaddr = ph[0].vaddr | 0x80000000;
			txtsz = ph[0].filesz - ph[0].paddr;
			dataddr = txtaddr + txtsz;
			bsssz = ph[0].memsz - ph[0].filesz;
			settext(fp, ep->elfentry | 0x80000000, txtaddr, txtsz, ph[0].offset);
			setdata(fp, dataddr, ph[0].paddr, ph[0].offset + txtsz, bsssz);
			setsym(fp, ph[1].filesz, 0, ph[1].memsz, ph[1].offset);
			free(ph);
			return 1;
		}

		werrstr("No TEXT or DATA sections");
		free(ph);
		return 0;
	}

	settext(fp, ep->elfentry, ph[it].vaddr, ph[it].memsz, ph[it].offset);
	setdata(fp, ph[id].vaddr, ph[id].filesz, ph[id].offset, ph[id].memsz - ph[id].filesz);
	if(is != -1)
		setsym(fp, ph[is].filesz, 0, ph[is].memsz, ph[is].offset);
	free(ph);
	return 1;
}
Esempio n. 21
0
	const ulong path::fsize() {
		update();
		return (pwfd->nFileSizeHigh * (ulong(MAXDWORD)+1)) + pwfd->nFileSizeLow;
	}