ogginfo2.c 31 KB
Newer Older
1 2 3 4
/* Ogginfo
 *
 * A tool to describe ogg file contents and metadata.
 *
5
 * Copyright 2002-2005 Michael Smith <msmith@xiph.org>
6 7 8
 * Licensed under the GNU GPL, distributed with this program.
 */

9 10 11
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
12 13 14 15 16

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
17 18
#include <stdarg.h>
#include <getopt.h>
Ralph Giles's avatar
Ralph Giles committed
19
#include <math.h>
20 21 22 23 24 25 26 27

#include <ogg/ogg.h>
#include <vorbis/codec.h>

#include <locale.h>
#include "utf8.h"
#include "i18n.h"

28 29
#include "theora.h"

30 31
#define CHUNK 4500

32 33 34 35 36 37
#ifdef _WIN32
#define I64FORMAT "I64d"
#else
#define I64FORMAT "lld"
#endif

38 39 40 41 42 43 44 45 46 47 48
struct vorbis_release {
    char *vendor_string;
    char *desc;
} releases[] = {
        {"Xiphophorus libVorbis I 20000508", "1.0 beta 1 or beta 2"},
        {"Xiphophorus libVorbis I 20001031", "1.0 beta 3"},
        {"Xiphophorus libVorbis I 20010225", "1.0 beta 4"},
        {"Xiphophorus libVorbis I 20010615", "1.0 rc1"},
        {"Xiphophorus libVorbis I 20010813", "1.0 rc2"},
        {"Xiphophorus libVorbis I 20011217", "1.0 rc3"},
        {"Xiphophorus libVorbis I 20011231", "1.0 rc3"},
Ralph Giles's avatar
Ralph Giles committed
49
        {"Xiph.Org libVorbis I 20020717", "1.0"},
Monty's avatar
 
Monty committed
50
        {"Xiph.Org libVorbis I 20030909", "1.0.1"},
51 52
        {"Xiph.Org libVorbis I 20040629", "1.1.0"},
	{"Xiph.Org libVorbis I 20050304", "1.1.1"},
53 54 55 56
        {NULL, NULL},
    };


57 58 59
/* TODO:
 *
 * - detect violations of muxing constraints
60 61
 * - detect granulepos 'gaps' (possibly vorbis-specific). (seperate from 
 *   serial-number gaps)
62 63
 */

64 65 66 67
typedef struct _stream_processor {
    void (*process_page)(struct _stream_processor *, ogg_page *);
    void (*process_end)(struct _stream_processor *);
    int isillegal;
68
    int constraint_violated;
69 70
    int shownillegal;
    int isnew;
71 72
    long seqno;
    int lostseq;
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96

    int start;
    int end;

    int num;
    char *type;

    ogg_uint32_t serial; /* must be 32 bit unsigned */
    ogg_stream_state os;
    void *data;
} stream_processor;

typedef struct {
    stream_processor *streams;
    int allocated;
    int used;

    int in_headers;
} stream_set;

typedef struct {
    vorbis_info vi;
    vorbis_comment vc;

Monty's avatar
 
Monty committed
97
    ogg_int64_t bytes;
98
    ogg_int64_t lastgranulepos;
99
    ogg_int64_t firstgranulepos;
100 101 102 103

    int doneheaders;
} misc_vorbis_info;

104 105 106 107 108 109 110 111 112
typedef struct {
    theora_info ti;
    theora_comment tc;

    ogg_int64_t bytes;
    ogg_int64_t lastgranulepos;
    ogg_int64_t firstgranulepos;

    int doneheaders;
113 114

    ogg_int64_t framenum_expected;
115 116
} misc_theora_info;

117 118 119 120
static int printinfo = 1;
static int printwarn = 1;
static int verbose = 1;

121 122
static int flawed;

123 124 125
#define CONSTRAINT_PAGE_AFTER_EOS   1
#define CONSTRAINT_MUXING_VIOLATED  2

126 127 128 129 130 131 132 133 134 135
static stream_set *create_stream_set(void) {
    stream_set *set = calloc(1, sizeof(stream_set));

    set->streams = calloc(5, sizeof(stream_processor));
    set->allocated = 5;
    set->used = 0;

    return set;
}

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
static void info(char *format, ...) 
{
    va_list ap;

    if(!printinfo)
        return;

    va_start(ap, format);
    vfprintf(stdout, format, ap);
    va_end(ap);
}

static void warn(char *format, ...) 
{
    va_list ap;

152
    flawed = 1;
153 154 155 156 157 158 159 160 161 162 163 164
    if(!printwarn)
        return;

    va_start(ap, format);
    vfprintf(stdout, format, ap);
    va_end(ap);
}

static void error(char *format, ...) 
{
    va_list ap;

165 166
    flawed = 1;

167 168 169 170 171
    va_start(ap, format);
    vfprintf(stdout, format, ap);
    va_end(ap);
}

172 173
static void check_xiph_comment(stream_processor *stream, int i, char *comment,
    int comment_length)
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
{
    char *sep = strchr(comment, '=');
    char *decoded;
    int j;
    int broken = 0;
    unsigned char *val;
    int bytes;
    int remaining;

    if(sep == NULL) {
        warn(_("Warning: Comment %d in stream %d has invalid "
              "format, does not contain '=': \"%s\"\n"), 
              i, stream->num, comment);
             return;
    }

    for(j=0; j < sep-comment; j++) {
        if(comment[j] < 0x20 || comment[j] > 0x7D) {
            warn(_("Warning: Invalid comment fieldname in "
                   "comment %d (stream %d): \"%s\"\n"),
                   i, stream->num, comment);
            broken = 1;
            break;
        }
    }

    if(broken)
	return;

Ralph Giles's avatar
Ralph Giles committed
203
    val = (unsigned char *)comment;
204

205 206
    j = sep-comment+1;
    while(j < comment_length)
207
    {
208
        remaining = comment_length - j;
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
        if((val[j] & 0x80) == 0)
            bytes = 1;
        else if((val[j] & 0x40) == 0x40) {
            if((val[j] & 0x20) == 0)
                bytes = 2;
            else if((val[j] & 0x10) == 0)
                bytes = 3;
            else if((val[j] & 0x08) == 0)
                bytes = 4;
            else if((val[j] & 0x04) == 0)
                bytes = 5;
            else if((val[j] & 0x02) == 0)
                bytes = 6;
            else {
                warn(_("Warning: Illegal UTF-8 sequence in "
                    "comment %d (stream %d): length marker wrong\n"),
                    i, stream->num);
                broken = 1;
                break;
            }
        }
        else {
            warn(_("Warning: Illegal UTF-8 sequence in comment "
                "%d (stream %d): length marker wrong\n"), i, stream->num);
            broken = 1;
            break;
        }

        if(bytes > remaining) {
            warn(_("Warning: Illegal UTF-8 sequence in comment "
                "%d (stream %d): too few bytes\n"), i, stream->num);
            broken = 1;
            break;
        }

        switch(bytes) {
            case 1:
                /* No more checks needed */
                break;
            case 2:
                if((val[j+1] & 0xC0) != 0x80)
                    broken = 1;
                if((val[j] & 0xFE) == 0xC0)
                    broken = 1;
                break;
            case 3:
                if(!((val[j] == 0xE0 && val[j+1] >= 0xA0 && val[j+1] <= 0xBF && 
                         (val[j+2] & 0xC0) == 0x80) ||
                     (val[j] >= 0xE1 && val[j] <= 0xEC && 
                         (val[j+1] & 0xC0) == 0x80 &&
                         (val[j+2] & 0xC0) == 0x80) ||
                     (val[j] == 0xED && val[j+1] >= 0x80 &&
                         val[j+1] <= 0x9F &&
                         (val[j+2] & 0xC0) == 0x80) ||
                     (val[j] >= 0xEE && val[j] <= 0xEF &&
                         (val[j+1] & 0xC0) == 0x80 &&
                         (val[j+2] & 0xC0) == 0x80)))
                     broken = 1;
                 if(val[j] == 0xE0 && (val[j+1] & 0xE0) == 0x80)
                     broken = 1;
                 break;
            case 4:
                 if(!((val[j] == 0xF0 && val[j+1] >= 0x90 &&
                         val[j+1] <= 0xBF &&
                         (val[j+2] & 0xC0) == 0x80 &&
                         (val[j+3] & 0xC0) == 0x80) ||
                     (val[j] >= 0xF1 && val[j] <= 0xF3 &&
                         (val[j+1] & 0xC0) == 0x80 &&
                         (val[j+2] & 0xC0) == 0x80 &&
                         (val[j+3] & 0xC0) == 0x80) ||
                     (val[j] == 0xF4 && val[j+1] >= 0x80 &&
                         val[j+1] <= 0x8F &&
                         (val[j+2] & 0xC0) == 0x80 &&
                         (val[j+3] & 0xC0) == 0x80)))
                     broken = 1;
                 if(val[j] == 0xF0 && (val[j+1] & 0xF0) == 0x80)
                     broken = 1;
                 break;
             /* 5 and 6 aren't actually allowed at this point */
             case 5:
                 broken = 1;
                 break;
             case 6:
                 broken = 1;
                 break;
         }

         if(broken) {
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
             char *simple = malloc (comment_length + 1);
             char *seq = malloc (comment_length * 3 + 1);
             static char hex[] = {'0', '1', '2', '3', '4', '5', '6', '7', 
                                  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
             int i, c1 = 0, c2 = 0;
             for (i = 0; i < comment_length; i++) {
               seq[c1++] = hex[((unsigned char)comment[i]) >> 4];
               seq[c1++] = hex[((unsigned char)comment[i]) & 0xf];
               seq[c1++] = ' ';

               if(comment[i] < 0x20 || comment[i] > 0x7D)
                 simple[c2++] = '?';
               else
                 simple[c2++] = comment[i];
             }
             seq[c1] = 0;
             simple[c2] = 0;
314
             warn(_("Warning: Illegal UTF-8 sequence in comment "
315 316
                   "%d (stream %d): invalid sequence \"%s\": %s\n"), i, 
                   stream->num, simple, seq);
317
             broken = 1;
318 319
             free (simple);
             free (seq);
320 321 322 323 324 325 326 327 328 329 330
             break;
         }

         j += bytes;
     }

     if(!broken) {
         if(utf8_decode(sep+1, &decoded) < 0) {
             warn(_("Warning: Failure in utf8 decoder. This should be impossible\n"));
             return;
	 }
331 332 333
         *sep = 0;
         info("\t%s=%s\n", comment, decoded);
         free(decoded);
334 335 336 337 338 339 340 341
     }
}

static void theora_process(stream_processor *stream, ogg_page *page)
{
    ogg_packet packet;
    misc_theora_info *inf = stream->data;
    int i, header=0;
342
    int res;
343 344 345 346 347

    ogg_stream_pagein(&stream->os, page);
    if(inf->doneheaders < 3)
        header = 1;

348 349 350 351 352 353 354 355 356
    while(1) {
        res = ogg_stream_packetout(&stream->os, &packet);
        if(res < 0) {
           warn(_("Warning: discontinuity in stream (%d)\n"), stream->num);
           continue;
        }
        else if (res == 0)
            break;

357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
        if(inf->doneheaders < 3) {
            if(theora_decode_header(&inf->ti, &inf->tc, &packet) < 0) {
                warn(_("Warning: Could not decode theora header "
                       "packet - invalid theora stream (%d)\n"), stream->num);
                continue;
            }
            inf->doneheaders++;
            if(inf->doneheaders == 3) {
                if(ogg_page_granulepos(page) != 0 || ogg_stream_packetpeek(&stream->os, NULL) == 1)
                    warn(_("Warning: Theora stream %d does not have headers "
                           "correctly framed. Terminal header page contains "
                           "additional packets or has non-zero granulepos\n"),
                            stream->num);
                info(_("Theora headers parsed for stream %d, "
                       "information follows...\n"), stream->num);

                info(_("Version: %d.%d.%d\n"), inf->ti.version_major, inf->ti.version_minor, inf->ti.version_subminor);
   
                info(_("Vendor: %s\n"), inf->tc.vendor);
                info(_("Width: %d\n"), inf->ti.frame_width);
                info(_("Height: %d\n"), inf->ti.frame_height);
378
		info(_("Total image: %d by %d, crop offset (%d, %d)\n"),
379 380 381 382 383 384 385 386 387
		    inf->ti.width, inf->ti.height, inf->ti.offset_x, inf->ti.offset_y);
		if(inf->ti.offset_x + inf->ti.frame_width > inf->ti.width)
		    warn(_("Frame offset/size invalid: width incorrect\n"));
		if(inf->ti.offset_y + inf->ti.frame_height > inf->ti.height)
		    warn(_("Frame offset/size invalid: height incorrect\n"));

		if(inf->ti.fps_numerator == 0 || inf->ti.fps_denominator == 0) 
		   warn(_("Invalid zero framerate\n"));
		else
388
		   info(_("Framerate %d/%d (%.02f fps)\n"), inf->ti.fps_numerator, inf->ti.fps_denominator, (float)inf->ti.fps_numerator/(float)inf->ti.fps_denominator);
389 390 391 392 393 394 395 396
		
		if(inf->ti.aspect_numerator == 0 || inf->ti.aspect_denominator == 0) 
		{
		    info(_("Aspect ratio undefined\n"));
		}	
		else
		{
		    float frameaspect = (float)inf->ti.frame_width/(float)inf->ti.frame_height * (float)inf->ti.aspect_numerator/(float)inf->ti.aspect_denominator; 
397
		    info(_("Pixel aspect ratio %d:%d (%f:1)\n"), inf->ti.aspect_numerator, inf->ti.aspect_denominator, (float)inf->ti.aspect_numerator/(float)inf->ti.aspect_denominator);
j's avatar
j committed
398
                    if(fabs(frameaspect - 4.0/3.0) < 0.02)
399
			info(_("Frame aspect 4:3\n"));
j's avatar
j committed
400
                    else if(fabs(frameaspect - 16.0/9.0) < 0.02)
401
			info(_("Frame aspect 16:9\n"));
402
		    else
j's avatar
j committed
403
			info(_("Frame aspect %f:1\n"), frameaspect);
404 405 406
		}

		if(inf->ti.colorspace == OC_CS_ITU_REC_470M)
407
		    info(_("Colourspace: Rec. ITU-R BT.470-6 System M (NTSC)\n")); 
408
		else if(inf->ti.colorspace == OC_CS_ITU_REC_470BG)
409
		    info(_("Colourspace: Rec. ITU-R BT.470-6 Systems B and G (PAL)\n")); 
410
		else
411
		    info(_("Colourspace unspecified\n"));
412 413

		if(inf->ti.pixelformat == OC_PF_420)
414
		    info(_("Pixel format 4:2:0\n"));
415
		else if(inf->ti.pixelformat == OC_PF_422)
416
		    info(_("Pixel format 4:2:2\n"));
417
		else if(inf->ti.pixelformat == OC_PF_444)
418
		    info(_("Pixel format 4:4:4\n"));
419
		else
420
		    warn(_("Pixel format invalid\n"));
421

422 423
		info(_("Target bitrate: %d kbps\n"), inf->ti.target_bitrate/1000);
		info(_("Nominal quality setting (0-63): %d\n"), inf->ti.quality);
424 425 426 427 428 429

                if(inf->tc.comments > 0)
                    info(_("User comments section follows...\n"));

                for(i=0; i < inf->tc.comments; i++) {
                    char *comment = inf->tc.user_comments[i];
430 431
		    check_xiph_comment(stream, i, comment, 
		            inf->tc.comment_lengths[i]);
432 433 434
		}
	    }
	}
Michael Smith's avatar
Michael Smith committed
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
        else {
            ogg_int64_t framenum;
            ogg_int64_t iframe,pframe;
            ogg_int64_t gp = packet.granulepos;

            if(gp > 0) {
                iframe=gp>>inf->ti.granule_shift;
                pframe=gp-(iframe<<inf->ti.granule_shift);
                framenum = iframe+pframe;
                if(inf->framenum_expected >= 0 && 
                    inf->framenum_expected != framenum)
                {
                    warn(_("Warning: Expected frame %" I64FORMAT 
                           ", got %" I64FORMAT "\n"), 
                           inf->framenum_expected, framenum);
                }
                inf->framenum_expected = framenum + 1;
            }
            else if (inf->framenum_expected >= 0) {
                inf->framenum_expected++;
            }
        }
457 458 459 460 461 462
    }

    if(!header) {
        ogg_int64_t gp = ogg_page_granulepos(page);
        if(gp > 0) {
            if(gp < inf->lastgranulepos)
463 464
                warn(_("Warning: granulepos in stream %d decreases from %" 
                        I64FORMAT " to %" I64FORMAT "\n"),
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
                        stream->num, inf->lastgranulepos, gp);
            inf->lastgranulepos = gp;
        }
        if(inf->firstgranulepos < 0) { /* Not set yet */
        }
        inf->bytes += page->header_len + page->body_len;
    }
}

static void theora_end(stream_processor *stream) 
{
    misc_theora_info *inf = stream->data;
    long minutes, seconds, milliseconds;
    double bitrate, time;

    /* This should be lastgranulepos - startgranulepos, or something like that*/
481 482 483
    ogg_int64_t iframe=inf->lastgranulepos>>inf->ti.granule_shift;
    ogg_int64_t pframe=inf->lastgranulepos-(iframe<<inf->ti.granule_shift);
    time = (double)(iframe+pframe) /
484 485 486 487 488 489 490
	((float)inf->ti.fps_numerator/(float)inf->ti.fps_denominator);
    minutes = (long)time / 60;
    seconds = (long)time - minutes*60;
    milliseconds = (long)((time - minutes*60 - seconds)*1000);
    bitrate = inf->bytes*8 / time / 1000.0;

    info(_("Theora stream %d:\n"
491
           "\tTotal data length: %" I64FORMAT " bytes\n"
492 493 494 495 496 497 498 499 500 501 502
           "\tPlayback length: %ldm:%02ld.%03lds\n"
           "\tAverage bitrate: %f kb/s\n"), 
            stream->num,inf->bytes, minutes, seconds, milliseconds, bitrate);

    theora_comment_clear(&inf->tc);
    theora_info_clear(&inf->ti);

    free(stream->data);
}


503 504 505
static void vorbis_process(stream_processor *stream, ogg_page *page )
{
    ogg_packet packet;
506
    misc_vorbis_info *inf = stream->data;
507
    int i, header=0, packets=0;
508
    int k;
509
    int res;
510 511

    ogg_stream_pagein(&stream->os, page);
512 513
    if(inf->doneheaders < 3)
        header = 1;
514

515 516 517 518 519 520 521 522 523
    while(1) {
        res = ogg_stream_packetout(&stream->os, &packet);
        if(res < 0) {
           warn(_("Warning: discontinuity in stream (%d)\n"), stream->num);
           continue;
        }
        else if (res == 0)
            break;

524
        packets++;
525 526 527
        if(inf->doneheaders < 3) {
            if(vorbis_synthesis_headerin(&inf->vi, &inf->vc, &packet) < 0) {
                warn(_("Warning: Could not decode vorbis header "
528 529
                       "packet %d - invalid vorbis stream (%d)\n"), 
                        inf->doneheaders, stream->num);
530 531
                continue;
            }
532 533
            inf->doneheaders++;
            if(inf->doneheaders == 3) {
534
                if(ogg_page_granulepos(page) != 0 || ogg_stream_packetpeek(&stream->os, NULL) == 1)
535 536 537 538
                    warn(_("Warning: Vorbis stream %d does not have headers "
                           "correctly framed. Terminal header page contains "
                           "additional packets or has non-zero granulepos\n"),
                            stream->num);
539 540 541 542
                info(_("Vorbis headers parsed for stream %d, "
                       "information follows...\n"), stream->num);

                info(_("Version: %d\n"), inf->vi.version);
543 544 545 546 547 548 549 550 551 552 553
                k = 0;
                while(releases[k].vendor_string) {
                    if(!strcmp(inf->vc.vendor, releases[k].vendor_string)) {
                        info(_("Vendor: %s (%s)\n"), inf->vc.vendor, 
                                    releases[k].desc);
                        break;
                    }
                    k++;
                }
                if(!releases[k].vendor_string)
                    info(_("Vendor: %s\n"), inf->vc.vendor);
554 555 556
                info(_("Channels: %d\n"), inf->vi.channels);
                info(_("Rate: %ld\n\n"), inf->vi.rate);

557
                if(inf->vi.bitrate_nominal > 0)
558 559
                    info(_("Nominal bitrate: %f kb/s\n"), 
                            (double)inf->vi.bitrate_nominal / 1000.0);
560
                else
561
                    info(_("Nominal bitrate not set\n"));
562

563
                if(inf->vi.bitrate_upper > 0)
564 565
                    info(_("Upper bitrate: %f kb/s\n"), 
                            (double)inf->vi.bitrate_upper / 1000.0);
566
                else
567
                    info(_("Upper bitrate not set\n"));
568

569
                if(inf->vi.bitrate_lower > 0)
570 571
                    info(_("Lower bitrate: %f kb/s\n"), 
                            (double)inf->vi.bitrate_lower / 1000.0);
572
                else
573
                    info(_("Lower bitrate not set\n"));
574

575 576
                if(inf->vc.comments > 0)
                    info(_("User comments section follows...\n"));
577

578
                for(i=0; i < inf->vc.comments; i++) {
579
                    char *comment = inf->vc.user_comments[i];
580 581
		    check_xiph_comment(stream, i, comment, 
		            inf->vc.comment_lengths[i]);
582
		}
583 584 585 586 587
            }
        }
    }

    if(!header) {
588 589 590
        ogg_int64_t gp = ogg_page_granulepos(page);
        if(gp > 0) {
            if(gp < inf->lastgranulepos)
591 592
                warn(_("Warning: granulepos in stream %d decreases from %" 
                        I64FORMAT " to %" I64FORMAT "\n" ),
593
                        stream->num, inf->lastgranulepos, gp);
594 595
            inf->lastgranulepos = gp;
        }
596 597 598 599 600
        else if(packets) {
            /* Only do this if we saw at least one packet ending on this page.
             * It's legal (though very unusual) to have no packets in a page at
             * all - this is occasionally used to have an empty EOS page */
            warn(_("Negative or zero granulepos (%lld) on vorbis stream outside of headers. This file was created by a buggy encoder\n"), gp);
601 602 603
        }
        if(inf->firstgranulepos < 0) { /* Not set yet */
        }
604
        inf->bytes += page->header_len + page->body_len;
605 606 607 608 609
    }
}

static void vorbis_end(stream_processor *stream) 
{
610
    misc_vorbis_info *inf = stream->data;
611
    long minutes, seconds, milliseconds;
612 613
    double bitrate, time;

614
    /* This should be lastgranulepos - startgranulepos, or something like that*/
615
    time = (double)inf->lastgranulepos / inf->vi.rate;
616 617
    minutes = (long)time / 60;
    seconds = (long)time - minutes*60;
618
    milliseconds = (long)((time - minutes*60 - seconds)*1000);
619
    bitrate = inf->bytes*8 / time / 1000.0;
620

621
    info(_("Vorbis stream %d:\n"
622
           "\tTotal data length: %" I64FORMAT " bytes\n"
623
           "\tPlayback length: %ldm:%02ld.%03lds\n"
624
           "\tAverage bitrate: %f kb/s\n"), 
625
            stream->num,inf->bytes, minutes, seconds, milliseconds, bitrate);
626

627 628
    vorbis_comment_clear(&inf->vc);
    vorbis_info_clear(&inf->vi);
629 630 631 632

    free(stream->data);
}

633 634 635 636 637
static void process_null(stream_processor *stream, ogg_page *page)
{
    /* This is for invalid streams. */
}

638 639 640 641 642 643 644 645 646 647
static void process_other(stream_processor *stream, ogg_page *page )
{
    ogg_packet packet;

    ogg_stream_pagein(&stream->os, page);

    while(ogg_stream_packetout(&stream->os, &packet) > 0) {
        /* Should we do anything here? Currently, we don't */
    }
}
648

649 650 651 652 653 654

static void free_stream_set(stream_set *set)
{
    int i;
    for(i=0; i < set->used; i++) {
        if(!set->streams[i].end) {
655
            warn(_("Warning: EOS not set on stream %d\n"), 
656
                    set->streams[i].num);
657 658
            if(set->streams[i].process_end)
                set->streams[i].process_end(&set->streams[i]);
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
        }
        ogg_stream_clear(&set->streams[i].os);
    }

    free(set->streams);
    free(set);
}

static int streams_open(stream_set *set)
{
    int i;
    int res=0;
    for(i=0; i < set->used; i++) {
        if(!set->streams[i].end)
            res++;
    }

    return res;
}

679 680 681 682 683 684 685
static void null_start(stream_processor *stream)
{
    stream->process_end = NULL;
    stream->type = "invalid";
    stream->process_page = process_null;
}

686
static void other_start(stream_processor *stream, char *type)
687
{
688 689 690 691
    if(type)
        stream->type = type;
    else
        stream->type = "unknown";
692 693 694 695
    stream->process_page = process_other;
    stream->process_end = NULL;
}

696 697 698 699 700 701 702 703 704 705
static void theora_start(stream_processor *stream)
{
    misc_theora_info *info;

    stream->type = "theora";
    stream->process_page = theora_process;
    stream->process_end = theora_end;

    stream->data = calloc(1, sizeof(misc_theora_info));
    info = stream->data;
706
    info->framenum_expected = -1;
707 708
}

709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
static void vorbis_start(stream_processor *stream)
{
    misc_vorbis_info *info;

    stream->type = "vorbis";
    stream->process_page = vorbis_process;
    stream->process_end = vorbis_end;

    stream->data = calloc(1, sizeof(misc_vorbis_info));

    info = stream->data;

    vorbis_comment_init(&info->vc);
    vorbis_info_init(&info->vi);

}

static stream_processor *find_stream_processor(stream_set *set, ogg_page *page)
{
    ogg_uint32_t serial = ogg_page_serialno(page);
    int i, found = 0;
    int invalid = 0;
731
    int constraint = 0;
732 733 734 735 736 737 738 739 740 741 742 743
    stream_processor *stream;

    for(i=0; i < set->used; i++) {
        if(serial == set->streams[i].serial) {
            /* We have a match! */
            found = 1;
            stream = &(set->streams[i]);

            set->in_headers = 0;
            /* if we have detected EOS, then this can't occur here. */
            if(stream->end) {
                stream->isillegal = 1;
744
                stream->constraint_violated = CONSTRAINT_PAGE_AFTER_EOS;
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
                return stream;
            }

            stream->isnew = 0;
            stream->start = ogg_page_bos(page);
            stream->end = ogg_page_eos(page);
            stream->serial = serial;
            return stream;
        }
    }

    /* If there are streams open, and we've reached the end of the
     * headers, then we can't be starting a new stream.
     * XXX: might this sometimes catch ok streams if EOS flag is missing,
     * but the stream is otherwise ok?
     */
761 762
    if(streams_open(set) && !set->in_headers) {
        constraint = CONSTRAINT_MUXING_VIOLATED;
763
        invalid = 1;
764
    }
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780

    set->in_headers = 1;

    if(set->allocated < set->used)
        stream = &set->streams[set->used];
    else {
        set->allocated += 5;
        set->streams = realloc(set->streams, sizeof(stream_processor)*
                set->allocated);
        stream = &set->streams[set->used];
    }
    set->used++;
    stream->num = set->used; /* We count from 1 */

    stream->isnew = 1;
    stream->isillegal = invalid;
781
    stream->constraint_violated = constraint;
782 783 784 785 786 787 788 789 790 791

    {
        int res;
        ogg_packet packet;

        /* We end up processing the header page twice, but that's ok. */
        ogg_stream_init(&stream->os, serial);
        ogg_stream_pagein(&stream->os, page);
        res = ogg_stream_packetout(&stream->os, &packet);
        if(res <= 0) {
792
            warn(_("Warning: Invalid header page, no packet found\n"));
793
            null_start(stream);
794
        }
j's avatar
j committed
795
        else if(packet.bytes >= 7 && memcmp(packet.packet, "\x01vorbis", 7)==0)
796
            vorbis_start(stream);
j's avatar
j committed
797
        else if(packet.bytes >= 7 && memcmp(packet.packet, "\x80theora", 7)==0) 
798
            theora_start(stream);
799 800
        else if(packet.bytes >= 8 && memcmp(packet.packet, "OggMIDI\0", 8)==0) 
            other_start(stream, "MIDI");
801 802 803 804
        else if(packet.bytes >= 4 && memcmp(packet.packet, "fLaC", 4)==0) 
            other_start(stream, "FLAC");
        else if(packet.bytes >= 8 && memcmp(packet.packet, "Speex   ", 8)==0) 
            other_start(stream, "speex");
805 806
        else
            other_start(stream, NULL);
807 808 809

        res = ogg_stream_packetout(&stream->os, &packet);
        if(res > 0) {
810
            warn(_("Warning: Invalid header page in stream %d, "
811 812 813 814 815 816 817 818 819 820 821 822
                              "contains multiple packets\n"), stream->num);
        }

        /* re-init, ready for processing */
        ogg_stream_clear(&stream->os);
        ogg_stream_init(&stream->os, serial);
   }

   stream->start = ogg_page_bos(page);
   stream->end = ogg_page_eos(page);
   stream->serial = serial;

823 824
   if(stream->serial == 0 || stream->serial == -1) {
       info(_("Note: Stream %d has serial number %d, which is legal but may "
825 826
              "cause problems with some tools.\n"), stream->num, 
               stream->serial);
827 828
   }

829 830 831
   return stream;
}

832 833
static int get_next_page(FILE *f, ogg_sync_state *sync, ogg_page *page, 
        ogg_int64_t *written)
834 835 836 837 838
{
    int ret;
    char *buffer;
    int bytes;

839
    while((ret = ogg_sync_pageseek(sync, page)) <= 0) {
840
        if(ret < 0)
841
            warn(_("Warning: Hole in data (%d bytes) found at approximate offset %" I64FORMAT " bytes. Corrupted ogg.\n"), *written);
842 843 844

        buffer = ogg_sync_buffer(sync, CHUNK);
        bytes = fread(buffer, 1, CHUNK, f);
845 846
        if(bytes <= 0) {
            ogg_sync_wrote(sync, 0);
847
            return 0;
848 849 850
        }
        ogg_sync_wrote(sync, bytes);
        *written += bytes;
851 852 853 854 855 856 857 858 859 860
    }

    return 1;
}

static void process_file(char *filename) {
    FILE *file = fopen(filename, "rb");
    ogg_sync_state sync;
    ogg_page page;
    stream_set *processors = create_stream_set();
861 862
    int gotpage = 0;
    ogg_int64_t written = 0;
863 864

    if(!file) {
865
        error(_("Error opening input file \"%s\": %s\n"), filename,
866 867 868 869
                    strerror(errno));
        return;
    }

870
    printf(_("Processing file \"%s\"...\n\n"), filename);
871 872 873

    ogg_sync_init(&sync);

874
    while(get_next_page(file, &sync, &page, &written)) {
875
        stream_processor *p = find_stream_processor(processors, &page);
876
        gotpage = 1;
877 878

        if(!p) {
879
            error(_("Could not find a processor for stream, bailing\n"));
880 881 882 883
            return;
        }

        if(p->isillegal && !p->shownillegal) {
884 885 886 887 888 889 890 891 892 893 894 895 896
            char *constraint;
            switch(p->constraint_violated) {
                case CONSTRAINT_PAGE_AFTER_EOS:
                    constraint = _("Page found for stream after EOS flag");
                    break;
                case CONSTRAINT_MUXING_VIOLATED:
                    constraint = _("Ogg muxing constraints violated, new "
                                   "stream before EOS of all previous streams");
                    break;
                default:
                    constraint = _("Error unknown.");
            }

897
            warn(_("Warning: illegally placed page(s) for logical stream %d\n"
898 899
                   "This indicates a corrupt ogg file: %s.\n"), 
                    p->num, constraint);
900
            p->shownillegal = 1;
901 902 903 904 905
            /* If it's a new stream, we want to continue processing this page
             * anyway to suppress additional spurious errors
             */
            if(!p->isnew)
                continue;
906 907 908
        }

        if(p->isnew) {
909
            info(_("New logical stream (#%d, serial: %08x): type %s\n"), 
910 911
                    p->num, p->serial, p->type);
            if(!p->start)
912
                warn(_("Warning: stream start flag not set on stream %d\n"),
913 914 915
                        p->num);
        }
        else if(p->start)
916
            warn(_("Warning: stream start flag found in mid-stream "
917 918
                      "on stream %d\n"), p->num);

919 920 921 922 923 924 925 926 927 928 929
        if(p->seqno++ != ogg_page_pageno(&page)) {
            if(!p->lostseq) 
                warn(_("Warning: sequence number gap in stream %d. Got page "
                       "%ld when expecting page %ld. Indicates missing data.\n"
                       ), p->num, ogg_page_pageno(&page), p->seqno - 1);
            p->seqno = ogg_page_pageno(&page);
            p->lostseq = 1;
        }
        else
            p->lostseq = 0;

930 931 932 933 934 935
        if(!p->isillegal) {
            p->process_page(p, &page);

            if(p->end) {
                if(p->process_end)
                    p->process_end(p);
936
                info(_("Logical stream %d ended\n"), p->num);
937
                p->isillegal = 1;
938
                p->constraint_violated = CONSTRAINT_PAGE_AFTER_EOS;
939 940 941 942
            }
        }
    }

943 944 945 946
    if(!gotpage)
        error(_("Error: No ogg data found in file \"%s\".\n"
                "Input probably not ogg.\n"), filename);

947 948 949 950 951 952 953
    free_stream_set(processors);

    ogg_sync_clear(&sync);

    fclose(file);
}

954
static void usage(void) {
955 956
    printf(_("ogginfo 1.1.0\n"
             "(c) 2003-2005 Michael Smith <msmith@xiph.org>\n"
957
             "\n"
Michael Smith's avatar
Michael Smith committed
958
             "Usage: ogginfo [flags] file1.ogg [file2.ogg ... fileN.ogg]\n"
959 960 961 962 963 964 965 966
             "Flags supported:\n"
             "\t-h Show this help message\n"
             "\t-q Make less verbose. Once will remove detailed informative\n"
             "\t   messages, two will remove warnings\n"
             "\t-v Make more verbose. This may enable more detailed checks\n"
             "\t   for some stream types.\n\n"));
}

967
int main(int argc, char **argv) {
968
    int f, ret;
969 970 971 972 973 974 975

    setlocale(LC_ALL, "");
    bindtextdomain(PACKAGE, LOCALEDIR);
    textdomain(PACKAGE);

    if(argc < 2) {
        fprintf(stderr, 
976
                _("Usage: ogginfo [flags] file1.ogg [file2.ogg ... fileN.ogg]\n"
977 978
                  "\n"
                  "Ogginfo is a tool for printing information about ogg files\n"
979 980
                  "and for diagnosing problems with them.\n"
                  "Full help shown with \"ogginfo -h\".\n"));
981 982 983
        exit(1);
    }

984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
    while((ret = getopt(argc, argv, "hvq")) >= 0) {
        switch(ret) {
            case 'h':
                usage();
                return 0;
            case 'v':
                verbose++;
                break;
            case 'q':
                verbose--;
                break;
        }
    }

    if(verbose < 1)
        printinfo = 0;
    if(verbose < 0) 
        printwarn = 0;

    if(optind >= argc) {
1004 1005
        fprintf(stderr, 
                _("No input files specified. \"ogginfo -h\" for help\n"));
1006 1007 1008
        return 1;
    }

1009 1010
    ret = 0;

1011
    for(f=optind; f < argc; f++) {
1012
        flawed = 0;
1013
        process_file(argv[f]);
1014 1015
        if(flawed != 0)
            ret = flawed;
1016 1017
    }

1018
    return ret;
1019
}