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

media / filters / source_buffer_state_unittest.cc [blame]

// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "media/filters/source_buffer_state.h"

#include <vector>

#include "base/functional/bind.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/string_number_conversions.h"
#include "base/test/gmock_callback_support.h"
#include "base/time/time.h"
#include "media/base/media_util.h"
#include "media/base/mock_filters.h"
#include "media/base/mock_media_log.h"
#include "media/base/stream_parser.h"
#include "media/base/test_helpers.h"
#include "media/filters/chunk_demuxer.h"
#include "media/filters/frame_processor.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace media {

using base::test::RunClosure;
using testing::_;
using testing::DoAll;
using testing::InvokeWithoutArgs;
using testing::Return;
using testing::SaveArg;

namespace {

AudioDecoderConfig CreateAudioConfig(AudioCodec codec) {
  return AudioDecoderConfig(codec, kSampleFormatPlanarF32,
                            CHANNEL_LAYOUT_STEREO, 1000, EmptyExtraData(),
                            EncryptionScheme::kUnencrypted);
}

VideoDecoderConfig CreateVideoConfig(VideoCodec codec, int w, int h) {
  gfx::Size size(w, h);
  gfx::Rect visible_rect(size);
  return VideoDecoderConfig(codec, VIDEO_CODEC_PROFILE_UNKNOWN,
                            VideoDecoderConfig::AlphaMode::kIsOpaque,
                            VideoColorSpace::REC709(), kNoTransformation, size,
                            visible_rect, size, EmptyExtraData(),
                            EncryptionScheme::kUnencrypted);
}

void AddAudioTrack(std::unique_ptr<MediaTracks>& t, AudioCodec codec, int id) {
  t->AddAudioTrack(CreateAudioConfig(codec), true, id, MediaTrack::Kind(),
                   MediaTrack::Label(), MediaTrack::Language());
}

void AddVideoTrack(std::unique_ptr<MediaTracks>& t, VideoCodec codec, int id) {
  t->AddVideoTrack(CreateVideoConfig(codec, 16, 16), true, id,
                   MediaTrack::Kind(), MediaTrack::Label(),
                   MediaTrack::Language());
}

}  // namespace

class SourceBufferStateTest : public ::testing::Test {
 public:
  SourceBufferStateTest() : mock_stream_parser_(nullptr) {}

  std::unique_ptr<SourceBufferState> CreateSourceBufferState() {
    std::unique_ptr<FrameProcessor> frame_processor =
        std::make_unique<FrameProcessor>(
            base::BindRepeating(&SourceBufferStateTest::OnUpdateDuration,
                                base::Unretained(this)),
            &media_log_);
    mock_stream_parser_ = new testing::StrictMock<MockStreamParser>();
    return base::WrapUnique(new SourceBufferState(
        base::WrapUnique(mock_stream_parser_.get()), std::move(frame_processor),
        base::BindRepeating(&SourceBufferStateTest::CreateDemuxerStream,
                            base::Unretained(this)),
        &media_log_));
  }

  std::unique_ptr<SourceBufferState> CreateAndInitSourceBufferState(
      const std::string& expected_codecs) {
    std::unique_ptr<SourceBufferState> sbs = CreateSourceBufferState();
    // Instead of using SaveArg<> to update |new_config_cb_| when mocked Init is
    // called, we use a lambda because SaveArg<> doesn't work if any of the
    // mocked method's arguments are move-only type.
    EXPECT_CALL(*mock_stream_parser_, Init(_, _, _, _, _, _, _))
        .WillOnce([&](auto init_cb, auto config_cb, auto new_buffers_cb,
                      auto encrypted_media_init_data_cb, auto new_segment_cb,
                      auto end_of_segment_cb,
                      auto media_log) { new_config_cb_ = config_cb; });
    sbs->Init(base::BindOnce(&SourceBufferStateTest::SourceInitDone,
                             base::Unretained(this)),
              expected_codecs,
              base::BindRepeating(
                  &SourceBufferStateTest::StreamParserEncryptedInitData,
                  base::Unretained(this)));

    sbs->SetTracksWatcher(base::BindRepeating(
        &SourceBufferStateTest::OnMediaTracksUpdated, base::Unretained(this)));

    // These tests are not expected to issue any parse warnings.
    EXPECT_CALL(*this, OnParseWarningMock(_)).Times(0);

    sbs->SetParseWarningCallback(base::BindRepeating(
        &SourceBufferStateTest::OnParseWarningMock, base::Unretained(this)));

    return sbs;
  }

  // Emulates appending and parsing some data to the SourceBufferState, since
  // OnNewConfigs can only be invoked when parse is in progress.
  bool AppendDataAndReportTracks(const std::unique_ptr<SourceBufferState>& sbs,
                                 std::unique_ptr<MediaTracks> tracks) {
    const uint8_t kStreamData[] = "stream_data";
    base::span<const uint8_t> stream_data = base::span(kStreamData);
    base::TimeDelta t;

    // Ensure `stream_data` fits within one StreamParser::Parse() call.
    CHECK_GT(StreamParser::kMaxPendingBytesPerParse,
             static_cast<int>(stream_data.size_bytes()));

    bool new_configs_result = false;

    EXPECT_CALL(*mock_stream_parser_, AppendToParseBuffer(stream_data))
        .WillOnce(Return(true));
    EXPECT_CALL(*mock_stream_parser_,
                Parse(StreamParser::kMaxPendingBytesPerParse))
        .WillOnce(
            DoAll(InvokeWithoutArgs([&] {
                    new_configs_result = new_config_cb_.Run(std::move(tracks));
                  }),
                  /* Indicate successful parse with no uninspected data. */
                  Return(StreamParser::ParseStatus::kSuccess)));

    EXPECT_TRUE(sbs->AppendToParseBuffer(stream_data));
    EXPECT_EQ(StreamParser::ParseStatus::kSuccess,
              sbs->RunSegmentParserLoop(t, t, &t));

    return new_configs_result;
  }

  MOCK_METHOD1(OnParseWarningMock, void(const SourceBufferParseWarning));
  MOCK_METHOD1(OnUpdateDuration, void(base::TimeDelta));

  MOCK_METHOD1(SourceInitDone, void(const StreamParser::InitParameters&));
  MOCK_METHOD2(StreamParserEncryptedInitData,
               void(EmeInitDataType, const std::vector<uint8_t>&));

  MOCK_METHOD1(MediaTracksUpdatedMock, void(std::unique_ptr<MediaTracks>&));
  void OnMediaTracksUpdated(std::unique_ptr<MediaTracks> tracks) {
    MediaTracksUpdatedMock(tracks);
  }

  ChunkDemuxerStream* CreateDemuxerStream(DemuxerStream::Type type) {
    static unsigned track_id = 0;
    demuxer_streams_.push_back(base::WrapUnique(new ChunkDemuxerStream(
        type, MediaTrack::Id(base::NumberToString(++track_id)))));
    return demuxer_streams_.back().get();
  }

  testing::StrictMock<MockMediaLog> media_log_;
  std::vector<std::unique_ptr<ChunkDemuxerStream>> demuxer_streams_;
  raw_ptr<MockStreamParser, DanglingUntriaged> mock_stream_parser_;
  StreamParser::NewConfigCB new_config_cb_;
};

TEST_F(SourceBufferStateTest, InitSourceBufferWithRelaxedCodecChecks) {
  std::unique_ptr<SourceBufferState> sbs = CreateSourceBufferState();
  EXPECT_CALL(*mock_stream_parser_, Init(_, _, _, _, _, _, _))
      .WillOnce([&](auto init_cb, auto config_cb, auto new_buffers_cb,
                    auto encrypted_media_init_data_cb, auto new_segment_cb,
                    auto end_of_segment_cb,
                    auto media_log) { new_config_cb_ = config_cb; });

  sbs->Init(
      base::BindOnce(&SourceBufferStateTest::SourceInitDone,
                     base::Unretained(this)),
      std::nullopt,
      base::BindRepeating(&SourceBufferStateTest::StreamParserEncryptedInitData,
                          base::Unretained(this)));

  sbs->SetTracksWatcher(base::BindRepeating(
      &SourceBufferStateTest::OnMediaTracksUpdated, base::Unretained(this)));

  EXPECT_CALL(*this, OnParseWarningMock(_)).Times(0);

  sbs->SetParseWarningCallback(base::BindRepeating(
      &SourceBufferStateTest::OnParseWarningMock, base::Unretained(this)));

  std::unique_ptr<MediaTracks> tracks(new MediaTracks());
  AddAudioTrack(tracks, AudioCodec::kVorbis, 1);

  EXPECT_FOUND_CODEC_NAME(Audio, "vorbis");
  EXPECT_CALL(*this, MediaTracksUpdatedMock(_));
  EXPECT_TRUE(AppendDataAndReportTracks(sbs, std::move(tracks)));
}

TEST_F(SourceBufferStateTest, InitSingleAudioTrack) {
  std::unique_ptr<SourceBufferState> sbs =
      CreateAndInitSourceBufferState("vorbis");

  std::unique_ptr<MediaTracks> tracks(new MediaTracks());
  AddAudioTrack(tracks, AudioCodec::kVorbis, 1);

  EXPECT_FOUND_CODEC_NAME(Audio, "vorbis");
  EXPECT_CALL(*this, MediaTracksUpdatedMock(_));
  EXPECT_TRUE(AppendDataAndReportTracks(sbs, std::move(tracks)));
}

TEST_F(SourceBufferStateTest, InitSingleVideoTrack) {
  std::unique_ptr<SourceBufferState> sbs =
      CreateAndInitSourceBufferState("vp8");

  std::unique_ptr<MediaTracks> tracks(new MediaTracks());
  AddVideoTrack(tracks, VideoCodec::kVP8, 1);

  EXPECT_FOUND_CODEC_NAME(Video, "vp8");
  EXPECT_CALL(*this, MediaTracksUpdatedMock(_));
  EXPECT_TRUE(AppendDataAndReportTracks(sbs, std::move(tracks)));
}

TEST_F(SourceBufferStateTest, InitMultipleTracks) {
  std::unique_ptr<SourceBufferState> sbs =
      CreateAndInitSourceBufferState("vorbis,vp8,opus,vp9");

  std::unique_ptr<MediaTracks> tracks(new MediaTracks());
  AddAudioTrack(tracks, AudioCodec::kVorbis, 1);
  AddAudioTrack(tracks, AudioCodec::kOpus, 2);
  AddVideoTrack(tracks, VideoCodec::kVP8, 3);
  AddVideoTrack(tracks, VideoCodec::kVP9, 4);

  EXPECT_FOUND_CODEC_NAME(Audio, "vorbis");
  EXPECT_FOUND_CODEC_NAME(Audio, "opus");
  EXPECT_FOUND_CODEC_NAME(Video, "vp9");
  EXPECT_FOUND_CODEC_NAME(Video, "vp8");
  EXPECT_CALL(*this, MediaTracksUpdatedMock(_));
  EXPECT_TRUE(AppendDataAndReportTracks(sbs, std::move(tracks)));
}

TEST_F(SourceBufferStateTest, AudioStreamMismatchesExpectedCodecs) {
  std::unique_ptr<SourceBufferState> sbs =
      CreateAndInitSourceBufferState("opus");
  std::unique_ptr<MediaTracks> tracks(new MediaTracks());
  AddAudioTrack(tracks, AudioCodec::kVorbis, 1);
  EXPECT_MEDIA_LOG(InitSegmentMismatchesMimeType("Audio", "vorbis"));
  EXPECT_FALSE(AppendDataAndReportTracks(sbs, std::move(tracks)));
}

TEST_F(SourceBufferStateTest, VideoStreamMismatchesExpectedCodecs) {
  std::unique_ptr<SourceBufferState> sbs =
      CreateAndInitSourceBufferState("vp9");
  std::unique_ptr<MediaTracks> tracks(new MediaTracks());
  AddVideoTrack(tracks, VideoCodec::kVP8, 1);
  EXPECT_MEDIA_LOG(InitSegmentMismatchesMimeType("Video", "vp8"));
  EXPECT_FALSE(AppendDataAndReportTracks(sbs, std::move(tracks)));
}

TEST_F(SourceBufferStateTest, MissingExpectedAudioStream) {
  std::unique_ptr<SourceBufferState> sbs =
      CreateAndInitSourceBufferState("opus,vp9");
  std::unique_ptr<MediaTracks> tracks(new MediaTracks());
  AddVideoTrack(tracks, VideoCodec::kVP9, 1);
  EXPECT_FOUND_CODEC_NAME(Video, "vp9");
  EXPECT_MEDIA_LOG(InitSegmentMissesExpectedTrack("opus"));
  EXPECT_FALSE(AppendDataAndReportTracks(sbs, std::move(tracks)));
}

TEST_F(SourceBufferStateTest, MissingExpectedVideoStream) {
  std::unique_ptr<SourceBufferState> sbs =
      CreateAndInitSourceBufferState("opus,vp9");
  std::unique_ptr<MediaTracks> tracks(new MediaTracks());
  tracks->AddAudioTrack(CreateAudioConfig(AudioCodec::kOpus), true, 1,
                        MediaTrack::Kind(), MediaTrack::Label(),
                        MediaTrack::Language());
  EXPECT_FOUND_CODEC_NAME(Audio, "opus");
  EXPECT_MEDIA_LOG(InitSegmentMissesExpectedTrack("vp9"));
  EXPECT_FALSE(AppendDataAndReportTracks(sbs, std::move(tracks)));
}

TEST_F(SourceBufferStateTest, TrackIdsChangeInSecondInitSegment) {
  std::unique_ptr<SourceBufferState> sbs =
      CreateAndInitSourceBufferState("opus,vp9");

  std::unique_ptr<MediaTracks> tracks(new MediaTracks());
  AddAudioTrack(tracks, AudioCodec::kOpus, 1);
  AddVideoTrack(tracks, VideoCodec::kVP9, 2);
  EXPECT_FOUND_CODEC_NAME(Audio, "opus");
  EXPECT_FOUND_CODEC_NAME(Video, "vp9");
  EXPECT_CALL(*this, MediaTracksUpdatedMock(_));
  AppendDataAndReportTracks(sbs, std::move(tracks));

  // This second set of tracks have bytestream track ids that differ from the
  // first init segment above (audio track id 1 -> 3, video track id 2 -> 4).
  // Bytestream track ids are allowed to change when there is only a single
  // track of each type.
  std::unique_ptr<MediaTracks> tracks2(new MediaTracks());
  AddAudioTrack(tracks2, AudioCodec::kOpus, 3);
  AddVideoTrack(tracks2, VideoCodec::kVP9, 4);
  EXPECT_CALL(*this, MediaTracksUpdatedMock(_));
  AppendDataAndReportTracks(sbs, std::move(tracks2));
}

TEST_F(SourceBufferStateTest, TrackIdChangeWithTwoAudioTracks) {
  std::unique_ptr<SourceBufferState> sbs =
      CreateAndInitSourceBufferState("vorbis,opus");

  std::unique_ptr<MediaTracks> tracks(new MediaTracks());
  AddAudioTrack(tracks, AudioCodec::kVorbis, 1);
  AddAudioTrack(tracks, AudioCodec::kOpus, 2);
  EXPECT_FOUND_CODEC_NAME(Audio, "vorbis");
  EXPECT_FOUND_CODEC_NAME(Audio, "opus");
  EXPECT_CALL(*this, MediaTracksUpdatedMock(_));
  EXPECT_TRUE(AppendDataAndReportTracks(sbs, std::move(tracks)));

  // Since we have two audio tracks, bytestream track ids must match the first
  // init segment.
  std::unique_ptr<MediaTracks> tracks2(new MediaTracks());
  AddAudioTrack(tracks2, AudioCodec::kVorbis, 1);
  AddAudioTrack(tracks2, AudioCodec::kOpus, 2);
  EXPECT_CALL(*this, MediaTracksUpdatedMock(_));
  EXPECT_TRUE(AppendDataAndReportTracks(sbs, std::move(tracks2)));

  // Emulate the situation where bytestream track ids have changed in the third
  // init segment. This must cause failure in the OnNewConfigs.
  std::unique_ptr<MediaTracks> tracks3(new MediaTracks());
  AddAudioTrack(tracks3, AudioCodec::kVorbis, 1);
  AddAudioTrack(tracks3, AudioCodec::kOpus, 3);
  EXPECT_MEDIA_LOG(UnexpectedTrack("audio", "3"));
  EXPECT_FALSE(AppendDataAndReportTracks(sbs, std::move(tracks3)));
}

TEST_F(SourceBufferStateTest, TrackIdChangeWithTwoVideoTracks) {
  std::unique_ptr<SourceBufferState> sbs =
      CreateAndInitSourceBufferState("vp8,vp9");

  std::unique_ptr<MediaTracks> tracks(new MediaTracks());
  AddVideoTrack(tracks, VideoCodec::kVP8, 1);
  AddVideoTrack(tracks, VideoCodec::kVP9, 2);
  EXPECT_FOUND_CODEC_NAME(Video, "vp8");
  EXPECT_FOUND_CODEC_NAME(Video, "vp9");
  EXPECT_CALL(*this, MediaTracksUpdatedMock(_));
  EXPECT_TRUE(AppendDataAndReportTracks(sbs, std::move(tracks)));

  // Since we have two video tracks, bytestream track ids must match the first
  // init segment.
  std::unique_ptr<MediaTracks> tracks2(new MediaTracks());
  AddVideoTrack(tracks2, VideoCodec::kVP8, 1);
  AddVideoTrack(tracks2, VideoCodec::kVP9, 2);
  EXPECT_CALL(*this, MediaTracksUpdatedMock(_));
  EXPECT_TRUE(AppendDataAndReportTracks(sbs, std::move(tracks2)));

  // Emulate the situation where bytestream track ids have changed in the third
  // init segment. This must cause failure in the OnNewConfigs.
  std::unique_ptr<MediaTracks> tracks3(new MediaTracks());
  AddVideoTrack(tracks3, VideoCodec::kVP8, 1);
  AddVideoTrack(tracks3, VideoCodec::kVP9, 3);
  EXPECT_MEDIA_LOG(UnexpectedTrack("video", "3"));
  EXPECT_FALSE(AppendDataAndReportTracks(sbs, std::move(tracks3)));
}

TEST_F(SourceBufferStateTest, TrackIdsSwappedInSecondInitSegment) {
  std::unique_ptr<SourceBufferState> sbs =
      CreateAndInitSourceBufferState("opus,vp9");

  std::unique_ptr<MediaTracks> tracks(new MediaTracks());
  AddAudioTrack(tracks, AudioCodec::kOpus, 1);
  AddVideoTrack(tracks, VideoCodec::kVP9, 2);
  EXPECT_FOUND_CODEC_NAME(Audio, "opus");
  EXPECT_FOUND_CODEC_NAME(Video, "vp9");
  EXPECT_CALL(*this, MediaTracksUpdatedMock(_));
  AppendDataAndReportTracks(sbs, std::move(tracks));

  // Track ids are swapped in the second init segment.
  std::unique_ptr<MediaTracks> tracks2(new MediaTracks());
  AddAudioTrack(tracks2, AudioCodec::kOpus, 2);
  AddVideoTrack(tracks2, VideoCodec::kVP9, 1);
  EXPECT_CALL(*this, MediaTracksUpdatedMock(_));
  AppendDataAndReportTracks(sbs, std::move(tracks2));
}

}  // namespace media