+static int get_stats(AVCodecContext *avctx, int eos)
+{
+#ifdef TH_ENCCTL_2PASS_OUT
+ TheoraContext *h = avctx->priv_data;
+ uint8_t *buf;
+ int bytes;
+
+ bytes = th_encode_ctl(h->t_state, TH_ENCCTL_2PASS_OUT, &buf, sizeof(buf));
+ if (bytes < 0) {
+ av_log(avctx, AV_LOG_ERROR, "Error getting first pass stats\n");
+ return -1;
+ }
+ if (!eos) {
+ h->stats = av_fast_realloc(h->stats, &h->stats_size,
+ h->stats_offset + bytes);
+ memcpy(h->stats + h->stats_offset, buf, bytes);
+ h->stats_offset += bytes;
+ } else {
+ int b64_size = AV_BASE64_SIZE(h->stats_offset);
+ // libtheora generates a summary header at the end
+ memcpy(h->stats, buf, bytes);
+ avctx->stats_out = av_malloc(b64_size);
+ av_base64_encode(avctx->stats_out, b64_size, h->stats, h->stats_offset);
+ }
+ return 0;
+#else
+ av_log(avctx, AV_LOG_ERROR, "libtheora too old to support 2pass\n");
+ return -1;
+#endif
+}
+
+// libtheora won't read the entire buffer we give it at once, so we have to
+// repeatedly submit it...
+static int submit_stats(AVCodecContext *avctx)
+{
+#ifdef TH_ENCCTL_2PASS_IN
+ TheoraContext *h = avctx->priv_data;
+ int bytes;
+ if (!h->stats) {
+ if (!avctx->stats_in) {
+ av_log(avctx, AV_LOG_ERROR, "No statsfile for second pass\n");
+ return -1;
+ }
+ h->stats_size = strlen(avctx->stats_in) * 3/4;
+ h->stats = av_malloc(h->stats_size);
+ h->stats_size = av_base64_decode(h->stats, avctx->stats_in, h->stats_size);
+ }
+ while (h->stats_size - h->stats_offset > 0) {
+ bytes = th_encode_ctl(h->t_state, TH_ENCCTL_2PASS_IN,
+ h->stats + h->stats_offset,
+ h->stats_size - h->stats_offset);
+ if (bytes < 0) {
+ av_log(avctx, AV_LOG_ERROR, "Error submitting stats\n");
+ return -1;
+ }
+ if (!bytes)
+ return 0;
+ h->stats_offset += bytes;
+ }
+ return 0;
+#else
+ av_log(avctx, AV_LOG_ERROR, "libtheora too old to support 2pass\n");
+ return -1;
+#endif
+}
+