/*
 * tngp/theora.h
 *
 * Copyright (C) 2021 bzt
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * @brief Vorbis / theora decoder header
 *
 */

#include "SDL2_mixer/src/music.h"                       /* Mix_Chunk */

/* using circular buffer must be thread safe, because there's only one producer and one consumer,
 * and head and tail are only changed by the producer and consumer respectively but never both */
#define THEORA_QUEUE_SIZE 512

typedef struct {
    uint32_t playms;                                    /* when to play this frame in millisec */
    uint8_t *vbuf;                                      /* data, in SDL_PIXELFORMAT_IYUV planar format */
} theora_frame_t;

typedef struct {
    /* public fields */
    volatile int hasAudio;                              /* has audio stream */
    volatile int hasVideo, w, h;                        /* has video stream, dimensions */
    /* private fields */
    volatile int started, stop, done;                   /* started, request stop to producer and acknowledge flag */
    volatile int ahead, atail, vhead, vtail;            /* circular buffer pointers */
    volatile Mix_Chunk chunk[THEORA_QUEUE_SIZE];        /* audio buffer */
    volatile theora_frame_t frame[THEORA_QUEUE_SIZE];   /* video buffer */
    volatile Uint32 baseticks;                          /* decode start time to get video play time */
    SDL_Thread *th;                                     /* thread identifier */
    world_asset_t *f, *once, *loop;                    /* file streams */
} theora_t;

extern theora_t theora_ctx;

void theora_callback(int channel);
void theora_produce(theora_t *ctx);
void theora_start(theora_t *ctx, world_asset_t *once, world_asset_t *loop);
void theora_stop(theora_t *ctx);
int theora_playing(theora_t *ctx);
Mix_Chunk *theora_audio(theora_t *ctx);
void theora_video(theora_t *ctx, SDL_Texture *texture);
