blob: 50c285616b9276d4a58acd3e74c55ea602d10216 [file] [log] [blame]
Henrik Lundina29b1482018-05-09 14:56:08 +02001/*
2 * Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "api/array_view.h"
12#include "api/audio_codecs/opus/audio_encoder_opus.h"
13#include "rtc_base/buffer.h"
14#include "rtc_base/checks.h"
15#include "test/fuzzers/fuzz_data_helper.h"
16
17namespace webrtc {
18namespace {
19
20// This function reads bytes from |data_view|, interprets them
21// as RTP timestamp and input samples, and sends them for encoding. The process
22// continues until no more data is available.
23void FuzzAudioEncoder(rtc::ArrayView<const uint8_t> data_view,
24 AudioEncoder* encoder) {
25 test::FuzzDataHelper data(data_view);
26 const size_t block_size_samples =
27 encoder->SampleRateHz() / 100 * encoder->NumChannels();
28 const size_t block_size_bytes = block_size_samples * sizeof(int16_t);
29 if (data_view.size() / block_size_bytes > 1000) {
30 // If the size of the fuzzer data is more than 1000 input blocks (i.e., more
31 // than 10 seconds), then don't fuzz at all for the fear of timing out.
32 return;
33 }
34
35 rtc::BufferT<int16_t> input_aligned(block_size_samples);
36 rtc::Buffer encoded;
37
38 // Each round in the loop below will need one block of samples + a 32-bit
39 // timestamp from the fuzzer input.
40 const size_t bytes_to_read = block_size_bytes + sizeof(uint32_t);
41 while (data.CanReadBytes(bytes_to_read)) {
42 const uint32_t timestamp = data.Read<uint32_t>();
43 auto byte_array = data.ReadByteArray(block_size_bytes);
44 // Align the data by copying to another array.
45 RTC_DCHECK_EQ(input_aligned.size() * sizeof(int16_t),
46 byte_array.size() * sizeof(uint8_t));
47 memcpy(input_aligned.data(), byte_array.data(), byte_array.size());
48 auto info = encoder->Encode(timestamp, input_aligned, &encoded);
49 }
50}
51
52} // namespace
53
54void FuzzOneInput(const uint8_t* data, size_t size) {
55 AudioEncoderOpus::Config config;
56 config.frame_size_ms = 20;
57 RTC_CHECK(config.IsOk());
58 constexpr int kPayloadType = 100;
59 std::unique_ptr<AudioEncoder> enc =
60 AudioEncoderOpus::MakeAudioEncoder(config, kPayloadType);
61 FuzzAudioEncoder(rtc::ArrayView<const uint8_t>(data, size), enc.get());
62}
63
64} // namespace webrtc