Cea608Decoder.java

/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package androidx.media3.extractor.text.cea;

import static androidx.media3.common.util.Assertions.checkNotNull;

import androidx.annotation.Nullable;
import androidx.media3.common.C;
import androidx.media3.common.Format;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.extractor.text.CuesWithTiming;
import androidx.media3.extractor.text.CuesWithTimingSubtitle;
import androidx.media3.extractor.text.Subtitle;
import androidx.media3.extractor.text.SubtitleDecoder;
import androidx.media3.extractor.text.SubtitleDecoderException;
import androidx.media3.extractor.text.SubtitleInputBuffer;
import androidx.media3.extractor.text.SubtitleOutputBuffer;
import androidx.media3.extractor.text.SubtitleParser.OutputOptions;
import com.google.common.collect.ImmutableList;
import java.nio.ByteBuffer;

/** A {@link SubtitleDecoder} for CEA-608 (also known as "line 21 captions" and "EIA-608"). */
@UnstableApi
public final class Cea608Decoder extends CeaDecoder {

  private static final CuesWithTiming EMPTY_CUES =
      new CuesWithTiming(
          ImmutableList.of(), /* startTimeUs= */ C.TIME_UNSET, /* durationUs= */ C.TIME_UNSET);

  private final Cea608Parser cea608Parser;

  @Nullable private CuesWithTiming cues;
  private boolean isNewSubtitleDataAvailable;
  private long lastCueUpdateUs;

  /**
   * Constructs an instance.
   *
   * @param parser A {@link Cea608Parser} to parse the subtitle data.
   */
  public Cea608Decoder(Cea608Parser parser) {
    this.cea608Parser = parser;
    lastCueUpdateUs = C.TIME_UNSET;
  }

  @Override
  public String getName() {
    return "Cea608Decoder";
  }

  @Override
  public void flush() {
    super.flush();
    isNewSubtitleDataAvailable = false;
    cues = null;
    cea608Parser.reset();
  }

  @Override
  public void release() {
    // Do nothing
  }

  @Nullable
  @Override
  public SubtitleOutputBuffer dequeueOutputBuffer() throws SubtitleDecoderException {
    SubtitleOutputBuffer outputBuffer = super.dequeueOutputBuffer();
    if (outputBuffer != null) {
      return outputBuffer;
    }
    if (shouldClearStuckCaptions()) {
      outputBuffer = getAvailableOutputBuffer();
      if (outputBuffer != null) {
        cues = EMPTY_CUES;
        lastCueUpdateUs = C.TIME_UNSET;
        Subtitle subtitle = createSubtitle();
        outputBuffer.setContent(getPositionUs(), subtitle, Format.OFFSET_SAMPLE_RELATIVE);
        return outputBuffer;
      }
    }
    return null;
  }

  @Override
  protected boolean isNewSubtitleDataAvailable() {
    return isNewSubtitleDataAvailable;
  }

  @Override
  protected Subtitle createSubtitle() {
    isNewSubtitleDataAvailable = false;
    return new CuesWithTimingSubtitle(ImmutableList.of(checkNotNull(cues)));
  }

  @SuppressWarnings("ByteBufferBackingArray")
  @Override
  protected void decode(SubtitleInputBuffer inputBuffer) {
    ByteBuffer subtitleData = checkNotNull(inputBuffer.data);

    cea608Parser.parse(
        subtitleData.array(),
        /* offset= */ subtitleData.arrayOffset(),
        /* length= */ subtitleData.limit(),
        OutputOptions.allCues(),
        /* output= */ cues -> {
          isNewSubtitleDataAvailable = true;
          // Remove the 'stuck captions' duration - in this class the clearing of stuck captions is
          // implemented by shouldClearStuckCaptions() below.
          this.cues =
              new CuesWithTiming(
                  cues.cues, /* startTimeUs= */ C.TIME_UNSET, /* durationUs= */ C.TIME_UNSET);
        });
  }

  /** See ANSI/CTA-608-E R-2014 Annex C.9 for Caption Erase Logic. */
  private boolean shouldClearStuckCaptions() {
    if (cea608Parser.validDataChannelTimeoutUs == C.TIME_UNSET || lastCueUpdateUs == C.TIME_UNSET) {
      return false;
    }
    long elapsedUs = getPositionUs() - lastCueUpdateUs;
    return elapsedUs >= cea608Parser.validDataChannelTimeoutUs;
  }
}