Ejemplo n.º 1
0
void start_sysinit(void)
{
	time_t tm = 0;

	char dev[64];
	char *disk = getdisc();

	if (disk == NULL) {
		fprintf(stderr, "no valid dd-wrt partition found, calling shell");
		eval("/bin/sh");
		exit(0);
	}

	FILE *in = fopen("/usr/local/nvram/nvram.db", "rb");

	if (in != NULL) {
		fclose(in);
		mkdir("/tmp/nvram", 0700);
		eval("cp", "/etc/nvram/nvram.db", "/tmp/nvram");
		eval("cp", "/etc/nvram/offsets.db", "/tmp/nvram");
		eval("/usr/sbin/convertnvram");
		nvram_commit();
		eval("rm", "-f", "/etc/nvram/nvram.db");
		eval("rm", "-f", "/etc/nvram/offsets.db");
	}
	//recover nvram if available
	in = fopen("/usr/local/nvram/nvram.bin", "rb");
	if (in == NULL) {
		fprintf(stderr, "recover broken nvram\n");
		sprintf(dev, "/dev/%s", disk);
		in = fopen(dev, "rb");
		fseeko(in, 0, SEEK_END);
		off_t mtdlen = ftello(in);
		fseeko(in, mtdlen - (65536 * 2), SEEK_SET);
		unsigned char *mem = malloc(65536);
		fread(mem, 65536, 1, in);
		fclose(in);
		if (mem[0] == 0x46 && mem[1] == 0x4c && mem[2] == 0x53 && mem[3] == 0x48) {
			fprintf(stderr, "found recovery\n");
			in = fopen("/usr/local/nvram/nvram.bin", "wb");
			if (in != NULL) {
				fwrite(mem, 65536, 1, in);
				fclose(in);
				free(mem);
				eval("sync");
				sleep(5);
				eval("event", "5", "1", "15");
			}
		}
		free(mem);
	} else {
		fclose(in);
	}

	if (!nvram_match("disable_watchdog", "1"))
		eval("watchdog");	// system watchdog
#ifdef HAVE_ERC
	if (isregistered_real() && nvram_match("ree_resetme", "1")) {
		fprintf(stderr, "Restoring REE default nvram\n");
		eval("nvram", "restore", "/etc/defaults/x86ree.backup");
		eval("reboot");
		eval("event", "5", "1", "15");
	}
#endif

	cprintf("sysinit() setup console\n");

	/*
	 * Setup console 
	 */

	cprintf("sysinit() klogctl\n");
	klogctl(8, NULL, atoi(nvram_safe_get("console_loglevel")));
	cprintf("sysinit() get router\n");

	/*
	 * eval("insmod","md5"); eval("insmod","aes"); eval("insmod","blowfish");
	 * eval("insmod","deflate"); eval("insmod","des");
	 * eval("insmod","michael_mic"); eval("insmod","cast5");
	 * eval("insmod","crypto_null"); 
	 */

	detect_ethernet_devices();
	eval("ifconfig", "eth0", "0.0.0.0", "up");
	eval("ifconfig", "eth1", "0.0.0.0", "up");
	eval("ifconfig", "eth2", "0.0.0.0", "up");
	eval("ifconfig", "eth3", "0.0.0.0", "up");

	struct ifreq ifr;
	int s;

	if ((s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW))) {
		char eabuf[32];

		strncpy(ifr.ifr_name, "eth0", IFNAMSIZ);
		ioctl(s, SIOCGIFHWADDR, &ifr);
		nvram_set("et0macaddr_safe", ether_etoa((unsigned char *)ifr.ifr_hwaddr.sa_data, eabuf));
		nvram_set("et0macaddr", ether_etoa((unsigned char *)ifr.ifr_hwaddr.sa_data, eabuf));
		close(s);
	}
	detect_wireless_devices();

	mknod("/dev/rtc", S_IFCHR | 0644, makedev(253, 0));
#ifdef HAVE_CPUTEMP
	// insmod("nsc_gpio");
	// insmod("scx200_gpio");
	// insmod("scx200_i2c");
	// insmod("scx200_acb");
	// insmod("lm77");
#endif

	nvram_set("wl0_ifname", "ath0");
	mknod("/dev/crypto", S_IFCHR | 0644, makedev(10, 70));
	/*
	 * Set a sane date 
	 */
	stime(&tm);
	cprintf("done\n");
	return;
}
/**
    \fn
    \brief
*/
bool      ADM_audioAccessFile::setPos(uint64_t pos)
{
    fseeko(_fd,_offset+pos,SEEK_SET);
    return true;
}
Ejemplo n.º 3
0
static int getM4aFrequency(FILE *fp)
{
    char atom[4];
    int tmp,i;
    __int64 initPos = ftello(fp);
    int freq = 0;

    if(fseeko(fp,0,SEEK_SET) != 0) goto end;

    while(1) { //skip until moov;
        if(fread(&tmp,4,1,fp) < 1) goto end;
        if(fread(atom,1,4,fp) < 4) goto end;
        tmp = SWAP32(tmp);
        if(!memcmp(atom,"moov",4)) break;
        if(fseeko(fp,tmp-8,SEEK_CUR) != 0) goto end;
    }

    while(1) { //skip until trak;
        if(fread(&tmp,4,1,fp) < 1) goto end;
        if(fread(atom,1,4,fp) < 4) goto end;
        tmp = SWAP32(tmp);
        if(!memcmp(atom,"trak",4)) break;
        if(fseeko(fp,tmp-8,SEEK_CUR) != 0) goto end;
    }

    while(1) { //skip until mdia;
        if(fread(&tmp,4,1,fp) < 1) goto end;
        if(fread(atom,1,4,fp) < 4) goto end;
        tmp = SWAP32(tmp);
        if(!memcmp(atom,"mdia",4)) break;
        if(fseeko(fp,tmp-8,SEEK_CUR) != 0) goto end;
    }

    while(1) { //skip until minf;
        if(fread(&tmp,4,1,fp) < 1) goto end;
        if(fread(atom,1,4,fp) < 4) goto end;
        tmp = SWAP32(tmp);
        if(!memcmp(atom,"minf",4)) break;
        if(fseeko(fp,tmp-8,SEEK_CUR) != 0) goto end;
    }

    while(1) { //skip until stbl;
        if(fread(&tmp,4,1,fp) < 1) goto end;
        if(fread(atom,1,4,fp) < 4) goto end;
        tmp = SWAP32(tmp);
        if(!memcmp(atom,"stbl",4)) break;
        if(fseeko(fp,tmp-8,SEEK_CUR) != 0) goto end;
    }

    while(1) { //skip until esds;
        if(fread(atom,1,4,fp) < 4) goto end;
        if(!memcmp(atom,"esds",4)) break;
        if(fseeko(fp,-3,SEEK_CUR) != 0) goto end;
    }

    if(fseeko(fp,5,SEEK_CUR) != 0) goto end;
    for(i=0; i<3; i++) {
        if(fread(atom,1,1,fp) < 1) goto end;
        if((unsigned char)atom[0] != 0x80) {
            if(fseeko(fp,-1,SEEK_CUR) != 0) goto end;
            break;
        }
    }
    if(fseeko(fp,5,SEEK_CUR) != 0) goto end;
    for(i=0; i<3; i++) {
        if(fread(atom,1,1,fp) < 1) goto end;
        if((unsigned char)atom[0] != 0x80) {
            if(fseeko(fp,-1,SEEK_CUR) != 0) goto end;
            break;
        }
    }
    if(fseeko(fp,15,SEEK_CUR) != 0) goto end;
    for(i=0; i<3; i++) {
        if(fread(atom,1,1,fp) < 1) goto end;
        if((unsigned char)atom[0] != 0x80) {
            if(fseeko(fp,-1,SEEK_CUR) != 0) goto end;
            break;
        }
    }
    if(fseeko(fp,1,SEEK_CUR) != 0) goto end;
    if(fread(atom,1,2,fp) < 2) goto end;
    tmp = (atom[0]<<1)&0xe;
    tmp |= (atom[1]>>7)&0x1;
    freq = srTable[tmp];

end:
    fseeko(fp,initPos,SEEK_SET);
    return freq;
}
Ejemplo n.º 4
0
int
GetLastKeyframe(FILE * file,	// output file [in]
                int nSkipKeyFrames,	// max number of frames to skip when searching for key frame [in]
                uint32_t * dSeek,	// offset of the last key frame [out]
                char **initialFrame,	// content of the last keyframe [out]
                int *initialFrameType,	// initial frame type (audio/video) [out]
                uint32_t * nInitialFrameSize)	// length of initialFrame [out]
{
    const size_t bufferSize = 16;
    char buffer[bufferSize];
    uint8_t dataType;
    int bAudioOnly;
    off_t size;

    fseek(file, 0, SEEK_END);
    size = ftello(file);

    fseek(file, 4, SEEK_SET);
    if (fread(&dataType, sizeof(uint8_t), 1, file) != 1)
        return RD_FAILED;

    bAudioOnly = (dataType & 0x4) && !(dataType & 0x1);

    RTMP_Log(RTMP_LOGDEBUG, "bAudioOnly: %d, size: %llu", bAudioOnly,
             (unsigned long long) size);

    // ok, we have to get the timestamp of the last keyframe (only keyframes are seekable) / last audio frame (audio only streams)

    //if(!bAudioOnly) // we have to handle video/video+audio different since we have non-seekable frames
    //{
    // find the last seekable frame
    off_t tsize = 0;
    uint32_t prevTagSize = 0;

    // go through the file and find the last video keyframe
    do
    {
        int xread;
skipkeyframe:
        if (size - tsize < 13)
        {
            RTMP_Log(RTMP_LOGERROR,
                     "Unexpected start of file, error in tag sizes, couldn't arrive at prevTagSize=0");
            return RD_FAILED;
        }
        fseeko(file, size - tsize - 4, SEEK_SET);
        xread = fread(buffer, 1, 4, file);
        if (xread != 4)
        {
            RTMP_Log(RTMP_LOGERROR, "Couldn't read prevTagSize from file!");
            return RD_FAILED;
        }

        prevTagSize = AMF_DecodeInt32(buffer);
        //RTMP_Log(RTMP_LOGDEBUG, "Last packet: prevTagSize: %d", prevTagSize);

        if (prevTagSize == 0)
        {
            RTMP_Log(RTMP_LOGERROR, "Couldn't find keyframe to resume from!");
            return RD_FAILED;
        }

        if (prevTagSize < 0 || prevTagSize > size - 4 - 13)
        {
            RTMP_Log(RTMP_LOGERROR,
                     "Last tag size must be greater/equal zero (prevTagSize=%d) and smaller then filesize, corrupt file!",
                     prevTagSize);
            return RD_FAILED;
        }
        tsize += prevTagSize + 4;

        // read header
        fseeko(file, size - tsize, SEEK_SET);
        if (fread(buffer, 1, 12, file) != 12)
        {
            RTMP_Log(RTMP_LOGERROR, "Couldn't read header!");
            return RD_FAILED;
        }
        //*
#ifdef _DEBUG
        uint32_t ts = AMF_DecodeInt24(buffer + 4);
        ts |= (buffer[7] << 24);
        RTMP_Log(RTMP_LOGDEBUG, "%02X: TS: %d ms", buffer[0], ts);
#endif //*/

        // this just continues the loop whenever the number of skipped frames is > 0,
        // so we look for the next keyframe to continue with
        //
        // this helps if resuming from the last keyframe fails and one doesn't want to start
        // the download from the beginning
        //
        if (nSkipKeyFrames > 0
                && !(!bAudioOnly
                     && (buffer[0] != 0x09 || (buffer[11] & 0xf0) != 0x10)))
        {
#ifdef _DEBUG
            RTMP_Log(RTMP_LOGDEBUG,
                     "xxxxxxxxxxxxxxxxxxxxxxxx Well, lets go one more back!");
#endif
            nSkipKeyFrames--;
            goto skipkeyframe;
        }

    }
    while ((bAudioOnly && buffer[0] != 0x08) || (!bAudioOnly && (buffer[0] != 0x09 || (buffer[11] & 0xf0) != 0x10)));	// as long as we don't have a keyframe / last audio frame

    // save keyframe to compare/find position in stream
    *initialFrameType = buffer[0];
    *nInitialFrameSize = prevTagSize - 11;
    *initialFrame = (char *) malloc(*nInitialFrameSize);

    fseeko(file, size - tsize + 11, SEEK_SET);
    if (fread(*initialFrame, 1, *nInitialFrameSize, file) != *nInitialFrameSize)
    {
        RTMP_Log(RTMP_LOGERROR, "Couldn't read last keyframe, aborting!");
        return RD_FAILED;
    }

    *dSeek = AMF_DecodeInt24(buffer + 4);	// set seek position to keyframe tmestamp
    *dSeek |= (buffer[7] << 24);
    //}
    //else // handle audio only, we can seek anywhere we'd like
    //{
    //}

    if (*dSeek < 0)
    {
        RTMP_Log(RTMP_LOGERROR,
                 "Last keyframe timestamp is negative, aborting, your file is corrupt!");
        return RD_FAILED;
    }
    RTMP_Log(RTMP_LOGDEBUG, "Last keyframe found at: %d ms, size: %d, type: %02X", *dSeek,
             *nInitialFrameSize, *initialFrameType);

    /*
       // now read the timestamp of the frame before the seekable keyframe:
       fseeko(file, size-tsize-4, SEEK_SET);
       if(fread(buffer, 1, 4, file) != 4) {
       RTMP_Log(RTMP_LOGERROR, "Couldn't read prevTagSize from file!");
       goto start;
       }
       uint32_t prevTagSize = RTMP_LIB::AMF_DecodeInt32(buffer);
       fseeko(file, size-tsize-4-prevTagSize+4, SEEK_SET);
       if(fread(buffer, 1, 4, file) != 4) {
       RTMP_Log(RTMP_LOGERROR, "Couldn't read previous timestamp!");
       goto start;
       }
       uint32_t timestamp = RTMP_LIB::AMF_DecodeInt24(buffer);
       timestamp |= (buffer[3]<<24);

       RTMP_Log(RTMP_LOGDEBUG, "Previous timestamp: %d ms", timestamp);
     */

    if (*dSeek != 0)
    {
        // seek to position after keyframe in our file (we will ignore the keyframes resent by the server
        // since they are sent a couple of times and handling this would be a mess)
        fseeko(file, size - tsize + prevTagSize + 4, SEEK_SET);

        // make sure the WriteStream doesn't write headers and ignores all the 0ms TS packets
        // (including several meta data headers and the keyframe we seeked to)
        //bNoHeader = TRUE; if bResume==true this is true anyway
    }

    //}

    return RD_SUCCESS;
}
Ejemplo n.º 5
0
int zfseeko(zfp *zf, off_t offset, int whence) {
    return zf->fp ? fseeko(zf->fp, offset, whence) : -1;
}
Ejemplo n.º 6
0
static size_t get_size_stdio(STDIOSTREAMFILE * streamfile) {
    fseeko(streamfile->infile,0,SEEK_END);
    return ftello(streamfile->infile);
}
Ejemplo n.º 7
0
static void
DoFile(const char *savedir, const char *device)
{
	static char *buf = NULL;
	struct partinfo	dpart;
	struct kerneldumpheader kdhf, kdhl;
	off_t mediasize, dumpsize, firsthd, lasthd, dmpcnt;
	FILE *info, *fp, *fpkern;
	mode_t oumask;
	int fd, fdinfo, fdkernin, error, wl;
	int nr, nw, hs, he = 0;
	int bounds, status;
	u_int sectorsize;

	bounds = getbounds();
	dmpcnt = 0;
	mediasize = 0;
	status = STATUS_UNKNOWN;

	if (buf == NULL) {
		buf = malloc(BUFFERSIZE);
		if (buf == NULL) {
			syslog(LOG_ERR, "%m");
			return;
		}
	}

	if (verbose)
		printf("checking for kernel dump on device %s\n", device);

	fd = open(device, O_RDWR);
	if (fd < 0) {
		syslog(LOG_ERR, "%s: %m", device);
		return;
	}

	bzero(&dpart, sizeof(dpart));
	error = ioctl(fd, DIOCGPART, &dpart);
	if (error) {
		syslog(LOG_ERR,
		    "couldn't find media and/or sector size of %s: %m", device);
		goto closefd;
	}
	mediasize = dpart.media_size;
	sectorsize = dpart.media_blksize;

	if (verbose) {
		printf("mediasize = %lld\n", (long long)mediasize);
		printf("sectorsize = %u\n", sectorsize);
	}

	lasthd = mediasize - sectorsize;
	lseek(fd, lasthd, SEEK_SET);
	error = read(fd, &kdhl, sizeof kdhl);
	if (error != sizeof kdhl) {
		syslog(LOG_ERR,
		    "error reading last dump header at offset %lld in %s: %m",
		    (long long)lasthd, device);
		goto closefd;
	}
	if (memcmp(kdhl.magic, KERNELDUMPMAGIC, sizeof kdhl.magic)) {
		if (verbose)
			printf("magic mismatch on last dump header on %s\n",
			    device);

		status = STATUS_BAD;
		if (force == 0)
			goto closefd;

		if (memcmp(kdhl.magic, KERNELDUMPMAGIC_CLEARED,
			    sizeof kdhl.magic) == 0) {
			if (verbose)
				printf("forcing magic on %s\n", device);
			memcpy(kdhl.magic, KERNELDUMPMAGIC,
			    sizeof kdhl.magic);
		} else {
			syslog(LOG_ERR, "unable to force dump - bad magic");
			goto closefd;
		}
	}
	if (dtoh32(kdhl.version) != KERNELDUMPVERSION) {
		syslog(LOG_ERR,
		    "unknown version (%d) in last dump header on %s",
		    dtoh32(kdhl.version), device);

		status = STATUS_BAD;
		if (force == 0)
			goto closefd;
	}

	nfound++;
	if (clear)
		goto nuke;

	if (kerneldump_parity(&kdhl)) {
		syslog(LOG_ERR,
		    "parity error on last dump header on %s", device);
		nerr++;
		status = STATUS_BAD;
		if (force == 0)
			goto closefd;
	}
	dumpsize = dtoh64(kdhl.dumplength);
	firsthd = lasthd - dumpsize - sizeof kdhf;
	lseek(fd, firsthd, SEEK_SET);
	error = read(fd, &kdhf, sizeof kdhf);
	if (error != sizeof kdhf) {
		syslog(LOG_ERR,
		    "error reading first dump header at offset %lld in %s: %m",
		    (long long)firsthd, device);
		nerr++;
		goto closefd;
	}

	if (verbose >= 2) {
		printf("First dump headers:\n");
		printheader(stdout, &kdhf, device, bounds, -1);

		printf("\nLast dump headers:\n");
		printheader(stdout, &kdhl, device, bounds, -1);
		printf("\n");
	}

	if (memcmp(&kdhl, &kdhf, sizeof kdhl)) {
		syslog(LOG_ERR,
		    "first and last dump headers disagree on %s", device);
		nerr++;
		status = STATUS_BAD;
		if (force == 0)
			goto closefd;
	} else {
		status = STATUS_GOOD;
	}

	if (checkfor) {
		printf("A dump exists on %s\n", device);
		close(fd);
		exit(0);
	}

	if (kdhl.panicstring[0])
		syslog(LOG_ALERT, "reboot after panic: %s", kdhl.panicstring);
	else
		syslog(LOG_ALERT, "reboot");

	if (verbose)
		printf("Checking for available free space\n");
	if (!check_space(savedir, dumpsize)) {
		nerr++;
		goto closefd;
	}

	writebounds(bounds + 1);

	/*
	 * Write kernel file.
	 */
	fdkernin = open(getbootfile(), O_RDONLY, 0);
	if (fdkernin < 0) {
		syslog(LOG_ERR, "%s: %m", getbootfile());
	}

	if (compress) {
		sprintf(buf, "kern.%d.gz", bounds);
		fpkern = zopen(buf, "w");
	} else {
		sprintf(buf, "kern.%d", bounds);
		fpkern = fopen(buf, "w");
	}
	if (fpkern == NULL) {
		syslog(LOG_ERR, "%s: %m", buf);
		close(fdkernin);
	}

	syslog(LOG_NOTICE, "writing %skernel to %s",
	    compress ? "compressed " : "", buf);

	while ((nr = read(fdkernin, buf, BUFFERSIZE)) > 0) {
		nw = fwrite(buf, 1, nr, fpkern);
		if (nw != nr) {
			syslog(LOG_ERR, "kern.%d: %m", bounds);
			syslog(LOG_WARNING,
			    "WARNING: kernel may be incomplete");
			exit(1);
		}
	}
	if (nr < 0) {
		syslog(LOG_ERR, "%s: %m", getbootfile());
		syslog(LOG_WARNING,
		    "WARNING: kernel may be incomplete");
		exit(1);
	}
	fclose(fpkern);
	close(fdkernin);


	sprintf(buf, "info.%d", bounds);

	/*
	 * Create or overwrite any existing dump header files.
	 */
	fdinfo = open(buf, O_WRONLY | O_CREAT | O_TRUNC, 0600);
	if (fdinfo < 0) {
		syslog(LOG_ERR, "%s: %m", buf);
		nerr++;
		goto closefd;
	}
	oumask = umask(S_IRWXG|S_IRWXO); /* Restrict access to the core file.*/
	if (compress) {
		sprintf(buf, "vmcore.%d.gz", bounds);
		fp = zopen(buf, "w");
	} else {
		sprintf(buf, "vmcore.%d", bounds);
		fp = fopen(buf, "w");
	}
	if (fp == NULL) {
		syslog(LOG_ERR, "%s: %m", buf);
		close(fdinfo);
		nerr++;
		goto closefd;
	}
	(void)umask(oumask);

	info = fdopen(fdinfo, "w");

	if (info == NULL) {
		syslog(LOG_ERR, "fdopen failed: %m");
		nerr++;
		goto closefd;
	}

	if (verbose)
		printheader(stdout, &kdhl, device, bounds, status);

	printheader(info, &kdhl, device, bounds, status);
	fclose(info);

	syslog(LOG_NOTICE, "writing %score to %s",
	    compress ? "compressed " : "", buf);

	while (dumpsize > 0) {
		wl = BUFFERSIZE;
		if (wl > dumpsize)
			wl = dumpsize;
		nr = read(fd, buf, wl);
		if (nr != wl) {
			if (nr == 0)
				syslog(LOG_WARNING,
				    "WARNING: EOF on dump device");
			else
				syslog(LOG_ERR, "read error on %s: %m", device);
			nerr++;
			goto closeall;
		}
		if (compress) {
			nw = fwrite(buf, 1, wl, fp);
		} else {
			for (nw = 0; nw < nr; nw = he) {
				/* find a contiguous block of zeroes */
				for (hs = nw; hs < nr; hs += BLOCKSIZE) {
					for (he = hs; he < nr && buf[he] == 0;
					    ++he)
						/* nothing */ ;
					/* is the hole long enough to matter? */
					if (he >= hs + BLOCKSIZE)
						break;
				}

				/* back down to a block boundary */
				he &= BLOCKMASK;

				/*
				 * 1) Don't go beyond the end of the buffer.
				 * 2) If the end of the buffer is less than
				 *    BLOCKSIZE bytes away, we're at the end
				 *    of the file, so just grab what's left.
				 */
				if (hs + BLOCKSIZE > nr)
					hs = he = nr;

				/*
				 * At this point, we have a partial ordering:
				 *     nw <= hs <= he <= nr
				 * If hs > nw, buf[nw..hs] contains non-zero data.
				 * If he > hs, buf[hs..he] is all zeroes.
				 */
				if (hs > nw)
					if (fwrite(buf + nw, hs - nw, 1, fp)
					    != 1)
					break;
				if (he > hs)
					if (fseeko(fp, he - hs, SEEK_CUR) == -1)
						break;
			}
		}
		if (nw != wl) {
			syslog(LOG_ERR,
			    "write error on vmcore.%d file: %m", bounds);
			syslog(LOG_WARNING,
			    "WARNING: vmcore may be incomplete");
			nerr++;
			goto closeall;
		}
		if (verbose) {
			dmpcnt += wl;
			printf("%llu\r", (unsigned long long)dmpcnt);
			fflush(stdout);
		}
		dumpsize -= wl;
	}
	if (verbose)
		printf("\n");

	if (fclose(fp) < 0) {
		syslog(LOG_ERR, "error on vmcore.%d: %m", bounds);
		nerr++;
		goto closeall;
	}
	nsaved++;

	if (verbose)
		printf("dump saved\n");

nuke:
	if (clear || !keep) {
		if (verbose)
			printf("clearing dump header\n");
		memcpy(kdhl.magic, KERNELDUMPMAGIC_CLEARED, sizeof kdhl.magic);
		lseek(fd, lasthd, SEEK_SET);
		error = write(fd, &kdhl, sizeof kdhl);
		if (error != sizeof kdhl)
			syslog(LOG_ERR,
			    "error while clearing the dump header: %m");
	}
	close(fd);
	return;

closeall:
	fclose(fp);

closefd:
	close(fd);
}
Ejemplo n.º 8
0
void UI_FINO2EDFwindow::SelectFileButton()
{
    FILE *inputfile=NULL,
          *outputfile=NULL;

    int i, j, k, p,
        temp,
        separator=';',
        edfsignals=0,
        ok,
        timestep,
        new_smpl_time=0,
        datarecords,
        str_start,
        column,
        line_nr;

    char txt_string[2048],
         path[512],
         outputfilename[MAX_PATH_LENGTH],
         line[2048],
         scratchpad[128],
         labels[MAX_SIGNALS][17],
         phys_dim[MAX_SIGNALS][9],
         phys_min[MAX_SIGNALS][9],
         phys_max[MAX_SIGNALS][9],
         patientname[81],
         recording[81],
         datetime[17];


    double sensitivity[MAX_SIGNALS],
           new_value[MAX_SIGNALS],
           old_value[MAX_SIGNALS];

    union {
        short two;
        char one[2];
    } var;



    for(j=0; j<MAX_SIGNALS; j++)
    {
        old_value[j] = 0.0;
    }

    enable_widgets(FALSE);

    if(!(strlen(PatientnameLineEdit->text().toLatin1().data())))
    {
        QMessageBox messagewindow(QMessageBox::Critical, "Invalid input", "Please enter a subjectname.");
        messagewindow.exec();
        enable_widgets(TRUE);
        return;
    }

    if(!(strlen(RecordingLineEdit->text().toLatin1().data())))
    {
        QMessageBox messagewindow(QMessageBox::Critical, "Invalid input", "Please enter a recordingdescription.");
        messagewindow.exec();
        enable_widgets(TRUE);
        return;
    }

    strcpy(path, QFileDialog::getOpenFileName(0, "Select inputfile", QString::fromLocal8Bit(recent_opendir), "Text files (*.txt *.TXT)").toLocal8Bit().data());

    if(!strcmp(path, ""))
    {
        enable_widgets(TRUE);
        return;
    }

    get_directory_from_path(recent_opendir, path, MAX_PATH_LENGTH);

    inputfile = fopeno(path, "rb");
    if(inputfile==NULL)
    {
        snprintf(txt_string, 2048, "Can not open file %s for reading.", path);
        QMessageBox messagewindow(QMessageBox::Critical, "Error", txt_string);
        messagewindow.exec();
        enable_widgets(TRUE);
        return;
    }

    /***************** check if the txtfile is valid ******************************/

    rewind(inputfile);

    if(fread(scratchpad, 5, 1, inputfile)!=1)
    {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while reading the inputfile.");
        messagewindow.exec();
        fclose(inputfile);
        enable_widgets(TRUE);
        return;
    }

    if(strncmp(scratchpad, "\"T\";", 4))
    {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "Unknown data in file (1).");
        messagewindow.exec();
        fclose(inputfile);
        enable_widgets(TRUE);
        return;
    }

    while(1)
    {
        temp = fgetc(inputfile);

        if(temp==EOF)
        {
            QMessageBox messagewindow(QMessageBox::Critical, "Error", "Reached end of file unexpectedly (2).");
            messagewindow.exec();
            fclose(inputfile);
            enable_widgets(TRUE);
            return;
        }

        if(temp=='\n')  break;
    }

    if(fread(scratchpad, 2, 1, inputfile)!=1)
    {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while reading inputfile (3).");
        messagewindow.exec();
        fclose(inputfile);
        enable_widgets(TRUE);
        return;
    }

    if(strncmp(scratchpad, "\"s\";", 4))
    {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "Unknown data in file (4).");
        messagewindow.exec();
        fclose(inputfile);
        enable_widgets(TRUE);
        return;
    }

    /***************** collect items *****************************************/

    rewind(inputfile);

    while(1)
    {
        temp = fgetc(inputfile);

        if(temp==EOF)
        {
            QMessageBox messagewindow(QMessageBox::Critical, "Error", "Reached end of file unexpectedly (5).");
            messagewindow.exec();
            fclose(inputfile);
            enable_widgets(TRUE);
            return;
        }

        if(temp==separator)
        {
            break;
        }
    }

    i = 0;

    while(temp!='\n')
    {
        temp = fgetc(inputfile);

        if(temp==EOF)
        {
            QMessageBox messagewindow(QMessageBox::Critical, "Error", "Reached end of file unexpectedly (6).");
            messagewindow.exec();
            fclose(inputfile);
            enable_widgets(TRUE);
            return;
        }

        if(temp=='\r')
        {
            continue;
        }

        if((temp==separator)||(temp=='\n'))
        {
            if(edfsignals>=MAX_SIGNALS)
            {
                QMessageBox messagewindow(QMessageBox::Critical, "Error", "Too many labels/signals (7).");
                messagewindow.exec();
                fclose(inputfile);
                enable_widgets(TRUE);
                return;
            }

            line[i] = 0;

            ok = 0;

            if(!strcmp(line, "\" reSYS\""))
            {
                strcpy(labels[edfsignals], "reSYS           ");
                strcpy(phys_dim[edfsignals], "mmHg    ");
                strcpy(phys_min[edfsignals], "-1024   ");
                strcpy(phys_max[edfsignals], "1024    ");
                sensitivity[edfsignals] = 31.0;
                ok = 1;
            }

            if(!strcmp(line, "\" fiSYS\""))
            {
                strcpy(labels[edfsignals], "fiSYS           ");
                strcpy(phys_dim[edfsignals], "mmHg    ");
                strcpy(phys_min[edfsignals], "-1024   ");
                strcpy(phys_max[edfsignals], "1024    ");
                sensitivity[edfsignals] = 31.0;
                ok = 1;
            }

            if(!strcmp(line, "\" reDIA\""))
            {
                strcpy(labels[edfsignals], "reDIA           ");
                strcpy(phys_dim[edfsignals], "mmHg    ");
                strcpy(phys_min[edfsignals], "-1024   ");
                strcpy(phys_max[edfsignals], "1024    ");
                sensitivity[edfsignals] = 31.0;
                ok = 1;
            }

            if(!strcmp(line, "\" fiDIA\""))
            {
                strcpy(labels[edfsignals], "fiDIA           ");
                strcpy(phys_dim[edfsignals], "mmHg    ");
                strcpy(phys_min[edfsignals], "-1024   ");
                strcpy(phys_max[edfsignals], "1024    ");
                sensitivity[edfsignals] = 31.0;
                ok = 1;
            }

            if(!strcmp(line, "\" reMAP\""))
            {
                strcpy(labels[edfsignals], "reMAP           ");
                strcpy(phys_dim[edfsignals], "mmHg    ");
                strcpy(phys_min[edfsignals], "-1024   ");
                strcpy(phys_max[edfsignals], "1024    ");
                sensitivity[edfsignals] = 31.0;
                ok = 1;
            }

            if(!strcmp(line, "\" fiMAP\""))
            {
                strcpy(labels[edfsignals], "fiMAP           ");
                strcpy(phys_dim[edfsignals], "mmHg    ");
                strcpy(phys_min[edfsignals], "-1024   ");
                strcpy(phys_max[edfsignals], "1024    ");
                sensitivity[edfsignals] = 31.0;
                ok = 1;
            }

            if(!strcmp(line, "\"  HR\""))
            {
                strcpy(labels[edfsignals], "HR              ");
                strcpy(phys_dim[edfsignals], "bpm     ");
                strcpy(phys_min[edfsignals], "-1024   ");
                strcpy(phys_max[edfsignals], "1024    ");
                sensitivity[edfsignals] = 31.0;
                ok = 1;
            }

            if(!strcmp(line, "\"   IBI\""))
            {
                strcpy(labels[edfsignals], "IBI             ");
                strcpy(phys_dim[edfsignals], "s       ");
                strcpy(phys_min[edfsignals], "-31.744 ");
                strcpy(phys_max[edfsignals], "31.744  ");
                sensitivity[edfsignals] = 1000.0;
                ok = 1;
            }

            if(!strcmp(line, "\"  SV\""))
            {
                strcpy(labels[edfsignals], "SV              ");
                strcpy(phys_dim[edfsignals], "ml      ");
                strcpy(phys_min[edfsignals], "-1024   ");
                strcpy(phys_max[edfsignals], "1024    ");
                sensitivity[edfsignals] = 31.0;
                ok = 1;
            }

            if(!strcmp(line, "\"    CO\""))
            {
                strcpy(labels[edfsignals], "CO              ");
                strcpy(phys_dim[edfsignals], "lpm     ");
                strcpy(phys_min[edfsignals], "-1024   ");
                strcpy(phys_max[edfsignals], "1024    ");
                sensitivity[edfsignals] = 31.0;
                ok = 1;
            }

            if(!strcmp(line, "\"   EJT\""))
            {
                strcpy(labels[edfsignals], "EJT             ");
                strcpy(phys_dim[edfsignals], "s       ");
                strcpy(phys_min[edfsignals], "-1024   ");
                strcpy(phys_max[edfsignals], "1024    ");
                sensitivity[edfsignals] = 31.0;
                ok = 1;
            }

            if(!strcmp(line, "\"    TPR\""))
            {
                strcpy(labels[edfsignals], "TPR             ");
                strcpy(phys_dim[edfsignals], "MU      ");
                strcpy(phys_min[edfsignals], "-1024   ");
                strcpy(phys_max[edfsignals], "1024    ");
                sensitivity[edfsignals] = 31.0;
                ok = 1;
            }

            if(!strcmp(line, "\" Artifact\""))
            {
                strcpy(labels[edfsignals], "Artifact        ");
                strcpy(phys_dim[edfsignals], "_TPSROD2");
                strcpy(phys_min[edfsignals], "0       ");
                strcpy(phys_max[edfsignals], "10000000");
                sensitivity[edfsignals] = 0.0063488;
                ok = 1;
            }

            if(!strcmp(line, "\" Zao\""))
            {
                strcpy(labels[edfsignals], "Zao             ");
                strcpy(phys_dim[edfsignals], "mMU     ");
                strcpy(phys_min[edfsignals], "-1024   ");
                strcpy(phys_max[edfsignals], "1024    ");
                sensitivity[edfsignals] = 31.0;
                ok = 1;
            }

            if(!strcmp(line, "\"   Cwk\""))
            {
                strcpy(labels[edfsignals], "Cwk             ");
                strcpy(phys_dim[edfsignals], "MU      ");
                strcpy(phys_min[edfsignals], "-1024   ");
                strcpy(phys_max[edfsignals], "1024    ");
                sensitivity[edfsignals] = 31.0;
                ok = 1;
            }

            if(!strcmp(line, "\" Height\""))
            {
                strcpy(labels[edfsignals], "Height          ");
                strcpy(phys_dim[edfsignals], "mmHg    ");
                strcpy(phys_min[edfsignals], "-1024   ");
                strcpy(phys_max[edfsignals], "1024    ");
                sensitivity[edfsignals] = 31.0;
                ok = 1;
            }

            if(!ok)
            {
                snprintf(txt_string, 2048, "Found unknown label/signal: %s", line);
                QMessageBox messagewindow(QMessageBox::Critical, "Error", txt_string);
                messagewindow.exec();
                fclose(inputfile);
                enable_widgets(TRUE);
                return;
            }

            edfsignals++;

            i = 0;
        }

        if(temp==separator)
        {
            continue;
        }

        line[i++] = temp;
    }

    if(!edfsignals)
    {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "There are no labels/signals.");
        messagewindow.exec();
        fclose(inputfile);
        enable_widgets(TRUE);
        return;
    }

    p = sprintf(patientname, "%s", PatientnameLineEdit->text().toLatin1().data());
    latin1_to_ascii(patientname, p);
    for( ; p<80; p++)
    {
        patientname[p] = ' ';
    }
    patientname[80] = 0;

    p = sprintf(recording, "%s", RecordingLineEdit->text().toLatin1().data());
    latin1_to_ascii(recording, p);
    for( ; p<80; p++)
    {
        recording[p] = ' ';
    }
    recording[80] = 0;

    sprintf(datetime,
            "%02i.%02i.%02i%02i.%02i.%02i",
            StartDatetimeedit->date().day(),
            StartDatetimeedit->date().month(),
            StartDatetimeedit->date().year() % 100,
            StartDatetimeedit->time().hour(),
            StartDatetimeedit->time().minute(),
            StartDatetimeedit->time().second());
    datetime[16] = 0;


    /***************** write header *****************************************/

    get_filename_from_path(outputfilename, path, MAX_PATH_LENGTH);
    remove_extension_from_filename(outputfilename);
    strcat(outputfilename, "_finometer.edf");

    path[0] = 0;
    if(recent_savedir[0]!=0)
    {
        strcpy(path, recent_savedir);
        strcat(path, "/");
    }
    strcat(path, outputfilename);

    strcpy(path, QFileDialog::getSaveFileName(0, "Output file", QString::fromLocal8Bit(path), "EDF files (*.edf *.EDF)").toLocal8Bit().data());

    if(!strcmp(path, ""))
    {
        enable_widgets(TRUE);
        fclose(inputfile);
        return;
    }

    get_directory_from_path(recent_savedir, path, MAX_PATH_LENGTH);

    outputfile = fopeno(path, "wb");
    if(outputfile==NULL)
    {
        snprintf(txt_string, 2048, "Can not open file %s for writing.", path);
        QMessageBox messagewindow(QMessageBox::Critical, "Error", txt_string);
        messagewindow.exec();
        enable_widgets(TRUE);
        fclose(inputfile);
        return;
    }

    fprintf(outputfile, "0       ");
    fprintf(outputfile, "%s", patientname);
    fprintf(outputfile, "%s", recording);
    fprintf(outputfile, "%s", datetime);
    fprintf(outputfile, "%-8i", 256 * edfsignals + 256);
    fprintf(outputfile, "                                            ");
    fprintf(outputfile, "-1      ");
    fprintf(outputfile, "0.01    ");
    fprintf(outputfile, "%-4i", edfsignals);

    for(i=0; i<edfsignals; i++)
    {
        fprintf(outputfile, "%s", labels[i]);
    }

    for(i=0; i<(80*edfsignals); i++)
    {
        fputc(' ', outputfile);
    }

    for(i=0; i<edfsignals; i++)
    {
        fprintf(outputfile, "%s", phys_dim[i]);
    }

    for(i=0; i<edfsignals; i++)
    {
        fprintf(outputfile, "%s", phys_min[i]);
    }

    for(i=0; i<edfsignals; i++)
    {
        fprintf(outputfile, "%s", phys_max[i]);
    }

    for(i=0; i<edfsignals; i++)
    {
        fprintf(outputfile, "-31744  ");
    }

    for(i=0; i<edfsignals; i++)
    {
        fprintf(outputfile, "31744   ");
    }

    for(i=0; i<(80*edfsignals); i++)
    {
        fputc(' ', outputfile);
    }

    for(i=0; i<edfsignals; i++)
    {
        fprintf(outputfile, "1       ");
    }

    for(i=0; i<(32*edfsignals); i++)
    {
        fputc(' ', outputfile);
    }

    /***************** start conversion **************************************/

    rewind(inputfile);

    for(i=0; ; )
    {
        temp = fgetc(inputfile);

        if(temp==EOF)
        {
            QMessageBox messagewindow(QMessageBox::Critical, "Error", "Reached end of file unexpectedly (8).");
            messagewindow.exec();
            fclose(inputfile);
            fclose(outputfile);
            enable_widgets(TRUE);
            return;
        }

        if(temp=='\n')  i++;

        if(i>1)  break;
    }

    QApplication::setOverrideCursor(Qt::WaitCursor);

    for(k=0; k<10; k++)  qApp->processEvents();

    i = 0;

    column = 0;

    datarecords = 0;

    str_start = 0;

    line_nr = 2;

    while(1)
    {
        temp = fgetc(inputfile);

        if(temp==EOF)
        {
            for(k=0; k<edfsignals; k++)
            {
                temp = (int)(new_value[k] * sensitivity[k]);

                if(temp>31744)  temp = 31744;

                if(temp<-31744)  temp = -31744;

                var.two = (short)temp;

                fputc(var.one[0], outputfile);
                fputc(var.one[1], outputfile);
            }

            datarecords++;

            break;
        }

        line[i] = temp;

        /**************************************/

        if(line[i]==',')
        {
            line[i] = '.';
        }

        if((line[i]==separator)||(line[i]=='\n'))
        {
            if(column)
            {
                new_value[column-1] = atof(line + str_start);
            }
            else
            {
                new_smpl_time = (int)(atof(line + str_start) * 100.0);
            }

            if(line[i]=='\n')
            {
                /**************************************/

                line_nr++;

                if(column!=edfsignals)
                {
                    QApplication::restoreOverrideCursor();
                    snprintf(txt_string, 2048, "Number of separators in line %i is wrong.", line_nr);
                    QMessageBox messagewindow(QMessageBox::Critical, "Error", txt_string);
                    messagewindow.exec();
                    fclose(inputfile);
                    fclose(outputfile);
                    enable_widgets(TRUE);
                    return;
                }

                timestep = new_smpl_time - datarecords;

                if(timestep<=0)
                {
                    QApplication::restoreOverrideCursor();
                    snprintf(txt_string, 2048, "Timestep <= 0 in line %i.", line_nr);
                    QMessageBox messagewindow(QMessageBox::Critical, "Error", txt_string);
                    messagewindow.exec();
                    fclose(inputfile);
                    fclose(outputfile);
                    enable_widgets(TRUE);
                    return;
                }

                for(j=0; j<timestep; j++)
                {
                    for(k=0; k<edfsignals; k++)
                    {
                        temp = (int)((old_value[k] + ((new_value[k] - old_value[k]) * ((double)j / (double)timestep))) * sensitivity[k]);

                        if(temp>31744)  temp = 31744;

                        if(temp<-31744)  temp = -31744;

                        var.two = (short)temp;

                        fputc(var.one[0], outputfile);
                        fputc(var.one[1], outputfile);
                    }

                    datarecords++;
                }

                for(j=0; j<edfsignals; j++)
                {
                    old_value[j] = new_value[j];
                }

                /**************************************/

                str_start = 0;

                i = 0;

                column = 0;

                continue;
            }

            str_start = i + 1;

            column++;
        }

        /**************************************/

        i++;

        if(i>2046)
        {
            QApplication::restoreOverrideCursor();
            snprintf(txt_string, 2048, "Line %i is too long.", line_nr);
            QMessageBox messagewindow(QMessageBox::Critical, "Error", txt_string);
            messagewindow.exec();
            fclose(inputfile);
            fclose(outputfile);
            enable_widgets(TRUE);
            return;
        }
    }

    QApplication::restoreOverrideCursor();

    fseeko(outputfile, 236LL, SEEK_SET);

    fprintf(outputfile, "%-8i", datarecords);

    if(fclose(outputfile))
    {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while closing outputfile.");
        messagewindow.exec();
        enable_widgets(TRUE);
        fclose(inputfile);
        return;
    }

    if(fclose(inputfile))
    {
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while closing inputfile.");
        messagewindow.exec();
    }

    snprintf(txt_string, 2048, "Done, EDF file is located at %s", path);
    QMessageBox messagewindow(QMessageBox::Information, "Ready", txt_string);
    messagewindow.setIconPixmap(QPixmap(":/images/ok.png"));
    messagewindow.exec();

    enable_widgets(TRUE);
}
Ejemplo n.º 9
0
int FilteredBlockReadClass::process_signalcomp(int datarecord_start)
{
  int j, k, s,
      temp=0;

  double dig_value=0.0;

  union {
          unsigned int one;
          signed int one_signed;
          unsigned short two[2];
          signed short two_signed[2];
          unsigned char four[4];
        } var;


  if((total_samples < 1) || (datarecord_cnt < 1))
  {
    return(-1);
  }

  if((datarecord_start < 0) || (datarecord_start >= hdr->datarecords))
  {
    return(-1);
  }

  if(datarecord_cnt > (hdr->datarecords - datarecord_start))
  {
    return(-1);
  }

  if(fseeko(inputfile, ((long long)hdr->hdrsize) + (((long long)datarecord_start) * ((long long) hdr->recordsize)), SEEK_SET) == -1LL)
  {
    return(-1);
  }

  if(fread(readbuf, hdr->recordsize * datarecord_cnt, 1, inputfile) != 1)
  {
    return(-1);
  }

  if((readbuf == NULL) || (processed_samples_buf == NULL))
  {
    return(-1);
  }

  for(s=0; s<total_samples; s++)
  {
    dig_value = 0.0;

    for(j=0; j<signalcomp->num_of_signals; j++)
    {
      if(signalcomp->edfhdr->bdf)
      {
        var.two[0] = *((unsigned short *)(
          readbuf
          + (signalcomp->edfhdr->recordsize * (s / samples_per_datrec))
          + signalcomp->edfhdr->edfparam[signalcomp->edfsignal[j]].buf_offset
          + ((s % samples_per_datrec) * 3)));

        var.four[2] = *((unsigned char *)(
          readbuf
          + (signalcomp->edfhdr->recordsize * (s / samples_per_datrec))
          + signalcomp->edfhdr->edfparam[signalcomp->edfsignal[j]].buf_offset
          + ((s % samples_per_datrec) * 3)
          + 2));

        if(var.four[2]&0x80)
        {
          var.four[3] = 0xff;
        }
        else
        {
          var.four[3] = 0x00;
        }

        temp = var.one_signed;
      }

      if(signalcomp->edfhdr->edf)
      {
        temp = *(((short *)(
          readbuf
          + (signalcomp->edfhdr->recordsize * (s / samples_per_datrec))
          + signalcomp->edfhdr->edfparam[signalcomp->edfsignal[j]].buf_offset))
          + (s % samples_per_datrec));
      }

      temp += signalcomp->edfhdr->edfparam[signalcomp->edfsignal[j]].offset;
      temp *= signalcomp->factor[j];

      dig_value += temp;
    }

    if(!skip_filters)
    {
      for(k=0; k<signalcomp->filter_cnt; k++)
      {
        dig_value = first_order_filter(dig_value, signalcomp->filter[k]);
      }

      for(k=0; k<signalcomp->ravg_filter_cnt; k++)
      {
        dig_value = run_ravg_filter(dig_value, signalcomp->ravg_filter[k]);
      }

      for(k=0; k<signalcomp->fidfilter_cnt; k++)
      {
        dig_value = signalcomp->fidfuncp[k](signalcomp->fidbuf[k], dig_value);
      }

      if(signalcomp->ecg_filter != NULL)
      {
        dig_value = run_ecg_filter(dig_value, signalcomp->ecg_filter);
      }
    }

    processed_samples_buf[s] = (dig_value * bitvalue);
  }

  return(0);
}
Ejemplo n.º 10
0
static void
gfrsub(FILE *infile)
{
	off_t frompos;
	int count;

	seensubj = seenfrom = NO;
	local = YES;
	subj[0] = from[0] = date[0] = '\0';

	/*
	 * Is this a normal message?
	 */
	if (fgets(inbuf, sizeof inbuf, infile)) {
		if (strncmp(inbuf, "From", 4)==0) {
			/*
			 * expected form starts with From
			 */
			seenfrom = YES;
			frompos = ftello(infile);
			ptr = from;
			in = nxtfld(inbuf);
			if (*in) {
				count = sizeof(from) - 1;
				while (*in && *in > ' ' && count-- > 0) {
					if (*in == ':' || *in == '@' ||
					    *in == '!')
						local = NO;
					*ptr++ = *in++;
				}
			}
			*ptr = '\0';
			if (*(in = nxtfld(in)))
				strncpy(date, in, sizeof date);
			else {
				date[0] = '\n';
				date[1] = '\0';
			}
		}
		else {
			/*
			 * not the expected form
			 */
			rewind(infile);
			return;
		}
	}
	else
		/*
		 * empty file ?
		 */
		return;

	/*
	 * look for Subject line until EOF or a blank line
	 */
	while (fgets(inbuf, sizeof inbuf, infile)
	    && !(blankline = (inbuf[0] == '\n'))) {
		/*
		 * extract Subject line
		 */
		if (!seensubj && strncmp(inbuf, "Subj", 4)==0) {
			seensubj = YES;
			frompos = ftello(infile);
			strncpy(subj, nxtfld(inbuf), sizeof subj);
		}
	}
	if (!blankline)
		/*
		 * ran into EOF
		 */
		fseeko(infile, frompos, SEEK_SET);

	if (!seensubj)
		/*
		 * for possible use with Mail
		 */
		strncpy(subj, "(No Subject)\n", sizeof subj);
}
Ejemplo n.º 11
0
/**
        \fn    dmx_indexer
        \brief Create index file    
        @param mpeg Name of the file to index
        @param file Name of the index file to create
        @param preferedAudio Default audio track
        @param nbTracks # of tracks, including video
        @param tracks track descriptor
        @return 1 on success, 0 on failure

    The incoming file can be mpeg PS/TS/ES or ASF.
    The payload can be mostly mpeg2, with some work done to support later mpeg4/H264 in TS mostly

*/
uint8_t dmx_indexer(const char *mpeg,const char *file,uint32_t preferedAudio,uint8_t autosync,uint32_t nbTracks,MPEG_TRACK *tracks)
{
        DIA_progressIndexing *work;
        dmx_demuxer *demuxer;

        char *realname=PathCanonize(mpeg);
        FILE *out;        
        DMX_TYPE mpegType;
        uint8_t  mpegTypeChar;
        uint32_t multi=0;
        
        dmx_payloadType payloadType=DMX_PAYLOAD_MPEG2;
        


        mpegType=dmxIdentify(realname);

        if(mpegType==DMX_MPG_UNKNOWN)
        {
                delete [] realname;
                return 0;
        }

     

        switch(mpegType)
        {
               case DMX_MPG_MSDVR:
                                {
                                  dmx_demuxerMSDVR *dmx;
                                  dmx=new dmx_demuxerMSDVR(nbTracks,tracks,0);
                                  demuxer=dmx;
                                  mpegTypeChar='M';
                                  break;
                                }
                case DMX_MPG_TS:
                case DMX_MPG_TS2:
                                {
                                dmx_demuxerTS *dmx;
                                dmx=new dmx_demuxerTS(nbTracks,tracks,0,mpegType);
                                demuxer=dmx;
                                switch(mpegType)
                                {
                                  case DMX_MPG_TS :mpegTypeChar='T';break;
                                  case DMX_MPG_TS2 :mpegTypeChar='S';break;
                                  default: ADM_assert(0);
                                }
                                switch(tracks[0].streamType)
                                  {
                                    case ADM_STREAM_H264:       payloadType=DMX_PAYLOAD_H264;break;
                                    case ADM_STREAM_MPEG4:      payloadType=DMX_PAYLOAD_MPEG4;break;
                                    case ADM_STREAM_MPEG_VIDEO: payloadType=DMX_PAYLOAD_MPEG2;break;
                                  default: ADM_assert(0);
  
                                  }
                                break;
                                }
                case DMX_MPG_ES:
                                demuxer=new dmx_demuxerES;
                                mpegTypeChar='E';
                                break;
                case DMX_MPG_H264_ES:
                                payloadType=DMX_PAYLOAD_H264;
                                demuxer=new dmx_demuxerES;
                                mpegTypeChar='E';
                                break;
                case DMX_MPG_PS:
                		{
                		dmx_demuxerPS *dmx;
                                fileParser    *fp;
                                FP_TYPE       type=FP_PROBE; 
                                        fp=new fileParser;
                                        fp->open(realname,&type);
                                        delete fp;
                                        if(type==FP_APPEND)
                                        {
                                          if(GUI_Question(QT_TR_NOOP("There is several mpeg file, append them ?")))
                                                        multi=1;
                                        }
                                        dmx=new dmx_demuxerPS(nbTracks,tracks,multi);
                                        demuxer=dmx;
                                        mpegTypeChar='P';
                            }
                                break;
                default : ADM_assert(0);

        }
        
        demuxer->open(realname);

        out=qfopen(file,"wt");
        if(!out)
        {
                        printf("\n Error : cannot open index !");
                        delete demuxer;
                        delete [] realname;
                        return 0;
        }
        qfprintf(out,"ADMY0003\n");
        qfprintf(out,"Type     : %c\n",mpegTypeChar); // ES for now
        qfprintf(out,"File     : %s\n",realname);
        qfprintf(out,"Append   : %d\n",multi);
        qfprintf(out,"Image    : %c\n",'P'); // Progressive
        qfprintf(out,"Picture  : %04lu x %04lu %05lu fps\n",0,0,0); // width...
        qfprintf(out,"Payload  : %c%c%c%c\n",'M','P','E','G'); // width...
        qfprintf(out,"Nb Gop   : %08lu \n",0); // width...
        qfprintf(out,"Nb Images: %010lu \n",0); // width...
        qfprintf(out,"Nb Audio : %02lu\n",nbTracks-1); 
        qfprintf(out,"Main aud : %02lu\n",preferedAudio); 
        qfprintf(out,"Streams  : ");
        for(int s=0;s<nbTracks;s++)
        {
                if(!s){
			qfprintf(out,"V%04x:%04x ",tracks[0].pid,tracks[0].pes);
		}else{
			qfprintf(out,"A%04x:%04x ",tracks[s].pid,tracks[s].pes);                
		}
        }
        qfprintf(out,"\n");
        qfprintf(out,"# NGop NImg nbImg type:abs:rel:size ...\n"); 

        
        uint8_t  grabbing=0,seq_found=0;
        
        uint32_t total_frame=0,val;

		uint32_t originalPriority = getpriority(PRIO_PROCESS, 0);
		uint32_t priorityLevel;

		prefs->get(PRIORITY_INDEXING,&priorityLevel);
		setpriority(PRIO_PROCESS, 0, ADM_getNiceValue(priorityLevel));

        work=new DIA_progressIndexing(mpeg);

        printf("*********Indexing started (%d audio tracks)***********\n",nbTracks);
        dmx_runData run;
        
        memset(&run,0,sizeof(dmx_runData));
        
        run.totalFileSize=demuxer->getSize();
        run.demuxer=demuxer;
        run.work=work;
        run.nbTrack=nbTracks;
        run.fd=out;
        
        dmx_videoIndexer *idxer=NULL;
        
        switch(payloadType)
        {
          case DMX_PAYLOAD_MPEG2:
                  {
                            idxer=new dmx_videoIndexerMpeg2(&run);
                            break;
                  }
          case DMX_PAYLOAD_MPEG4:ADM_assert(0);
          case DMX_PAYLOAD_H264:
                            idxer=new dmx_videoIndexerH264(&run);
                            break;
          default: ADM_assert(0);
        }                
        
        idxer->run();
        idxer->cleanup();
        
        delete idxer;
        idxer=NULL;
        
              
        printf("*********Indexing Ended (%d audio tracks)***********\n",nbTracks);

         switch(run.imageAR)
         {
           case 1: 	qfprintf(out,"# Video Aspect Ratio : %s\n", "1:1" );break;
           case 2: 	qfprintf(out,"# Video Aspect Ratio : %s\n", "4:3" );break;
           case 3: 	qfprintf(out,"# Video Aspect Ratio : %s\n", "16:9" );break;
           default:
              printf("imageAR=%u\n",run.imageAR);
              GUI_Error_HIG(QT_TR_NOOP("Can't determine aspect ratio"),NULL);
	}

        /* Now update......... */
          fseeko(out,0,SEEK_SET);
        // Update if needed
        uint32_t compfps,delta=computeTimeDifference(&(run.firstStamp),&(run.lastStamp));

        delta=delta/1000; // in second
        if(delta)
        {
                 compfps= (1000*run.nbImage)/delta;    // 3 Million images should be enough, no overflow                
        }
        else
        {
                compfps=run.imageFPS;
        }

        // Detect film (i.e. NTSC with computed fps close to 24)
        if(run.imageFPS==29970 || run.imageFPS==30000)
        {
                if(compfps>23800 && compfps < 24200) run.imageFPS=23976;
        }
        // Detect interlaced vs progressive
        // If field encoded, the average fps is about twice as theoritical fps
        char type='P';
        float err;

        err=run.imageFPS*2;
        err-=compfps;
        err*=100;
        err/=run.imageFPS*2;
        if(err<0) err=-err;
        printf("%lu :%lu / %lu , %f\n",run.imageFPS,run.imageFPS*2,compfps,err);

        if(err<10) 
        {
                type='I';
                printf("Seems to be field encoded\n");
        }
        else
        {
                printf("Seems to be frame encoded\n");
        }

        // Now dump the delta PTS
        // *****************Update header*************
        qfprintf(out,"ADMY0003\n");
        qfprintf(out,"Type     : %c\n",mpegTypeChar); // ES for now
        qfprintf(out,"File     : %s\n",realname);
        qfprintf(out,"Append   : %d\n",multi);
        qfprintf(out,"Image    : %c\n",type); // Progressive
        qfprintf(out,"Picture  : %04lu x %04lu %05lu fps\n",run.imageW,run.imageH,run.imageFPS); // width...
        switch(payloadType)
        {
          case DMX_PAYLOAD_MPEG2:
                            qfprintf(out,"Payload  : MPEG\n"); // MPEG,MP_4,H264
                            break;
          case DMX_PAYLOAD_MPEG4:
                            qfprintf(out,"Payload  : MP_4\n"); // MPEG,MP_4,H264
                            break;
          case DMX_PAYLOAD_H264:
                            qfprintf(out,"Payload  : H264\n"); // MPEG,MP_4,H264
                            break;
          default: ADM_assert(0);
        }                            
        qfprintf(out,"Nb Gop   : %08lu \n",run.nbGop); // width...
        qfprintf(out,"Nb Images: %010lu \n",run.nbImage); // width...

        qfclose(out);
        delete work;  

        printf("*********Indexing stopped***********\n");
        printf("Found       :%lu gop\n",run.nbGop);
        printf("Found       :%lu image\n",run.nbImage);                
        printf("Average fps :%lu /1000 fps\n",compfps);

          delete demuxer;
          delete [] realname;

		  setpriority(PRIO_PROCESS, 0, originalPriority);

          return 1;
}
Ejemplo n.º 12
0
static void
ask(const char *prompt)
{
	char	inch;
	int	n, cmsg, fd;
	off_t	oldpos;
	FILE	*cpfrom, *cpto;

	printf("%s ", prompt);
	fflush(stdout);
	intrpflg = NO;
	(void) fgets(inbuf, sizeof inbuf, stdin);
	if ((n = strlen(inbuf)) > 0 && inbuf[n - 1] == '\n')
		inbuf[n - 1] = '\0';
	if (intrpflg)
		inbuf[0] = 'x';

	/*
	 * Handle 'mail' and 'save' here.
	 */
	if ((inch = inbuf[0]) == 's' || inch == 'm') {
		if (inbuf[1] == '-')
			cmsg = prevmsg;
		else if (isdigit(inbuf[1]))
			cmsg = atoi(&inbuf[1]);
		else
			cmsg = msg;
		snprintf(fname, sizeof(fname), "%s/%d", _PATH_MSGS, cmsg);

		oldpos = ftello(newmsg);

		cpfrom = fopen(fname, "r");
		if (!cpfrom) {
			printf("Message %d not found\n", cmsg);
			ask (prompt);
			return;
		}

		if (inch == 's') {
			in = nxtfld(inbuf);
			if (*in) {
				for (n=0; in[n] > ' '; n++) { /* sizeof fname? */
					fname[n] = in[n];
				}
				fname[n] = '\0';
			}
			else
				strcpy(fname, "Messages");
			fd = open(fname, O_RDWR|O_EXCL|O_CREAT|O_APPEND);
		}
		else {
			strcpy(fname, _PATH_TMP);
			fd = mkstemp(fname);
			if (fd != -1) {
				snprintf(cmdbuf, sizeof(cmdbuf), _PATH_MAIL,
				    fname);
				mailing = YES;
			}
		}
		if (fd == -1 || (cpto = fdopen(fd, "a")) == NULL) {
			if (fd != -1)
				close(fd);
			warn("%s", fname);
			mailing = NO;
			fseeko(newmsg, oldpos, SEEK_SET);
			ask(prompt);
			return;
		}

		while ((n = fread(inbuf, 1, sizeof inbuf, cpfrom)))
			fwrite(inbuf, 1, n, cpto);

		fclose(cpfrom);
		fclose(cpto);
		fseeko(newmsg, oldpos, SEEK_SET);/* reposition current message */
		if (inch == 's')
			printf("Message %d saved in \"%s\"\n", cmsg, fname);
		else {
			system(cmdbuf);
			unlink(fname);
			mailing = NO;
		}
		ask(prompt);
	}
}
Ejemplo n.º 13
0
/*
 * Function:  main
 * ---------------
 * - takes arguments from command line
 * - opens input and output files
 * - checks for file format (pcap, pcapng, snoop, ...)
 * - runs fixing function depending on format
 * - evaluates result
 *
 * argc:  number of cmd line args
 * argv:  array of pointers to cmd line args
 *
 * returns:  1    success (filed repaired)
 *           0    success (nothing to fix)
 *          -1    error (parameters)
 *          -2    error (cannot open input file)
 *          -3    error (cannot open output file for writing)
 *          -4    error (input file is empty)
 *          -5    error (input file is too small)
 *          -6    error (filetype is known but not supported)
 *          -11   error (not a pcap file)
 *          -12   error (unable to recover pcap file)
 *          -13   error (EOF while reading input file)
 *          -255  error (unkown)
 *
 */
int main(int argc, char *argv[]) {
  FILE *pcap, *pcap_fix;		/* input and output file */
  int option_index = 0;			/* getopt_long option index */
  int c;                        /* getopts loop counter */
  int res;                      /* return values */
  char *filename;               /* filename of input file */
  char *filebname;              /* filebasename of input file (without path) */
  char *filename_fix = NULL;    /* filename of output file */
  uint64_t bytes;		        /* read/written blocks counter */
  uint64_t filesize;	        /* file size of input pcap file in bytes */

  /* init getopt_long options struct */
  struct option long_options[] = {
    {"deep-scan", no_argument, 0, 'd'},				        /* --deep-scan == -d */
    {"pcapng", no_argument, 0, 'n'},				        /* --pcapng == -n */
    {"outfile", required_argument, 0, 'o'},		    /* --outfile == -o */
    {"data-link-type", required_argument, 0, 't'},		    /* --data-link-type == -t */
    {"verbose", no_argument, 0, 'v'},				        /* --verbose == -v */
    {0, 0, 0, 0}
  };

  /* print out pcapfix header information */
  printf("pcapfix %s (c) 2012-2014 Robert Krause\n\n", VERSION);

  /* scan for options and arguments */
  while ((c = getopt_long(argc, argv, ":t:o:v::d::n::", long_options, &option_index)) != -1) {
    switch (c) {
      case 0:	/* getopt_long options evaluation */
        break;
      case 'd':	/* deep scan */
        deep_scan++;
        break;
      case 'n':	/* pcapng format */
        pcapng++;
        break;
      case 'o':	/* output file name */
        filename_fix = malloc(strlen(optarg));
	strcpy(filename_fix, optarg);
        break;
      case 't':	/* data link type */
        data_link_type = atoi(optarg);
        break;
      case 'v':	/* verbose */
        verbose++;
        break;
      case '?': /* unknown option */
        usage(argv[0]);
        return -1;
      default:
        abort();
    }
  }

  /* filename is first argument */
  filename = argv[optind++];

  /* if filename is not set, output usage information */
  if (filename == NULL) {
    usage(argv[0]);
    return(-1);
  }

  /* open input file */
  printf("[*] Reading from file: %s\n", filename);
  pcap = fopen(filename, "rb");
  if (!pcap) {
    perror("[-] Cannot open input file");
    return(-2);
  }

  /* check for preassigned fixed file name */
  if (filename_fix == NULL) {

    /* open output file */
    /* we need to extract the basename first (windows and linux use different functions) */
    filebname = malloc(strlen(filename)+1);
    #ifdef __WIN32__
      char *fileext = malloc(strlen(filename));   /* file extention to be used in output file as well */
      _splitpath(filename, NULL, NULL, filebname, fileext);	/* windown method (_splitpath) */
      strcat(filebname, fileext);
      free(fileext);
    # else
      strcpy(filebname, basename(filename));		/* unix method (basename) */
    #endif
    filename_fix = malloc(strlen(filebname)+7);	/* size of outputfile depends on inputfile's length */

    /* prepare output file name: "fixed_" + inputfilename */
    strcpy(filename_fix, "fixed_");
    strcat(filename_fix, filebname);
    free(filebname);
  }

  /* open the file for writing */
  pcap_fix = fopen(filename_fix, "wb");
  if (!pcap_fix) {
    perror("[-] Cannot open output file for writing");
    return(-3);
  }
  printf("[*] Writing to file: %s\n", filename_fix);

  /* basic checks of input file */

  /* get file size */
  fseeko(pcap, 0, SEEK_END);
  filesize = ftello(pcap);
  printf("[*] File size: %" PRIu64 " bytes.\n", filesize);

  /* check for empty file */
  if (filesize == 0) {
    printf("[-] The source file is empty.\n\n");
    fclose(pcap);
    fclose(pcap_fix);
    remove(filename_fix);
    return(-4);
  }

  /* reset file pointer to file begin */
  fseeko(pcap, 0, SEEK_SET);

  /* read header to header magic for further inspection */
  bytes = fread(&header_magic, sizeof(header_magic), 1, pcap);
  if (bytes == 0) {
    printf("[-] Cannot read file header (file too small?).\n\n");
    fclose(pcap);
    fclose(pcap_fix);
    remove(filename_fix);
    return(-5);
  }
  fseeko(pcap, 0, SEEK_SET);

  /* check for file type */
  switch (header_magic) {

    /* etherpeek file format --> often used with pcapfix but NOT supported (yet) */
    case ETHERPEEK_MAGIC:
      printf("[-] This is a EtherPeek/AiroPeek/OmniPeek file, which is not supported.\n\n");

      /* close input and output files */
      fclose(pcap);
      fclose(pcap_fix);

      /* delete output file due to no changes failure */
      remove(filename_fix);

      return(-6);

    /* netmon file format --> often used with pcapfix but NOT supported (yet) */
    case NETMON_MAGIC:
    case NETMON11_MAGIC:
      printf("[-] This is a NetMon file, which is not supported.\n\n");

      /* close input and output files */
      fclose(pcap);
      fclose(pcap_fix);

      /* delete output file due to no changes failure */
      remove(filename_fix);

      return(-6);

    /* SNOOP file format --> often used with pcapfix but NOT supported (yet) */
    case SNOOP_MAGIC:
      printf("[-] This is a SNOOP file, which is not supported.\n\n");

      /* close input and output files */
      fclose(pcap);
      fclose(pcap_fix);

      /* delete output file due to no changes failure */
      remove(filename_fix);

      return(-6);

    case BTSNOOP_MAGIC:
      printf("[-] This is a BTSNOOP file, which is not supported.\n\n");

      /* close input and output files */
      fclose(pcap);
      fclose(pcap_fix);

      /* delete output file due to no changes failure */
      remove(filename_fix);

      return(-6);

    case PCAP_EXT_MAGIC:
    case PCAP_EXT_MAGIC_SWAPPED:
      printf("[-] This is an extended tcpdump file, which is not supported, *YET*!\n");
      printf("[*] If you need really need this filetype to be supported write a brief email to [email protected]\n\n");

      /* close input and output files */
      fclose(pcap);
      fclose(pcap_fix);

      /* delete output file due to no changes failure */
      remove(filename_fix);

      return(-6);

    /* PCAPNG format */
    case PCAPNG_MAGIC:
      printf("[+] This is a PCAPNG file.\n");
      res = fix_pcapng(pcap, pcap_fix);
      break;

    /* classic PCAP format */
    case PCAP_MAGIC:
    case PCAP_MAGIC_SWAPPED:
      printf("[+] This is a PCAP file.\n");
      if (pcapng > 0) {
        printf("[!] Your wish is my command! I will handle it as PCAPNG nevertheless.\n");
        res = fix_pcapng(pcap, pcap_fix);
      } else {
        res = fix_pcap(pcap, pcap_fix);
      }
      break;

    /* if the file type is unknown (maybe header corrupted) assume classic PCAP format */
    default:
      if (pcapng > 0) {
        printf("[*] Unknown file type. Assuming PCAPNG format.\n");
        res = fix_pcapng(pcap, pcap_fix);
      } else {
        printf("[*] Unknown file type. Assuming PCAP format.\n");
        res = fix_pcap(pcap, pcap_fix);
      }
      break;
  }

  /* evaluate result of fixing function */
  switch (res) {

    /* no corruption found; all fields were valid */
    case 0:
      printf("[*] Your pcap file looks proper. Nothing to fix!\n\n");

      /* close input and output files */
      fclose(pcap);
      fclose(pcap_fix);

      /* delete output file due to no changes failure */
      remove(filename_fix);

      return(0);

    /* there is NO indication that this has ever been a pcap file at all */
    case -1:
      printf("[-] FAILED: This file does not seem to be a pcap/pcapng file!\n\n");

      /* close input and output files */
      fclose(pcap);
      fclose(pcap_fix);

      /* delete output file due to failure */
      remove(filename_fix);

      /* deep scan dependent output */
      if (pcapng == 0) {
        if (deep_scan == 0) printf("If you are SURE that there are pcap packets inside, try with deep scan option (-d) to find them!\n\n");
        else printf("There is REALLY no pcap packet inside this file!!!\n\n");
      }

      return(res-10);

    /* it seems to be a pcap file, but pcapfix can NOT repair it (yet) */
    case -2:
      printf("[-] FAILED: Unable to recover pcap file.\n\n");

      /* some hints for verbose mode and pcapfix improvement support */
      if (!verbose) printf("Try executing pcapfix with -v option to trace the corruption!\n");
      printf("You may help to improve pcapfix by sending your pcap file to [email protected]\n\n");

      /* close input and output files */
      fclose(pcap);
      fclose(pcap_fix);

      /* delete output file due to failure */
      remove(filename_fix);

      return(res-10);

    /* fread did not succeed; might be caused by early EOF; but it should NOT happen at all */
    case -3:
      printf("[-] FAILED: EOF while reading input file.\n\n");

      /* some hints for verbose mode and pcapfix improvement support */
      if (!verbose) printf("Try executing pcapfix with -v option to trace the corruption!\n");
      printf("You may help to improve pcapfix by sending your pcap file to [email protected]\n\n");

      /* close input and output files */
      fclose(pcap);
      fclose(pcap_fix);

      /* delete output file due to failure */
      remove(filename_fix);

      return(res-10);
  }

  /* file has been progressed properly. what is the result (number of corruptions)? */

  if (res > 0) {
    /* Successful repaired! (res > 0) */

    printf("[+] SUCCESS: %d Corruption(s) fixed!\n\n", res);
    return(1);

  } else {
    /* Unknown Error (res < 0); this should NEVER happen! */

    printf("[-] UNKNOWN ERROR (%d)\n\n", res);
    printf("Please report this bug to [email protected] (including -v -v output).\n\n");
    return(-255);

  }

}
Ejemplo n.º 14
0
int main(int argc, char *argv[])
{
	FILE *f;
	char buf[36];
	foreign_metadata_t *fm;
	const char *fn, *error;
	size_t i;
	FLAC__uint32 size;

	if(argc != 2) {
		fprintf(stderr, "usage: %s { file.wav | file.aif }\n", argv[0]);
		return 1;
	}
	fn = argv[1];
	if(0 == (f = fopen(fn, "rb")) || fread(buf, 1, 4, f) != 4) {
		fprintf(stderr, "ERROR opening %s for reading\n", fn);
		return 1;
	}
	fclose(f);
	if(0 == (fm = flac__foreign_metadata_new(memcmp(buf, "RIFF", 4) && memcmp(buf, "RF64", 4)? FOREIGN_BLOCK_TYPE__AIFF : FOREIGN_BLOCK_TYPE__RIFF))) {
		fprintf(stderr, "ERROR: out of memory\n");
		return 1;
	}
	if(fm->type == FOREIGN_BLOCK_TYPE__AIFF) {
		if(!flac__foreign_metadata_read_from_aiff(fm, fn, &error)) {
			fprintf(stderr, "ERROR reading chunks from %s: %s\n", fn, error);
			return 1;
		}
	}
	else {
		if(!flac__foreign_metadata_read_from_wave(fm, fn, &error)) {
			fprintf(stderr, "ERROR reading chunks from %s: %s\n", fn, error);
			return 1;
		}
	}
	if(0 == (f = fopen(fn, "rb"))) {
		fprintf(stderr, "ERROR opening %s for reading\n", fn);
		return 1;
	}
	for(i = 0; i < fm->num_blocks; i++) {
		if(fseeko(f, fm->blocks[i].offset, SEEK_SET) < 0) {
			fprintf(stderr, "ERROR seeking in %s\n", fn);
			return 1;
		}
		if(fread(buf, 1, i==0?12:8, f) != (i==0?12:8)) {
			fprintf(stderr, "ERROR reading %s\n", fn);
			return 1;
		}
		size = unpack32_((const FLAC__byte*)buf+4, fm->type);
		printf("block:[%c%c%c%c] size=%08x=(%10u)", buf[0], buf[1], buf[2], buf[3], size, size);
		if(i == 0)
			printf(" type:[%c%c%c%c]", buf[8], buf[9], buf[10], buf[11]);
		else if(fm->type == FOREIGN_BLOCK_TYPE__AIFF && i == fm->audio_block)
			printf(" offset size=%08x=(%10u)", fm->ssnd_offset_size, fm->ssnd_offset_size);
		else if(fm->type == FOREIGN_BLOCK_TYPE__RIFF && i == 1 && !memcmp(buf, "ds64", 4)) {
			if(fread(buf+8, 1, 36-8, f) != 36-8) {
				fprintf(stderr, "ERROR reading %s\n", fn);
				return 1;
			}
#ifdef _MSC_VER
			printf(" RIFF size=%016I64x=(%I64u)", unpack64le_(buf+8), unpack64le_(buf+8));
			printf(" data size=%016I64x=(%I64u)", unpack64le_(buf+16), unpack64le_(buf+16));
			printf(" sample count=%016I64x=(%I64u)", unpack64le_(buf+24), unpack64le_(buf+24));
#else
			printf(" RIFF size=%016llx=(%llu)", unpack64le_(buf+8), unpack64le_(buf+8));
			printf(" data size=%016llx=(%llu)", unpack64le_(buf+16), unpack64le_(buf+16));
			printf(" sample count=%016llx=(%llu)", unpack64le_(buf+24), unpack64le_(buf+24));
#endif
			printf(" table size=%08x=(%u)", unpack32le_(buf+32), unpack32le_(buf+32));
		}
		printf("\n");
	}
	fclose(f);
	flac__foreign_metadata_delete(fm);
	return 0;
}
Ejemplo n.º 15
0
static FLAC__bool stream_decoder_test_respond_(FLAC__StreamDecoder *decoder, StreamDecoderClientData *dcd, FLAC__bool is_ogg)
{
	FLAC__StreamDecoderInitStatus init_status;

	if(!FLAC__stream_decoder_set_md5_checking(decoder, true))
		return die_s_("at FLAC__stream_decoder_set_md5_checking(), returned false", decoder);

	/* for FLAC__stream_encoder_init_FILE(), the FLAC__stream_encoder_finish() closes the file so we have to keep re-opening: */
	if(dcd->layer == LAYER_FILE) {
		printf("opening %sFLAC file... ", is_ogg? "Ogg ":"");
		open_test_file(dcd, is_ogg, "rb");
		if(0 == dcd->file) {
			printf("ERROR (%s)\n", strerror(errno));
			return false;
		}
		printf("OK\n");
	}

	switch(dcd->layer) {
		case LAYER_STREAM:
			printf("testing FLAC__stream_decoder_init_%sstream()... ", is_ogg? "ogg_":"");
			init_status = is_ogg?
				FLAC__stream_decoder_init_ogg_stream(decoder, stream_decoder_read_callback_, /*seek_callback=*/0, /*tell_callback=*/0, /*length_callback=*/0, /*eof_callback=*/0, stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, dcd) :
				FLAC__stream_decoder_init_stream(decoder, stream_decoder_read_callback_, /*seek_callback=*/0, /*tell_callback=*/0, /*length_callback=*/0, /*eof_callback=*/0, stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, dcd)
			;
			break;
		case LAYER_SEEKABLE_STREAM:
			printf("testing FLAC__stream_decoder_init_%sstream()... ", is_ogg? "ogg_":"");
			init_status = is_ogg?
				FLAC__stream_decoder_init_ogg_stream(decoder, stream_decoder_read_callback_, stream_decoder_seek_callback_, stream_decoder_tell_callback_, stream_decoder_length_callback_, stream_decoder_eof_callback_, stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, dcd) :
				FLAC__stream_decoder_init_stream(decoder, stream_decoder_read_callback_, stream_decoder_seek_callback_, stream_decoder_tell_callback_, stream_decoder_length_callback_, stream_decoder_eof_callback_, stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, dcd);
			break;
		case LAYER_FILE:
			printf("testing FLAC__stream_decoder_init_%sFILE()... ", is_ogg? "ogg_":"");
			init_status = is_ogg?
				FLAC__stream_decoder_init_ogg_FILE(decoder, dcd->file, stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, dcd) :
				FLAC__stream_decoder_init_FILE(decoder, dcd->file, stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, dcd);
			break;
		case LAYER_FILENAME:
			printf("testing FLAC__stream_decoder_init_%sfile()... ", is_ogg? "ogg_":"");
			init_status = is_ogg?
				FLAC__stream_decoder_init_ogg_file(decoder, flacfilename(is_ogg), stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, dcd) :
				FLAC__stream_decoder_init_file(decoder, flacfilename(is_ogg), stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, dcd);
			break;
		default:
			die_("internal error 000");
			return false;
	}
	if(init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK)
		return die_s_(0, decoder);
	printf("OK\n");

	dcd->current_metadata_number = 0;

	if(dcd->layer < LAYER_FILE && fseeko(dcd->file, 0, SEEK_SET) < 0) {
		printf("FAILED rewinding input, errno = %d\n", errno);
		return false;
	}

	printf("testing FLAC__stream_decoder_process_until_end_of_stream()... ");
	if(!FLAC__stream_decoder_process_until_end_of_stream(decoder))
		return die_s_("returned false", decoder);
	printf("OK\n");

	printf("testing FLAC__stream_decoder_finish()... ");
	if(!FLAC__stream_decoder_finish(decoder))
		return die_s_("returned false", decoder);
	printf("OK\n");

	return true;
}
Ejemplo n.º 16
0
int save_annotations(UI_Mainwindow *mainwindow, FILE *outputfile, struct edfhdrblock *hdr, struct annotationblock *annotlist)
{
  int i, j, k, n, p=0,
      new_edfsignals=0,
      signalslist[MAXSIGNALS],
      datarecords,
      annot_len,
      annot_smp_per_record,
      annot_recordsize,
      timestamp_decimals,
      timestamp_digits,
      annots_per_datrec,
      space,
      progress_steps;

  char *readbuf,
       scratchpad[256],
       *annot_buf;

  long long time;

  FILE *inputfile;

  struct annotationblock *annot;

  inputfile = hdr->file_hdl;

  for(i=0; i<hdr->edfsignals; i++)
  {
    if(!hdr->edfparam[i].annotation)
    {
      signalslist[new_edfsignals] = i;

      new_edfsignals++;
    }
  }

  datarecords = hdr->datarecords;

  time = (hdr->datarecords * hdr->long_data_record_duration) / TIME_DIMENSION;

  timestamp_decimals = get_tal_timestamp_decimal_cnt(hdr);
  if(timestamp_decimals < 0)
  {
    return(1);
  }

  timestamp_digits = get_tal_timestamp_digit_cnt(hdr);
  if(timestamp_digits < 0)
  {
    return(1);
  }

  annot = annotlist;

  annot_len = get_max_annotation_strlen(&annot);

  i = edfplus_annotation_count(&annot);

  annots_per_datrec = i / datarecords;

  if(i % datarecords)
  {
    annots_per_datrec++;
  }

  annot_recordsize = (annot_len * annots_per_datrec) + timestamp_digits + timestamp_decimals + 4;

  if(timestamp_decimals)
  {
    annot_recordsize++;
  }

  if(hdr->edf)
  {
    annot_smp_per_record = annot_recordsize / 2;

    if(annot_recordsize % annot_smp_per_record)
    {
      annot_smp_per_record++;

      annot_recordsize = annot_smp_per_record * 2;
    }
  }
  else
  {
    annot_smp_per_record = annot_recordsize / 3;

    if(annot_recordsize % annot_smp_per_record)
    {
      annot_smp_per_record++;

      annot_recordsize = annot_smp_per_record * 3;
    }
  }

  readbuf = (char *)malloc(hdr->recordsize);
  if(readbuf==NULL)
  {
    return(1);
  }

  annot_buf = (char *)malloc(annot_recordsize + 10);
  if(annot_buf==NULL)
  {
    free(readbuf);
    return(1);
  }

///////////////////////////////////////////////////////////////////

  rewind(outputfile);

  if(hdr->edf)
  {
    fprintf(outputfile, "0       ");
  }
  else
  {
    fprintf(outputfile, "XBIOSEMI");
    rewind(outputfile);
    fputc(255, outputfile);
    fseeko(outputfile, 0LL, SEEK_END);
  }
  fseeko(inputfile, 8LL, SEEK_SET);
  if((hdr->edfplus)||(hdr->bdfplus))
  {
    if(fread(scratchpad, 176, 1, inputfile)!=1)
    {
      free(readbuf);
      free(annot_buf);
      return(2);
    }

    if((hdr->genuine_nk) && (hdr->nk_triggers_read))
    {
      space = 0;

      for(n=80; n<160; n++)
      {
        if(scratchpad[n] == ' ')
        {
          space++;

          if(space > 3)
          {
            break;
          }
        }
      }

      n += 14;

      if(n<150)
      {
        if(!strncmp(scratchpad + n, "EEG", 3))
        {
          scratchpad[n] = 'e';
          scratchpad[n+1] = 'e';
          scratchpad[n+2] = 'g';
        }
      }
    }

    if(fwrite(scratchpad, 176, 1, outputfile)!=1)
    {
      free(readbuf);
      free(annot_buf);
      return(3);
    }
  }
  else
  {
    sprintf(scratchpad, "X X X X ");
    if(fread(scratchpad + 8, 80, 1, inputfile)!=1)
    {
      free(readbuf);
      free(annot_buf);
      return(2);
    }
    if(fwrite(scratchpad, 80, 1, outputfile)!=1)
    {
      free(readbuf);
      free(annot_buf);
      return(3);
    }
    sprintf(scratchpad, "Startdate X X X X ");
    if(fread(scratchpad + 18, 80, 1, inputfile)!=1)
    {
      free(readbuf);
      free(annot_buf);
      return(2);
    }
    if(fwrite(scratchpad, 80, 1, outputfile)!=1)
    {
      free(readbuf);
      free(annot_buf);
      return(3);
    }
    if(fread(scratchpad, 16, 1, inputfile)!=1)
    {
      free(readbuf);
      free(annot_buf);
      return(2);
    }
    if(fwrite(scratchpad, 16, 1, outputfile)!=1)
    {
      free(readbuf);
      free(annot_buf);
      return(3);
    }
  }
  fprintf(outputfile, "%-8i", (new_edfsignals * 256) + 512);
  if(hdr->edf)
  {
    fprintf(outputfile, "EDF+C");
  }
  else
  {
    fprintf(outputfile, "BDF+C");
  }
  for(i=0; i<39; i++)
  {
    fputc(' ', outputfile);
  }
  fprintf(outputfile, "%-8i", datarecords);
  snprintf(scratchpad, 256, "%.12f", hdr->data_record_duration);
  remove_trailing_zeros(scratchpad);
  strcat(scratchpad, "         ");
  if((!strncmp(scratchpad, "0.", 2)) && (scratchpad[8] != ' '))
  {
    scratchpad[9] = 0;
    fprintf(outputfile, "%s", scratchpad + 1);
  }
  else
  {
    scratchpad[8] = 0;
    fprintf(outputfile, "%s", scratchpad);
  }
  fprintf(outputfile, "%-4i", new_edfsignals + 1);

  for(i=0; i<new_edfsignals; i++)
  {
    fprintf(outputfile, "%s", hdr->edfparam[signalslist[i]].label);
  }
  if(hdr->edf)
  {
    fprintf(outputfile, "%s", "EDF Annotations ");
  }
  else
  {
    fprintf(outputfile, "%s", "BDF Annotations ");
  }
  for(i=0; i<new_edfsignals; i++)
  {
    fprintf(outputfile, "%s", hdr->edfparam[signalslist[i]].transducer);
  }
  for(i=0; i<80; i++)
  {
    fputc(' ', outputfile);
  }
  for(i=0; i<new_edfsignals; i++)
  {
    fprintf(outputfile, "%s", hdr->edfparam[signalslist[i]].physdimension);
  }
  for(i=0; i<8; i++)
  {
    fputc(' ', outputfile);
  }
  for(i=0; i<new_edfsignals; i++)
  {
    snprintf(scratchpad, 256, "%f", hdr->edfparam[signalslist[i]].phys_min);
    for(k=0; k<8; k++)
    {
      if(scratchpad[k]=='.')
      {
        for(j=7; j>=0; j--)
        {
          if((scratchpad[j]!='.')&&(scratchpad[j]!='0'))
          {
            break;
          }

          if(scratchpad[j]=='.')
          {
            scratchpad[j] = ' ';
            break;
          }

          scratchpad[j] = ' ';
        }
        break;
      }
      scratchpad[8] = 0;
    }
    fprintf(outputfile, "%s", scratchpad);
  }
  fprintf(outputfile, "-1      ");
  for(i=0; i<new_edfsignals; i++)
  {
    snprintf(scratchpad, 256, "%f", hdr->edfparam[signalslist[i]].phys_max);
    for(k=0; k<8; k++)
    {
      if(scratchpad[k]=='.')
      {
        for(j=7; j>=0; j--)
        {
          if((scratchpad[j]!='.')&&(scratchpad[j]!='0'))
          {
            break;
          }

          if(scratchpad[j]=='.')
          {
            scratchpad[j] = ' ';
            break;
          }

          scratchpad[j] = ' ';
        }
        break;
      }
    }
    scratchpad[8] = 0;
    fprintf(outputfile, "%s", scratchpad);
  }
  fprintf(outputfile, "1       ");
  for(i=0; i<new_edfsignals; i++)
  {
    fprintf(outputfile, "%-8i", hdr->edfparam[signalslist[i]].dig_min);
  }
  if(hdr->edf)
  {
    fprintf(outputfile, "%s", "-32768  ");
  }
  else
  {
    fprintf(outputfile, "%s", "-8388608");
  }
  for(i=0; i<new_edfsignals; i++)
  {
    fprintf(outputfile, "%-8i", hdr->edfparam[signalslist[i]].dig_max);
  }
  if(hdr->edf)
  {
    fprintf(outputfile, "%s", "32767   ");
  }
  else
  {
    fprintf(outputfile, "%s", "8388607 ");
  }
  for(i=0; i<new_edfsignals; i++)
  {
    fprintf(outputfile, "%s", hdr->edfparam[signalslist[i]].prefilter);
  }
  for(i=0; i<80; i++)
  {
    fputc(' ', outputfile);
  }
  for(i=0; i<new_edfsignals; i++)
  {
    fprintf(outputfile, "%-8i", hdr->edfparam[signalslist[i]].smp_per_record);
  }
  fprintf(outputfile, "%-8i", annot_smp_per_record);
  for(i=0; i<((new_edfsignals * 32) + 32); i++)
  {
   fputc(' ', outputfile);
  }

///////////////////////////////////////////////////////////////////

  QProgressDialog progress("Saving file...", "Abort", 0, datarecords, mainwindow);
  progress.setWindowModality(Qt::WindowModal);
  progress.setMinimumDuration(200);

  progress_steps = datarecords / 100;
  if(progress_steps < 1)
  {
    progress_steps = 1;
  }

  fseeko(inputfile, (long long)(hdr->hdrsize), SEEK_SET);

  annot = annotlist;

  time = hdr->starttime_offset;

  for(k=0; k<datarecords; k++)
  {
    if(!(k%progress_steps))
    {
      progress.setValue(k);

      qApp->processEvents();

      if(progress.wasCanceled() == true)
      {
        free(readbuf);
        free(annot_buf);
        return(4);
      }
    }

    if(fread(readbuf, hdr->recordsize, 1, inputfile) != 1)
    {
      free(readbuf);
      free(annot_buf);
      return(2);
    }

    if(hdr->edf)
    {
      for(i=0; i<new_edfsignals; i++)
      {
        for(j=0; j<hdr->edfparam[signalslist[i]].smp_per_record; j++)
        {
          fputc(*((unsigned char *)(readbuf + hdr->edfparam[signalslist[i]].buf_offset + (j * 2))), outputfile);
          fputc(*((unsigned char *)(readbuf + hdr->edfparam[signalslist[i]].buf_offset + (j * 2) + 1)), outputfile);
        }
      }
    }
    else
    {
      for(i=0; i<new_edfsignals; i++)
      {
        for(j=0; j<hdr->edfparam[signalslist[i]].smp_per_record; j++)
        {
          fputc(*((unsigned char *)(readbuf + hdr->edfparam[signalslist[i]].buf_offset + (j * 3))), outputfile);
          fputc(*((unsigned char *)(readbuf + hdr->edfparam[signalslist[i]].buf_offset + (j * 3) + 1)), outputfile);
          fputc(*((unsigned char *)(readbuf + hdr->edfparam[signalslist[i]].buf_offset + (j * 3) + 2)), outputfile);
        }
      }
    }

#ifdef Q_WS_WIN
    switch(timestamp_decimals)
    {
      case 0 : p = snprintf(annot_buf, 16, "+%I64d", time / TIME_DIMENSION);
                break;
      case 1 : p = snprintf(annot_buf, 16, "+%I64d.%01I64d", time / TIME_DIMENSION, (time % TIME_DIMENSION) / 1000000LL);
                break;
      case 2 : p = snprintf(annot_buf, 16, "+%I64d.%02I64d", time / TIME_DIMENSION, (time % TIME_DIMENSION) / 100000LL);
                break;
      case 3 : p = snprintf(annot_buf, 16, "+%I64d.%03I64d", time / TIME_DIMENSION, (time % TIME_DIMENSION) / 10000LL);
                break;
      case 4 : p = snprintf(annot_buf, 16, "+%I64d.%04I64d", time / TIME_DIMENSION, (time % TIME_DIMENSION) / 1000LL);
                break;
      case 5 : p = snprintf(annot_buf, 16, "+%I64d.%05I64d", time / TIME_DIMENSION, (time % TIME_DIMENSION) / 100LL);
                break;
      case 6 : p = snprintf(annot_buf, 16, "+%I64d.%06I64d", time / TIME_DIMENSION, (time % TIME_DIMENSION) / 10LL);
                break;
      case 7 : p = snprintf(annot_buf, 16, "+%I64d.%07I64d", time / TIME_DIMENSION, time % TIME_DIMENSION);
                break;
    }
#else
    switch(timestamp_decimals)
    {
      case 0 : p = snprintf(annot_buf, 16, "+%lli", time / TIME_DIMENSION);
                break;
      case 1 : p = snprintf(annot_buf, 16, "+%lli.%01lli", time / TIME_DIMENSION, (time % TIME_DIMENSION) / 1000000LL);
                break;
      case 2 : p = snprintf(annot_buf, 16, "+%lli.%02lli", time / TIME_DIMENSION, (time % TIME_DIMENSION) / 100000LL);
                break;
      case 3 : p = snprintf(annot_buf, 16, "+%lli.%03lli", time / TIME_DIMENSION, (time % TIME_DIMENSION) / 10000LL);
                break;
      case 4 : p = snprintf(annot_buf, 16, "+%lli.%04lli", time / TIME_DIMENSION, (time % TIME_DIMENSION) / 1000LL);
                break;
      case 5 : p = snprintf(annot_buf, 16, "+%lli.%05lli", time / TIME_DIMENSION, (time % TIME_DIMENSION) / 100LL);
                break;
      case 6 : p = snprintf(annot_buf, 16, "+%lli.%06lli", time / TIME_DIMENSION, (time % TIME_DIMENSION) / 10LL);
                break;
      case 7 : p = snprintf(annot_buf, 16, "+%lli.%07lli", time / TIME_DIMENSION, time % TIME_DIMENSION);
                break;
    }
#endif
    annot_buf[p++] = 20;
    annot_buf[p++] = 20;
    annot_buf[p++] = 0;

    if(annot!=NULL)
    {
      for(i=0; i<annots_per_datrec; i++)
      {
        if(annot!=NULL)
        {
          if(annot->onset<0)
          {
#ifdef Q_WS_WIN
            p += snprintf(annot_buf + p, 20, "-%I64d.%07I64d", -(annot->onset / TIME_DIMENSION), -(annot->onset % TIME_DIMENSION));
#else
            p += snprintf(annot_buf + p, 20, "-%lli.%07lli", -(annot->onset / TIME_DIMENSION), -(annot->onset % TIME_DIMENSION));
#endif
          }
          else
          {
#ifdef Q_WS_WIN
            p += snprintf(annot_buf + p, 20, "+%I64d.%07I64d", annot->onset / TIME_DIMENSION, annot->onset % TIME_DIMENSION);
#else
            p += snprintf(annot_buf + p, 20, "+%lli.%07lli", annot->onset / TIME_DIMENSION, annot->onset % TIME_DIMENSION);
#endif
          }

          for(j=0; j<7; j++)
          {
            if(annot_buf[p - j - 1] != '0')
            {
              break;
            }
          }

          if(j)
          {
            p -= j;

            if(j == 7)
            {
              p--;
            }
          }

          if(annot->duration[0])
          {
            annot_buf[p++] = 21;

            p += sprintf(annot_buf + p, "%s", annot->duration);
          }

          annot_buf[p++] = 20;

          p += sprintf(annot_buf + p, "%s", annot->annotation);

          annot_buf[p++] = 20;
          annot_buf[p++] = 0;

          annot = annot->next_annotation;
        }
      }
    }

    for(; p<annot_recordsize; p++)
    {
      annot_buf[p] = 0;
    }

    if(fwrite(annot_buf, annot_recordsize, 1, outputfile) != 1)
    {
      free(readbuf);
      free(annot_buf);
      return(3);
    }

    time += hdr->long_data_record_duration;
  }

  progress.reset();

  free(readbuf);
  free(annot_buf);

  return(0);
}
Ejemplo n.º 17
0
static FLAC__bool test_stream_decoder(Layer layer, FLAC__bool is_ogg)
{
	FLAC__StreamDecoder *decoder;
	FLAC__StreamDecoderInitStatus init_status;
	FLAC__StreamDecoderState state;
	StreamDecoderClientData decoder_client_data;
	FLAC__bool expect;

	decoder_client_data.layer = layer;

	printf("\n+++ libFLAC unit test: FLAC__StreamDecoder (layer: %s, format: %s)\n\n", LayerString[layer], is_ogg? "Ogg FLAC" : "FLAC");

	printf("testing FLAC__stream_decoder_new()... ");
	decoder = FLAC__stream_decoder_new();
	if(0 == decoder) {
		printf("FAILED, returned NULL\n");
		return false;
	}
	printf("OK\n");

	printf("testing FLAC__stream_decoder_delete()... ");
	FLAC__stream_decoder_delete(decoder);
	printf("OK\n");

	printf("testing FLAC__stream_decoder_new()... ");
	decoder = FLAC__stream_decoder_new();
	if(0 == decoder) {
		printf("FAILED, returned NULL\n");
		return false;
	}
	printf("OK\n");

	switch(layer) {
		case LAYER_STREAM:
		case LAYER_SEEKABLE_STREAM:
			printf("testing FLAC__stream_decoder_init_%sstream()... ", is_ogg? "ogg_":"");
			init_status = is_ogg?
				FLAC__stream_decoder_init_ogg_stream(decoder, 0, 0, 0, 0, 0, 0, 0, 0, 0) :
				FLAC__stream_decoder_init_stream(decoder, 0, 0, 0, 0, 0, 0, 0, 0, 0);
			break;
		case LAYER_FILE:
			printf("testing FLAC__stream_decoder_init_%sFILE()... ", is_ogg? "ogg_":"");
			init_status = is_ogg?
				FLAC__stream_decoder_init_ogg_FILE(decoder, stdin, 0, 0, 0, 0) :
				FLAC__stream_decoder_init_FILE(decoder, stdin, 0, 0, 0, 0);
			break;
		case LAYER_FILENAME:
			printf("testing FLAC__stream_decoder_init_%sfile()... ", is_ogg? "ogg_":"");
			init_status = is_ogg?
				FLAC__stream_decoder_init_ogg_file(decoder, flacfilename(is_ogg), 0, 0, 0, 0) :
				FLAC__stream_decoder_init_file(decoder, flacfilename(is_ogg), 0, 0, 0, 0);
			break;
		default:
			die_("internal error 003");
			return false;
	}
	if(init_status != FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS)
		return die_s_(0, decoder);
	printf("OK\n");

	printf("testing FLAC__stream_decoder_delete()... ");
	FLAC__stream_decoder_delete(decoder);
	printf("OK\n");

	num_expected_ = 0;
	expected_metadata_sequence_[num_expected_++] = &streaminfo_;

	printf("testing FLAC__stream_decoder_new()... ");
	decoder = FLAC__stream_decoder_new();
	if(0 == decoder) {
		printf("FAILED, returned NULL\n");
		return false;
	}
	printf("OK\n");

	if(is_ogg) {
		printf("testing FLAC__stream_decoder_set_ogg_serial_number()... ");
		if(!FLAC__stream_decoder_set_ogg_serial_number(decoder, file_utils__ogg_serial_number))
			return die_s_("returned false", decoder);
		printf("OK\n");
	}

	printf("testing FLAC__stream_decoder_set_md5_checking()... ");
	if(!FLAC__stream_decoder_set_md5_checking(decoder, true))
		return die_s_("returned false", decoder);
	printf("OK\n");

	if(layer < LAYER_FILENAME) {
		printf("opening %sFLAC file... ", is_ogg? "Ogg ":"");
		open_test_file(&decoder_client_data, is_ogg, "rb");
		if(0 == decoder_client_data.file) {
			printf("ERROR (%s)\n", strerror(errno));
			return false;
		}
		printf("OK\n");
	}

	switch(layer) {
		case LAYER_STREAM:
			printf("testing FLAC__stream_decoder_init_%sstream()... ", is_ogg? "ogg_":"");
			init_status = is_ogg?
				FLAC__stream_decoder_init_ogg_stream(decoder, stream_decoder_read_callback_, /*seek_callback=*/0, /*tell_callback=*/0, /*length_callback=*/0, /*eof_callback=*/0, stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, &decoder_client_data) :
				FLAC__stream_decoder_init_stream(decoder, stream_decoder_read_callback_, /*seek_callback=*/0, /*tell_callback=*/0, /*length_callback=*/0, /*eof_callback=*/0, stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, &decoder_client_data);
			break;
		case LAYER_SEEKABLE_STREAM:
			printf("testing FLAC__stream_decoder_init_%sstream()... ", is_ogg? "ogg_":"");
			init_status = is_ogg?
				FLAC__stream_decoder_init_ogg_stream(decoder, stream_decoder_read_callback_, stream_decoder_seek_callback_, stream_decoder_tell_callback_, stream_decoder_length_callback_, stream_decoder_eof_callback_, stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, &decoder_client_data) :
				FLAC__stream_decoder_init_stream(decoder, stream_decoder_read_callback_, stream_decoder_seek_callback_, stream_decoder_tell_callback_, stream_decoder_length_callback_, stream_decoder_eof_callback_, stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, &decoder_client_data);
			break;
		case LAYER_FILE:
			printf("testing FLAC__stream_decoder_init_%sFILE()... ", is_ogg? "ogg_":"");
			init_status = is_ogg?
				FLAC__stream_decoder_init_ogg_FILE(decoder, decoder_client_data.file, stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, &decoder_client_data) :
				FLAC__stream_decoder_init_FILE(decoder, decoder_client_data.file, stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, &decoder_client_data);
			break;
		case LAYER_FILENAME:
			printf("testing FLAC__stream_decoder_init_%sfile()... ", is_ogg? "ogg_":"");
			init_status = is_ogg?
				FLAC__stream_decoder_init_ogg_file(decoder, flacfilename(is_ogg), stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, &decoder_client_data) :
				FLAC__stream_decoder_init_file(decoder, flacfilename(is_ogg), stream_decoder_write_callback_, stream_decoder_metadata_callback_, stream_decoder_error_callback_, &decoder_client_data);
			break;
		default:
			die_("internal error 009");
			return false;
	}
	if(init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK)
		return die_s_(0, decoder);
	printf("OK\n");

	printf("testing FLAC__stream_decoder_get_state()... ");
	state = FLAC__stream_decoder_get_state(decoder);
	printf("returned state = %u (%s)... OK\n", state, FLAC__StreamDecoderStateString[state]);

	decoder_client_data.current_metadata_number = 0;
	decoder_client_data.ignore_errors = false;
	decoder_client_data.error_occurred = false;

	printf("testing FLAC__stream_decoder_get_md5_checking()... ");
	if(!FLAC__stream_decoder_get_md5_checking(decoder)) {
		printf("FAILED, returned false, expected true\n");
		return false;
	}
	printf("OK\n");

	printf("testing FLAC__stream_decoder_process_until_end_of_metadata()... ");
	if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder))
		return die_s_("returned false", decoder);
	printf("OK\n");

	printf("testing FLAC__stream_decoder_process_single()... ");
	if(!FLAC__stream_decoder_process_single(decoder))
		return die_s_("returned false", decoder);
	printf("OK\n");

	printf("testing FLAC__stream_decoder_skip_single_frame()... ");
	if(!FLAC__stream_decoder_skip_single_frame(decoder))
		return die_s_("returned false", decoder);
	printf("OK\n");

	if(layer < LAYER_FILE) {
		printf("testing FLAC__stream_decoder_flush()... ");
		if(!FLAC__stream_decoder_flush(decoder))
			return die_s_("returned false", decoder);
		printf("OK\n");

		decoder_client_data.ignore_errors = true;
		printf("testing FLAC__stream_decoder_process_single()... ");
		if(!FLAC__stream_decoder_process_single(decoder))
			return die_s_("returned false", decoder);
		printf("OK\n");
		decoder_client_data.ignore_errors = false;
	}

	expect = (layer != LAYER_STREAM);
	printf("testing FLAC__stream_decoder_seek_absolute()... ");
	if(FLAC__stream_decoder_seek_absolute(decoder, 0) != expect)
		return die_s_(expect? "returned false" : "returned true", decoder);
	printf("OK\n");

	printf("testing FLAC__stream_decoder_process_until_end_of_stream()... ");
	if(!FLAC__stream_decoder_process_until_end_of_stream(decoder))
		return die_s_("returned false", decoder);
	printf("OK\n");

	expect = (layer != LAYER_STREAM);
	printf("testing FLAC__stream_decoder_seek_absolute()... ");
	if(FLAC__stream_decoder_seek_absolute(decoder, 0) != expect)
		return die_s_(expect? "returned false" : "returned true", decoder);
	printf("OK\n");

	printf("testing FLAC__stream_decoder_get_channels()... ");
	{
		unsigned channels = FLAC__stream_decoder_get_channels(decoder);
		if(channels != streaminfo_.data.stream_info.channels) {
			printf("FAILED, returned %u, expected %u\n", channels, streaminfo_.data.stream_info.channels);
			return false;
		}
	}
	printf("OK\n");

	printf("testing FLAC__stream_decoder_get_bits_per_sample()... ");
	{
		unsigned bits_per_sample = FLAC__stream_decoder_get_bits_per_sample(decoder);
		if(bits_per_sample != streaminfo_.data.stream_info.bits_per_sample) {
			printf("FAILED, returned %u, expected %u\n", bits_per_sample, streaminfo_.data.stream_info.bits_per_sample);
			return false;
		}
	}
	printf("OK\n");

	printf("testing FLAC__stream_decoder_get_sample_rate()... ");
	{
		unsigned sample_rate = FLAC__stream_decoder_get_sample_rate(decoder);
		if(sample_rate != streaminfo_.data.stream_info.sample_rate) {
			printf("FAILED, returned %u, expected %u\n", sample_rate, streaminfo_.data.stream_info.sample_rate);
			return false;
		}
	}
	printf("OK\n");

	printf("testing FLAC__stream_decoder_get_blocksize()... ");
	{
		unsigned blocksize = FLAC__stream_decoder_get_blocksize(decoder);
		/* value could be anything since we're at the last block, so accept any reasonable answer */
		printf("returned %u... %s\n", blocksize, blocksize>0? "OK" : "FAILED");
		if(blocksize == 0)
			return false;
	}

	printf("testing FLAC__stream_decoder_get_channel_assignment()... ");
	{
		FLAC__ChannelAssignment ca = FLAC__stream_decoder_get_channel_assignment(decoder);
		printf("returned %u (%s)... OK\n", (unsigned)ca, FLAC__ChannelAssignmentString[ca]);
	}

	if(layer < LAYER_FILE) {
		printf("testing FLAC__stream_decoder_reset()... ");
		if(!FLAC__stream_decoder_reset(decoder)) {
			state = FLAC__stream_decoder_get_state(decoder);
			printf("FAILED, returned false, state = %u (%s)\n", state, FLAC__StreamDecoderStateString[state]);
			return false;
		}
		printf("OK\n");

		if(layer == LAYER_STREAM) {
			/* after a reset() we have to rewind the input ourselves */
			printf("rewinding input... ");
			if(fseeko(decoder_client_data.file, 0, SEEK_SET) < 0) {
				printf("FAILED, errno = %d\n", errno);
				return false;
			}
			printf("OK\n");
		}

		decoder_client_data.current_metadata_number = 0;

		printf("testing FLAC__stream_decoder_process_until_end_of_stream()... ");
		if(!FLAC__stream_decoder_process_until_end_of_stream(decoder))
			return die_s_("returned false", decoder);
		printf("OK\n");
	}

	printf("testing FLAC__stream_decoder_finish()... ");
	if(!FLAC__stream_decoder_finish(decoder))
		return die_s_("returned false", decoder);
	printf("OK\n");

	/*
	 * respond all
	 */

	printf("testing FLAC__stream_decoder_set_metadata_respond_all()... ");
	if(!FLAC__stream_decoder_set_metadata_respond_all(decoder))
		return die_s_("returned false", decoder);
	printf("OK\n");

	num_expected_ = 0;
	if(is_ogg) { /* encoder moves vorbis comment after streaminfo according to ogg mapping */
		expected_metadata_sequence_[num_expected_++] = &streaminfo_;
		expected_metadata_sequence_[num_expected_++] = &vorbiscomment_;
		expected_metadata_sequence_[num_expected_++] = &padding_;
		expected_metadata_sequence_[num_expected_++] = &seektable_;
		expected_metadata_sequence_[num_expected_++] = &application1_;
		expected_metadata_sequence_[num_expected_++] = &application2_;
		expected_metadata_sequence_[num_expected_++] = &cuesheet_;
		expected_metadata_sequence_[num_expected_++] = &picture_;
		expected_metadata_sequence_[num_expected_++] = &unknown_;
	}
	else {
		expected_metadata_sequence_[num_expected_++] = &streaminfo_;
		expected_metadata_sequence_[num_expected_++] = &padding_;
		expected_metadata_sequence_[num_expected_++] = &seektable_;
		expected_metadata_sequence_[num_expected_++] = &application1_;
		expected_metadata_sequence_[num_expected_++] = &application2_;
		expected_metadata_sequence_[num_expected_++] = &vorbiscomment_;
		expected_metadata_sequence_[num_expected_++] = &cuesheet_;
		expected_metadata_sequence_[num_expected_++] = &picture_;
		expected_metadata_sequence_[num_expected_++] = &unknown_;
	}

	if(!stream_decoder_test_respond_(decoder, &decoder_client_data, is_ogg))
		return false;

	/*
	 * ignore all
	 */

	printf("testing FLAC__stream_decoder_set_metadata_ignore_all()... ");
	if(!FLAC__stream_decoder_set_metadata_ignore_all(decoder))
		return die_s_("returned false", decoder);
	printf("OK\n");

	num_expected_ = 0;

	if(!stream_decoder_test_respond_(decoder, &decoder_client_data, is_ogg))
		return false;

	/*
	 * respond all, ignore VORBIS_COMMENT
	 */

	printf("testing FLAC__stream_decoder_set_metadata_respond_all()... ");
	if(!FLAC__stream_decoder_set_metadata_respond_all(decoder))
		return die_s_("returned false", decoder);
	printf("OK\n");

	printf("testing FLAC__stream_decoder_set_metadata_ignore(VORBIS_COMMENT)... ");
	if(!FLAC__stream_decoder_set_metadata_ignore(decoder, FLAC__METADATA_TYPE_VORBIS_COMMENT))
		return die_s_("returned false", decoder);
	printf("OK\n");

	num_expected_ = 0;
	expected_metadata_sequence_[num_expected_++] = &streaminfo_;
	expected_metadata_sequence_[num_expected_++] = &padding_;
	expected_metadata_sequence_[num_expected_++] = &seektable_;
	expected_metadata_sequence_[num_expected_++] = &application1_;
	expected_metadata_sequence_[num_expected_++] = &application2_;
	expected_metadata_sequence_[num_expected_++] = &cuesheet_;
	expected_metadata_sequence_[num_expected_++] = &picture_;
	expected_metadata_sequence_[num_expected_++] = &unknown_;

	if(!stream_decoder_test_respond_(decoder, &decoder_client_data, is_ogg))
		return false;

	/*
	 * respond all, ignore APPLICATION
	 */

	printf("testing FLAC__stream_decoder_set_metadata_respond_all()... ");
	if(!FLAC__stream_decoder_set_metadata_respond_all(decoder))
		return die_s_("returned false", decoder);
	printf("OK\n");

	printf("testing FLAC__stream_decoder_set_metadata_ignore(APPLICATION)... ");
	if(!FLAC__stream_decoder_set_metadata_ignore(decoder, FLAC__METADATA_TYPE_APPLICATION))
		return die_s_("returned false", decoder);
	printf("OK\n");

	num_expected_ = 0;
	if(is_ogg) { /* encoder moves vorbis comment after streaminfo according to ogg mapping */
		expected_metadata_sequence_[num_expected_++] = &streaminfo_;
		expected_metadata_sequence_[num_expected_++] = &vorbiscomment_;
		expected_metadata_sequence_[num_expected_++] = &padding_;
		expected_metadata_sequence_[num_expected_++] = &seektable_;
		expected_metadata_sequence_[num_expected_++] = &cuesheet_;
		expected_metadata_sequence_[num_expected_++] = &picture_;
		expected_metadata_sequence_[num_expected_++] = &unknown_;
	}
	else {
		expected_metadata_sequence_[num_expected_++] = &streaminfo_;
		expected_metadata_sequence_[num_expected_++] = &padding_;
		expected_metadata_sequence_[num_expected_++] = &seektable_;
		expected_metadata_sequence_[num_expected_++] = &vorbiscomment_;
		expected_metadata_sequence_[num_expected_++] = &cuesheet_;
		expected_metadata_sequence_[num_expected_++] = &picture_;
		expected_metadata_sequence_[num_expected_++] = &unknown_;
	}

	if(!stream_decoder_test_respond_(decoder, &decoder_client_data, is_ogg))
		return false;

	/*
	 * respond all, ignore APPLICATION id of app#1
	 */

	printf("testing FLAC__stream_decoder_set_metadata_respond_all()... ");
	if(!FLAC__stream_decoder_set_metadata_respond_all(decoder))
		return die_s_("returned false", decoder);
	printf("OK\n");

	printf("testing FLAC__stream_decoder_set_metadata_ignore_application(of app block #1)... ");
	if(!FLAC__stream_decoder_set_metadata_ignore_application(decoder, application1_.data.application.id))
		return die_s_("returned false", decoder);
	printf("OK\n");

	num_expected_ = 0;
	if(is_ogg) { /* encoder moves vorbis comment after streaminfo according to ogg mapping */
		expected_metadata_sequence_[num_expected_++] = &streaminfo_;
		expected_metadata_sequence_[num_expected_++] = &vorbiscomment_;
		expected_metadata_sequence_[num_expected_++] = &padding_;
		expected_metadata_sequence_[num_expected_++] = &seektable_;
		expected_metadata_sequence_[num_expected_++] = &application2_;
		expected_metadata_sequence_[num_expected_++] = &cuesheet_;
		expected_metadata_sequence_[num_expected_++] = &picture_;
		expected_metadata_sequence_[num_expected_++] = &unknown_;
	}
	else {
		expected_metadata_sequence_[num_expected_++] = &streaminfo_;
		expected_metadata_sequence_[num_expected_++] = &padding_;
		expected_metadata_sequence_[num_expected_++] = &seektable_;
		expected_metadata_sequence_[num_expected_++] = &application2_;
		expected_metadata_sequence_[num_expected_++] = &vorbiscomment_;
		expected_metadata_sequence_[num_expected_++] = &cuesheet_;
		expected_metadata_sequence_[num_expected_++] = &picture_;
		expected_metadata_sequence_[num_expected_++] = &unknown_;
	}

	if(!stream_decoder_test_respond_(decoder, &decoder_client_data, is_ogg))
		return false;

	/*
	 * respond all, ignore APPLICATION id of app#1 & app#2
	 */

	printf("testing FLAC__stream_decoder_set_metadata_respond_all()... ");
	if(!FLAC__stream_decoder_set_metadata_respond_all(decoder))
		return die_s_("returned false", decoder);
	printf("OK\n");

	printf("testing FLAC__stream_decoder_set_metadata_ignore_application(of app block #1)... ");
	if(!FLAC__stream_decoder_set_metadata_ignore_application(decoder, application1_.data.application.id))
		return die_s_("returned false", decoder);
	printf("OK\n");

	printf("testing FLAC__stream_decoder_set_metadata_ignore_application(of app block #2)... ");
	if(!FLAC__stream_decoder_set_metadata_ignore_application(decoder, application2_.data.application.id))
		return die_s_("returned false", decoder);
	printf("OK\n");

	num_expected_ = 0;
	if(is_ogg) { /* encoder moves vorbis comment after streaminfo according to ogg mapping */
		expected_metadata_sequence_[num_expected_++] = &streaminfo_;
		expected_metadata_sequence_[num_expected_++] = &vorbiscomment_;
		expected_metadata_sequence_[num_expected_++] = &padding_;
		expected_metadata_sequence_[num_expected_++] = &seektable_;
		expected_metadata_sequence_[num_expected_++] = &cuesheet_;
		expected_metadata_sequence_[num_expected_++] = &picture_;
		expected_metadata_sequence_[num_expected_++] = &unknown_;
	}
	else {
		expected_metadata_sequence_[num_expected_++] = &streaminfo_;
		expected_metadata_sequence_[num_expected_++] = &padding_;
		expected_metadata_sequence_[num_expected_++] = &seektable_;
		expected_metadata_sequence_[num_expected_++] = &vorbiscomment_;
		expected_metadata_sequence_[num_expected_++] = &cuesheet_;
		expected_metadata_sequence_[num_expected_++] = &picture_;
		expected_metadata_sequence_[num_expected_++] = &unknown_;
	}

	if(!stream_decoder_test_respond_(decoder, &decoder_client_data, is_ogg))
		return false;

	/*
	 * ignore all, respond VORBIS_COMMENT
	 */

	printf("testing FLAC__stream_decoder_set_metadata_ignore_all()... ");
	if(!FLAC__stream_decoder_set_metadata_ignore_all(decoder))
		return die_s_("returned false", decoder);
	printf("OK\n");

	printf("testing FLAC__stream_decoder_set_metadata_respond(VORBIS_COMMENT)... ");
	if(!FLAC__stream_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_VORBIS_COMMENT))
		return die_s_("returned false", decoder);
	printf("OK\n");

	num_expected_ = 0;
	expected_metadata_sequence_[num_expected_++] = &vorbiscomment_;

	if(!stream_decoder_test_respond_(decoder, &decoder_client_data, is_ogg))
		return false;

	/*
	 * ignore all, respond APPLICATION
	 */

	printf("testing FLAC__stream_decoder_set_metadata_ignore_all()... ");
	if(!FLAC__stream_decoder_set_metadata_ignore_all(decoder))
		return die_s_("returned false", decoder);
	printf("OK\n");

	printf("testing FLAC__stream_decoder_set_metadata_respond(APPLICATION)... ");
	if(!FLAC__stream_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_APPLICATION))
		return die_s_("returned false", decoder);
	printf("OK\n");

	num_expected_ = 0;
	expected_metadata_sequence_[num_expected_++] = &application1_;
	expected_metadata_sequence_[num_expected_++] = &application2_;

	if(!stream_decoder_test_respond_(decoder, &decoder_client_data, is_ogg))
		return false;

	/*
	 * ignore all, respond APPLICATION id of app#1
	 */

	printf("testing FLAC__stream_decoder_set_metadata_ignore_all()... ");
	if(!FLAC__stream_decoder_set_metadata_ignore_all(decoder))
		return die_s_("returned false", decoder);
	printf("OK\n");

	printf("testing FLAC__stream_decoder_set_metadata_respond_application(of app block #1)... ");
	if(!FLAC__stream_decoder_set_metadata_respond_application(decoder, application1_.data.application.id))
		return die_s_("returned false", decoder);
	printf("OK\n");

	num_expected_ = 0;
	expected_metadata_sequence_[num_expected_++] = &application1_;

	if(!stream_decoder_test_respond_(decoder, &decoder_client_data, is_ogg))
		return false;

	/*
	 * ignore all, respond APPLICATION id of app#1 & app#2
	 */

	printf("testing FLAC__stream_decoder_set_metadata_ignore_all()... ");
	if(!FLAC__stream_decoder_set_metadata_ignore_all(decoder))
		return die_s_("returned false", decoder);
	printf("OK\n");

	printf("testing FLAC__stream_decoder_set_metadata_respond_application(of app block #1)... ");
	if(!FLAC__stream_decoder_set_metadata_respond_application(decoder, application1_.data.application.id))
		return die_s_("returned false", decoder);
	printf("OK\n");

	printf("testing FLAC__stream_decoder_set_metadata_respond_application(of app block #2)... ");
	if(!FLAC__stream_decoder_set_metadata_respond_application(decoder, application2_.data.application.id))
		return die_s_("returned false", decoder);
	printf("OK\n");

	num_expected_ = 0;
	expected_metadata_sequence_[num_expected_++] = &application1_;
	expected_metadata_sequence_[num_expected_++] = &application2_;

	if(!stream_decoder_test_respond_(decoder, &decoder_client_data, is_ogg))
		return false;

	/*
	 * respond all, ignore APPLICATION, respond APPLICATION id of app#1
	 */

	printf("testing FLAC__stream_decoder_set_metadata_respond_all()... ");
	if(!FLAC__stream_decoder_set_metadata_respond_all(decoder))
		return die_s_("returned false", decoder);
	printf("OK\n");

	printf("testing FLAC__stream_decoder_set_metadata_ignore(APPLICATION)... ");
	if(!FLAC__stream_decoder_set_metadata_ignore(decoder, FLAC__METADATA_TYPE_APPLICATION))
		return die_s_("returned false", decoder);
	printf("OK\n");

	printf("testing FLAC__stream_decoder_set_metadata_respond_application(of app block #1)... ");
	if(!FLAC__stream_decoder_set_metadata_respond_application(decoder, application1_.data.application.id))
		return die_s_("returned false", decoder);
	printf("OK\n");

	num_expected_ = 0;
	if(is_ogg) { /* encoder moves vorbis comment after streaminfo according to ogg mapping */
		expected_metadata_sequence_[num_expected_++] = &streaminfo_;
		expected_metadata_sequence_[num_expected_++] = &vorbiscomment_;
		expected_metadata_sequence_[num_expected_++] = &padding_;
		expected_metadata_sequence_[num_expected_++] = &seektable_;
		expected_metadata_sequence_[num_expected_++] = &application1_;
		expected_metadata_sequence_[num_expected_++] = &cuesheet_;
		expected_metadata_sequence_[num_expected_++] = &picture_;
		expected_metadata_sequence_[num_expected_++] = &unknown_;
	}
	else {
		expected_metadata_sequence_[num_expected_++] = &streaminfo_;
		expected_metadata_sequence_[num_expected_++] = &padding_;
		expected_metadata_sequence_[num_expected_++] = &seektable_;
		expected_metadata_sequence_[num_expected_++] = &application1_;
		expected_metadata_sequence_[num_expected_++] = &vorbiscomment_;
		expected_metadata_sequence_[num_expected_++] = &cuesheet_;
		expected_metadata_sequence_[num_expected_++] = &picture_;
		expected_metadata_sequence_[num_expected_++] = &unknown_;
	}

	if(!stream_decoder_test_respond_(decoder, &decoder_client_data, is_ogg))
		return false;

	/*
	 * ignore all, respond APPLICATION, ignore APPLICATION id of app#1
	 */

	printf("testing FLAC__stream_decoder_set_metadata_ignore_all()... ");
	if(!FLAC__stream_decoder_set_metadata_ignore_all(decoder))
		return die_s_("returned false", decoder);
	printf("OK\n");

	printf("testing FLAC__stream_decoder_set_metadata_respond(APPLICATION)... ");
	if(!FLAC__stream_decoder_set_metadata_respond(decoder, FLAC__METADATA_TYPE_APPLICATION))
		return die_s_("returned false", decoder);
	printf("OK\n");

	printf("testing FLAC__stream_decoder_set_metadata_ignore_application(of app block #1)... ");
	if(!FLAC__stream_decoder_set_metadata_ignore_application(decoder, application1_.data.application.id))
		return die_s_("returned false", decoder);
	printf("OK\n");

	num_expected_ = 0;
	expected_metadata_sequence_[num_expected_++] = &application2_;

	if(!stream_decoder_test_respond_(decoder, &decoder_client_data, is_ogg))
		return false;

	if(layer < LAYER_FILE) /* for LAYER_FILE, FLAC__stream_decoder_finish() closes the file */
		fclose(decoder_client_data.file);

	printf("testing FLAC__stream_decoder_delete()... ");
	FLAC__stream_decoder_delete(decoder);
	printf("OK\n");

	printf("\nPASSED!\n");

	return true;
}
Ejemplo n.º 18
0
static int mxf_skip(FILE* mxfFile, uint64_t len)
{
    CHK_ORET(fseeko(mxfFile, len, SEEK_CUR) == 0);
    
    return 1;
}
Ejemplo n.º 19
0
static size_t read_the_rest(uint8_t * dest, off_t offset, size_t length, STDIOSTREAMFILE * streamfile) {
    size_t length_read_total=0;

    /* is the beginning at least there? */
    if (offset >= streamfile->offset && offset < streamfile->offset+streamfile->validsize) {
        size_t length_read;
        off_t offset_into_buffer = offset-streamfile->offset;
        length_read = streamfile->validsize-offset_into_buffer;
        memcpy(dest,streamfile->buffer+offset_into_buffer,length_read);
        length_read_total += length_read;
        length -= length_read;
        offset += length_read;
        dest += length_read;
    }

    /* TODO: What would make more sense here is to read the whole request
     * at once into the dest buffer, as it must be large enough, and then
     * copy some part of that into our own buffer.
     * The destination buffer is supposed to be much smaller than the
     * STREAMFILE buffer, though. Maybe we should only ever return up
     * to the buffer size to avoid having to deal with things like this
     * which are outside of my intended use.
     */
    /* read as much of the beginning of the request as possible, proceed */
    while (length>0) {
        size_t length_to_read;
        size_t length_read=0;
        streamfile->validsize=0;
        if (fseeko(streamfile->infile,offset,SEEK_SET)) return length_read;
        streamfile->offset=offset;

        /* decide how much must be read this time */
        if (length>streamfile->buffersize) length_to_read=streamfile->buffersize;
        else length_to_read=length;

        /* always try to fill the buffer */
        length_read = fread(streamfile->buffer,1,streamfile->buffersize,streamfile->infile);
        streamfile->validsize=length_read;

#ifdef PROFILE_STREAMFILE
        if (ferror(streamfile->infile)) {
            clearerr(streamfile->infile);
            streamfile->error_count++;
        }

        streamfile->bytes_read += length_read;
#endif

        /* if we can't get enough to satisfy the request we give up */
        if (length_read < length_to_read) {
            memcpy(dest,streamfile->buffer,length_read);
            length_read_total+=length_read;
            return length_read_total;
        }

        /* use the new buffer */
        memcpy(dest,streamfile->buffer,length_to_read);
        length_read_total+=length_to_read;
        length-=length_to_read;
        dest+=length_to_read;
        offset+=length_to_read;
    }

    return length_read_total;
}
Ejemplo n.º 20
0
void read_gadget_binary_local(char       *filename_root_in,
                              int         snapshot_number,
                              int         i_coord,
                              int         i_load,
                              int         n_load,
                              GBPREAL     mass_array[N_GADGET_TYPE],
                              slab_info  *slab,
                              cosmo_info *cosmo,
                              plist_info *plist){
  size_t     n_of_type_local[N_GADGET_TYPE];
  size_t     n_of_type[N_GADGET_TYPE];
  size_t     type_counter[N_GADGET_TYPE];
  GBPREAL   *x_array[N_GADGET_TYPE];
  GBPREAL   *y_array[N_GADGET_TYPE];
  GBPREAL   *z_array[N_GADGET_TYPE];
  GBPREAL   *vx_array[N_GADGET_TYPE];
  GBPREAL   *vy_array[N_GADGET_TYPE];
  GBPREAL   *vz_array[N_GADGET_TYPE];
  int        i_type;

  // Determine file format and read the header
  gadget_read_info   fp_gadget;
  int                flag_filefound=init_gadget_read(filename_root_in,snapshot_number,&fp_gadget);
  int                flag_multifile=fp_gadget.flag_multifile;
  int                flag_file_type=fp_gadget.flag_file_type;
  gadget_header_info header        =fp_gadget.header;

  // A file was found ... 
  if(flag_filefound){
    char **pname;
    SID_log("Reading GADGET binary file...",SID_LOG_OPEN|SID_LOG_TIMER);

    pname=plist->species;

    // Expansion factor (or time) 
    ADaPS_store(&(plist->data),(void *)(&(header.time)),"expansion_factor",ADaPS_SCALAR_DOUBLE);
    ADaPS_store(&(plist->data),(void *)(&(header.time)),"time",            ADaPS_SCALAR_DOUBLE);

    // Redshift
    double d_value;
    d_value=(double)header.redshift;
    ADaPS_store(&(plist->data),(void *)(&d_value),"redshift",ADaPS_SCALAR_DOUBLE);

    // Number of particles and masses for each species in all files
    size_t n_all[N_GADGET_TYPE];
    for(i_type=0;i_type<N_GADGET_TYPE;i_type++){
      n_all[i_type]     =(size_t)header.n_all_lo_word[i_type]+((size_t)header.n_all_hi_word[i_type])<<32;
      mass_array[i_type]=(GBPREAL)header.mass_array[i_type];
    }

    // Number of files in this snapshot 
    int n_files;
    ADaPS_store(&(plist->data),(void *)(&(header.n_files)),"n_files",ADaPS_SCALAR_INT);
    n_files=header.n_files;

    // Cosmology 

    // Omega_o
    d_value=(double)header.Omega_M; 
    ADaPS_store(&(plist->data),(void *)(&d_value),"Omega_M",ADaPS_SCALAR_DOUBLE);

    // Omega_Lambda 
    d_value=(double)header.Omega_Lambda; 
    ADaPS_store(&(plist->data),(void *)(&d_value),"Omega_Lambda",ADaPS_SCALAR_DOUBLE);

    // Hubble parameter 
    double h_Hubble;
    double redshift;
    h_Hubble=(double)header.h_Hubble; 
    if(h_Hubble<1e-10) h_Hubble=1.;
    ADaPS_store(&(plist->data),(void *)(&h_Hubble),"h_Hubble",ADaPS_SCALAR_DOUBLE);
    redshift=header.redshift;
    ADaPS_store(&(plist->data),(void *)(&redshift),"redshift",ADaPS_SCALAR_DOUBLE);

    // Count and report the total number of particles
    size_t n_particles_all;
    int    n_non_zero;
    n_particles_all=0;
    for(i_type=0,n_non_zero=0;i_type<N_GADGET_TYPE;i_type++){
      if(n_all[i_type]>0){
        n_particles_all+=n_all[i_type];
        n_non_zero++;
      }
    }
    SID_log("%zd",SID_LOG_CONTINUE,n_particles_all);
    if(n_non_zero>0)
      SID_log(" (",SID_LOG_CONTINUE,n_particles_all);
    for(i_type=0;i_type<N_GADGET_TYPE;i_type++){
      if(n_all[i_type]>0){
        if(i_type==n_non_zero-1){
          if(n_non_zero>1)
            SID_log("and %lld %s",SID_LOG_CONTINUE,n_all[i_type],pname[i_type]);
          else
            SID_log("%lld %s",SID_LOG_CONTINUE,n_all[i_type],pname[i_type]);
        }
        else{
          if(n_non_zero>1)
            SID_log("%lld %s, ",SID_LOG_CONTINUE,n_all[i_type],pname[i_type]);        
          else
            SID_log("%lld %s",SID_LOG_CONTINUE,n_all[i_type],pname[i_type]);        
        }
      }
    }
    if(n_non_zero>0)
      SID_log(") particles...",SID_LOG_CONTINUE);
    else
      SID_log(" particles...",SID_LOG_CONTINUE);

    // Count the number of particles that will be scattered to each rank
    char     filename[MAX_FILENAME_LENGTH];
    size_t   k_particle;
    int      i_file;
    int      record_length_open;
    int      record_length_close;
    size_t   i_particle;
    size_t   i_buffer;
    size_t   i_step;
    int      i_type;
    size_t   index;
    GBPREAL *pos_buffer;
    GBPREAL *vel_buffer;
    double   pos_test;

    // Initialize some arrays
    pos_buffer=(GBPREAL *)SID_malloc(sizeof(GBPREAL)*READ_BUFFER_ALLOC_LOCAL);
    vel_buffer=(GBPREAL *)SID_malloc(sizeof(GBPREAL)*READ_BUFFER_ALLOC_LOCAL);
    for(i_type=0;i_type<N_GADGET_TYPE;i_type++){
       n_of_type_local[i_type]=0;
       n_of_type[i_type]      =0;
       type_counter[i_type]   =0;
    }

    // Determine how many particles of each type will end-up on each core
    SID_log("Performing domain decomposition...",SID_LOG_OPEN|SID_LOG_TIMER);
    int n_read;
    if(n_load<n_files)
       n_read=n_files;
    else
       n_read=1;
    for(i_file=i_load;i_file<(i_load+n_read);i_file++){

      set_gadget_filename(&fp_gadget,i_file,filename);

      // Read header and move to the positions
      FILE *fp_pos;
      FILE *fp_vel;
      fp_pos=fopen(filename,"r");
      fread_verify(&record_length_open,4,1,fp_pos);
      fread_verify(&header,sizeof(gadget_header_info),1,fp_pos);
      fread_verify(&record_length_close,4,1,fp_pos);
      if(record_length_open!=record_length_close)
        SID_log_warning("Problem with GADGET record size (close of header)",ERROR_LOGIC);
      fread_verify(&record_length_open,4,1,fp_pos);

      // Create a file pointer to the velocities
      fp_vel=fopen(filename,"r");
      fread_verify(&record_length_open,4,1,fp_vel);
      fseeko(fp_vel,(off_t)(record_length_open),SEEK_CUR);
      fread_verify(&record_length_close,4,1,fp_vel);
      fread_verify(&record_length_open,4,1,fp_vel);
      fseeko(fp_vel,(off_t)(record_length_open),SEEK_CUR);
      fread_verify(&record_length_close,4,1,fp_vel);
      if(record_length_open!=record_length_close)
        SID_log_warning("Problem with GADGET record size (close of positons)",ERROR_LOGIC);
      fread_verify(&record_length_open,4,1,fp_vel);

      // We only have to worry about z-space effects for domain decomposition in this one case.
      if(i_coord==1){
         for(i_type=0;i_type<N_GADGET_TYPE;i_type++){
            for(i_particle=0;i_particle<header.n_file[i_type];i_particle+=i_step){
               i_step=MIN(READ_BUFFER_SIZE_LOCAL,header.n_file[i_type]-i_particle);
               if(SID.I_am_Master){
                  fread_verify(pos_buffer,sizeof(GBPREAL),3*i_step,fp_pos);
                  fread_verify(vel_buffer,sizeof(GBPREAL),3*i_step,fp_vel);
               }
               SID_Bcast(pos_buffer,sizeof(GBPREAL)*3*i_step,MASTER_RANK,SID.COMM_WORLD);
               SID_Bcast(vel_buffer,sizeof(GBPREAL)*3*i_step,MASTER_RANK,SID.COMM_WORLD);
               for(i_buffer=0;i_buffer<i_step;i_buffer++){
                  index=3*i_buffer;
                  pos_test =(double)(pos_buffer[index]);
                  pos_test+=(double)(1e3*h_Hubble*((double)vel_buffer[index])/(a_of_z(redshift)*M_PER_MPC*H_convert(H_z(redshift,cosmo))));
                  if(pos_test<0)                pos_test+=header.box_size;
                  if(pos_test>=header.box_size) pos_test-=header.box_size;
                  if(pos_test>=slab->x_min_local && pos_test<slab->x_max_local)
                     n_of_type_local[i_type]++;
               }
            }
         }
      }
      else{
         for(i_type=0;i_type<N_GADGET_TYPE;i_type++){
            for(i_particle=0;i_particle<header.n_file[i_type];i_particle+=i_step){
               i_step=MIN(READ_BUFFER_SIZE_LOCAL,header.n_file[i_type]-i_particle);
               if(SID.I_am_Master){
                  fread_verify(pos_buffer,sizeof(GBPREAL),3*i_step,fp_pos);
                  fread_verify(vel_buffer,sizeof(GBPREAL),3*i_step,fp_vel);
               }
               SID_Bcast(pos_buffer,sizeof(GBPREAL)*3*i_step,MASTER_RANK,SID.COMM_WORLD);
               SID_Bcast(vel_buffer,sizeof(GBPREAL)*3*i_step,MASTER_RANK,SID.COMM_WORLD);
               for(i_buffer=0;i_buffer<i_step;i_buffer++){
                  pos_test=pos_buffer[3*i_buffer];
                  if(pos_test>=slab->x_min_local && pos_test<slab->x_max_local)
                    n_of_type_local[i_type]++;
               }
            }
            i_step=MIN(READ_BUFFER_SIZE_LOCAL,header.n_file[i_type]-i_particle);
         }
      }
      fclose(fp_pos);
      fclose(fp_vel);
    }
    SID_log("Done.",SID_LOG_CLOSE);

    // Allocate arrays
    for(i_type=0;i_type<N_GADGET_TYPE;i_type++){
       if(n_all[i_type]>0){
          x_array[i_type] =(GBPREAL *)SID_malloc(sizeof(GBPREAL)*n_of_type_local[i_type]);
          y_array[i_type] =(GBPREAL *)SID_malloc(sizeof(GBPREAL)*n_of_type_local[i_type]);
          z_array[i_type] =(GBPREAL *)SID_malloc(sizeof(GBPREAL)*n_of_type_local[i_type]);
          vx_array[i_type]=(GBPREAL *)SID_malloc(sizeof(GBPREAL)*n_of_type_local[i_type]);
          vy_array[i_type]=(GBPREAL *)SID_malloc(sizeof(GBPREAL)*n_of_type_local[i_type]);
          vz_array[i_type]=(GBPREAL *)SID_malloc(sizeof(GBPREAL)*n_of_type_local[i_type]);
       }
    }

    // Perform read
    SID_log("Performing read...",SID_LOG_OPEN|SID_LOG_TIMER);
    for(i_file=i_load;i_file<(i_load+n_read);i_file++){

      set_gadget_filename(&fp_gadget,i_file,filename);

      // Read header and move to the positions
      FILE *fp_pos;
      FILE *fp_vel;
      fp_pos=fopen(filename,"r");
      fread_verify(&record_length_open,4,1,fp_pos);
      fread_verify(&header,sizeof(gadget_header_info),1,fp_pos);
      fread_verify(&record_length_close,4,1,fp_pos);
      if(record_length_open!=record_length_close)
        SID_log_warning("Problem with GADGET record size (close of header)",ERROR_LOGIC);
      fread_verify(&record_length_open,4,1,fp_pos);

      // Create a file pointer to the velocities
      fp_vel=fopen(filename,"r");
      fread_verify(&record_length_open,4,1,fp_vel);
      fseeko(fp_vel,(off_t)(record_length_open),SEEK_CUR);
      fread_verify(&record_length_close,4,1,fp_vel);
      fread_verify(&record_length_open,4,1,fp_vel);
      fseeko(fp_vel,(off_t)(record_length_open),SEEK_CUR);
      fread_verify(&record_length_close,4,1,fp_vel);
      if(record_length_open!=record_length_close)
        SID_log_warning("Problem with GADGET record size (close of positions)",ERROR_LOGIC);
      fread_verify(&record_length_open,4,1,fp_vel);

      // Perform the read and populate the local position arrays
      size_t   i_particle;
      size_t   i_step;
      int      i_type;
      for(i_type=0;i_type<N_GADGET_TYPE;i_type++){
         for(i_particle=0;i_particle<header.n_file[i_type];i_particle+=i_step){
            i_step=MIN(READ_BUFFER_SIZE_LOCAL,header.n_file[i_type]-i_particle);
            if(SID.I_am_Master){
               fread_verify(pos_buffer,sizeof(GBPREAL),3*i_step,fp_pos);
               fread_verify(vel_buffer,sizeof(GBPREAL),3*i_step,fp_vel);
            }
            SID_Bcast(pos_buffer,sizeof(GBPREAL)*3*i_step,MASTER_RANK,SID.COMM_WORLD);
            SID_Bcast(vel_buffer,sizeof(GBPREAL)*3*i_step,MASTER_RANK,SID.COMM_WORLD);
            for(i_buffer=0;i_buffer<i_step;i_buffer++){
               double x_test;
               double y_test;
               double z_test;
               double vx_test;
               double vy_test;
               double vz_test;
               index=3*i_buffer;
               x_test =(double)pos_buffer[index+0];
               y_test =(double)pos_buffer[index+1];
               z_test =(double)pos_buffer[index+2];
               vx_test=(double)vel_buffer[index+0];
               vy_test=(double)vel_buffer[index+1];
               vz_test=(double)vel_buffer[index+2];
               switch(i_coord){
                  case 1:
                     x_test+=(1e3*h_Hubble*vx_test/(a_of_z(redshift)*M_PER_MPC*H_convert(H_z(redshift,cosmo))));
                     if(x_test<0)                x_test+=header.box_size;
                     if(x_test>=header.box_size) x_test-=header.box_size;
                     break;
                  case 2:
                     y_test+=(1e3*h_Hubble*vy_test/(a_of_z(redshift)*M_PER_MPC*H_convert(H_z(redshift,cosmo))));
                     if(y_test<0)                y_test+=header.box_size;
                     if(y_test>=header.box_size) y_test-=header.box_size;
                     break;
                  case 3:
                     z_test+=(1e3*h_Hubble*vz_test/(a_of_z(redshift)*M_PER_MPC*H_convert(H_z(redshift,cosmo))));
                     if(z_test<0)                z_test+=header.box_size;
                     if(z_test>=header.box_size) z_test-=header.box_size;
                     break;
               }
               if(x_test>=slab->x_min_local && x_test<slab->x_max_local){
                  x_array[i_type][type_counter[i_type]] =x_test;
                  y_array[i_type][type_counter[i_type]] =y_test;
                  z_array[i_type][type_counter[i_type]] =z_test;
                  vx_array[i_type][type_counter[i_type]]=vx_test;
                  vy_array[i_type][type_counter[i_type]]=vy_test;
                  vz_array[i_type][type_counter[i_type]]=vz_test;
                  type_counter[i_type]++;
               }
            }
         }
      }

      // Close file pointers
      fclose(fp_pos);
      fclose(fp_vel);
    }
    SID_free(SID_FARG pos_buffer);
    SID_free(SID_FARG vel_buffer);
    SID_log("Done.",SID_LOG_CLOSE);

    // Sanity checks
    size_t n_particles_local;
    size_t n_particles_read;
    size_t n_particles_test;
    for(i_type=0,n_particles_local=0,n_particles_test=0;i_type<N_GADGET_TYPE;i_type++){
      n_particles_local+=n_of_type_local[i_type];
      n_particles_test +=n_all[i_type];
    }
    SID_Allreduce(&n_particles_local,&n_particles_read,1,SID_SIZE_T,SID_SUM,SID.COMM_WORLD);
    if(n_particles_read!=n_particles_test && n_load==1)
       SID_trap_error("Total particle counts don't make sense after read_gadget (ie. %zd!=%zd).",ERROR_LOGIC,n_particles_read,n_particles_test);
    for(i_type=0;i_type<N_GADGET_TYPE;i_type++){
       SID_Allreduce(&(n_of_type_local[i_type]),&(n_of_type[i_type]),1,SID_SIZE_T,SID_SUM,SID.COMM_WORLD);
       if(n_of_type[i_type]!=n_all[i_type] && n_load==1)
          SID_trap_error("Particle counts don't make sense after read_gadget (ie. %zd!=%zd).",ERROR_LOGIC,n_of_type[i_type],n_all[i_type]);
    }

    // Store results
    for(i_type=0;i_type<N_GADGET_TYPE;i_type++){
      if(n_of_type[i_type]>0){
        ADaPS_store(&(plist->data),(void *)(&(n_of_type_local[i_type])),"n_%s",         ADaPS_SCALAR_SIZE_T,pname[i_type]);
        ADaPS_store(&(plist->data),(void *)(&(n_of_type[i_type])),      "n_all_%s",     ADaPS_SCALAR_SIZE_T,pname[i_type]);
      }
    }
    ADaPS_store(&(plist->data),(void *)(&n_particles_all),"n_particles_all",ADaPS_SCALAR_SIZE_T);
    for(i_type=0;i_type<N_GADGET_TYPE;i_type++){
      if(n_of_type_local[i_type]>0){
        ADaPS_store(&(plist->data),(void *)x_array[i_type], "x_%s", ADaPS_DEFAULT, pname[i_type]);
        ADaPS_store(&(plist->data),(void *)y_array[i_type], "y_%s", ADaPS_DEFAULT, pname[i_type]);
        ADaPS_store(&(plist->data),(void *)z_array[i_type], "z_%s", ADaPS_DEFAULT, pname[i_type]);
        ADaPS_store(&(plist->data),(void *)vx_array[i_type],"vx_%s",ADaPS_DEFAULT,pname[i_type]);
        ADaPS_store(&(plist->data),(void *)vy_array[i_type],"vy_%s",ADaPS_DEFAULT,pname[i_type]);
        ADaPS_store(&(plist->data),(void *)vz_array[i_type],"vz_%s",ADaPS_DEFAULT,pname[i_type]);
      }
    }
    SID_log("Done.",SID_LOG_CLOSE);
  }
}
Ejemplo n.º 21
0
int
OpenResumeFile(const char *flvFile,	// file name [in]
               FILE ** file,	// opened file [out]
               off_t * size,	// size of the file [out]
               char **metaHeader,	// meta data read from the file [out]
               uint32_t * nMetaHeaderSize,	// length of metaHeader [out]
               double *duration)	// duration of the stream in ms [out]
{
    size_t bufferSize = 0;
    char hbuf[16], *buffer = NULL;

    *nMetaHeaderSize = 0;
    *size = 0;

    *file = fopen(flvFile, "r+b");
    if (!*file)
        return RD_SUCCESS;		// RD_SUCCESS, because we go to fresh file mode instead of quiting

    fseek(*file, 0, SEEK_END);
    *size = ftello(*file);
    fseek(*file, 0, SEEK_SET);

    if (*size > 0)
    {
        // verify FLV format and read header
        uint32_t prevTagSize = 0;

        // check we've got a valid FLV file to continue!
        if (fread(hbuf, 1, 13, *file) != 13)
        {
            RTMP_Log(RTMP_LOGERROR, "Couldn't read FLV file header!");
            return RD_FAILED;
        }
        if (hbuf[0] != 'F' || hbuf[1] != 'L' || hbuf[2] != 'V'
                || hbuf[3] != 0x01)
        {
            RTMP_Log(RTMP_LOGERROR, "Invalid FLV file!");
            return RD_FAILED;
        }

        if ((hbuf[4] & 0x05) == 0)
        {
            RTMP_Log(RTMP_LOGERROR,
                     "FLV file contains neither video nor audio, aborting!");
            return RD_FAILED;
        }

        uint32_t dataOffset = AMF_DecodeInt32(hbuf + 5);
        fseek(*file, dataOffset, SEEK_SET);

        if (fread(hbuf, 1, 4, *file) != 4)
        {
            RTMP_Log(RTMP_LOGERROR, "Invalid FLV file: missing first prevTagSize!");
            return RD_FAILED;
        }
        prevTagSize = AMF_DecodeInt32(hbuf);
        if (prevTagSize != 0)
        {
            RTMP_Log(RTMP_LOGWARNING,
                     "First prevTagSize is not zero: prevTagSize = 0x%08X",
                     prevTagSize);
        }

        // go through the file to find the meta data!
        off_t pos = dataOffset + 4;
        int bFoundMetaHeader = FALSE;

        while (pos < *size - 4 && !bFoundMetaHeader)
        {
            fseeko(*file, pos, SEEK_SET);
            if (fread(hbuf, 1, 4, *file) != 4)
                break;

            uint32_t dataSize = AMF_DecodeInt24(hbuf + 1);

            if (hbuf[0] == 0x12)
            {
                if (dataSize > bufferSize)
                {
                    /* round up to next page boundary */
                    bufferSize = dataSize + 4095;
                    bufferSize ^= (bufferSize & 4095);
                    free(buffer);
                    buffer = (char *)malloc(bufferSize);
                    if (!buffer)
                        return RD_FAILED;
                }

                fseeko(*file, pos + 11, SEEK_SET);
                if (fread(buffer, 1, dataSize, *file) != dataSize)
                    break;

                AMFObject metaObj;
                int nRes = AMF_Decode(&metaObj, buffer, dataSize, FALSE);
                if (nRes < 0)
                {
                    RTMP_Log(RTMP_LOGERROR, "%s, error decoding meta data packet",
                             __FUNCTION__);
                    break;
                }

                AVal metastring;
                AMFProp_GetString(AMF_GetProp(&metaObj, NULL, 0), &metastring);

                if (AVMATCH(&metastring, &av_onMetaData))
                {
                    AMF_Dump(&metaObj);

                    *nMetaHeaderSize = dataSize;
                    if (*metaHeader)
                        free(*metaHeader);
                    *metaHeader = (char *) malloc(*nMetaHeaderSize);
                    memcpy(*metaHeader, buffer, *nMetaHeaderSize);

                    // get duration
                    AMFObjectProperty prop;
                    if (RTMP_FindFirstMatchingProperty
                            (&metaObj, &av_duration, &prop))
                    {
                        *duration = AMFProp_GetNumber(&prop);
                        RTMP_Log(RTMP_LOGDEBUG, "File has duration: %f", *duration);
                    }

                    bFoundMetaHeader = TRUE;
                    break;
                }
                //metaObj.Reset();
                //delete obj;
            }
            pos += (dataSize + 11 + 4);
        }

        free(buffer);
        if (!bFoundMetaHeader)
            RTMP_Log(RTMP_LOGWARNING, "Couldn't locate meta data!");
    }

    return RD_SUCCESS;
}
Ejemplo n.º 22
0
int EDF_annotations::get_annotations(int file_num, struct edfhdrblock *edf_hdr, struct annotationblock **annotslist, int read_nk_trigger_signal)
{
  int i, j, k, p, r=0, n,
      edfsignals,
      datarecords,
      recordsize,
      discontinuous,
      *annot_ch,
      nr_annot_chns,
      max,
      onset,
      duration,
      duration_start,
      zero,
      max_tal_ln,
      error,
      annots_in_record,
      annots_in_tal,
      samplesize=2,
      nk_triggers_smpls=0,
      nk_triggers_bufoffset=0,
      nk_triggers_enabled=0,
      nk_triggers_channel=0,
      nk_triggers_cnt=0,
      sf,
      progress_steps;

  unsigned short nk_triggerfields=0,
                 nk_old_triggerfields=0;

  char *scratchpad,
       *cnv_buf,
       *time_in_txt,
       *duration_in_txt,
       nk_triggerlabel[16][32];


  long long data_record_duration,
            elapsedtime,
            time_tmp=0LL,
            nk_trigger_sample_duration=0LL;

  FILE *inputfile;

  struct edfparamblock *edfparam;

  struct annotationblock *new_annotation=NULL,
                         *temp_annotation;



  inputfile = edf_hdr->file_hdl;
  edfsignals = edf_hdr->edfsignals;
  recordsize = edf_hdr->recordsize;
  edfparam = edf_hdr->edfparam;
  nr_annot_chns = edf_hdr->nr_annot_chns;
  datarecords = edf_hdr->datarecords;
  data_record_duration = edf_hdr->long_data_record_duration;
  discontinuous = edf_hdr->discontinuous;
  annot_ch = edf_hdr->annot_ch;

  if(edf_hdr->edfplus)
  {
    samplesize = 2;
  }
  if(edf_hdr->bdfplus)
  {
    samplesize = 3;
  }

  if((edf_hdr->edfplus) && (read_nk_trigger_signal))
  {
    if(data_record_duration == 1000000LL)
    {
      if(check_device(edf_hdr->plus_equipment) == 0)
      {
        for(i=0; i<edfsignals; i++)
        {
          if(!strcmp(edfparam[i].label, "Events/Markers  "))
          {
            sf = edf_hdr->edfparam[i].smp_per_record;

            error = 1;

            switch(sf)
            {
              case  10 : error = 0;
                         break;
              case  20 : error = 0;
                         break;
              case  50 : error = 0;
                         break;
              case 100 : error = 0;
                         break;
            }

            for(j=0; j<edfsignals; j++)
            {
              if(edf_hdr->edfparam[j].smp_per_record != sf)
              {
                if(!edf_hdr->edfparam[j].annotation)
                {
                  error = 1;
                }
              }
            }

            if(edf_hdr->nr_annot_chns != 1)  error = 1;

            if(!error)
            {
              nk_triggers_channel = i;

              nk_triggers_bufoffset = edfparam[nk_triggers_channel].buf_offset;

              nk_triggers_smpls = edfparam[nk_triggers_channel].smp_per_record;

              nk_trigger_sample_duration = data_record_duration / (long long)nk_triggers_smpls;

              strcpy(nk_triggerlabel[0], "CAL mode");
              strcpy(nk_triggerlabel[1], "RESET condition");
              strcpy(nk_triggerlabel[2], "External mark");
              strcpy(nk_triggerlabel[3], "Photo/HV mark");
              strcpy(nk_triggerlabel[4], "Remote mark");
              strcpy(nk_triggerlabel[5], "HV mark");
              strcpy(nk_triggerlabel[6], "DC trigger 9");
              strcpy(nk_triggerlabel[7], "DC trigger 10");
              strcpy(nk_triggerlabel[8], "DC trigger 11");
              strcpy(nk_triggerlabel[9], "DC trigger 12");
              strcpy(nk_triggerlabel[10], "DC trigger 13");
              strcpy(nk_triggerlabel[11], "DC trigger 14");
              strcpy(nk_triggerlabel[12], "DC trigger 15");
              strcpy(nk_triggerlabel[13], "DC trigger 16");
              strcpy(nk_triggerlabel[14], "");
              strcpy(nk_triggerlabel[15], "");

              nk_triggers_enabled = 1;

              edf_hdr->genuine_nk = 1;

              break;
            }
          }
        }
      }
    }
  }

  cnv_buf = (char *)calloc(1, recordsize);
  if(cnv_buf==NULL)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Memory allocation error occurred when trying to read annotations.\n(cnv_buf)");
    messagewindow.exec();
    return(1);
  }

  max_tal_ln = 0;

  for(i=0; i<nr_annot_chns; i++)
  {
    if(max_tal_ln<edfparam[annot_ch[i]].smp_per_record * samplesize)  max_tal_ln = edfparam[annot_ch[i]].smp_per_record * samplesize;
  }

  if(max_tal_ln<128)  max_tal_ln = 128;

  scratchpad = (char *)calloc(1, max_tal_ln + 3);
  if(scratchpad==NULL)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Memory allocation error occurred when trying to read annotations.\n(scratchpad)");
    messagewindow.exec();
    free(cnv_buf);
    return(1);
  }

  time_in_txt = (char *)calloc(1, max_tal_ln + 3);
  if(time_in_txt==NULL)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Memory allocation error occurred when trying to read annotations.\n(time_in_txt)");
    messagewindow.exec();
    free(cnv_buf);
    free(scratchpad);
    return(1);
  }

  duration_in_txt = (char *)calloc(1, max_tal_ln + 3);
  if(duration_in_txt==NULL)
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "Memory allocation error occurred when trying to read annotations.\n(duration_in_txt)");
    messagewindow.exec();
    free(cnv_buf);
    free(scratchpad);
    free(time_in_txt);
    return(1);
  }

  if(fseeko(inputfile, (long long)((edfsignals + 1) * 256), SEEK_SET))
  {
    QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred when reading inputfile annotations. (fseek())");
    messagewindow.exec();
    free(cnv_buf);
    free(scratchpad);
    free(time_in_txt);
    free(duration_in_txt);
    return(2);
  }

  QProgressDialog progress("Scanning file for annotations...", "Abort", 0, datarecords);
  progress.setWindowModality(Qt::WindowModal);
  progress.setMinimumDuration(200);

  progress_steps = datarecords / 100;
  if(progress_steps < 1)
  {
    progress_steps = 1;
  }

  elapsedtime = 0;

  for(i=0; i<datarecords; i++)
  {
    if(!(i%progress_steps))
    {
      progress.setValue(i);

      qApp->processEvents();

      if(progress.wasCanceled() == TRUE)
      {
        edf_hdr->annots_not_read = 1;

        free(cnv_buf);
        free(scratchpad);
        free(time_in_txt);
        free(duration_in_txt);
        return(11);
      }
    }

    if(fread(cnv_buf, recordsize, 1, inputfile)!=1)
    {
      progress.reset();
      QMessageBox messagewindow(QMessageBox::Critical, "Error", "An error occurred while reading inputfile annotations. (fread())");
      messagewindow.exec();
      free(cnv_buf);
      free(scratchpad);
      free(time_in_txt);
      free(duration_in_txt);
      return(2);
    }


/************** process annotationsignals (if any) **************/

    error = 0;

    for(r=0; r<nr_annot_chns; r++)
    {
      n = 0;
      zero = 0;
      onset = 0;
      duration = 0;
      duration_start = 0;
      scratchpad[0] = 0;
      annots_in_tal = 0;
      annots_in_record = 0;

      p = edfparam[annot_ch[r]].buf_offset;
      max = edfparam[annot_ch[r]].smp_per_record * samplesize;

/************** process one annotation signal ****************/

      if(cnv_buf[p + max - 1]!=0)
      {
        error = 5;
        goto END;
      }

      if(!r)  /* if it's the first annotation signal, then check */
      {       /* the timekeeping annotation */
        error = 1;

        for(k=0; k<(max-2); k++)
        {
          scratchpad[k] = cnv_buf[p + k];

          if(scratchpad[k]==20)
          {
            if(cnv_buf[p + k + 1]!=20)
            {
              error = 6;
              goto END;
            }
            scratchpad[k] = 0;
            if(is_onset_number(scratchpad))
            {
              error = 36;
              goto END;
            }
            else
            {
              time_tmp = get_long_time(scratchpad);
              if(i)
              {
                if(discontinuous)
                {
                  if((time_tmp-elapsedtime)<data_record_duration)
                  {
                    error = 4;
                    goto END;
                  }
                }
                else
                {
                  if((time_tmp-elapsedtime)!=data_record_duration)
                  {
                    error = 3;
                    goto END;
                  }
                }
              }
              else
              {
                if(time_tmp>=TIME_DIMENSION)
                {
                  error = 2;
                  goto END;
                }
                else
                {
                  edf_hdr->starttime_offset = time_tmp;
                }
              }
              elapsedtime = time_tmp;
              error = 0;
              break;
            }
          }
        }
      }

      for(k=0; k<max; k++)
      {
        scratchpad[n] = cnv_buf[p + k];

        if(!scratchpad[n])
        {
          if(!zero)
          {
            if(k)
            {
              if(cnv_buf[p + k - 1]!=20)
              {
                error = 33;
                goto END;
              }
            }
            n = 0;
            onset = 0;
            duration = 0;
            duration_start = 0;
            scratchpad[0] = 0;
            annots_in_tal = 0;
          }
          zero++;
          continue;
        }
        if(zero>1)
        {
          error = 34;
          goto END;
        }
        zero = 0;

        if((scratchpad[n]==20)||(scratchpad[n]==21))
        {
          if(scratchpad[n]==21)
          {
            if(duration||duration_start||onset||annots_in_tal)
            {               /* it's not allowed to have multiple duration fields */
              error = 35;   /* in one TAL or to have a duration field which is   */
              goto END;     /* not immediately behind the onsetfield             */
            }
            duration_start = 1;
          }

          if((scratchpad[n]==20)&&onset&&(!duration_start))
          {
            if(r||annots_in_record)
            {
              if(n >= 0)
              {
                new_annotation = (struct annotationblock *)calloc(1, sizeof(struct annotationblock));
                if(new_annotation==NULL)
                {
                  progress.reset();
                  QMessageBox messagewindow(QMessageBox::Critical, "Error", "A memory allocation error occurred while reading annotations.");
                  messagewindow.exec();
                  free(cnv_buf);
                  free(scratchpad);
                  free(time_in_txt);
                  free(duration_in_txt);
                  return(1);
                }

                new_annotation->next_annotation = NULL;
                new_annotation->file_num = file_num;

                new_annotation->annotation[0] = 0;

                if(duration)  strcpy(new_annotation->duration, duration_in_txt);
                else  new_annotation->duration[0] = 0;

                for(j=0; j<n; j++)
                {
                  if(j==MAX_ANNOTATION_LEN)  break;
                  new_annotation->annotation[j] = scratchpad[j];
                }
                new_annotation->annotation[j] = 0;

                new_annotation->file_num = edf_hdr->file_num;

                new_annotation->onset = get_long_time(time_in_txt);

                if(*annotslist!=NULL)
                {
                  temp_annotation = *annotslist;
                  while(temp_annotation->next_annotation)  temp_annotation = temp_annotation->next_annotation;

                  new_annotation->former_annotation = temp_annotation;
                  temp_annotation->next_annotation = new_annotation;
                }
                else
                {
                  new_annotation->former_annotation = NULL;
                  *annotslist = new_annotation;
                }
              }
            }

            annots_in_tal++;
            annots_in_record++;
            n = 0;
            continue;
          }

          if(!onset)
          {
            scratchpad[n] = 0;
            if(is_onset_number(scratchpad))
            {
              error = 36;
              goto END;
            }
            onset = 1;
            n = 0;
            strcpy(time_in_txt, scratchpad);
            continue;
          }

          if(duration_start)
          {
            scratchpad[n] = 0;
            if(is_duration_number(scratchpad))
            {
              error = 37;
              goto END;
            }

            for(j=0; j<n; j++)
            {
              if(j==15)  break;
              duration_in_txt[j] = scratchpad[j];
              if((duration_in_txt[j]<32)||(duration_in_txt[j]>126))
              {
                duration_in_txt[j] = '.';
              }
            }
            duration_in_txt[j] = 0;

            duration = 1;
            duration_start = 0;
            n = 0;
            continue;
          }
        }

        n++;
      }

 END:

/****************** end ************************/

      if(error)
      {
        progress.reset();
        QMessageBox messagewindow(QMessageBox::Critical, "Error", "Can not read annotations because there is an EDF or BDF incompatibility in this file.\n"
                                                                  "For more information, run the EDF/BDF compatibility checker in the Tools menu.");
        messagewindow.exec();
        free(cnv_buf);
        free(scratchpad);
        free(time_in_txt);
        free(duration_in_txt);
        return(9);
      }
    }

/************** process NK triggers ****************/

    if(nk_triggers_enabled)
    {
      if(nk_triggers_cnt < 100000)
      {
        for(k=0; k<nk_triggers_smpls; k++)
        {
          nk_triggerfields = *((unsigned char *)cnv_buf + nk_triggers_bufoffset + (k * 2) + 1);

          nk_triggerfields <<= 8;

          nk_triggerfields += *((unsigned char *)cnv_buf + nk_triggers_bufoffset + (k * 2));

          for(j=0; j<14; j++)
          {
            if((nk_triggerfields & (1 << j)) && (!(nk_old_triggerfields & (1 << j))))
            {
              nk_triggers_cnt++;

              new_annotation = (struct annotationblock *)calloc(1, sizeof(struct annotationblock));
              if(new_annotation==NULL)
              {
                progress.reset();
                QMessageBox messagewindow(QMessageBox::Critical, "Error", "A memory allocation error occurred while reading annotations.");
                messagewindow.exec();
                free(cnv_buf);
                free(scratchpad);
                free(time_in_txt);
                free(duration_in_txt);
                return(1);
              }

              new_annotation->file_num = edf_hdr->file_num;
              new_annotation->next_annotation = NULL;
              new_annotation->file_num = file_num;
              strcpy(new_annotation->annotation, nk_triggerlabel[j]);

              new_annotation->onset = ((long long)i * data_record_duration) + ((long long)k * nk_trigger_sample_duration);

              new_annotation->onset += edf_hdr->starttime_offset;

              if(*annotslist!=NULL)
              {
                temp_annotation = *annotslist;
                while(temp_annotation->next_annotation)  temp_annotation = temp_annotation->next_annotation;

                new_annotation->former_annotation = temp_annotation;
                temp_annotation->next_annotation = new_annotation;
              }
              else
              {
                new_annotation->former_annotation = NULL;
                *annotslist = new_annotation;
              }
            }
          }

          nk_old_triggerfields = nk_triggerfields;
        }
      }

      edf_hdr->nk_triggers_read = 1;
    }
  }

  edfplus_annotation_sort(&annotslist[file_num]);

  progress.reset();

  free(cnv_buf);
  free(scratchpad);
  free(time_in_txt);
  free(duration_in_txt);

  return(0);
}
Ejemplo n.º 23
0
Archivo: tox.c Proyecto: autious/uTox
void log_read(Tox *tox, int fid)
{
    uint8_t path[512], *p;
    FILE *file;

    p = path + datapath(path);

    int len = log_file_name(p, sizeof(path) - (p - path), tox, fid);
    if (len == -1) {
        debug("Error getting log file name for friend %d\n", fid);
        return;
    }

    file = fopen((char*)path, "rb");
    if(!file) {
        debug("File not found (%s)\n", path);
        p = path + datapath_old(path);

        len = log_file_name(p, sizeof(path) - (p - path), tox, fid);
        if (len == -1) {
            debug("Error getting log file name for friend %d\n", fid);
            return;
        }

        file = fopen((char*) path, "rb");
        if (!file) {
            debug("File not found (%s)\n", path);
            return;
        }
    }

    LOG_FILE_MSG_HEADER header;
    off_t rewinds[MAX_BACKLOG_MESSAGES] = {};
    size_t records_count = 0;

    /* todo: some checks to avoid crashes with corrupted log files */
    /* first find the last MAX_BACKLOG_MESSAGES messages in the log */
    while(1 == fread(&header, sizeof(LOG_FILE_MSG_HEADER), 1, file)) {
        fseeko(file, header.namelen + header.length, SEEK_CUR);

        rewinds[records_count % countof(rewinds)] =
                (off_t) sizeof(LOG_FILE_MSG_HEADER) + header.namelen + header.length;
        records_count++;
    }

    if(ferror(file) || !feof(file)) {
        // TODO: consider removing or truncating the log file.
        // If !feof() this means that the file has an incomplete record,
        // which would prevent it from loading forever, even though
        // new records will keep being appended as usual.
        debug("Log read error (%s)\n", path);
        fclose(file);
        return;
    }

    // Backtrack to read last MAX_BACKLOG_MESSAGES in full.
    off_t rewind = 0;
    MSG_IDX i;
    for(i = 0; (i < records_count) && (i < countof(rewinds)); i++) {
        rewind += rewinds[i];
    }
    fseeko(file, -rewind, SEEK_CUR);

    MSG_DATA *m = &friend[fid].msg;
    m->data = malloc(sizeof(void*) * i);
    m->n = 0;

    /* add the messages */
    while((0 < i) && (1 == fread(&header, sizeof(LOG_FILE_MSG_HEADER), 1, file))) {
        i--;

        // Skip unused friend name recorded at the time.
        fseeko(file, header.namelen, SEEK_CUR);

        MESSAGE *msg = NULL;
        switch(header.msg_type) {
        case LOG_FILE_MSG_TYPE_ACTION: {
            msg = malloc(sizeof(MESSAGE) + header.length);
            msg->msg_type = MSG_TYPE_ACTION_TEXT;
            break;
        }
        case LOG_FILE_MSG_TYPE_TEXT: {
            msg = malloc(sizeof(MESSAGE) + header.length);
            msg->msg_type = MSG_TYPE_TEXT;
            break;
        }
        default: {
            debug("Unknown backlog message type(%d), skipping.\n", (int)header.msg_type);
            fseeko(file, header.length, SEEK_CUR);
            continue;
        }
        }

        // Read text message.
        msg->author = header.flags & 1;
        msg->length = header.length;

        if(1 != fread(msg->msg, msg->length, 1, file)) {
            debug("Log read error (%s)\n", path);
            fclose(file);
            return;
        }

        struct tm *ti;
        time_t rawtime = header.time;
        ti = localtime(&rawtime);

        msg->time = ti->tm_hour * 60 + ti->tm_min;

        m->data[m->n++] = msg;

        debug("loaded backlog: %d: %.*s\n", fid, msg->length, msg->msg);
    }

    fclose(file);
}
Ejemplo n.º 24
0
int OTF_File_seek( OTF_File* file, uint64_t pos ) {


	int ret;

#ifdef HAVE_ZLIB
	int sync;
	uint64_t read;
#endif /* HAVE_ZLIB */


	if ( NULL != file->externalbuffer ) {

		OTF_fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
			"not yet supported in 'external buffer' mode.\n",
			__FUNCTION__, __FILE__, __LINE__ );
		return -1;
	}


	if( OTF_FILEMODE_WRITE == file->mode ) {
		
		OTF_fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
				"current file->mode is OTF_FILEMODE_WRITE. seeking forbidden.\n",
				__FUNCTION__, __FILE__, __LINE__ );

		return -1;
	}
		
	
	if( 0 == OTF_File_revive( file, OTF_FILEMODE_SEEK ) ) {

		OTF_fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
				"OTF_File_revive() failed.\n",
				__FUNCTION__, __FILE__, __LINE__ );

		return -1;
	}
	

	ret= fseeko( file->file, pos, SEEK_SET );
	
#ifdef HAVE_ZLIB

	if ( NULL != file->z && 0 == ret ) {

		do {

			/*
			OTF_fprintf( stderr, "OTF_File_seek() with zlib: jump to %llu\n", 
					(unsigned long long) pos );
			*/

			/* OLD:
			read= fread( file->zbuffer, 1, file->zbuffersize, file->file );
			*/
			read= OTF_File_read_internal( file, file->zbuffer, file->zbuffersize );


			/*
			OTF_fprintf( stderr, "OTF_File_seek() with zlib: read %llu bytes\n", 
					(unsigned long long) read );
			*/

			file->z->next_in= file->zbuffer;
			file->z->avail_in= (uInt) read;
			file->z->total_in= 0;

			/* re-initialize z object */
			inflateEnd( file->z );
			inflateInit( file->z );

			/* do not sync at very beginning of compressed stream because it 
			would skip the first block */
			sync= Z_OK;
			if ( 0 != pos ) {

				sync= inflateSync( file->z );
			}

			if ( Z_OK == sync ) {

				return ret;
			}

			if ( Z_BUF_ERROR == sync ) {
			
				continue;
			}
			
			if ( Z_DATA_ERROR == sync ) {
			
				OTF_fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
						"Z_DATA_ERROR.\n",
						__FUNCTION__, __FILE__, __LINE__ );
				
				return -1;
			}

			if ( Z_STREAM_ERROR == sync ) {
			
				OTF_fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
						"Z_STREAM_ERROR.\n",
						__FUNCTION__, __FILE__, __LINE__ );
				
				return -1;
			}

		} while ( 1 );
	}

#endif /* HAVE_ZLIB */

	return ret;
}
Ejemplo n.º 25
0
void forward_modeling(sf_file Fdat, sf_mpi *mpipar, sf_sou soupar, sf_acqui acpar, sf_vec_s array, bool verb)
/*< acoustic forward modeling >*/
{
	int ix, iz, is, ir, it;
	int sx, rx, sz, rz, frectx, frectz;
	int nz, nx, padnz, padnx, padnzx, nt, nr, nb;

	float dx2, dz2, dt2, dt;
	float **vv, **dd;
	float **p0, **p1, **p2, **term, **tmparray, *rr;

	FILE *swap;

	MPI_Comm comm=MPI_COMM_WORLD;

	swap=fopen("temswap.bin", "wb+");

	padnz=acpar->padnz;
	padnx=acpar->padnx;
	padnzx=padnz*padnx;
	nz=acpar->nz;
	nx=acpar->nx;
	nt=acpar->nt;
	nr=acpar->nr;
	nb=acpar->nb;
	sz=acpar->sz;
	rz=acpar->rz;
	frectx=soupar->frectx;
	frectz=soupar->frectz;

	dx2=acpar->dx*acpar->dx;
	dz2=acpar->dz*acpar->dz;
	dt2=acpar->dt*acpar->dt;
	dt=acpar->dt;

	vv = sf_floatalloc2(padnz, padnx);
	dd=sf_floatalloc2(nt, nr);

	p0=sf_floatalloc2(padnz, padnx);
	p1=sf_floatalloc2(padnz, padnx);
	p2=sf_floatalloc2(padnz, padnx);
	term=sf_floatalloc2(padnz, padnx);
	rr=sf_floatalloc(padnzx);

	/* padding and convert vector to 2-d array */
	pad2d(array->vv, vv, nz, nx, nb);

	for(is=mpipar->cpuid; is<acpar->ns; is+=mpipar->numprocs){
		sf_warning("###### is=%d ######", is+1);

		memset(dd[0], 0., nr*nt*sizeof(float));
		memset(p0[0], 0., padnzx*sizeof(float));
		memset(p1[0], 0., padnzx*sizeof(float));
		memset(p2[0], 0., padnzx*sizeof(float));
		
		sx=acpar->s0_v+is*acpar->ds_v;
		source_map(sx, sz, frectx, frectz, padnx, padnz, padnzx, rr);

		for(it=0; it<nt; it++){
			if(verb) sf_warning("Modeling is=%d; it=%d;", is+1, it);

			/* output data */
			for(ir=0; ir<acpar->nr2[is]; ir++){
				rx=acpar->r0_v[is]+ir*acpar->dr_v;
				dd[acpar->r02[is]+ir][it]=p1[rx][rz];
			}

			/* laplacian operator */
			laplace(p1, term, padnx, padnz, dx2, dz2);
			
			/* load source */
			for(ix=0; ix<padnx; ix++){
				for(iz=0; iz<padnz; iz++){
					term[ix][iz] += rr[ix*padnz+iz]*array->ww[it];
				}
			}

			/* update */
			for(ix=0; ix<padnx; ix++){
				for(iz=0; iz<padnz; iz++){
					p2[ix][iz]=2*p1[ix][iz]-p0[ix][iz]+vv[ix][iz]*vv[ix][iz]*dt2*term[ix][iz];
				}
			}
			
			/* swap wavefield pointer of different time steps */
			tmparray=p0; p0=p1; p1=p2; p2=tmparray;

			/* boundary condition */
			apply_sponge(p0, acpar->bc, padnx, padnz, nb);
			apply_sponge(p1, acpar->bc, padnx, padnz, nb);
		} // end of time loop

		fseeko(swap, is*nr*nt*sizeof(float), SEEK_SET);
		fwrite(dd[0], sizeof(float), nr*nt, swap);
	}// end of shot loop
	fclose(swap);
	MPI_Barrier(comm);

	/* transfer data to Fdat */
	if(mpipar->cpuid==0){
		swap=fopen("temswap.bin", "rb");
		for(is=0; is<acpar->ns; is++){
			fseeko(swap, is*nr*nt*sizeof(float), SEEK_SET);
			fread(dd[0], sizeof(float), nr*nt, swap);
			sf_floatwrite(dd[0], nr*nt, Fdat);
		}
		fclose(swap);
		remove("temswap.bin");
	}
	MPI_Barrier(comm);
	
	/* release allocated memory */
	free(*p0); free(p0); free(*p1); free(p1);
	free(*p2); free(p2); free(*vv); free(vv);
	free(*dd); free(dd);
	free(rr); free(*term); free(term);
}
Ejemplo n.º 26
0
int OTF_File_revive( OTF_File* file, OTF_FileMode mode  ) {


	if ( NULL != file->externalbuffer ) {

		/* no need to revive, everything is fine in 'external buffer' mode */
		return 1;
	}


	switch ( mode ) {

	case OTF_FILEMODE_READ :
	
		/* *** read *** */

		if ( NULL == file->file ) {

			/* file currently closed, aka open or reopen */

			/* 
			OTF_fprintf( stderr, "OTF_File_revive() READ: ask FileManager for free handle\n" );
			*/
			if ( 0 == OTF_FileManager_guaranteeFile( file->manager ) ) {

				OTF_fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
						"OTF_FileManager_guaranteeFile() failed.\n",
						__FUNCTION__, __FILE__, __LINE__ );
				
				return 0;
			}

			/* open first time, as we open O_RDONLY plus O_NOATIME, which fopen doesn't know, use open/fdopen  */
#ifdef _GNU_SOURCE
			{

				int fd;
				int retry_num = 5;
				int flags = O_RDONLY | O_NOATIME;

				while ( -1 == ( fd = open( file->filename, flags ) ) ) {

					/* if the user is not the owner of the file, open with O_NOATIME will fail with errno == EPERM;
					   try to open without O_NOATIME again to avoid this problem */
					if ( EPERM == errno ) {

						flags = O_RDONLY;
						continue;

						/* the file name might be stale, e.g. on Network File System (NFS) */
					} else if ( ESTALE == errno && 0 < --retry_num ) {

						sleep(1);
						continue;

					} else {

						/* show this error every time */
						OTF_fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
								"cannot open file %s for reading. Maybe the number of "
								"opened filehandles exceeds your system's limit\n",
								__FUNCTION__, __FILE__, __LINE__, file->filename );

						return 0;
					}

				}
	
				file->file= fdopen( fd, "r" );

			}
#else /* _GNU_SOURCE */
			file->file= fopen( file->filename, "rb" );
#endif /* _GNU_SOURCE */
			if( NULL == file->file ) {

				/* show this error every time */
				OTF_fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
						"cannot open file %s for reading. Maybe the number of "
						"opened filehandles exceeds your system's limit\n",
						__FUNCTION__, __FILE__, __LINE__, file->filename );

				return 0;
			}

			/* Upon repoen, seek to the current position */
			if ( 0 != file->pos ) {
				fseeko( file->file, file->pos, SEEK_SET );
			}

			
			if ( 0 == OTF_FileManager_registerFile( file->manager, file ) ) {

				OTF_fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
						"OTF_FileManager_registerFile() failed.\n",
						__FUNCTION__, __FILE__, __LINE__ );
				
				return 0;
			}

		} else {

			/* file already opened */
			/*
			OTF_fprintf( stderr, "OTF_File_revive() READ: update FileManagers LRU list\n" );
			*/
			if ( 0 ==  OTF_FileManager_touchFile( file->manager, file ) ) {

				OTF_fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
						"OTF_FileManager_touchFile() failed.\n",
						__FUNCTION__, __FILE__, __LINE__ );
				
				return 0;
			}
		}

		return 1;

	case OTF_FILEMODE_WRITE :

		/* *** write *** */

		if ( NULL == file->file ) {

			/* file currently closed */

			/*
			OTF_fprintf( stderr, "OTF_File_revive() WRITE: ask FileManager for free handle\n" );
			*/
			if ( 0 == OTF_FileManager_guaranteeFile( file->manager ) ) {

				OTF_fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
						"OTF_FileManager_guaranteeFile() failed.\n",
						__FUNCTION__, __FILE__, __LINE__ );
				
				return 0;
			}

			if ( 0 != file->pos ) {

				/* re-open */

				file->file= fopen( file->filename, "ab" );
				if( NULL == file->file ) {
					
					/* show this error every time */
					OTF_fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
						"cannot open file %s for writing. Maybe the number of "
						"opened filehandles exceeds your system's limit\n",
						__FUNCTION__, __FILE__, __LINE__, file->filename );
				
					return 0;
				}

			} else {

				/* open first time */

				file->file= fopen( file->filename, "wb" );
				if( NULL == file->file ) {
					
					/* show this error every time */
					OTF_fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
						"cannot open file %s for writing. Maybe the number of "
						"opened filehandles exceeds your system's limit\n",
						__FUNCTION__, __FILE__, __LINE__, file->filename );
				
					return 0;
				}
			}

			/*
			OTF_fprintf( stderr, "OTF_File_revive() WRITE: register opened file with FileManager\n" );
			*/
			if ( 0 == OTF_FileManager_registerFile( file->manager, file ) ) {

				OTF_fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
						"OTF_FileManager_registerFile() failed.\n",
						__FUNCTION__, __FILE__, __LINE__ );
				
				return 0;
			}

		} else {

			/* file already opened */
			/*
			OTF_fprintf( stderr, "OTF_File_revive() WRITE: update FileManagers LRU list\n" );
			*/
			if ( 0 ==  OTF_FileManager_touchFile( file->manager, file ) ) {

				OTF_fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
						"OTF_FileManager_touchFile() failed.\n",
						__FUNCTION__, __FILE__, __LINE__ );
				
				return 0;
			}
		}

		return 1;

	case OTF_FILEMODE_SEEK :
	
		/* *** seek *** */

		if ( NULL == file->file ) {

			/* file currently closed */

			/*
			OTF_fprintf( stderr, "OTF_File_revive() READ: ask FileManager for free handle\n" );
			*/
			if ( 0 == OTF_FileManager_guaranteeFile( file->manager ) ) {

				OTF_fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
						"OTF_FileManager_guaranteeFile() failed.\n",
						__FUNCTION__, __FILE__, __LINE__ );

				return 0;
			}

			if ( 0 != file->pos ) {

				/* re-open */

				file->file= fopen( file->filename, "rb" );
				if( NULL == file->file ) {
					
					/* show this error every time */
					OTF_fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
						"cannot open file %s for reading. Maybe the number of "
						"opened filehandles exceeds your system's limit\n",
						__FUNCTION__, __FILE__, __LINE__, file->filename );
				
					return 0;
				}

				/* dont need to seek to the saved position because there 
				will be another seek anyway*/
				/*
				fseeko( file->file, file->pos, SEEK_SET );
				*/

			} else {

				/* open first time */

				file->file= fopen( file->filename, "rb" );
				if( NULL == file->file ) {
					
					/* show this error every time */
					OTF_fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
						"cannot open file %s for reading. Maybe the number of "
						"opened filehandles exceeds your system's limit\n",
						__FUNCTION__, __FILE__, __LINE__, file->filename );
				
					return 0;
				}
			}

			/*
			OTF_fprintf( stderr, "OTF_File_revive() SEEK: register opened file with FileManager\n" );
			*/
			if ( 0 == OTF_FileManager_registerFile( file->manager, file ) ) {

				OTF_fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
						"OTF_FileManager_registerFile() failed.\n",
						__FUNCTION__, __FILE__, __LINE__ );
				
				return 0;
			}

		} else {

			/* file already opened */
			/*
			OTF_fprintf( stderr, "OTF_File_revive() READ: update FileManagers LRU list\n" );
			*/
			if ( 0 ==  OTF_FileManager_touchFile( file->manager, file ) ) {

				OTF_fprintf( stderr, "ERROR in function %s, file: %s, line: %i:\n "
						"OTF_FileManager_touchFile() failed.\n",
						__FUNCTION__, __FILE__, __LINE__ );
				
				return 0;
			}
		}

		return 1;


	default:

		/* *** unknown mode *** */

		return 0;
	}
}
Ejemplo n.º 27
0
//______________________________________
//
// Open and recursively read the atoms
// until we got the information we want
// i.e. :
//	index for audio and video track
//	esds for mpeg4
//	size / codec used
//
// We don't care about sync atom and all
// other stuff which are pretty useless on
// 3gp file anyway.
//______________________________________
uint8_t    MP4Header::open(const char *name)
{
        printf("** opening 3gpp files **");
        _fd=fopen(name,"rb");
        if(!_fd)
        {
                printf("\n cannot open %s \n",name);
                return 0;
        }
#define CLR(x)              memset(& x,0,sizeof(  x));

        CLR( _videostream);
        CLR(  _mainaviheader);

        _videostream.dwScale=1000;
        _videostream.dwRate=10000;
        _mainaviheader.dwMicroSecPerFrame=100000;;     // 10 fps hard coded

        adm_atom *atom=new adm_atom(_fd);
        // Some mp4/mov files have the data at the end but do start properly
        // detect and workaround...
        // Check it is not mdat start(ADM_memcpy_0)
        uint8_t check[4];
        fseeko(_fd,4,SEEK_SET);
        fread(check,4,1,_fd);
        fseeko(_fd,0,SEEK_SET);
        if(check[0]=='m' && check[1]=='d' &&check[2]=='a' && check[3]=='t')
        {
                        uint64_t of;
                                        printf("Data first, header later...\n");
                                        of=atom->read32();
                                        if(of==1)
                                        {
                                          atom->read32();	// size
                                          atom->read32();	// fcc
                                          of=atom->read64();
                                        }
                                        fseeko(_fd,of,SEEK_SET);
                                        printf("Header starts at %"LLX"\n",of);
                                        delete atom;
                                        atom=new adm_atom(_fd);
        }
        //**************

        if(!lookupMainAtoms((void*) atom))
        {
          printf("Cannot find needed atom\n");
          fclose(_fd);
		  delete atom;
          return 0;
        }

        delete atom;

	      _isvideopresent=1;
	      _isaudiopresent=0;

              _videostream.fccType=fourCC::get((uint8_t *)"vids");
              _video_bih.biBitCount=24;
              _videostream.dwInitialFrames= 0;
              _videostream.dwStart= 0;

	printf("\n");


        if(!VDEO.index)
        {
                printf("No index!\n");
                return 0;
        }

        // If it is mpeg4 and we have extra data
        // Decode vol header to get the real width/height
        // The mpeg4/3GP/Mov header is often misleading

        if(fourCC::check(_videostream.fccHandler,(uint8_t *)"DIVX"))
        {
            if(VDEO.extraDataSize)
            {
                uint32_t w,h,ti;
                if(extractMpeg4Info(VDEO.extraData,VDEO.extraDataSize,&w,&h,&ti))
                {
                    printf("MP4 Corrected size : %"LU" x %"LU"\n",w,h);
                    _video_bih.biWidth=_mainaviheader.dwWidth=w ;
                    _video_bih.biHeight=_mainaviheader.dwHeight=h;
                }
            }else { printf("No extradata to probe\n");}

        }
        else
        {

        /*
            Same story for H263 : Analyze 1st frame to get the real width/height
        */
            if(fourCC::check(_videostream.fccHandler,(uint8_t *)"H263"))
            {
                uint32_t w,h,sz;
                uint8_t *bfer=NULL;
                sz=VDEO.index[0].size;
                if(sz)
                {
                        bfer=new uint8_t[sz];
                        ADMCompressedImage img;
                        img.data=bfer;
                        if(getFrame(0,&img))
                        {
                        if(extractH263Info(bfer,sz,&w,&h))
                        {
                            printf("H263 Corrected size : %"LU" x %"LU"\n",w,h);
                            _video_bih.biWidth=_mainaviheader.dwWidth=w ;
                            _video_bih.biHeight=_mainaviheader.dwHeight=h;
                        }
                        else
                        {
                                  printf("H263 COULD NOT EXTRACT SIZE, using : %"LU" x %"LU"\n",
                                      _video_bih.biWidth,  _video_bih.biHeight);
                        }
                        }
                        delete [] bfer;
                }
            }
        }
        /*
                Now build audio tracks
        */
        if(nbAudioTrack) _isaudiopresent=1; // Still needed ?
        for(int audio=0;audio<nbAudioTrack;audio++)
        {
            audioAccess[audio]=new ADM_mp4AudioAccess(name,&(_tracks[1+audio]));
            audioStream[audio]=ADM_audioCreateStream(&(_tracks[1+audio]._rdWav), audioAccess[audio]);
        }
        fseeko(_fd,0,SEEK_SET);
        printf("3gp/mov file successfully read..\n");
        return 1;
}
Ejemplo n.º 28
0
void createBTreeIndex(char *text, char *bin, char *index, char *output, int verbose) {
    int i, j, k;
    struct timespec start, stop;
    node *root;
    node *assign = NULL;
    FILE *fb;
    FILE *ft;
    FILE *fo;
    record *rec;
    genBank_t *g = NULL;
    int count = 0;
    char *line = NULL;
    size_t len = 0;
    ssize_t read;
    off_t oTotal, oCurr;
    int taxId;
    int gi;
    float score;
    int pFrom;
    int pTo;
    int noGene = 0;

    fb = fopen(bin, "rb");
    if (!fb) {
        fprintf(stdout, "Unable to open file %s\n", bin);
        exit(-1);
    }

    ft = fopen(text, "r");
    if (!ft) {
        fprintf(stdout, "Unable to open file %s\n", text);
        exit(-1);
    }

    fo = fopen(output, "w");
    if (!fo) {
        fprintf(stdout, "Unable to open file %s\n", output);
        exit(-1);
    }

    root = readIndexBtree(index);

    fseeko(ft, 0, SEEK_END);
    oTotal = ftello(ft);
    fseeko(ft, 0, SEEK_SET);

    k = 1;
    printf("Performing the gene assignment ... \n");
    fflush(NULL);
    clock_gettime(CLOCK_MONOTONIC, &start);
    while ((read = getline(&line, &len, ft)) != -1) {
        oCurr = ftello(ft);
        if ((i = sscanf(line, "%*s\t%d\t%d\t%f\t%d\t%d", &taxId, &gi, &score, &pFrom, &pTo)) == 5) {
            clock_gettime(CLOCK_MONOTONIC, &stop);
            j = timespecDiff(&stop, &start) / 1000000000;
            if (verbose) {
                printf("\tLines reads %d. Reads without genes %d. GIs with genes %d. Elapsed time %lu sec. Estimated time %lu sec.\r", k, noGene, count, j, (j * oTotal / oCurr));
            }
            rec = find(root, gi, false);
            if (rec != NULL) {
                if (!assignGenes(&assign, &g, &count, fb, *((off_t *) rec->value), pFrom, pTo)) {
                    noGene++;
                }
            } else {
                noGene++;
            }
            k++;
        } else {
            printf("Can't parse the line: %d\t", i);
            printf("[[%s]]\n", line);
            exit(-1);
        }
    }
    printf("\tLines reads %d. Reads without genes %d. GIs with genes %d. Elapsed time %lu sec. Estimated time %lu sec.\n", k++, noGene, count, j, (j * oTotal / oCurr));
    fflush(NULL);
    if (line) free(line);
    line = malloc(sizeof (char) * 1);
    len = 1;

    if (g != NULL) {
        qsort(g, count, sizeof (genBank_t), cmpGenBank);
        for (i = 0; i < count; i++) {
            if (g[i].cds != NULL) {
                qsort(g[i].cds, g[i].cds_number, sizeof (cds_t), cmpCDSSum);
                for (j = 0; j < g[i].cds_number; j++) {

                    line[0] = '\0';
                    if (g[i].cds[j].cog_number != 0) {
                        for (k = 0; k < g[i].cds[j].cog_number; k++) {
                            if (len <= strlen(line) + strlen(g[i].cds[j].cog[k]) + 2) {
                                len += strlen(g[i].cds[j].cog[k]) + 2;
                                if (k < g[i].cds[j].cog_number - 1) len++;
                                line = (char *) realloc(line, sizeof (char) * len);
                            }
                            strcat(line, g[i].cds[j].cog[k]);
                            if (k < g[i].cds[j].cog_number - 1) {
                                strcat(line, ",");
                            }
                        }
                        if (strlen(line) + 3 < len) {
                            len += 3;
                            line = (char *) realloc(line, sizeof (char) * len);
                        }
                        strcat(line, "\t");
                    } else {
                        if (len < 3) {
                            len = 3;
                            line = (char *) realloc(line, sizeof (char) * len);
                        }
                        strcat(line, "-\t");
                    }
                    if (g[i].cds[j].protClust_number != 0) {
                        for (k = 0; k < g[i].cds[j].protClust_number; k++) {
                            if (len <= strlen(line) + strlen(g[i].cds[j].protClust[k]) + 2) {
                                len += strlen(g[i].cds[j].protClust[k]) + 2;
                                if (k < g[i].cds[j].protClust_number - 1) len++;
                                line = (char *) realloc(line, sizeof (char) * len);
                            }
                            strcat(line, g[i].cds[j].protClust[k]);
                            if (k < g[i].cds[j].protClust_number - 1) {
                                strcat(line, ",");
                            }
                        }
                    } else {
                        if (strlen(line) + 4 > len) {
                            len += 4;
                            line = (char *) realloc(line, sizeof (char) * len);
                        }
                        strcat(line, "-");
                    }

                    fprintf(fo, "%s\t%d\t%s\t%s\t%d\t%s\n",
                            g[i].locusName, g[i].taxId,
                            g[i].cds[j].proteinId,
                            g[i].cds[j].locusName,
                            g[i].cds[j].hits,
                            line);
                    freeCDS(g[i].cds + j);
                }
                free(g[i].cds);
            }
            if (g[i].locusName) free(g[i].locusName);
        }
        free(g);
    }

    destroy_tree(assign, freeDataAssign);
    destroy_tree(root, freeData);
    if (line) free(line);
    fclose(fb);
    fclose(ft);
    fclose(fo);
}
Ejemplo n.º 29
0
void finalizeAtom(_TCHAR *path, int bitrate, int mode, int modeQuality, int samplerate, SInt64 frame, AudioStreamBasicDescription *asbd, mp4Metadata_t *metadata)
{
    unsigned int tmp;
    char atom[4];
    int udtaSize = 0;
    int bufferSize = 1024*1024;
    char *tmpbuf = (char *)malloc(bufferSize);
    char *tmpbuf2 = (char *)malloc(bufferSize);
    char *read = tmpbuf;
    char *write = tmpbuf2;
    char *swap;
    FILE *fp;
    unsigned char *udta = NULL;
    WIN32_FILE_ATTRIBUTE_DATA fi;

    GetFileAttributesEx(path,GetFileExInfoStandard,&fi);
    __int64 origSize = ((unsigned __int64)fi.nFileSizeHigh << 32)|fi.nFileSizeLow;

    if(_tfopen_s(&fp, path, _T("r+b"))) return;

    int actualFreq = getM4aFrequency(fp);
    if(actualFreq && (actualFreq != samplerate)) frame = (int)floor(0.5+(double)frame*actualFreq/samplerate);
    int padding = (int)((SInt64)ceil((frame + 2112)/1024.0)*1024 - (frame + 2112));

    ComponentDescription cd;
    cd.componentType = 'aenc';
    cd.componentSubType = asbd->mFormatID;
    cd.componentManufacturer = kAppleManufacturer;
    cd.componentFlags = 0;
    cd.componentFlagsMask = 0;
    int version = GetComponentVersion((ComponentInstance)FindNextComponent(NULL, &cd));

    if(!bitrate) {
        while(1) { //skip until mdat;
            if(fread(&tmp,4,1,fp) < 1) goto end;
            if(fread(atom,1,4,fp) < 4) goto end;
            tmp = SWAP32(tmp);
            if(!memcmp(atom,"mdat",4)) break;
            if(fseeko(fp,tmp-8,SEEK_CUR) != 0) goto end;
        }
        bitrate = (int)ceil(0.5+(tmp-8)/((double)frame/actualFreq)*8) ;
        rewind(fp);
    }

    udta = setupUdta(metadata,bitrate,mode,modeQuality,padding,frame,version,&udtaSize);
    int i;

    while(1) { //skip until moov;
        if(fread(&tmp,4,1,fp) < 1) goto end;
        if(fread(atom,1,4,fp) < 4) goto end;
        tmp = SWAP32(tmp);
        if(!memcmp(atom,"moov",4)) break;
        if(fseeko(fp,tmp-8,SEEK_CUR) != 0) goto end;
    }

    if(fseeko(fp,-8,SEEK_CUR) != 0) goto end;

    /* update moov atom size */
    __int64 pos_moov = ftello(fp);
    if(fread(&tmp,4,1,fp) < 1) goto end;
    int moovSize = SWAP32(tmp);
    if(fseeko(fp,-4,SEEK_CUR) != 0) goto end;
    tmp = SWAP32(moovSize + udtaSize);
    if(fwrite(&tmp,4,1,fp) < 1) goto end;

    if(fseeko(fp,4,SEEK_CUR) != 0) goto end;

    while(1) { //skip until trak;
        if(fread(&tmp,4,1,fp) < 1) goto end;
        if(fread(atom,1,4,fp) < 4) goto end;
        tmp = SWAP32(tmp);
        if(!memcmp(atom,"trak",4)) break;
        if(fseeko(fp,tmp-8,SEEK_CUR) != 0) goto end;
    }

    while(1) { //skip until mdia;
        if(fread(&tmp,4,1,fp) < 1) goto end;
        if(fread(atom,1,4,fp) < 4) goto end;
        tmp = SWAP32(tmp);
        if(!memcmp(atom,"mdia",4)) break;
        if(fseeko(fp,tmp-8,SEEK_CUR) != 0) goto end;
    }

    while(1) { //skip until minf;
        if(fread(&tmp,4,1,fp) < 1) goto end;
        if(fread(atom,1,4,fp) < 4) goto end;
        tmp = SWAP32(tmp);
        if(!memcmp(atom,"minf",4)) break;
        if(fseeko(fp,tmp-8,SEEK_CUR) != 0) goto end;
    }

    while(1) { //skip until stbl;
        if(fread(&tmp,4,1,fp) < 1) goto end;
        if(fread(atom,1,4,fp) < 4) goto end;
        tmp = SWAP32(tmp);
        if(!memcmp(atom,"stbl",4)) break;
        if(fseeko(fp,tmp-8,SEEK_CUR) != 0) goto end;
    }

    __int64 nextAtom = ftello(fp);

    while(1) { //skip until stsz;
        if(fread(&tmp,4,1,fp) < 1) goto end;
        if(fread(atom,1,4,fp) < 4) goto end;
        tmp = SWAP32(tmp);
        if(!memcmp(atom,"stsz",4)) break;
        if(fseeko(fp,tmp-8,SEEK_CUR) != 0) goto end;
    }

    if(fseeko(fp,4,SEEK_CUR) != 0) goto end;

    /* estimate maximum bitrate */
    int maxBitrate = 0;
    if(fread(&tmp,4,1,fp) < 1) goto end;
    tmp = SWAP32(tmp);
    if(tmp) maxBitrate = tmp * 8 * actualFreq / 1024;
    else {
        if(fread(&tmp,4,1,fp) < 1) goto end;
        int frameNum = SWAP32(tmp);
        int frameSize;
        int sample;
        for(i=0,sample=0,frameSize=0; i<frameNum; i++) {
            if(fread(&tmp,4,1,fp) < 1) goto end;
            tmp = SWAP32(tmp);
            if(sample + 1024 >= actualFreq) {
                frameSize += (int)((actualFreq - sample)/1024.0 * tmp);
                if(frameSize*8 > maxBitrate) maxBitrate = frameSize*8;
                sample = 1024 - (actualFreq - sample);
                frameSize = (int)(sample/1024.0 * tmp);
                continue;
            }
            frameSize += tmp;
            sample += 1024;
        }
    }

    if(fseeko(fp,nextAtom,SEEK_SET) != 0) goto end;

    /* write bitrate info */
    while(1) { //skip until esds;
        if(fread(atom,1,4,fp) < 4) goto end;
        if(!memcmp(atom,"esds",4)) break;
        if(fseeko(fp,-3,SEEK_CUR) != 0) goto end;
    }

    if(fseeko(fp,5,SEEK_CUR) != 0) goto end;
    for(i=0; i<3; i++) {
        if(fread(atom,1,1,fp) < 1) goto end;
        if((unsigned char)atom[0] != 0x80) {
            if(fseeko(fp,-1,SEEK_CUR) != 0) goto end;
            break;
        }
    }
    if(fseeko(fp,5,SEEK_CUR) != 0) goto end;
    for(i=0; i<3; i++) {
        if(fread(atom,1,1,fp) < 1) goto end;
        if((unsigned char)atom[0] != 0x80) {
            if(fseeko(fp,-1,SEEK_CUR) != 0) goto end;
            break;
        }
    }
    if(fseeko(fp,6,SEEK_CUR) != 0) goto end;
    tmp = SWAP32(maxBitrate);
    if(fwrite(&tmp,4,1,fp) < 1) goto end;
    tmp = SWAP32(bitrate);
    if(fwrite(&tmp,4,1,fp) < 1) goto end;

    if(fseeko(fp,nextAtom,SEEK_SET) != 0) goto end;

    while(1) { //skip until stco;
        if(fread(&tmp,4,1,fp) < 1) goto end;
        if(fread(atom,1,4,fp) < 4) goto end;
        tmp = SWAP32(tmp);
        if(!memcmp(atom,"stco",4)) break;
        if(fseeko(fp,tmp-8,SEEK_CUR) != 0) goto end;
    }

    int *stco = (int *)malloc(tmp-8);
    if(fread(stco,1,tmp-8,fp) < tmp-8) goto end;
    int nElement = SWAP32(stco[1]);

    /* update stco atom */

    for(i=0; i<nElement; i++) {
        stco[2+i] = SWAP32(SWAP32(stco[2+i])+udtaSize);
    }
    if(fseeko(fp,8-(int)tmp,SEEK_CUR) != 0) goto end;
    if(fwrite(stco,1,tmp-8,fp) < tmp-8) goto end;

    free(stco);

    /* write tags */
    if(fseeko(fp,pos_moov,SEEK_SET) != 0) goto end;
    if(fseeko(fp,moovSize,SEEK_CUR) != 0) goto end;

    __int64 pos_tag = ftello(fp);
    __int64 bytesToMove = origSize-pos_tag;

    if(bytesToMove < udtaSize) {
        if(bufferSize < udtaSize) {
            tmpbuf = (char *)realloc(tmpbuf,udtaSize);
            read = tmpbuf;
        }
        if((int)fread(read,1,(size_t)bytesToMove,fp) < bytesToMove) goto end;
        if(fseeko(fp,0,SEEK_END) != 0) goto end;
        if((int)fwrite(read,1,(size_t)(udtaSize-bytesToMove),fp) < (udtaSize-bytesToMove)) goto end;
        if((int)fwrite(read,1,(size_t)bytesToMove,fp) < bytesToMove) goto end;
    }
    else if(bytesToMove > bufferSize) {
        if(bufferSize < udtaSize) {
            tmpbuf = (char *)realloc(tmpbuf,udtaSize);
            tmpbuf2 = (char *)realloc(tmpbuf2,udtaSize);
            read = tmpbuf;
            write = tmpbuf2;
            bufferSize = udtaSize;
            if(bytesToMove <= bufferSize) goto moveBlock_is_smaller_than_buffer;
        }
        if((int)fread(write,1,bufferSize,fp) < bufferSize) goto end;
        bytesToMove -= bufferSize;
        while(bytesToMove > bufferSize) {
            if((int)fread(read,1,bufferSize,fp) < bufferSize) goto end;
            if(fseeko(fp,udtaSize-2*bufferSize,SEEK_CUR) != 0) goto end;
            if((int)fwrite(write,1,bufferSize,fp) < bufferSize) goto end;
            if(fseeko(fp,bufferSize-udtaSize,SEEK_CUR) != 0) goto end;
            swap = read;
            read = write;
            write = swap;
            bytesToMove -= bufferSize;
        }
        if((int)fread(read,1,(size_t)bytesToMove,fp) < bytesToMove) goto end;
        if(fseeko(fp,udtaSize-bufferSize-bytesToMove,SEEK_CUR) != 0) goto end;
        if((int)fwrite(write,1,bufferSize,fp) < bufferSize) goto end;
        if((int)fwrite(read,1,(size_t)bytesToMove,fp) < bytesToMove) goto end;
    }
    else {
moveBlock_is_smaller_than_buffer:
        if((int)fread(read,1,(size_t)bytesToMove,fp) < bytesToMove) goto end;
        if(udtaSize < bytesToMove) {
            if(fseeko(fp,udtaSize-bytesToMove,SEEK_CUR) != 0) goto end;
        }
        else {
            if(fseeko(fp,0-bytesToMove,SEEK_CUR) != 0) goto end;
            if((int)fwrite(udta,1,udtaSize,fp) < udtaSize) goto end;
        }
        if((int)fwrite(read,1,(size_t)bytesToMove,fp) < bytesToMove) goto end;
    }

    if(fseeko(fp,pos_tag,SEEK_SET) != 0) goto end;

    if((int)fwrite(udta,1,udtaSize,fp) < udtaSize) goto end;

end:
    fclose(fp);
    if(udta) free(udta);
    free(tmpbuf);
    free(tmpbuf2);
}
Ejemplo n.º 30
0
//setter verdien
void popset (struct popl *popha,int DocID,int pop) {
	//skriver ny verdi
        fseeko((*popha).fh,DocID * sizeof(pop),SEEK_SET);

        fwrite(&pop,sizeof(pop),1,(*popha).fh);
}