oggz-chop.c 21 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
/*
   Copyright (C) 2008 Annodex Association

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

   - Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

   - Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

   - Neither the name of the Annodex Association nor the names of its
   contributors may be used to endorse or promote products derived from
   this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
   PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE ASSOCIATION OR
   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "config.h"

#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <errno.h>
38
#include <math.h>
39 40 41

#include <oggz/oggz.h>

42
#include "oggz-chop.h"
43
#include "skeleton.h"
44

45 46 47 48 49 50
#ifdef OGG_H_CONST_CORRECT
#define OGG_PAGE_CONST(x) (x)
#else
#define OGG_PAGE_CONST(x) ((ogg_page *)x)
#endif

51 52 53 54
#ifdef WIN32                                                                   
#define snprintf _snprintf
#endif 

55 56 57 58 59
/************************************************************
 * OCTrackState
 */

typedef struct _OCTrackState {
60 61 62 63
  /* Skeleton track info (fisbone) */
  fisbone_packet fisbone;

  /* Page accumulator for the GOP before the chop start */
64 65 66 67 68 69 70 71 72
  OggzTable * page_accum;

  int headers_remaining;

  /* Greatest previously inferred keyframe value */
  ogg_int64_t prev_keyframe;

} OCTrackState;

73 74 75 76 77
static OCTrackState *
track_state_new (void)
{
  OCTrackState * ts;

78 79
  if ((ts = (OCTrackState *) malloc (sizeof(*ts))) == NULL)
    return NULL;
80 81 82 83 84 85 86 87 88 89 90

  memset (ts, 0, sizeof(*ts));

  return ts;
}

static void
track_state_delete (OCTrackState * ts)
{
  if (ts == NULL) return;

91 92
  fisbone_clear (&ts->fisbone);

93 94 95 96 97 98 99 100 101 102 103 104 105 106
  /* XXX: delete accumulated pages */
  oggz_table_delete (ts->page_accum);

  free (ts);

  return;
}

/* Add a track to the overall state */
static OCTrackState *
track_state_add (OggzTable * state, long serialno)
{
  OCTrackState * ts;

107 108
  if ((ts = track_state_new ()) == NULL)
    return NULL;
109

110 111 112 113 114 115 116 117
  if (oggz_table_insert (state, serialno, ts) == ts) {
    return ts;
  } else {
    track_state_delete (ts);
    return NULL;
  }
}

118 119 120
static void
state_init (OCState * state)
{
121
  /* Initialize fishead presentation time */
122
  state->fishead.ptime_n = state->start * (ogg_int64_t)1000;
123 124 125
  state->fishead.ptime_d = 1000;

  /* Initialize track table and page accumulator */
126
  state->tracks = oggz_table_new ();
127
  state->status = OC_INIT;
128 129 130 131 132 133 134 135 136 137 138 139 140 141
}

static void
state_clear (OCState * state)
{
  int i, ntracks;

  ntracks = oggz_table_size (state->tracks);
  for (i = 0; i < ntracks; i++) {
    track_state_delete (oggz_table_nth(state->tracks, i, NULL));
  }
  oggz_table_delete (state->tracks);
}

142 143 144 145 146 147 148 149 150
/************************************************************
 * ogg_page helpers
 */

static ogg_page *
_ogg_page_copy (const ogg_page * og)
{
  ogg_page * new_og;

151 152 153 154 155 156 157
  if ((new_og = malloc (sizeof (*og))) == NULL)
    return NULL;

  if ((new_og->header = malloc (og->header_len)) == NULL) {
    free (new_og);
    return NULL;
  }
158 159
  new_og->header_len = og->header_len;
  memcpy (new_og->header, og->header, og->header_len);
160 161 162 163 164 165

  if ((new_og->body = malloc (og->body_len)) == NULL) {
    free (new_og->header);
    free (new_og);
    return NULL;
  }
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
  new_og->body_len = og->body_len;
  memcpy (new_og->body, og->body, og->body_len);

  return new_og;
}

static void
_ogg_page_free (const ogg_page * og)
{
  if (og == NULL) return;

  free (og->header);
  free (og->body);
  free ((ogg_page *)og);
}

static void
conrad's avatar
conrad committed
183
_ogg_page_set_eos (const ogg_page * og)
184 185 186 187
{
  if (og == NULL) return;

  og->header[5] |= 0x04;
conrad's avatar
conrad committed
188
  ogg_page_checksum_set (OGG_PAGE_CONST(og));
189 190 191
}

static void
192
fwrite_ogg_page (OCState * state, const ogg_page * og)
193 194 195
{
  if (og == NULL) return;

196 197 198 199
  if (!state->dry_run) {
    fwrite (og->header, 1, og->header_len, state->outfile);
    fwrite (og->body, 1, og->body_len, state->outfile);
  }
200 201
}

202 203 204 205 206 207 208 209 210 211
/************************************************************
 * OCPageAccum
 */

typedef struct _OCPageAccum {
  ogg_page * og;
  double time;
} OCPageAccum;

static OCPageAccum *
212
page_accum_new (const ogg_page * og, double time)
213 214 215
{
  OCPageAccum * pa;

216 217 218 219 220 221 222 223
  if ((pa = malloc(sizeof (*pa))) == NULL)
    return NULL;

  if ((pa->og = _ogg_page_copy (og)) == NULL) {
    free (pa);
    return NULL;
  }

224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
  pa->time = time;

  return pa;
}

static void
page_accum_delete (OCPageAccum * pa)
{
  if (pa == NULL) return;

  _ogg_page_free (pa->og);
  free (pa);
}

static void
track_state_remove_page_accum (OCTrackState * ts)
{
  int i, accum_size;

  if (ts == NULL || ts->page_accum == NULL) return;

  accum_size = oggz_table_size (ts->page_accum);

247
  for (i = accum_size-1; i >= 0; i--) {
248 249 250 251 252
    page_accum_delete((OCPageAccum *)oggz_table_lookup (ts->page_accum, i));
    oggz_table_remove (ts->page_accum, (long)i);
  }
}

253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
/*
 * Advance the page accumulator:
 *   - Remove all pages that only contain packets from the previous GOP.
 *   - Shift all remaining packets to start from index 0
 * Returns: the new size of the page accumulator.
 */
static int
track_state_advance_page_accum (OCTrackState * ts)
{
  int i, accum_size;
  int e, earliest_new; /* Index into page accumulator of the earliest page that
                        * contains a packet from the new GOP */
  OCPageAccum * pa;

  if (ts == NULL || ts->page_accum == NULL) return 0;

  earliest_new = accum_size = oggz_table_size (ts->page_accum);

  /* Working backwards through the page accumulator ... */
  for (i = accum_size-1; i >= 0; i--) {
    pa = (OCPageAccum *) oggz_table_lookup (ts->page_accum, i);

275
    /* If we have a page with granulepos, it necessarily contains the end
276 277 278 279 280 281 282 283 284
     * of a packet from an earlier GOP, and thus this is the last page that
     * we need to recover.
     */
    if (ogg_page_granulepos (pa->og) != -1) {
      earliest_new = i;
      break;
    }
  }

285 286
  /* If all accumulated pages have no granulepos, keep them,
   * and do not modify start_granule */
287 288
  if (earliest_new == 0) return accum_size;

conrad's avatar
conrad committed
289 290
  /* WTF: This check is from my original implementation of this function in
   * changeset:3557. How can it arise? -Conrad 20081028 */
291 292 293 294 295 296
  if (earliest_new > accum_size)
    earliest_new = accum_size;

  /* Delete the rest */
  for (i = earliest_new-1; i >= 0; i--) {
    pa = (OCPageAccum *) oggz_table_lookup (ts->page_accum, i);
297 298 299
    /* Record this track's start_granule as the granulepos of the page prior
     * to earliest_new */
    if (i == (earliest_new-1)) {
300
      ts->fisbone.start_granule = ogg_page_granulepos (pa->og);
301
    }
302 303 304 305 306 307 308 309 310 311 312 313 314 315
    page_accum_delete(pa);
    oggz_table_remove (ts->page_accum, (long)i);
  }

  /* Shift the best */
  for (i = 0, e = earliest_new; e < accum_size; i++, e++) {
    pa = (OCPageAccum *) oggz_table_lookup (ts->page_accum, e);
    oggz_table_insert (ts->page_accum, i, pa);
    oggz_table_remove (ts->page_accum, (long)e);
  }

  return accum_size - earliest_new;
}

316
/************************************************************
317
 * Skeleton
318 319
 */

320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
static long
skeleton_write_packet (OCState * state, ogg_packet * op)
{
  int iret;
  long ret;

  op->packetno = -1;
  iret = oggz_write_feed (state->skeleton_writer, op, state->skeleton_serialno,
                          OGGZ_FLUSH_BEFORE|OGGZ_FLUSH_AFTER, NULL);

  ret = oggz_run (state->skeleton_writer);
  fflush (state->outfile);

  return ret;
}

336 337
/* MIME types, for use in Skeleton. This must be in the same order as
 * enum OggzStreamContent defined in <oggz/oggz_constants.h> */
338 339 340 341 342 343 344 345 346 347 348 349 350
const char * type_names[] = {
  "video/theora",
  "audio/vorbis",
  "audio/speex",
  "audio/x-oggpcm",
  "text/cmml",
  "application/x-annodex-2",
  NULL, /* Skeleton */
  "audio/flac",
  "audio/flac",
  NULL, /* AnxData */
  "audio/celt",
  "application/x-kate",
351
  "video/dirac",
352 353 354
  NULL /* UNKNOWN */
};

355
static int
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
fisbone_init (OGGZ * oggz, OCState * state, OCTrackState * ts, long serialno)
{
  OggzStreamContent content_type;
  const char * name;
  int len;

  if (ts == NULL) return -1;

  ts->fisbone.serial_no = serialno;
  ts->fisbone.nr_header_packet = oggz_stream_get_numheaders (oggz, serialno);
  oggz_get_granulerate (oggz, serialno, &ts->fisbone.granule_rate_n, &ts->fisbone.granule_rate_d);
  ts->fisbone.start_granule = 0;
  ts->fisbone.preroll = 0;
  ts->fisbone.granule_shift = (unsigned char) oggz_get_granuleshift (oggz, serialno);
  if (state->original_had_skeleton) {
    /* Wait, and copy over message headers from original */
    ts->fisbone.message_header_fields = NULL;
    ts->fisbone.current_header_size = FISBONE_SIZE;
  } else {
    /* XXX: C99 */
#define CONTENT_TYPE_FMT "Content-Type: %s\r\n"
    content_type = oggz_stream_get_content (oggz, serialno);
    name = type_names[content_type];
    len = snprintf (NULL, 0, CONTENT_TYPE_FMT, name);
380 381 382
    if ((ts->fisbone.message_header_fields = malloc(len+1)) == NULL) {
      return -1;
    }
383 384 385 386 387 388 389 390 391
    snprintf (ts->fisbone.message_header_fields, len+1, CONTENT_TYPE_FMT, name);
    ts->fisbone.current_header_size = len+1;
  }

  return 0;
}

static long
fisbones_write (OCState * state)
392 393
{
  OCTrackState * ts;
394 395 396
  long serialno;
  ogg_packet op;
  int i, ntracks, ret = -1001;
397

398
  if (!state->do_skeleton) return -1;
399

400
  ntracks = oggz_table_size (state->tracks);
401

402 403 404 405 406 407 408
  /* Write fisbones */
  for (i=0; i < ntracks; i++) {
    ts = oggz_table_nth (state->tracks, i, &serialno);
    ret = ogg_from_fisbone (&ts->fisbone, &op);
    ret = skeleton_write_packet (state, &op);
    _ogg_free (op.packet);
  }
409

410 411 412 413
  /* Write Skeleton EOS page */
  memset (&op, 0, sizeof(op));
  op.e_o_s = 1;
  ret = skeleton_write_packet (state, &op);
414

415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
  return ret;
}

static int
fishead_update (OCState * state, const ogg_page * og)
{
  fishead_packet fishead;

  fishead_from_ogg_page (og, &fishead);
  state->fishead.btime_n = fishead.btime_n;
  state->fishead.btime_d = fishead.btime_d;

  return 0;
}

static long
fishead_write (OCState * state)
{
  ogg_packet op;
  int ret = -1001;

  if (state->do_skeleton) {
    ogg_from_fishead (&state->fishead, &op);
    ret = skeleton_write_packet (state, &op);
    _ogg_free (op.packet);
440 441
  }

442
  return ret;
443 444
}

445 446 447 448
/************************************************************
 * chop
 */

449 450 451 452 453 454 455 456 457 458 459
static int
write_accum (OCState * state)
{
  OCTrackState * ts;
  OCPageAccum * pa;
  OggzTable * candidates;
  long serialno, min_serialno;
  int i, ntracks, ncandidates=0, remaining=0, min_i, cn, min_cn;
  ogg_page * og, * min_og;
  double min_time;

conrad's avatar
conrad committed
460
  if (state->status >= OC_GLUE_DONE) return -1;
461 462 463 464 465 466 467 468 469 470 471 472

  /*
   * We create a table of candidate tracks, which are all those which
   * have a page_accum table, ie. for which granuleshift matters.
   * We insert into this table the index of the next page_accum element
   * to be merged for that track. All start at 0.
   * The variable 'remaining' counts down the total number of accumulated
   * pages to be written from all candidate tracks.
   */

  /* Prime candidates */
  candidates = oggz_table_new ();
conrad's avatar
conrad committed
473 474 475 476 477

  /* XXX: we offset the candidate indices by some small positive number to
   * avoid storing 0, as OggzTable treats insertion of NULL as a deletion */
#define CN_OFFSET (0x7)

478 479 480 481 482
  ntracks = oggz_table_size (state->tracks);
  for (i=0; i < ntracks; i++) {
    ts = oggz_table_nth (state->tracks, i, &serialno);
    if (ts != NULL && ts->page_accum != NULL) {
      ncandidates++;
conrad's avatar
conrad committed
483
      oggz_table_insert (candidates, serialno, (void *)CN_OFFSET);
484 485 486 487 488 489 490 491 492 493 494 495
      remaining += oggz_table_size (ts->page_accum);
    }
  }

  /* Merge candidates */
  while (remaining > 0) {
    /* Find minimum page in all accum buffers */
    min_time = 10e100;
    min_cn = -1;
    min_og = NULL;
    min_serialno = -1;
    for (i=0; i < ncandidates; i++) {
conrad's avatar
conrad committed
496
      cn = ((int) oggz_table_nth (candidates, i, &serialno)) - CN_OFFSET;
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
      ts = oggz_table_lookup (state->tracks, serialno);
      if (ts && ts->page_accum) {
        if (cn < oggz_table_size (ts->page_accum)) {
          pa = oggz_table_nth (ts->page_accum, cn, NULL);

          if (pa->time < min_time) {
            min_i = i;
            min_cn = cn;
            min_og = pa->og;
            min_serialno = serialno;
            min_time = pa->time;
          }
        }
      }
    }

    if (min_og) {
      /* Increment index for minimum page */
conrad's avatar
conrad committed
515 516
      oggz_table_insert (candidates, min_serialno,
                         (void *)(min_cn+1+CN_OFFSET));
517 518

      /* Write out minimum page */
519
      fwrite_ogg_page (state, min_og);
520 521
    }

conrad's avatar
conrad committed
522 523 524
    /* Let's lexically forget about this CN_OFFSET silliness */
#undef CN_OFFSET

525 526 527 528 529 530 531 532 533 534 535
    remaining--;
  }

  /* Cleanup */
  for (i=0; i < ntracks; i++) {
    ts = oggz_table_nth (state->tracks, i, &serialno);
    track_state_remove_page_accum (ts);
  }

  oggz_table_delete (candidates);

conrad's avatar
conrad committed
536
  state->status = OC_GLUE_DONE;
537 538 539 540
 
  return 0;
}

541 542 543 544
/* Forward declaration */
static int
read_plain (OGGZ * oggz, const ogg_page * og, long serialno, void * user_data);

conrad's avatar
conrad committed
545 546 547
/* Write out the fisbones and accumulated pages before the chop point.
 * This is called once by read_plain() below as soon as a page beyond the
 * chop start is read. */
548 549 550 551 552 553 554
static int
chop_glue (OCState * state, OGGZ * oggz)
{
  int i, ntracks;
  long serialno;
  OCTrackState * ts;

conrad's avatar
conrad committed
555
  if (state->status < OC_GLUE_DONE) {
556 557 558 559 560 561 562 563 564 565 566 567 568 569
    /* Write in fisbones */
    fisbones_write (state);

    /* Write out accumulated pages */
    write_accum (state);

    /* Switch all tracks to the plain page reader */
    ntracks = oggz_table_size (state->tracks);
    for (i=0; i < ntracks; i++) {
      ts = oggz_table_nth (state->tracks, i, &serialno);
      oggz_set_read_page (oggz, serialno, read_plain, state);
    }
  }

conrad's avatar
conrad committed
570
  state->status = OC_GLUE_DONE;
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598

  return 0;
}

/*
 * OggzReadPageCallback read_plain
 *
 * A page reading callback for tracks without granuleshift.
 */
static int
read_plain (OGGZ * oggz, const ogg_page * og, long serialno, void * user_data)
{
  OCState * state = (OCState *)user_data;
  OCTrackState * ts;
  double page_time;
  long gp;

  ts = oggz_table_lookup (state->tracks, serialno);

  page_time = oggz_tell_units (oggz) / 1000.0;

#ifdef DEBUG
  printf ("page_time: %g\tspan (%g, %g)\n", page_time, state->start, state->end);
  printf ("\tpageno: %d, numheaders %d\n", ogg_page_pageno(og),
          oggz_stream_get_numheaders (oggz, serialno));
#endif

  if (page_time < state->start) {
conrad's avatar
conrad committed
599 600
    if ((gp = ogg_page_granulepos (OGG_PAGE_CONST(og))) != -1)
      ts->fisbone.start_granule = ogg_page_granulepos (OGG_PAGE_CONST(og));
601 602 603
  } else if (page_time >= state->start &&
      (state->end == -1 || page_time <= state->end)) {

conrad's avatar
conrad committed
604
    if (state->status < OC_GLUE_DONE) {
605 606 607
      chop_glue (state, oggz);
    }

608
    fwrite_ogg_page (state, og);
609 610
  } else if (state->end != -1.0 && page_time > state->end) {
    /* This is the first page past the end time; set EOS */
conrad's avatar
conrad committed
611
    _ogg_page_set_eos (og);
612
    fwrite_ogg_page (state, og);
613 614 615 616 617 618 619 620

    /* Stop handling this track */
    oggz_set_read_page (oggz, serialno, NULL, NULL);
  }

  return OGGZ_CONTINUE;
}

621 622 623 624 625 626 627 628 629 630
/*
 * OggzReadPageCallback read_gs
 *
 * A page reading callback for tracks with granuleshift.
 */
static int
read_gs (OGGZ * oggz, const ogg_page * og, long serialno, void * user_data)
{
  OCState * state = (OCState *)user_data;
  OCTrackState * ts;
631
  OCPageAccum * pa;
632 633 634 635 636 637 638 639 640 641 642
  double page_time;
  ogg_int64_t granulepos, keyframe;
  int granuleshift, i, accum_size;
  ogg_page * accum_og;

  page_time = oggz_tell_units (oggz) / 1000.0;

  ts = oggz_table_lookup (state->tracks, serialno);
  accum_size = oggz_table_size (ts->page_accum);

  if (page_time >= state->start) {
643 644
    /* Glue in fisbones, write out accumulated pages */
    chop_glue (state, oggz);
645 646 647 648 649 650

    /* Switch to the plain page reader */
    oggz_set_read_page (oggz, serialno, read_plain, state);
    return read_plain (oggz, og, serialno, user_data);
  } /* else { ... */

651
  granulepos = ogg_page_granulepos (OGG_PAGE_CONST(og));
652 653 654 655 656
  if (granulepos != -1) {
    granuleshift = oggz_get_granuleshift (oggz, serialno);
    keyframe = granulepos >> granuleshift;

    if (keyframe != ts->prev_keyframe) {
conrad's avatar
conrad committed
657
      if (ogg_page_continued(OGG_PAGE_CONST(og))) {
658 659 660 661 662 663 664
        /* If this new-keyframe page is continued, advance the page accumulator,
         * ie. recover earlier pages from this new GOP */
        accum_size = track_state_advance_page_accum (ts);
      } else {
        /* Otherwise, just clear the page accumulator */
        track_state_remove_page_accum (ts);
        accum_size = 0;
665 666 667 668 669 670 671 672
      }

      /* Record this as prev_keyframe */
      ts->prev_keyframe = keyframe;
    }
  }

  /* Add a copy of this to the page accumulator */
673 674
  pa = page_accum_new (og, page_time);
  oggz_table_insert (ts->page_accum, accum_size, pa);
675 676 677 678 679 680 681 682 683 684 685 686 687 688

  return OGGZ_CONTINUE;
}

/*
 * OggzReadPageCallback read_headers
 *
 * A page reading callback for header pages
 */
static int
read_headers (OGGZ * oggz, const ogg_page * og, long serialno, void * user_data)
{
  OCState * state = (OCState *)user_data;
  OCTrackState * ts;
689
  OggzStreamContent content_type;
690
  fisbone_packet fisbone;
691

692
  content_type = oggz_stream_get_content(oggz, serialno);
693 694
  switch (content_type) {
  case OGGZ_CONTENT_SKELETON:
695 696 697 698 699 700
    if (fisbone_from_ogg_page (og, &fisbone) != -1) {
      if ((ts = oggz_table_lookup (state->tracks, fisbone.serial_no)) != NULL) {
        ts->fisbone.current_header_size = fisbone.current_header_size;
        ts->fisbone.message_header_fields = fisbone.message_header_fields;
      }
    }
701 702 703 704 705
    break;
  default:
    ts = oggz_table_lookup (state->tracks, serialno);
    if (ts == NULL) break;

706
    fwrite_ogg_page (state, og);
707

708
    ts->headers_remaining -= ogg_page_packets (OGG_PAGE_CONST(og));
709

710 711 712 713 714 715 716
    if (ts->headers_remaining <= 0) {
      if (state->start == 0.0 || oggz_get_granuleshift (oggz, serialno) == 0) {
        oggz_set_read_page (oggz, serialno, read_plain, state);
      } else {
        ts->page_accum = oggz_table_new();
        oggz_set_read_page (oggz, serialno, read_gs, state);
      }
717 718 719 720 721 722 723 724 725 726 727 728
    }
  }

  return OGGZ_CONTINUE;
}

static int
read_bos (OGGZ * oggz, const ogg_page * og, long serialno, void * user_data)
{
  OCState * state = (OCState *)user_data;
  OCTrackState * ts;
  double page_time;
729
  OggzStreamContent content_type;
730

731
  if (ogg_page_bos (OGG_PAGE_CONST(og))) {
732 733
    content_type = oggz_stream_get_content(oggz, serialno);
    if(content_type == OGGZ_CONTENT_SKELETON) {
734 735 736 737 738
      if (state->do_skeleton) {
        state->original_had_skeleton = 1;
        state->skeleton_serialno = serialno;
        fishead_update (state, og);
      }
739
    } else {
740 741 742 743 744 745 746 747
      if ((ts = track_state_add (state->tracks, serialno)) == NULL) {
        /* Out of memory */
        return OGGZ_STOP_ERR;
      }
      if (fisbone_init (oggz, state, ts, serialno) == -1) {
        /* Out of memory */
        return OGGZ_STOP_ERR;
      }
748 749
      ts->headers_remaining = ts->fisbone.nr_header_packet;
    }
750

751 752 753
    /* Write the Skeleton BOS page out */
    if (state->status == OC_INIT) {
      fishead_write (state);
conrad's avatar
conrad committed
754
      state->status = OC_GLUING;
755 756
    }

757 758 759 760 761 762 763 764 765 766
    oggz_set_read_page (oggz, serialno, read_headers, state);
    read_headers (oggz, og, serialno, user_data);
  } else {
    /* Deregister the catch-all page reading callback */
    oggz_set_read_page (oggz, -1, NULL, NULL);
  }

  return OGGZ_CONTINUE;
}

767
int
768
chop (OCState * state)
769 770 771
{
  OGGZ * oggz;

772 773 774 775 776
  if (state == NULL || state->infilename == NULL) {
    fprintf (stderr, "oggz-chop: Initialization state invalid\n");
    return -1;
  }

777
  state_init (state);
778

779
  if (strcmp (state->infilename, "-") == 0) {
780 781
    oggz = oggz_open_stdio (stdin, OGGZ_READ|OGGZ_AUTO);
  } else {
782
    oggz = oggz_open (state->infilename, OGGZ_READ|OGGZ_AUTO);
783 784
  }

conrad's avatar
conrad committed
785 786
  if (oggz == NULL) return -1;

787 788 789 790 791 792 793 794 795 796 797
  if (!state->dry_run) {
    if (state->outfilename == NULL) {
      state->outfile = stdout;
    } else {
      state->outfile = fopen (state->outfilename, "wb");
      if (state->outfile == NULL) {
        fprintf (stderr, "oggz-chop: unable to open output file %s\n",
  	       state->outfilename);
        oggz_close(oggz);
        return -1;
      }
798 799 800
    }
  }

801 802 803 804 805 806 807 808
  /* Only need the writer if creating skeleton */
  if (state->do_skeleton) {
    state->skeleton_writer = oggz_open_stdio (state->outfile, OGGZ_WRITE);
    /* Choose a serialno that does not appear in the input stream. */
    state->skeleton_serialno = oggz_serialno_new (oggz);
  }

  /* set up a demux filter on the reader */
809
  oggz_set_read_page (oggz, -1, read_bos, state);
810 811 812 813 814 815

  oggz_run_set_blocksize (oggz, 1024*1024);
  oggz_run (oggz);

  oggz_close (oggz);

816
  if (state->outfilename != NULL && !state->dry_run) {
817 818 819
    fclose (state->outfile);
  }

820 821
  state_clear (state);

822 823
  return 0; 
}