Automatically set internal bit depth to at least the input bit depth.

Upgrade profile if required.

Change-Id: Ieb2b77d2446290a8fc749739247a01e8f0600c55
diff --git a/aomenc.c b/aomenc.c
index 497c8d5..742f264 100644
--- a/aomenc.c
+++ b/aomenc.c
@@ -40,12 +40,12 @@
 #include "aom/aomdx.h"
 #endif
 
-#include "aom/aom_integer.h"
-#include "aom_ports/mem_ops.h"
-#include "aom_ports/aom_timer.h"
-#include "./rate_hist.h"
 #include "./aomstats.h"
+#include "./rate_hist.h"
 #include "./warnings.h"
+#include "aom/aom_integer.h"
+#include "aom_ports/aom_timer.h"
+#include "aom_ports/mem_ops.h"
 #if CONFIG_WEBM_IO
 #include "./webmenc.h"
 #endif
@@ -1860,6 +1860,9 @@
   uint64_t cx_time = 0;
   int stream_cnt = 0;
   int res = 0;
+#if CONFIG_AOM_HIGHBITDEPTH
+  int profile_updated = 0;
+#endif
 
   memset(&input, 0, sizeof(input));
   exec_name = argv_[0];
@@ -1963,6 +1966,39 @@
           { stream->config.cfg.g_input_bit_depth = input.bit_depth; });
     }
 
+#if CONFIG_AOM_HIGHBITDEPTH
+    /* Automatically set the codec bit depth to match the input bit depth.
+     * Upgrade the profile if required. */
+    FOREACH_STREAM({
+      if (stream->config.cfg.g_input_bit_depth >
+          (unsigned int)stream->config.cfg.g_bit_depth) {
+        stream->config.cfg.g_bit_depth = stream->config.cfg.g_input_bit_depth;
+      }
+      if (stream->config.cfg.g_bit_depth > 8) {
+        switch (stream->config.cfg.g_profile) {
+          case 0:
+            stream->config.cfg.g_profile = 2;
+            profile_updated = 1;
+            break;
+          case 1:
+            stream->config.cfg.g_profile = 3;
+            profile_updated = 1;
+            break;
+          default: break;
+        }
+      }
+      if (stream->config.cfg.g_profile > 1) {
+        stream->config.use_16bit_internal = 1;
+      }
+      if (profile_updated) {
+        fprintf(stderr,
+                "Warning: automatically upgrading to profile %d to "
+                "match input format.\n",
+                stream->config.cfg.g_profile);
+      }
+    });
+#endif
+
     FOREACH_STREAM(set_stream_dimensions(stream, input.width, input.height));
     FOREACH_STREAM(validate_stream_config(stream, &global));