File: MP3ADU.cpp

package info (click to toggle)
liblivemedia 2006.03.17-2
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 2,928 kB
  • ctags: 4,588
  • sloc: cpp: 35,064; ansic: 979; makefile: 78; sh: 73
file content (635 lines) | stat: -rw-r--r-- 20,762 bytes parent folder | download
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
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
203
204
205
206
207
208
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)

This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
more details.

You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
**********/
// "liveMedia"
// Copyright (c) 1996-2005 Live Networks, Inc.  All rights reserved.
// 'ADU' MP3 streams (for improved loss-tolerance)
// Implementation

#include "MP3ADU.hh"
#include "MP3ADUdescriptor.hh"
#include "MP3Internals.hh"
#include <string.h>

#ifdef TEST_LOSS
#include "GroupsockHelper.hh"
#endif

// Segment data structures, used in the implementation below:

#define SegmentBufSize 2000	/* conservatively high */

class Segment {
public:
  unsigned char buf[SegmentBufSize];
  unsigned char* dataStart() { return &buf[descriptorSize]; }
  unsigned frameSize; // if it's a non-ADU frame
  unsigned dataHere(); // if it's a non-ADU frame

  unsigned descriptorSize;
  static unsigned const headerSize;
  unsigned sideInfoSize, aduSize;
  unsigned backpointer;

  struct timeval presentationTime;
  unsigned durationInMicroseconds;
};

unsigned const Segment::headerSize = 4;

#define SegmentQueueSize 10

class SegmentQueue {
public:
  SegmentQueue(Boolean directionIsToADU, Boolean includeADUdescriptors)
    : fDirectionIsToADU(directionIsToADU),
      fIncludeADUdescriptors(includeADUdescriptors) {
    reset();
  }

  Segment s[SegmentQueueSize];

  unsigned headIndex() {return fHeadIndex;}
  Segment& headSegment() {return s[fHeadIndex];}

  unsigned nextFreeIndex() {return fNextFreeIndex;}
  Segment& nextFreeSegment() {return s[fNextFreeIndex];}
  Boolean isEmpty() {return isEmptyOrFull() && totalDataSize() == 0;}
  Boolean isFull() {return isEmptyOrFull() && totalDataSize() > 0;}

  static unsigned nextIndex(unsigned ix) {return (ix+1)%SegmentQueueSize;}
  static unsigned prevIndex(unsigned ix) {return (ix+SegmentQueueSize-1)%SegmentQueueSize;}

  unsigned totalDataSize() {return fTotalDataSize;}

  void enqueueNewSegment(FramedSource* inputSource, FramedSource* usingSource);

  Boolean dequeue();

  Boolean insertDummyBeforeTail(unsigned backpointer);

  void reset() { fHeadIndex = fNextFreeIndex = fTotalDataSize = 0; }

private:
  static void sqAfterGettingSegment(void* clientData,
				    unsigned numBytesRead,
				    unsigned numTruncatedBytes,
				    struct timeval presentationTime,
				    unsigned durationInMicroseconds);

  Boolean sqAfterGettingCommon(Segment& seg, unsigned numBytesRead); 
  Boolean isEmptyOrFull() {return headIndex() == nextFreeIndex();}

  unsigned fHeadIndex, fNextFreeIndex, fTotalDataSize;

  // The following is used for asynchronous reads:
  FramedSource* fUsingSource;

  // This tells us whether the direction in which we're being used
  // is MP3->ADU, or vice-versa.  (This flag is used for debugging output.)
  Boolean fDirectionIsToADU;

  // The following is true iff we're used to enqueue incoming
  // ADU frames, and these have an ADU descriptor in front
  Boolean fIncludeADUdescriptors;
};

////////// ADUFromMP3Source //////////

ADUFromMP3Source::ADUFromMP3Source(UsageEnvironment& env,
				   FramedSource* inputSource,
				   Boolean includeADUdescriptors)
  : FramedFilter(env, inputSource),
    fAreEnqueueingMP3Frame(False),
    fSegments(new SegmentQueue(True /* because we're MP3->ADU */,
			       False /*no descriptors in incoming frames*/)),
    fIncludeADUdescriptors(includeADUdescriptors),
    fTotalDataSizeBeforePreviousRead(0), fScale(1), fFrameCounter(0) {
}

ADUFromMP3Source::~ADUFromMP3Source() {
  delete fSegments;
}


char const* ADUFromMP3Source::MIMEtype() const {
  return "audio/MPA-ROBUST";
}

ADUFromMP3Source* ADUFromMP3Source::createNew(UsageEnvironment& env,
                                              FramedSource* inputSource,
                                              Boolean includeADUdescriptors) {
  // The source must be a MPEG audio source:
  if (strcmp(inputSource->MIMEtype(), "audio/MPEG") != 0) {
    env.setResultMsg(inputSource->name(), " is not an MPEG audio source");
    return NULL;
  }

  return new ADUFromMP3Source(env, inputSource, includeADUdescriptors);
}

void ADUFromMP3Source::resetInput() {
  fSegments->reset();
}

Boolean ADUFromMP3Source::setScaleFactor(int scale) {
  if (scale < 1) return False;
  fScale = scale;
  return True;
}

void ADUFromMP3Source::doGetNextFrame() {
  if (!fAreEnqueueingMP3Frame) {
    // Arrange to enqueue a new MP3 frame:
    fTotalDataSizeBeforePreviousRead = fSegments->totalDataSize();
    fAreEnqueueingMP3Frame = True;
    fSegments->enqueueNewSegment(fInputSource, this);
  } else {
    // Deliver an ADU from a previously-read MP3 frame:
    fAreEnqueueingMP3Frame = False;

    if (!doGetNextFrame1()) {
      // An internal error occurred; act as if our source went away:
      FramedSource::handleClosure(this);
    }
  }
}

Boolean ADUFromMP3Source::doGetNextFrame1() {
  // First, check whether we have enough previously-read data to output an
  // ADU for the last-read MP3 frame:
  unsigned tailIndex;
  Segment* tailSeg;
  Boolean needMoreData;

  if (fSegments->isEmpty()) {
    needMoreData = True;
    tailSeg = NULL; tailIndex = 0; // unneeded, but stops compiler warnings
  } else {
    tailIndex = SegmentQueue::prevIndex(fSegments->nextFreeIndex());
    tailSeg = &(fSegments->s[tailIndex]);

    needMoreData
	  = fTotalDataSizeBeforePreviousRead < tailSeg->backpointer // bp points back too far
      || tailSeg->backpointer + tailSeg->dataHere() < tailSeg->aduSize; // not enough data
  }

  if (needMoreData) {
    // We don't have enough data to output an ADU from the last-read MP3
    // frame, so need to read another one and try again:
    doGetNextFrame();
    return True;
  }

  // Output an ADU from the tail segment:
  fFrameSize = tailSeg->headerSize+tailSeg->sideInfoSize+tailSeg->aduSize;
  fPresentationTime = tailSeg->presentationTime;
  fDurationInMicroseconds = tailSeg->durationInMicroseconds;
  unsigned descriptorSize
    = fIncludeADUdescriptors ? ADUdescriptor::computeSize(fFrameSize) : 0;
#ifdef DEBUG
  fprintf(stderr, "m->a:outputting ADU %d<-%d, nbr:%d, sis:%d, dh:%d, (descriptor size: %d)\n", tailSeg->aduSize, tailSeg->backpointer, fFrameSize, tailSeg->sideInfoSize, tailSeg->dataHere(), descriptorSize);
#endif
  if (descriptorSize + fFrameSize > fMaxSize) {
    envir() << "ADUFromMP3Source::doGetNextFrame1(): not enough room ("
	    << descriptorSize + fFrameSize << ">"
	    << fMaxSize << ")\n";
    fFrameSize = 0;
    return False;
  }

  unsigned char* toPtr = fTo;
  // output the ADU descriptor:
  if (fIncludeADUdescriptors) {
    fFrameSize += ADUdescriptor::generateDescriptor(toPtr, fFrameSize);
  }

  // output header and side info:
  memmove(toPtr, tailSeg->dataStart(),
	  tailSeg->headerSize + tailSeg->sideInfoSize);
  toPtr += tailSeg->headerSize + tailSeg->sideInfoSize;

  // go back to the frame that contains the start of our data:
  unsigned offset = 0;
  unsigned i = tailIndex;
  unsigned prevBytes = tailSeg->backpointer;
  while (prevBytes > 0) {
    i = SegmentQueue::prevIndex(i);
    unsigned dataHere = fSegments->s[i].dataHere();
    if (dataHere < prevBytes) {
      prevBytes -= dataHere;
    } else {
      offset = dataHere - prevBytes;
      break;
    }
  }

  // dequeue any segments that we no longer need:
  while (fSegments->headIndex() != i) {
    fSegments->dequeue(); // we're done with it
  }

  unsigned bytesToUse = tailSeg->aduSize;
  while (bytesToUse > 0) {
    Segment& seg = fSegments->s[i];
    unsigned char* fromPtr
      = &seg.dataStart()[seg.headerSize + seg.sideInfoSize + offset];
    unsigned dataHere = seg.dataHere() - offset;
    unsigned bytesUsedHere = dataHere < bytesToUse ? dataHere : bytesToUse;
    memmove(toPtr, fromPtr, bytesUsedHere);
    bytesToUse -= bytesUsedHere;
    toPtr += bytesUsedHere;
    offset = 0;
    i = SegmentQueue::nextIndex(i);
  }


  if (fFrameCounter++%fScale == 0) {
    // Call our own 'after getting' function.  Because we're not a 'leaf'
    // source, we can call this directly, without risking infinite recursion.
    afterGetting(this);
  } else {
    // Don't use this frame; get another one:
    doGetNextFrame();
  }

  return True;
}


////////// MP3FromADUSource //////////

MP3FromADUSource::MP3FromADUSource(UsageEnvironment& env,
				   FramedSource* inputSource,
				   Boolean includeADUdescriptors)
  : FramedFilter(env, inputSource),
    fAreEnqueueingADU(False),
    fSegments(new SegmentQueue(False /* because we're ADU->MP3 */,
			       includeADUdescriptors)),
    fIncludeADUdescriptors(includeADUdescriptors) {
}

MP3FromADUSource::~MP3FromADUSource() {
  delete fSegments;
}

char const* MP3FromADUSource::MIMEtype() const {
  return "audio/MPEG";
}

MP3FromADUSource* MP3FromADUSource::createNew(UsageEnvironment& env,
					      FramedSource* inputSource,
					      Boolean includeADUdescriptors) {
  // The source must be an MP3 ADU source:
  if (strcmp(inputSource->MIMEtype(), "audio/MPA-ROBUST") != 0) {
    env.setResultMsg(inputSource->name(), " is not an MP3 ADU source");
    return NULL;
  }

  return new MP3FromADUSource(env, inputSource, includeADUdescriptors);
}


void MP3FromADUSource::doGetNextFrame() {
  if (fAreEnqueueingADU) insertDummyADUsIfNecessary();
  fAreEnqueueingADU = False;

  if (needToGetAnADU()) {
    // Before returning a frame, we must enqueue at least one ADU:
#ifdef TEST_LOSS
  NOTE: This code no longer works, because it uses synchronous reads,
  which are no longer supported.
    static unsigned const framesPerPacket = 10;
    static unsigned const frameCount = 0;
    static Boolean packetIsLost;
    while (1) {
      if ((frameCount++)%framesPerPacket == 0) {
	packetIsLost = (our_random()%10 == 0); // simulate 10% packet loss #####
      }

      if (packetIsLost) {
	// Read and discard the next input frame (that would be part of
	// a lost packet):
	Segment dummySegment;
	unsigned numBytesRead;
	struct timeval presentationTime;
	// (this works only if the source can be read synchronously)
	fInputSource->syncGetNextFrame(dummySegment.buf,
				       sizeof dummySegment.buf, numBytesRead,
				       presentationTime);
      } else {
	break; // from while (1)
      }
    }
#endif

    fAreEnqueueingADU = True;
    fSegments->enqueueNewSegment(fInputSource, this);
  } else {
    // Return a frame now:
    generateFrameFromHeadADU();
        // sets fFrameSize, fPresentationTime, and fDurationInMicroseconds

    // Call our own 'after getting' function.  Because we're not a 'leaf'
    // source, we can call this directly, without risking infinite recursion.
    afterGetting(this);
  }
}

Boolean MP3FromADUSource::needToGetAnADU() {
  // Check whether we need to first enqueue a new ADU before we
  // can generate a frame for our head ADU.
  Boolean needToEnqueue = True;

  if (!fSegments->isEmpty()) {
    unsigned index = fSegments->headIndex();
    Segment* seg = &(fSegments->headSegment());
    int const endOfHeadFrame = (int) seg->dataHere();
    unsigned frameOffset = 0;
    
    while (1) {
      int endOfData = frameOffset - seg->backpointer + seg->aduSize;
      if (endOfData >= endOfHeadFrame) {
	// We already have enough data to generate a frame
	needToEnqueue = False;
	break;
      }
      
      frameOffset += seg->dataHere();
      index = SegmentQueue::nextIndex(index);
      if (index == fSegments->nextFreeIndex()) break;
      seg = &(fSegments->s[index]);
    }
  }
  
  return needToEnqueue;
}

void MP3FromADUSource::insertDummyADUsIfNecessary() {
  if (fSegments->isEmpty()) return; // shouldn't happen

  // The tail segment (ADU) is assumed to have been recently
  // enqueued.  If its backpointer would overlap the data
  // of the previous ADU, then we need to insert one or more
  // empty, 'dummy' ADUs ahead of it.  (This situation should occur
  // only if an intermediate ADU was lost.)
  
  unsigned tailIndex
    = SegmentQueue::prevIndex(fSegments->nextFreeIndex());
  Segment* tailSeg = &(fSegments->s[tailIndex]);
  
  while (1) {
    unsigned prevADUend; // relative to the start of the new ADU
    if (fSegments->headIndex() != tailIndex) {
      // there is a previous segment
      unsigned prevIndex = SegmentQueue::prevIndex(tailIndex);
      Segment& prevSegment = fSegments->s[prevIndex];
      prevADUend = prevSegment.dataHere() + prevSegment.backpointer;
      if (prevSegment.aduSize > prevADUend) {
	// shouldn't happen if the previous ADU was well-formed
	prevADUend = 0;
      } else {
	prevADUend -= prevSegment.aduSize;
      }
    } else {
      prevADUend = 0;
    }
    
    if (tailSeg->backpointer > prevADUend) {
      // We need to insert a dummy ADU in front of the tail
#ifdef DEBUG
      fprintf(stderr, "a->m:need to insert a dummy ADU (%d, %d, %d) [%d, %d]\n", tailSeg->backpointer, prevADUend, tailSeg->dataHere(), fSegments->headIndex(), fSegments->nextFreeIndex());
#endif
      tailIndex = fSegments->nextFreeIndex();
      if (!fSegments->insertDummyBeforeTail(prevADUend)) return;
      tailSeg = &(fSegments->s[tailIndex]);
    } else {
      break; // no more dummy ADUs need to be inserted
    }
  }
}

Boolean MP3FromADUSource::generateFrameFromHeadADU() {
    // Output a frame for the head ADU:
    if (fSegments->isEmpty()) return False;
    unsigned index = fSegments->headIndex();
    Segment* seg = &(fSegments->headSegment());
#ifdef DEBUG
    fprintf(stderr, "a->m:outputting frame for %d<-%d (fs %d, dh %d), (descriptorSize: %d)\n", seg->aduSize, seg->backpointer, seg->frameSize, seg->dataHere(), seg->descriptorSize);
#endif
    unsigned char* toPtr = fTo;
    
    // output header and side info:
    fFrameSize = seg->frameSize;
    fPresentationTime = seg->presentationTime;
    fDurationInMicroseconds = seg->durationInMicroseconds;
    memmove(toPtr, seg->dataStart(), seg->headerSize + seg->sideInfoSize);
    toPtr += seg->headerSize + seg->sideInfoSize;
    
    // zero out the rest of the frame, in case ADU data doesn't fill it all in
    unsigned bytesToZero = seg->dataHere(); 
    for (unsigned i = 0; i < bytesToZero; ++i) {
      toPtr[i] = '\0';
    }
    
    // Fill in the frame with appropriate ADU data from this and
    // subsequent ADUs:
    unsigned frameOffset = 0;
    unsigned toOffset = 0;
    unsigned const endOfHeadFrame = seg->dataHere();

    while (toOffset < endOfHeadFrame) {
      int startOfData = frameOffset - seg->backpointer;
      if (startOfData > (int)endOfHeadFrame) break; // no more ADUs needed
      
      int endOfData = startOfData + seg->aduSize;
      if (endOfData > (int)endOfHeadFrame) {
	endOfData = endOfHeadFrame;
      }
      
      unsigned fromOffset;
      if (startOfData <= (int)toOffset) {
	fromOffset = toOffset - startOfData;
	startOfData = toOffset;
	if (endOfData < startOfData) endOfData = startOfData;
      } else {
	fromOffset = 0;
	
	// we may need some padding bytes beforehand
	unsigned bytesToZero = startOfData - toOffset;
#ifdef DEBUG
	if (bytesToZero > 0) fprintf(stderr, "a->m:outputting %d zero bytes (%d, %d, %d, %d)\n", bytesToZero, startOfData, toOffset, frameOffset, seg->backpointer);
#endif
	toOffset += bytesToZero;
      }
      
      unsigned char* fromPtr
	= &seg->dataStart()[seg->headerSize + seg->sideInfoSize + fromOffset];
      unsigned bytesUsedHere = endOfData - startOfData;
#ifdef DEBUG
      if (bytesUsedHere > 0) fprintf(stderr, "a->m:outputting %d bytes from %d<-%d\n", bytesUsedHere, seg->aduSize, seg->backpointer);
#endif
      memmove(toPtr + toOffset, fromPtr, bytesUsedHere);
      toOffset += bytesUsedHere;
      
      frameOffset += seg->dataHere();
      index = SegmentQueue::nextIndex(index);
      if (index == fSegments->nextFreeIndex()) break;
      seg = &(fSegments->s[index]);
    }
    
    fSegments->dequeue();

    return True;
}


////////// Segment //////////

unsigned Segment::dataHere() {
  int result = frameSize - (headerSize + sideInfoSize);
  if (result < 0) {
    return 0;
  }

  return (unsigned)result;
} 

////////// SegmentQueue //////////

void SegmentQueue::enqueueNewSegment(FramedSource* inputSource,
				     FramedSource* usingSource) {
  if (isFull()) {
    usingSource->envir() << "SegmentQueue::enqueueNewSegment() overflow\n";
    FramedSource::handleClosure(usingSource);
    return;
  }
  
  fUsingSource = usingSource;
  
  Segment& seg = nextFreeSegment();
  inputSource->getNextFrame(seg.buf, sizeof seg.buf,
			    sqAfterGettingSegment, this,
			    FramedSource::handleClosure, usingSource);
}

void SegmentQueue::sqAfterGettingSegment(void* clientData,
					 unsigned numBytesRead,
					 unsigned /*numTruncatedBytes*/,
					 struct timeval presentationTime,
					 unsigned durationInMicroseconds) {
  SegmentQueue* segQueue = (SegmentQueue*)clientData;
  Segment& seg = segQueue->nextFreeSegment();

  seg.presentationTime = presentationTime;
  seg.durationInMicroseconds = durationInMicroseconds;

  if (segQueue->sqAfterGettingCommon(seg, numBytesRead)) {
#ifdef DEBUG
    char const* direction = segQueue->fDirectionIsToADU ? "m->a" : "a->m";
    fprintf(stderr, "%s:read frame %d<-%d, fs:%d, sis:%d, dh:%d, (descriptor size: %d)\n", direction, seg.aduSize, seg.backpointer, seg.frameSize, seg.sideInfoSize, seg.dataHere(), seg.descriptorSize);
#endif
  }

  // Continue our original calling source where it left off:
  segQueue->fUsingSource->doGetNextFrame();
}

// Common code called after a new segment is enqueued
Boolean SegmentQueue::sqAfterGettingCommon(Segment& seg,
					   unsigned numBytesRead) { 
  unsigned char* fromPtr = seg.buf;

  if (fIncludeADUdescriptors) {
    // The newly-read data is assumed to be an ADU with a descriptor
    // in front
    (void)ADUdescriptor::getRemainingFrameSize(fromPtr);
    seg.descriptorSize = (unsigned)(fromPtr-seg.buf);
  } else {
    seg.descriptorSize = 0;
  }

  // parse the MP3-specific info in the frame to get the ADU params
  unsigned hdr;
  MP3SideInfo sideInfo;
  if (!GetADUInfoFromMP3Frame(fromPtr, numBytesRead,
			      hdr, seg.frameSize,
			      sideInfo, seg.sideInfoSize,
			      seg.backpointer, seg.aduSize)) {
    return False;
  }
  
  // If we've just read an ADU (rather than a regular MP3 frame), then use the
  // entire "numBytesRead" data for the 'aduSize', so that we include any
  // 'ancillary data' that may be present at the end of the ADU:
  if (!fDirectionIsToADU) {
    unsigned newADUSize
      = numBytesRead - seg.descriptorSize - 4/*header size*/ - seg.sideInfoSize;
    if (newADUSize > seg.aduSize) seg.aduSize = newADUSize;
  }
  fTotalDataSize += seg.dataHere();
  fNextFreeIndex = nextIndex(fNextFreeIndex);

  return True;
}

Boolean SegmentQueue::dequeue() {
  if (isEmpty()) {
    fUsingSource->envir() << "SegmentQueue::dequeue(): underflow!\n";
    return False;
  }

  Segment& seg = s[headIndex()];
  fTotalDataSize -= seg.dataHere();
  fHeadIndex = nextIndex(fHeadIndex);
  return True;
}

Boolean SegmentQueue::insertDummyBeforeTail(unsigned backpointer) {
  if (isEmptyOrFull()) return False;

  // Copy the current tail segment to its new position, then modify the
  // old tail segment to be a 'dummy' ADU

  unsigned newTailIndex = nextFreeIndex();
  Segment& newTailSeg = s[newTailIndex];

  unsigned oldTailIndex = prevIndex(newTailIndex);
  Segment& oldTailSeg = s[oldTailIndex];

  newTailSeg = oldTailSeg; // structure copy

  // Begin by setting (replacing) the ADU descriptor of the dummy ADU:
  unsigned char* ptr = oldTailSeg.buf;
  if (fIncludeADUdescriptors) {
    unsigned remainingFrameSize
      = oldTailSeg.headerSize + oldTailSeg.sideInfoSize + 0 /* 0-size ADU */;
    unsigned currentDescriptorSize = oldTailSeg.descriptorSize;

    if (currentDescriptorSize == 2) {
      ADUdescriptor::generateTwoByteDescriptor(ptr, remainingFrameSize);
    } else {
      (void)ADUdescriptor::generateDescriptor(ptr, remainingFrameSize);
    }
  }

  // Then zero out the side info of the dummy frame:
  if (!ZeroOutMP3SideInfo(ptr, oldTailSeg.frameSize,
			  backpointer)) return False;

  unsigned dummyNumBytesRead
    = oldTailSeg.descriptorSize + 4/*header size*/ + oldTailSeg.sideInfoSize;
  return sqAfterGettingCommon(oldTailSeg, dummyNumBytesRead);
}