Replace gflags usages with rtc_base/flags in all targets based on test_main

BUG=webrtc:7644

Review-Url: https://codereview.webrtc.org/2995363002
Cr-Original-Commit-Position: refs/heads/master@{#19580}
Cr-Mirrored-From: https://chromium.googlesource.com/external/webrtc
Cr-Mirrored-Commit: 9b2f20c6187f29e0c5105ff436b2fc787f924976
diff --git a/audio/BUILD.gn b/audio/BUILD.gn
index 8d8db4b..2c62584 100644
--- a/audio/BUILD.gn
+++ b/audio/BUILD.gn
@@ -112,13 +112,13 @@
 
       deps = [
         "../common_audio",
+        "../rtc_base:rtc_base_approved",
         "../system_wrappers",
         "../test:fake_audio_device",
         "../test:test_common",
         "../test:test_main",
         "//testing/gmock",
         "//testing/gtest",
-        "//third_party/gflags",
       ]
       if (is_android) {
         deps += [ "//testing/android/native_test:native_test_native_code" ]
@@ -161,7 +161,6 @@
       "../test:test_main",
       "//testing/gmock",
       "//testing/gtest",
-      "//third_party/gflags",
     ]
 
     data = [
diff --git a/audio/test/low_bandwidth_audio_test.cc b/audio/test/low_bandwidth_audio_test.cc
index 55f8621..ea0cdf0 100644
--- a/audio/test/low_bandwidth_audio_test.cc
+++ b/audio/test/low_bandwidth_audio_test.cc
@@ -10,16 +10,16 @@
 
 #include <algorithm>
 
-#include "gflags/gflags.h"
 #include "webrtc/audio/test/low_bandwidth_audio_test.h"
 #include "webrtc/common_audio/wav_file.h"
-#include "webrtc/test/gtest.h"
+#include "webrtc/rtc_base/flags.h"
 #include "webrtc/system_wrappers/include/sleep.h"
+#include "webrtc/test/gtest.h"
 #include "webrtc/test/testsupport/fileutils.h"
 
 
-DEFINE_int32(sample_rate_hz, 16000,
-             "Sample rate (Hz) of the produced audio files.");
+DEFINE_int(sample_rate_hz, 16000,
+           "Sample rate (Hz) of the produced audio files.");
 
 DEFINE_bool(quick, false,
             "Don't do the full audio recording. "
@@ -31,7 +31,7 @@
 constexpr int kExtraRecordTimeMs = 500;
 
 std::string FileSampleRateSuffix() {
-  return std::to_string(FLAGS_sample_rate_hz / 1000);
+  return std::to_string(FLAG_sample_rate_hz / 1000);
 }
 
 }  // namespace
@@ -72,7 +72,7 @@
 std::unique_ptr<test::FakeAudioDevice::Renderer>
     AudioQualityTest::CreateRenderer() {
   return test::FakeAudioDevice::CreateBoundedWavFileWriter(
-      AudioOutputFile(), FLAGS_sample_rate_hz);
+      AudioOutputFile(), FLAG_sample_rate_hz);
 }
 
 void AudioQualityTest::OnFakeAudioDevicesCreated(
@@ -112,7 +112,7 @@
 }
 
 void AudioQualityTest::PerformTest() {
-  if (FLAGS_quick) {
+  if (FLAG_quick) {
     // Let the recording run for a small amount of time to check if it works.
     SleepMs(1000);
   } else {
diff --git a/modules/audio_coding/BUILD.gn b/modules/audio_coding/BUILD.gn
index a3964c9..abe064f 100644
--- a/modules/audio_coding/BUILD.gn
+++ b/modules/audio_coding/BUILD.gn
@@ -1630,7 +1630,6 @@
       "../../rtc_base:rtc_base_approved",
       "../../test:test_support",
       "//testing/gtest",
-      "//third_party/gflags",
     ]
   }
 
@@ -1816,9 +1815,9 @@
       ":neteq_quality_test_support",
       ":neteq_tools",
       ":webrtc_opus",
+      "../../rtc_base:rtc_base_approved",
       "../../test:test_main",
       "//testing/gtest",
-      "//third_party/gflags",
     ]
   }
 
@@ -1856,7 +1855,6 @@
       "../../system_wrappers:system_wrappers_default",
       "../../test:test_main",
       "//testing/gtest",
-      "//third_party/gflags",
     ]
   }
 
@@ -1874,7 +1872,6 @@
       "../../rtc_base:rtc_base_approved",
       "../../test:test_main",
       "//testing/gtest",
-      "//third_party/gflags",
     ]
   }
 
@@ -1892,7 +1889,6 @@
       "../../rtc_base:rtc_base_approved",
       "../../test:test_main",
       "//testing/gtest",
-      "//third_party/gflags",
     ]
   }
 
@@ -2179,7 +2175,6 @@
       "../../test:test_support",
       "//testing/gmock",
       "//testing/gtest",
-      "//third_party/gflags",
     ]
 
     defines = audio_coding_defines
diff --git a/modules/audio_coding/neteq/neteq_unittest.cc b/modules/audio_coding/neteq/neteq_unittest.cc
index ec7e2bb..303973c 100644
--- a/modules/audio_coding/neteq/neteq_unittest.cc
+++ b/modules/audio_coding/neteq/neteq_unittest.cc
@@ -20,13 +20,13 @@
 #include <string>
 #include <vector>
 
-#include "gflags/gflags.h"
 #include "webrtc/api/audio_codecs/builtin_audio_decoder_factory.h"
 #include "webrtc/common_types.h"
 #include "webrtc/modules/audio_coding/codecs/pcm16b/pcm16b.h"
 #include "webrtc/modules/audio_coding/neteq/tools/audio_loop.h"
 #include "webrtc/modules/audio_coding/neteq/tools/rtp_file_source.h"
 #include "webrtc/modules/include/module_common_types.h"
+#include "webrtc/rtc_base/flags.h"
 #include "webrtc/rtc_base/ignore_wundef.h"
 #include "webrtc/rtc_base/protobuf_utils.h"
 #include "webrtc/rtc_base/sha1digest.h"
@@ -460,7 +460,7 @@
                    output_checksum,
                    network_stats_checksum,
                    rtcp_stats_checksum,
-                   FLAGS_gen_ref);
+                   FLAG_gen_ref);
 }
 
 #if !defined(WEBRTC_IOS) && !defined(WEBRTC_ANDROID) &&             \
@@ -496,7 +496,7 @@
                    output_checksum,
                    network_stats_checksum,
                    rtcp_stats_checksum,
-                   FLAGS_gen_ref);
+                   FLAG_gen_ref);
 }
 
 // Use fax mode to avoid time-scaling. This is to simplify the testing of
diff --git a/modules/audio_coding/neteq/test/neteq_ilbc_quality_test.cc b/modules/audio_coding/neteq/test/neteq_ilbc_quality_test.cc
index 4e5f159..2f8ca1b 100644
--- a/modules/audio_coding/neteq/test/neteq_ilbc_quality_test.cc
+++ b/modules/audio_coding/neteq/test/neteq_ilbc_quality_test.cc
@@ -13,11 +13,10 @@
 #include "webrtc/modules/audio_coding/codecs/ilbc/audio_encoder_ilbc.h"
 #include "webrtc/modules/audio_coding/neteq/tools/neteq_quality_test.h"
 #include "webrtc/rtc_base/checks.h"
+#include "webrtc/rtc_base/flags.h"
 #include "webrtc/rtc_base/safe_conversions.h"
 #include "webrtc/test/testsupport/fileutils.h"
 
-using google::RegisterFlagValidator;
-using google::ParseCommandLineFlags;
 using testing::InitGoogleTest;
 
 namespace webrtc {
@@ -26,33 +25,27 @@
 static const int kInputSampleRateKhz = 8;
 static const int kOutputSampleRateKhz = 8;
 
-// Define switch for frame size.
-static bool ValidateFrameSize(const char* flagname, int32_t value) {
-  if (value == 20 || value == 30 || value == 40 || value == 60)
-    return true;
-  printf("Invalid frame size, should be 20, 30, 40, or 60 ms.");
-  return false;
-}
-
-DEFINE_int32(frame_size_ms, 20, "Codec frame size (milliseconds).");
-
-static const bool frame_size_dummy =
-    RegisterFlagValidator(&FLAGS_frame_size_ms, &ValidateFrameSize);
+DEFINE_int(frame_size_ms, 20, "Codec frame size (milliseconds).");
 
 }  // namespace
 
 class NetEqIlbcQualityTest : public NetEqQualityTest {
  protected:
   NetEqIlbcQualityTest()
-      : NetEqQualityTest(FLAGS_frame_size_ms,
+      : NetEqQualityTest(FLAG_frame_size_ms,
                          kInputSampleRateKhz,
                          kOutputSampleRateKhz,
-                         NetEqDecoder::kDecoderILBC) {}
+                         NetEqDecoder::kDecoderILBC) {
+    // Flag validation
+    RTC_CHECK(FLAG_frame_size_ms == 20 || FLAG_frame_size_ms == 30 ||
+              FLAG_frame_size_ms == 40 || FLAG_frame_size_ms == 60)
+        << "Invalid frame size, should be 20, 30, 40, or 60 ms.";
+  }
 
   void SetUp() override {
     ASSERT_EQ(1u, channels_) << "iLBC supports only mono audio.";
     AudioEncoderIlbcConfig config;
-    config.frame_size_ms = FLAGS_frame_size_ms;
+    config.frame_size_ms = FLAG_frame_size_ms;
     encoder_.reset(new AudioEncoderIlbcImpl(config, 102));
     NetEqQualityTest::SetUp();
   }
diff --git a/modules/audio_coding/neteq/test/neteq_isac_quality_test.cc b/modules/audio_coding/neteq/test/neteq_isac_quality_test.cc
index 8506e32..5a73a6a 100644
--- a/modules/audio_coding/neteq/test/neteq_isac_quality_test.cc
+++ b/modules/audio_coding/neteq/test/neteq_isac_quality_test.cc
@@ -10,9 +10,8 @@
 
 #include "webrtc/modules/audio_coding/codecs/isac/fix/include/isacfix.h"
 #include "webrtc/modules/audio_coding/neteq/tools/neteq_quality_test.h"
+#include "webrtc/rtc_base/flags.h"
 
-using google::RegisterFlagValidator;
-using google::ParseCommandLineFlags;
 using testing::InitGoogleTest;
 
 namespace webrtc {
@@ -22,18 +21,7 @@
 static const int kIsacInputSamplingKhz = 16;
 static const int kIsacOutputSamplingKhz = 16;
 
-// Define switch for bit rate.
-static bool ValidateBitRate(const char* flagname, int32_t value) {
-  if (value >= 10 && value <= 32)
-    return true;
-  printf("Invalid bit rate, should be between 10 and 32 kbps.");
-  return false;
-}
-
-DEFINE_int32(bit_rate_kbps, 32, "Target bit rate (kbps).");
-
-static const bool bit_rate_dummy =
-    RegisterFlagValidator(&FLAGS_bit_rate_kbps, &ValidateBitRate);
+DEFINE_int(bit_rate_kbps, 32, "Target bit rate (kbps).");
 
 }  // namespace
 
@@ -55,7 +43,11 @@
                        kIsacOutputSamplingKhz,
                        NetEqDecoder::kDecoderISAC),
       isac_encoder_(NULL),
-      bit_rate_kbps_(FLAGS_bit_rate_kbps) {}
+      bit_rate_kbps_(FLAG_bit_rate_kbps) {
+    // Flag validation
+    RTC_CHECK(FLAG_bit_rate_kbps >= 10 && FLAG_bit_rate_kbps <= 32)
+        << "Invalid bit rate, should be between 10 and 32 kbps.";
+  }
 
 void NetEqIsacQualityTest::SetUp() {
   ASSERT_EQ(1u, channels_) << "iSAC supports only mono audio.";
diff --git a/modules/audio_coding/neteq/test/neteq_opus_quality_test.cc b/modules/audio_coding/neteq/test/neteq_opus_quality_test.cc
index eac8476..f4edf37 100644
--- a/modules/audio_coding/neteq/test/neteq_opus_quality_test.cc
+++ b/modules/audio_coding/neteq/test/neteq_opus_quality_test.cc
@@ -11,9 +11,8 @@
 #include "webrtc/modules/audio_coding/codecs/opus/opus_interface.h"
 #include "webrtc/modules/audio_coding/codecs/opus/opus_inst.h"
 #include "webrtc/modules/audio_coding/neteq/tools/neteq_quality_test.h"
+#include "webrtc/rtc_base/flags.h"
 
-using google::RegisterFlagValidator;
-using google::ParseCommandLineFlags;
 using testing::InitGoogleTest;
 
 namespace webrtc {
@@ -23,79 +22,24 @@
 static const int kOpusBlockDurationMs = 20;
 static const int kOpusSamplingKhz = 48;
 
-// Define switch for bit rate.
-static bool ValidateBitRate(const char* flagname, int32_t value) {
-  if (value >= 6 && value <= 510)
-    return true;
-  printf("Invalid bit rate, should be between 6 and 510 kbps.");
-  return false;
-}
+DEFINE_int(bit_rate_kbps, 32, "Target bit rate (kbps).");
 
-DEFINE_int32(bit_rate_kbps, 32, "Target bit rate (kbps).");
-
-static const bool bit_rate_dummy =
-    RegisterFlagValidator(&FLAGS_bit_rate_kbps, &ValidateBitRate);
-
-// Define switch for complexity.
-static bool ValidateComplexity(const char* flagname, int32_t value) {
-  if (value >= -1 && value <= 10)
-    return true;
-  printf("Invalid complexity setting, should be between 0 and 10.");
-  return false;
-}
-
-DEFINE_int32(complexity, 10, "Complexity: 0 ~ 10 -- defined as in Opus"
+DEFINE_int(complexity, 10, "Complexity: 0 ~ 10 -- defined as in Opus"
     "specification.");
 
-static const bool complexity_dummy =
-    RegisterFlagValidator(&FLAGS_complexity, &ValidateComplexity);
+DEFINE_int(maxplaybackrate, 48000, "Maximum playback rate (Hz).");
 
-// Define switch for maxplaybackrate
-DEFINE_int32(maxplaybackrate, 48000, "Maximum playback rate (Hz).");
+DEFINE_int(application, 0, "Application mode: 0 -- VOIP, 1 -- Audio.");
 
-// Define switch for application mode.
-static bool ValidateApplication(const char* flagname, int32_t value) {
-  if (value != 0 && value != 1) {
-    printf("Invalid application mode, should be 0 or 1.");
-    return false;
-  }
-  return true;
-}
-
-DEFINE_int32(application, 0, "Application mode: 0 -- VOIP, 1 -- Audio.");
-
-static const bool application_dummy =
-    RegisterFlagValidator(&FLAGS_application, &ValidateApplication);
-
-// Define switch for reported packet loss rate.
-static bool ValidatePacketLossRate(const char* flagname, int32_t value) {
-  if (value >= 0 && value <= 100)
-    return true;
-  printf("Invalid packet loss percentile, should be between 0 and 100.");
-  return false;
-}
-
-DEFINE_int32(reported_loss_rate, 10, "Reported percentile of packet loss.");
-
-static const bool reported_loss_rate_dummy =
-    RegisterFlagValidator(&FLAGS_reported_loss_rate, &ValidatePacketLossRate);
+DEFINE_int(reported_loss_rate, 10, "Reported percentile of packet loss.");
 
 DEFINE_bool(fec, false, "Enable FEC for encoding (-nofec to disable).");
 
 DEFINE_bool(dtx, false, "Enable DTX for encoding (-nodtx to disable).");
 
-// Define switch for number of sub packets to repacketize.
-static bool ValidateSubPackets(const char* flagname, int32_t value) {
-  if (value >= 1 && value <= 3)
-    return true;
-  printf("Invalid number of sub packets, should be between 1 and 3.");
-  return false;
-}
-DEFINE_int32(sub_packets, 1, "Number of sub packets to repacketize.");
-static const bool sub_packets_dummy =
-    RegisterFlagValidator(&FLAGS_sub_packets, &ValidateSubPackets);
+DEFINE_int(sub_packets, 1, "Number of sub packets to repacketize.");
 
-}  // namepsace
+}  // namespace
 
 class NetEqOpusQualityTest : public NetEqQualityTest {
  protected:
@@ -119,7 +63,7 @@
 };
 
 NetEqOpusQualityTest::NetEqOpusQualityTest()
-    : NetEqQualityTest(kOpusBlockDurationMs * FLAGS_sub_packets,
+    : NetEqQualityTest(kOpusBlockDurationMs * FLAG_sub_packets,
                        kOpusSamplingKhz,
                        kOpusSamplingKhz,
                        NetEqDecoder::kDecoderOpus),
@@ -127,18 +71,34 @@
       repacketizer_(NULL),
       sub_block_size_samples_(
           static_cast<size_t>(kOpusBlockDurationMs * kOpusSamplingKhz)),
-      bit_rate_kbps_(FLAGS_bit_rate_kbps),
-      fec_(FLAGS_fec),
-      dtx_(FLAGS_dtx),
-      complexity_(FLAGS_complexity),
-      maxplaybackrate_(FLAGS_maxplaybackrate),
-      target_loss_rate_(FLAGS_reported_loss_rate),
-      sub_packets_(FLAGS_sub_packets) {
+      bit_rate_kbps_(FLAG_bit_rate_kbps),
+      fec_(FLAG_fec),
+      dtx_(FLAG_dtx),
+      complexity_(FLAG_complexity),
+      maxplaybackrate_(FLAG_maxplaybackrate),
+      target_loss_rate_(FLAG_reported_loss_rate),
+      sub_packets_(FLAG_sub_packets) {
+  // Flag validation
+  RTC_CHECK(FLAG_bit_rate_kbps >= 6 && FLAG_bit_rate_kbps <= 510)
+      << "Invalid bit rate, should be between 6 and 510 kbps.";
+
+  RTC_CHECK(FLAG_complexity >= -1 && FLAG_complexity <= 10)
+      << "Invalid complexity setting, should be between 0 and 10.";
+
+  RTC_CHECK(FLAG_application == 0 || FLAG_application == 1)
+      << "Invalid application mode, should be 0 or 1.";
+
+  RTC_CHECK(FLAG_reported_loss_rate >= 0 && FLAG_reported_loss_rate <= 100)
+      << "Invalid packet loss percentile, should be between 0 and 100.";
+
+  RTC_CHECK(FLAG_sub_packets >= 1 && FLAG_sub_packets <= 3)
+      << "Invalid number of sub packets, should be between 1 and 3.";
+
   // Redefine decoder type if input is stereo.
   if (channels_ > 1) {
     decoder_type_ = NetEqDecoder::kDecoderOpus_2ch;
   }
-  application_ = FLAGS_application;
+  application_ = FLAG_application;
 }
 
 void NetEqOpusQualityTest::SetUp() {
diff --git a/modules/audio_coding/neteq/test/neteq_pcmu_quality_test.cc b/modules/audio_coding/neteq/test/neteq_pcmu_quality_test.cc
index eb75fda..5ea9056 100644
--- a/modules/audio_coding/neteq/test/neteq_pcmu_quality_test.cc
+++ b/modules/audio_coding/neteq/test/neteq_pcmu_quality_test.cc
@@ -13,11 +13,10 @@
 #include "webrtc/modules/audio_coding/codecs/g711/audio_encoder_pcm.h"
 #include "webrtc/modules/audio_coding/neteq/tools/neteq_quality_test.h"
 #include "webrtc/rtc_base/checks.h"
+#include "webrtc/rtc_base/flags.h"
 #include "webrtc/rtc_base/safe_conversions.h"
 #include "webrtc/test/testsupport/fileutils.h"
 
-using google::RegisterFlagValidator;
-using google::ParseCommandLineFlags;
 using testing::InitGoogleTest;
 
 namespace webrtc {
@@ -26,33 +25,27 @@
 static const int kInputSampleRateKhz = 8;
 static const int kOutputSampleRateKhz = 8;
 
-// Define switch for frame size.
-static bool ValidateFrameSize(const char* flagname, int32_t value) {
-  if (value >= 10 && value <= 60 && (value % 10) == 0)
-    return true;
-  printf("Invalid frame size, should be 10, 20, ..., 60 ms.");
-  return false;
-}
-
-DEFINE_int32(frame_size_ms, 20, "Codec frame size (milliseconds).");
-
-static const bool frame_size_dummy =
-    RegisterFlagValidator(&FLAGS_frame_size_ms, &ValidateFrameSize);
+DEFINE_int(frame_size_ms, 20, "Codec frame size (milliseconds).");
 
 }  // namespace
 
 class NetEqPcmuQualityTest : public NetEqQualityTest {
  protected:
   NetEqPcmuQualityTest()
-      : NetEqQualityTest(FLAGS_frame_size_ms,
+      : NetEqQualityTest(FLAG_frame_size_ms,
                          kInputSampleRateKhz,
                          kOutputSampleRateKhz,
-                         NetEqDecoder::kDecoderPCMu) {}
+                         NetEqDecoder::kDecoderPCMu) {
+    // Flag validation
+    RTC_CHECK(FLAG_frame_size_ms >= 10 && FLAG_frame_size_ms <= 60 &&
+              (FLAG_frame_size_ms % 10) == 0)
+        << "Invalid frame size, should be 10, 20, ..., 60 ms.";
+  }
 
   void SetUp() override {
     ASSERT_EQ(1u, channels_) << "PCMu supports only mono audio.";
     AudioEncoderPcmU::Config config;
-    config.frame_size_ms = FLAGS_frame_size_ms;
+    config.frame_size_ms = FLAG_frame_size_ms;
     encoder_.reset(new AudioEncoderPcmU(config));
     NetEqQualityTest::SetUp();
   }
diff --git a/modules/audio_coding/neteq/tools/neteq_performance_test.cc b/modules/audio_coding/neteq/tools/neteq_performance_test.cc
index ef0e31e..8d0cf90 100644
--- a/modules/audio_coding/neteq/tools/neteq_performance_test.cc
+++ b/modules/audio_coding/neteq/tools/neteq_performance_test.cc
@@ -80,7 +80,7 @@
   AudioFrame out_frame;
   while (time_now_ms < runtime_ms) {
     while (packet_input_time_ms <= time_now_ms) {
-      // Drop every N packets, where N = FLAGS_lossrate.
+      // Drop every N packets, where N = FLAG_lossrate.
       bool lost = false;
       if (lossrate > 0) {
         lost = ((rtp_header.sequenceNumber - 1) % lossrate) == 0;
diff --git a/modules/audio_coding/neteq/tools/neteq_quality_test.cc b/modules/audio_coding/neteq/tools/neteq_quality_test.cc
index bca24d8..85adb59 100644
--- a/modules/audio_coding/neteq/tools/neteq_quality_test.cc
+++ b/modules/audio_coding/neteq/tools/neteq_quality_test.cc
@@ -27,6 +27,17 @@
 const int kInitSeed = 0x12345678;
 const int kPacketLossTimeUnitMs = 10;
 
+const std::string& DefaultInFilename() {
+  static const std::string path =
+      ResourcePath("audio_coding/speech_mono_16kHz", "pcm");
+  return path;
+}
+
+const std::string& DefaultOutFilename() {
+  static const std::string path = OutputPath() + "neteq_quality_test_out.pcm";
+  return path;
+}
+
 // Common validator for file names.
 static bool ValidateFilename(const std::string& value, bool write) {
   FILE* fid = write ? fopen(value.c_str(), "wb") : fopen(value.c_str(), "rb");
@@ -36,133 +47,28 @@
   return true;
 }
 
-// Define switch for input file name.
-static bool ValidateInFilename(const char* flagname, const std::string& value) {
-  if (!ValidateFilename(value, false)) {
-    printf("Invalid input filename.");
-    return false;
-  }
-  return true;
-}
-
-DEFINE_string(
-    in_filename,
-    ResourcePath("audio_coding/speech_mono_16kHz", "pcm"),
-    "Filename for input audio (specify sample rate with --input_sample_rate ,"
+DEFINE_string(in_filename, DefaultInFilename().c_str(),
+    "Filename for input audio (specify sample rate with --input_sample_rate, "
     "and channels with --channels).");
 
-static const bool in_filename_dummy =
-    RegisterFlagValidator(&FLAGS_in_filename, &ValidateInFilename);
+DEFINE_int(input_sample_rate, 16000, "Sample rate of input file in Hz.");
 
-// Define switch for sample rate.
-static bool ValidateSampleRate(const char* flagname, int32_t value) {
-  if (value == 8000 || value == 16000 || value == 32000 || value == 48000)
-    return true;
-  printf("Invalid sample rate should be 8000, 16000, 32000 or 48000 Hz.");
-  return false;
-}
+DEFINE_int(channels, 1, "Number of channels in input audio.");
 
-DEFINE_int32(input_sample_rate, 16000, "Sample rate of input file in Hz.");
+DEFINE_string(out_filename, DefaultOutFilename().c_str(),
+    "Name of output audio file.");
 
-static const bool sample_rate_dummy =
-    RegisterFlagValidator(&FLAGS_input_sample_rate, &ValidateSampleRate);
+DEFINE_int(runtime_ms, 10000, "Simulated runtime (milliseconds).");
 
-// Define switch for channels.
-static bool ValidateChannels(const char* flagname, int32_t value) {
-  if (value == 1)
-    return true;
-  printf("Invalid number of channels, current support only 1.");
-  return false;
-}
+DEFINE_int(packet_loss_rate, 10, "Percentile of packet loss.");
 
-DEFINE_int32(channels, 1, "Number of channels in input audio.");
-
-static const bool channels_dummy =
-    RegisterFlagValidator(&FLAGS_channels, &ValidateChannels);
-
-// Define switch for output file name.
-static bool ValidateOutFilename(const char* flagname,
-                                const std::string& value) {
-  if (!ValidateFilename(value, true)) {
-    printf("Invalid output filename.");
-    return false;
-  }
-  return true;
-}
-
-DEFINE_string(out_filename,
-              OutputPath() + "neteq_quality_test_out.pcm",
-              "Name of output audio file.");
-
-static const bool out_filename_dummy =
-    RegisterFlagValidator(&FLAGS_out_filename, &ValidateOutFilename);
-
-// Define switch for packet loss rate.
-static bool ValidatePacketLossRate(const char* /* flag_name */, int32_t value) {
-  if (value >= 0 && value <= 100)
-    return true;
-  printf("Invalid packet loss percentile, should be between 0 and 100.");
-  return false;
-}
-
-// Define switch for runtime.
-static bool ValidateRuntime(const char* flagname, int32_t value) {
-  if (value > 0)
-    return true;
-  printf("Invalid runtime, should be greater than 0.");
-  return false;
-}
-
-DEFINE_int32(runtime_ms, 10000, "Simulated runtime (milliseconds).");
-
-static const bool runtime_dummy =
-    RegisterFlagValidator(&FLAGS_runtime_ms, &ValidateRuntime);
-
-DEFINE_int32(packet_loss_rate, 10, "Percentile of packet loss.");
-
-static const bool packet_loss_rate_dummy =
-    RegisterFlagValidator(&FLAGS_packet_loss_rate, &ValidatePacketLossRate);
-
-// Define switch for random loss mode.
-static bool ValidateRandomLossMode(const char* /* flag_name */, int32_t value) {
-  if (value >= 0 && value <= 2)
-    return true;
-  printf("Invalid random packet loss mode, should be between 0 and 2.");
-  return false;
-}
-
-DEFINE_int32(random_loss_mode, 1,
+DEFINE_int(random_loss_mode, 1,
     "Random loss mode: 0--no loss, 1--uniform loss, 2--Gilbert Elliot loss.");
-static const bool random_loss_mode_dummy =
-    RegisterFlagValidator(&FLAGS_random_loss_mode, &ValidateRandomLossMode);
 
-// Define switch for burst length.
-static bool ValidateBurstLength(const char* /* flag_name */, int32_t value) {
-  if (value >= kPacketLossTimeUnitMs)
-    return true;
-  printf("Invalid burst length, should be greater than %d ms.",
-         kPacketLossTimeUnitMs);
-  return false;
-}
-
-DEFINE_int32(burst_length, 30,
+DEFINE_int(burst_length, 30,
     "Burst length in milliseconds, only valid for Gilbert Elliot loss.");
 
-static const bool burst_length_dummy =
-    RegisterFlagValidator(&FLAGS_burst_length, &ValidateBurstLength);
-
-// Define switch for drift factor.
-static bool ValidateDriftFactor(const char* /* flag_name */, double value) {
-  if (value > -0.1)
-    return true;
-  printf("Invalid drift factor, should be greater than -0.1.");
-  return false;
-}
-
-DEFINE_double(drift_factor, 0.0, "Time drift factor.");
-
-static const bool drift_factor_dummy =
-    RegisterFlagValidator(&FLAGS_drift_factor, &ValidateDriftFactor);
+DEFINE_float(drift_factor, 0.0, "Time drift factor.");
 
 // ProbTrans00Solver() is to calculate the transition probability from no-loss
 // state to itself in a modified Gilbert Elliot packet loss model. The result is
@@ -211,11 +117,11 @@
                                    int out_sampling_khz,
                                    NetEqDecoder decoder_type)
     : decoder_type_(decoder_type),
-      channels_(static_cast<size_t>(FLAGS_channels)),
+      channels_(static_cast<size_t>(FLAG_channels)),
       decoded_time_ms_(0),
       decodable_time_ms_(0),
-      drift_factor_(FLAGS_drift_factor),
-      packet_loss_rate_(FLAGS_packet_loss_rate),
+      drift_factor_(FLAG_drift_factor),
+      packet_loss_rate_(FLAG_packet_loss_rate),
       block_duration_ms_(block_duration_ms),
       in_sampling_khz_(in_sampling_khz),
       out_sampling_khz_(out_sampling_khz),
@@ -223,13 +129,43 @@
           static_cast<size_t>(in_sampling_khz_ * block_duration_ms_)),
       payload_size_bytes_(0),
       max_payload_bytes_(0),
-      in_file_(new ResampleInputAudioFile(FLAGS_in_filename,
-                                          FLAGS_input_sample_rate,
+      in_file_(new ResampleInputAudioFile(FLAG_in_filename,
+                                          FLAG_input_sample_rate,
                                           in_sampling_khz * 1000)),
       rtp_generator_(
           new RtpGenerator(in_sampling_khz_, 0, 0, decodable_time_ms_)),
       total_payload_size_bytes_(0) {
-  const std::string out_filename = FLAGS_out_filename;
+  // Flag validation
+  RTC_CHECK(ValidateFilename(FLAG_in_filename, false))
+      << "Invalid input filename.";
+
+  RTC_CHECK(FLAG_input_sample_rate == 8000 || FLAG_input_sample_rate == 16000 ||
+            FLAG_input_sample_rate == 32000 || FLAG_input_sample_rate == 48000)
+      << "Invalid sample rate should be 8000, 16000, 32000 or 48000 Hz.";
+
+  RTC_CHECK_EQ(FLAG_channels, 1)
+      << "Invalid number of channels, current support only 1.";
+
+  RTC_CHECK(ValidateFilename(FLAG_out_filename, true))
+      << "Invalid output filename.";
+
+  RTC_CHECK_GT(FLAG_runtime_ms, 0)
+      << "Invalid runtime, should be greater than 0.";
+
+  RTC_CHECK(FLAG_packet_loss_rate >= 0 && FLAG_packet_loss_rate <= 100)
+      << "Invalid packet loss percentile, should be between 0 and 100.";
+
+  RTC_CHECK(FLAG_random_loss_mode >= 0 && FLAG_random_loss_mode <= 2)
+      << "Invalid random packet loss mode, should be between 0 and 2.";
+
+  RTC_CHECK_GE(FLAG_burst_length, kPacketLossTimeUnitMs)
+      << "Invalid burst length, should be greater than or equal to "
+      << kPacketLossTimeUnitMs << " ms.";
+
+  RTC_CHECK_GT(FLAG_drift_factor, -0.1)
+      << "Invalid drift factor, should be greater than -0.1.";
+
+  const std::string out_filename = FLAG_out_filename;
   const std::string log_filename = out_filename + ".log";
   log_file_.open(log_filename.c_str(), std::ofstream::out);
   RTC_CHECK(log_file_.is_open());
@@ -298,7 +234,7 @@
   rtp_generator_->set_drift_factor(drift_factor_);
 
   int units = block_duration_ms_ / kPacketLossTimeUnitMs;
-  switch (FLAGS_random_loss_mode) {
+  switch (FLAG_random_loss_mode) {
     case 1: {
       // |unit_loss_rate| is the packet loss rate for each unit time interval
       // (kPacketLossTimeUnitMs). Since a packet loss event is generated if any
@@ -312,8 +248,8 @@
       break;
     }
     case 2: {
-      // |FLAGS_burst_length| should be integer times of kPacketLossTimeUnitMs.
-      ASSERT_EQ(0, FLAGS_burst_length % kPacketLossTimeUnitMs);
+      // |FLAG_burst_length| should be integer times of kPacketLossTimeUnitMs.
+      ASSERT_EQ(0, FLAG_burst_length % kPacketLossTimeUnitMs);
 
       // We do not allow 100 percent packet loss in Gilbert Elliot model, which
       // makes no sense.
@@ -331,7 +267,7 @@
       // prob_trans_00 ^ (units - 1) = (loss_rate - 1) / prob_trans_10 *
       //     prob_trans_00 + (1 - loss_rate) * (1 + 1 / prob_trans_10).
       double loss_rate = 0.01f * packet_loss_rate_;
-      double prob_trans_10 = 1.0f * kPacketLossTimeUnitMs / FLAGS_burst_length;
+      double prob_trans_10 = 1.0f * kPacketLossTimeUnitMs / FLAG_burst_length;
       double prob_trans_00 = ProbTrans00Solver(units, loss_rate, prob_trans_10);
       loss_model_.reset(new GilbertElliotLoss(1.0f - prob_trans_10,
                                               1.0f - prob_trans_00));
@@ -415,7 +351,7 @@
 void NetEqQualityTest::Simulate() {
   int audio_size_samples;
 
-  while (decoded_time_ms_ < FLAGS_runtime_ms) {
+  while (decoded_time_ms_ < FLAG_runtime_ms) {
     // Assume 10 packets in packets buffer.
     while (decodable_time_ms_ - 10 * block_duration_ms_ < decoded_time_ms_) {
       ASSERT_TRUE(in_file_->Read(in_size_samples_ * channels_, &in_data_[0]));
@@ -432,7 +368,7 @@
     }
   }
   Log() << "Average bit rate was "
-        << 8.0f * total_payload_size_bytes_ / FLAGS_runtime_ms
+        << 8.0f * total_payload_size_bytes_ / FLAG_runtime_ms
         << " kbps"
         << std::endl;
 }
diff --git a/modules/audio_coding/neteq/tools/neteq_quality_test.h b/modules/audio_coding/neteq/tools/neteq_quality_test.h
index 731a7c9..c1964b6 100644
--- a/modules/audio_coding/neteq/tools/neteq_quality_test.h
+++ b/modules/audio_coding/neteq/tools/neteq_quality_test.h
@@ -13,7 +13,6 @@
 
 #include <fstream>
 #include <memory>
-#include <gflags/gflags.h>
 
 #include "webrtc/common_types.h"
 #include "webrtc/modules/audio_coding/neteq/include/neteq.h"
@@ -21,11 +20,10 @@
 #include "webrtc/modules/audio_coding/neteq/tools/input_audio_file.h"
 #include "webrtc/modules/audio_coding/neteq/tools/rtp_generator.h"
 #include "webrtc/modules/include/module_common_types.h"
+#include "webrtc/rtc_base/flags.h"
 #include "webrtc/test/gtest.h"
 #include "webrtc/typedefs.h"
 
-using google::RegisterFlagValidator;
-
 namespace webrtc {
 namespace test {
 
diff --git a/test/BUILD.gn b/test/BUILD.gn
index 1480448..2a49019 100644
--- a/test/BUILD.gn
+++ b/test/BUILD.gn
@@ -171,11 +171,8 @@
 }
 
 if (!build_with_chromium) {
-  # This target depends on //third_party/gflags and since chromium does not
-  # have gflags it causes an error when Gn parses this BUILD.gn file.
-  # It seems that Gn eagerly tries to understand if all the targets are
-  # buildable (even deps). Obviously gflags is not buildable in chromium
-  # so if a target depends on this BUILD.gn file we hit this error.
+  # This target used to depend on //third_party/gflags which Chromium does not
+  # provide. TODO(oprypin): remove the conditional.
   rtc_source_set("test_main") {
     testonly = true
     sources = [
@@ -191,7 +188,6 @@
       "../system_wrappers:metrics_default",
       "//testing/gmock",
       "//testing/gtest",
-      "//third_party/gflags",
     ]
   }
 
@@ -220,7 +216,6 @@
       "../system_wrappers",
       "//testing/gmock",
       "//testing/gtest",
-      "//third_party/gflags",
     ]
 
     if (!is_ios) {
@@ -261,7 +256,6 @@
     deps = [
       ":fileutils",
       "../rtc_base:rtc_base_approved",
-      "//third_party/gflags",
     ]
   }
 
@@ -345,9 +339,9 @@
       ":video_test_common",
       ":video_test_support",
       "../modules/video_capture",
+      "../rtc_base:rtc_base_approved",
       "//testing/gmock",
       "//testing/gtest",
-      "//third_party/gflags",
     ]
   }
 }
diff --git a/test/test_main.cc b/test/test_main.cc
index 3f6d4f1..3790a68 100644
--- a/test/test_main.cc
+++ b/test/test_main.cc
@@ -8,7 +8,7 @@
  *  be found in the AUTHORS file in the root of the source tree.
  */
 
-#include "gflags/gflags.h"
+#include "webrtc/rtc_base/flags.h"
 #include "webrtc/rtc_base/logging.h"
 #include "webrtc/system_wrappers/include/metrics_default.h"
 #include "webrtc/test/field_trial.h"
@@ -33,6 +33,8 @@
     "E.g. running with --force_fieldtrials=WebRTC-FooFeature/Enable/"
     " will assign the group Enable to field trial WebRTC-FooFeature.");
 
+DEFINE_bool(help, false, "Print this message.");
+
 int main(int argc, char* argv[]) {
   ::testing::InitGoogleMock(&argc, argv);
 
@@ -41,15 +43,22 @@
   if (rtc::LogMessage::GetLogToDebug() > rtc::LS_INFO)
     rtc::LogMessage::LogToDebug(rtc::LS_INFO);
 
-  google::ParseCommandLineFlags(&argc, &argv, false);
+  if (rtc::FlagList::SetFlagsFromCommandLine(&argc, argv, false)) {
+    return 1;
+  }
+  if (FLAG_help) {
+    rtc::FlagList::Print(nullptr, false);
+    return 0;
+  }
 
   webrtc::test::SetExecutablePath(argv[0]);
-  webrtc::test::InitFieldTrialsFromString(FLAGS_force_fieldtrials);
+  std::string fieldtrials = FLAG_force_fieldtrials;
+  webrtc::test::InitFieldTrialsFromString(fieldtrials);
   webrtc::metrics::Enable();
 
-  rtc::LogMessage::SetLogToStderr(FLAGS_logs);
+  rtc::LogMessage::SetLogToStderr(FLAG_logs);
   std::unique_ptr<webrtc::test::TraceToStderr> trace_to_stderr;
-  if (FLAGS_logs)
+  if (FLAG_logs)
       trace_to_stderr.reset(new webrtc::test::TraceToStderr);
 #if defined(WEBRTC_IOS)
   rtc::test::InitTestSuite(RUN_ALL_TESTS, argc, argv);
diff --git a/test/testsupport/test_output.cc b/test/testsupport/test_output.cc
index aea5110..f9d64b4 100644
--- a/test/testsupport/test_output.cc
+++ b/test/testsupport/test_output.cc
@@ -12,32 +12,39 @@
 
 #include <string.h>
 
-#include "gflags/gflags.h"
 #include "webrtc/rtc_base/file.h"
+#include "webrtc/rtc_base/flags.h"
 #include "webrtc/rtc_base/logging.h"
 #include "webrtc/rtc_base/pathutils.h"
 #include "webrtc/test/testsupport/fileutils.h"
 
+namespace {
+const std::string& DefaultOutputPath() {
+  static const std::string path = webrtc::test::OutputPath();
+  return path;
+}
+}
+
 DEFINE_string(test_output_dir,
-              webrtc::test::OutputPath(),
+              DefaultOutputPath().c_str(),
               "The output folder where test output should be saved.");
 
 namespace webrtc {
 namespace test {
 
 bool GetTestOutputDir(std::string* out_dir) {
-  if (FLAGS_test_output_dir.empty()) {
+  if (strlen(FLAG_test_output_dir) == 0) {
     LOG(LS_WARNING) << "No test_out_dir defined.";
     return false;
   }
-  *out_dir = FLAGS_test_output_dir;
+  *out_dir = FLAG_test_output_dir;
   return true;
 }
 
 bool WriteToTestOutput(const char* filename,
                        const uint8_t* buffer,
                        size_t length) {
-  if (FLAGS_test_output_dir.empty()) {
+  if (strlen(FLAG_test_output_dir) == 0) {
     LOG(LS_WARNING) << "No test_out_dir defined.";
     return false;
   }
@@ -48,7 +55,7 @@
   }
 
   rtc::File output =
-      rtc::File::Create(rtc::Pathname(FLAGS_test_output_dir, filename));
+      rtc::File::Create(rtc::Pathname(FLAG_test_output_dir, filename));
 
   return output.IsOpen() && output.Write(buffer, length) == length;
 }
diff --git a/test/testsupport/test_output_unittest.cc b/test/testsupport/test_output_unittest.cc
index 511ce6f..a082dc1 100644
--- a/test/testsupport/test_output_unittest.cc
+++ b/test/testsupport/test_output_unittest.cc
@@ -14,8 +14,8 @@
 
 #include <string>
 
-#include "gflags/gflags.h"
 #include "webrtc/rtc_base/file.h"
+#include "webrtc/rtc_base/flags.h"
 #include "webrtc/rtc_base/pathutils.h"
 #include "webrtc/rtc_base/platform_file.h"
 #include "webrtc/test/gtest.h"
@@ -26,10 +26,10 @@
 namespace test {
 
 TEST(IsolatedOutputTest, ShouldRejectInvalidIsolatedOutDir) {
-  std::string backup = FLAGS_test_output_dir;
-  FLAGS_test_output_dir = "";
+  const char* backup = FLAG_test_output_dir;
+  FLAG_test_output_dir = "";
   ASSERT_FALSE(WriteToTestOutput("a-file", "some-contents"));
-  FLAGS_test_output_dir = backup;
+  FLAG_test_output_dir = backup;
 }
 
 TEST(IsolatedOutputTest, ShouldRejectInvalidFileName) {
@@ -42,7 +42,7 @@
   const char* filename = "a-file";
   const char* content = "some-contents";
   if (WriteToTestOutput(filename, content)) {
-    rtc::Pathname out_file(FLAGS_test_output_dir, filename);
+    rtc::Pathname out_file(FLAG_test_output_dir, filename);
     rtc::File input = rtc::File::Open(out_file);
     EXPECT_TRUE(input.IsOpen());
     EXPECT_TRUE(input.Seek(0));
diff --git a/video/BUILD.gn b/video/BUILD.gn
index b815ace..c855105 100644
--- a/video/BUILD.gn
+++ b/video/BUILD.gn
@@ -118,7 +118,6 @@
       "../test:video_test_support",
       "../voice_engine",
       "//testing/gtest",
-      "//third_party/gflags",
     ]
     if (!build_with_chromium && is_clang) {
       # Suppress warnings from the Chromium Clang plugin (bugs.webrtc.org/163).
@@ -171,7 +170,6 @@
       "../test:test_support",
       "//testing/gmock",
       "//testing/gtest",
-      "//third_party/gflags",
     ]
     if (!build_with_chromium && is_clang) {
       # Suppress warnings from the Chromium Clang plugin (bugs.webrtc.org/163).
diff --git a/video/video_quality_test.cc b/video/video_quality_test.cc
index 7caa636..1e7ce0f 100644
--- a/video/video_quality_test.cc
+++ b/video/video_quality_test.cc
@@ -18,7 +18,6 @@
 #include <string>
 #include <vector>
 
-#include "gflags/gflags.h"
 #include "webrtc/call/call.h"
 #include "webrtc/common_video/libyuv/include/webrtc_libyuv.h"
 #include "webrtc/logging/rtc_event_log/rtc_event_log.h"
@@ -34,6 +33,7 @@
 #include "webrtc/rtc_base/checks.h"
 #include "webrtc/rtc_base/cpu_time.h"
 #include "webrtc/rtc_base/event.h"
+#include "webrtc/rtc_base/flags.h"
 #include "webrtc/rtc_base/format_macros.h"
 #include "webrtc/rtc_base/logging.h"
 #include "webrtc/rtc_base/memory_usage.h"
@@ -838,7 +838,7 @@
     // Saving only the worst frame for manual analysis. Intention here is to
     // only detect video corruptions and not to track picture quality. Thus,
     // jpeg is used here.
-    if (FLAGS_save_worst_frame && worst_frame_) {
+    if (FLAG_save_worst_frame && worst_frame_) {
       std::string output_dir;
       test::GetTestOutputDir(&output_dir);
       std::string output_path =
diff --git a/voice_engine/BUILD.gn b/voice_engine/BUILD.gn
index e82691a..e458fee 100644
--- a/voice_engine/BUILD.gn
+++ b/voice_engine/BUILD.gn
@@ -200,7 +200,6 @@
       "../test:video_test_common",
       "//testing/gmock",
       "//testing/gtest",
-      "//third_party/gflags",
     ]
 
     if (is_android) {
diff --git a/voice_engine/file_player_unittests.cc b/voice_engine/file_player_unittests.cc
index 38ee987..8762957 100644
--- a/voice_engine/file_player_unittests.cc
+++ b/voice_engine/file_player_unittests.cc
@@ -17,7 +17,7 @@
 #include <memory>
 #include <string>
 
-#include "gflags/gflags.h"
+#include "webrtc/rtc_base/flags.h"
 #include "webrtc/rtc_base/md5digest.h"
 #include "webrtc/rtc_base/stringencode.h"
 #include "webrtc/test/gtest.h"
@@ -38,7 +38,7 @@
         output_file_(NULL) {}
 
   void SetUp() override {
-    if (FLAGS_file_player_output) {
+    if (FLAG_file_player_output) {
       std::string output_file =
           webrtc::test::OutputPath() + "file_player_unittest_out.pcm";
       output_file_ = fopen(output_file.c_str(), "wb");
@@ -64,7 +64,7 @@
       EXPECT_EQ(
           0, player_->Get10msAudioFromFile(out, &num_samples, kSampleRateHz));
       checksum.Update(out, num_samples * sizeof(out[0]));
-      if (FLAGS_file_player_output) {
+      if (FLAG_file_player_output) {
         ASSERT_EQ(num_samples,
                   fwrite(out, sizeof(out[0]), num_samples, output_file_));
       }