/*
 * Subtitles that are pictures (Blu-ray's PGS, DVD's, DVB's), read and
 * decoded by us for when the picture is taken apart (3D, all round):
 * mpv would draw them over the whole frame, cut in two between the
 * eyes, and it hands over no text for them as it does for the others.
 *
 * A thread reads the file a second time with FFmpeg, only the one
 * subtitle stream, staying LEAD_S ahead of where mpv plays (what mpv
 * just read is still in the page cache) and seeking when it jumps. A
 * file of subtitles alone (.sup, .idx) is read whole. What it decodes
 * comes to the main loop, which alone keeps the list: the stage draws
 * from it without locks.
 */
#include <math.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include "video.h"

#define LEAD_S 30 // read this far ahead of the picture
#define BACK_S 10 // after a seek, from this far before (one still showing)
#define KEEP_S 120 // let what ended longer ago than this go

struct reader {
	GThread *thread;
	unsigned gen;
	char *path;
	int index; // the stream, -1: the first subtitles in the file
	int fallback_w, fallback_h; // the canvas, when the stream says none
	GMutex lock;
	GCond cond;
	/* Under the lock */
	bool stop;
	double want; // where mpv plays
	double from, to; // what has been read, by the subtitles' times
};

struct arrival {
	unsigned gen;
	struct vd_subpicture *pic; // NULL: the thread gave up
};

static struct {
	struct reader *r;
	unsigned gen;
	GPtrArray *pics; // struct vd_subpicture, by start
	void (*changed)(bool failed);
} b;

static void pic_free(struct vd_subpicture *pic) {
	for (int i = 0; i < pic->count; i++) {
		cairo_surface_destroy(pic->rects[i].pic);
	}
	g_free(pic->rects);
	g_free(pic);
}

/* Palette pictures into cairo's: AV_PIX_FMT_RGB32 is ARGB in a native
 * word, as cairo's, but not premultiplied */
static cairo_surface_t *rect_surface(const AVSubtitleRect *rect) {
	cairo_surface_t *s = cairo_image_surface_create(CAIRO_FORMAT_ARGB32,
		rect->w, rect->h);
	if (cairo_surface_status(s) != CAIRO_STATUS_SUCCESS) {
		cairo_surface_destroy(s);
		return NULL;
	}
	const uint32_t *palette = (const uint32_t *)rect->data[1];
	uint8_t *dst = cairo_image_surface_get_data(s);
	int stride = cairo_image_surface_get_stride(s);
	cairo_surface_flush(s);
	for (int y = 0; y < rect->h; y++) {
		const uint8_t *src = rect->data[0] + y * rect->linesize[0];
		uint32_t *row = (uint32_t *)(dst + y * stride);
		for (int x = 0; x < rect->w; x++) {
			uint32_t c = src[x] < rect->nb_colors ? palette[src[x]] : 0;
			uint32_t a = c >> 24;
			uint32_t r = ((c >> 16) & 0xff) * a / 255;
			uint32_t g = ((c >> 8) & 0xff) * a / 255;
			uint32_t bl = (c & 0xff) * a / 255;
			row[x] = a << 24 | r << 16 | g << 8 | bl;
		}
	}
	cairo_surface_mark_dirty(s);
	return s;
}

static gboolean arrived(gpointer data);

static void post(struct reader *r, struct vd_subpicture *pic) {
	struct arrival *a = g_new0(struct arrival, 1);
	a->gen = r->gen;
	a->pic = pic;
	g_idle_add(arrived, a);
}

static int interrupted(void *data) {
	struct reader *r = data;
	g_mutex_lock(&r->lock);
	bool stop = r->stop;
	g_mutex_unlock(&r->lock);
	return stop;
}

static void decoded(struct reader *r, AVCodecContext *dec, AVStream *st,
		const AVPacket *pkt, AVSubtitle *sub) {
	double base = av_q2d(st->time_base);
	int64_t pts = sub->pts != AV_NOPTS_VALUE ?
		av_rescale_q(sub->pts, AV_TIME_BASE_Q, st->time_base) : pkt->pts;
	if (pts == AV_NOPTS_VALUE) {
		return;
	}
	struct vd_subpicture *pic = g_new0(struct vd_subpicture, 1);
	pic->start = pts * base + sub->start_display_time / 1000.0;
	/* PGS says no end: the next one (an empty one, often) ends it */
	if (sub->end_display_time > sub->start_display_time &&
			sub->end_display_time != UINT32_MAX) {
		pic->end = pts * base + sub->end_display_time / 1000.0;
	} else if (pkt->duration > 0) {
		pic->end = pic->start + pkt->duration * base;
	} else {
		pic->end = INFINITY;
	}
	pic->canvas_w = dec->width > 0 ? dec->width : r->fallback_w;
	pic->canvas_h = dec->height > 0 ? dec->height : r->fallback_h;
	pic->rects = g_new0(struct vd_subrect, sub->num_rects);
	for (unsigned i = 0; i < sub->num_rects; i++) {
		const AVSubtitleRect *rect = sub->rects[i];
		if (rect->type != SUBTITLE_BITMAP || rect->w <= 0 || rect->h <= 0) {
			continue;
		}
		cairo_surface_t *s = rect_surface(rect);
		if (s) {
			pic->rects[pic->count++] = (struct vd_subrect){ rect->x,
				rect->y, rect->w, rect->h, s };
		}
	}
	post(r, pic);
}

static gpointer read_thread(gpointer data) {
	struct reader *r = data;
	AVFormatContext *fmt = avformat_alloc_context();
	AVCodecContext *dec = NULL;
	AVPacket *pkt = av_packet_alloc();
	bool ok = false;
	fmt->interrupt_callback = (AVIOInterruptCB){ interrupted, r };
	if (avformat_open_input(&fmt, r->path, NULL, NULL) < 0) {
		fmt = NULL;
		goto out;
	}
	if (avformat_find_stream_info(fmt, NULL) < 0) {
		goto out;
	}
	AVStream *st = NULL;
	for (unsigned i = 0; i < fmt->nb_streams; i++) {
		AVStream *s = fmt->streams[i];
		bool is_sub = s->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE;
		if (st == NULL && is_sub && (r->index < 0 || (int)i == r->index)) {
			st = s;
		} else {
			s->discard = AVDISCARD_ALL;
		}
	}
	const AVCodec *codec = st ? avcodec_find_decoder(st->codecpar->codec_id) : NULL;
	if (codec == NULL || !(codec->id == AV_CODEC_ID_HDMV_PGS_SUBTITLE ||
			codec->id == AV_CODEC_ID_DVD_SUBTITLE ||
			codec->id == AV_CODEC_ID_DVB_SUBTITLE ||
			codec->id == AV_CODEC_ID_XSUB)) {
		goto out;
	}
	dec = avcodec_alloc_context3(codec);
	if (avcodec_parameters_to_context(dec, st->codecpar) < 0 ||
			avcodec_open2(dec, codec, NULL) < 0) {
		goto out;
	}
	ok = true;
	/* A file of subtitles alone is small: read it all, never seek */
	bool alone = fmt->nb_streams == 1;
	bool at_end = false;
	for (;;) {
		g_mutex_lock(&r->lock);
		while (!r->stop && (at_end || r->to > r->want + LEAD_S) &&
				!(r->want < r->from && !alone)) {
			g_cond_wait(&r->cond, &r->lock);
		}
		bool stop = r->stop;
		double want = r->want;
		/* Nothing read yet after a seek doesn't count as behind: only
		 * a jump well past what was read does */
		bool jump = !alone && (want < r->from || want > r->to + LEAD_S * 2);
		if (jump) {
			r->from = r->to = fmax(0, want - BACK_S);
		}
		double from = r->from;
		g_mutex_unlock(&r->lock);
		if (stop) {
			break;
		}
		if (jump) {
			int64_t ts = (int64_t)(from * AV_TIME_BASE);
			avformat_seek_file(fmt, -1, INT64_MIN, ts, ts, 0);
			avcodec_flush_buffers(dec);
			at_end = false;
		}
		int err = av_read_frame(fmt, pkt);
		if (err < 0) {
			if (err == AVERROR_EXIT) {
				break;
			}
			at_end = true;
			g_mutex_lock(&r->lock);
			r->to = INFINITY;
			g_mutex_unlock(&r->lock);
			continue;
		}
		if (pkt->stream_index == st->index) {
			AVSubtitle sub;
			int got = 0;
			if (avcodec_decode_subtitle2(dec, &sub, &got, pkt) >= 0 && got) {
				decoded(r, dec, st, pkt, &sub);
				avsubtitle_free(&sub);
			}
			if (pkt->pts != AV_NOPTS_VALUE) {
				g_mutex_lock(&r->lock);
				r->to = fmax(r->to, pkt->pts * av_q2d(st->time_base));
				g_mutex_unlock(&r->lock);
			}
		}
		av_packet_unref(pkt);
	}
out:
	if (!ok) {
		post(r, NULL);
	}
	av_packet_free(&pkt);
	avcodec_free_context(&dec);
	avformat_close_input(&fmt);
	return NULL;
}

/* Into the list by start; the same one read again after a seek is let be */
static gboolean arrived(gpointer data) {
	struct arrival *a = data;
	if (a->gen != b.gen || b.r == NULL) {
		if (a->pic) {
			pic_free(a->pic);
		}
		g_free(a);
		return G_SOURCE_REMOVE;
	}
	if (a->pic == NULL) {
		bitsubs_close();
		if (b.changed) {
			b.changed(true);
		}
		g_free(a);
		return G_SOURCE_REMOVE;
	}
	struct vd_subpicture *pic = a->pic;
	guint at = b.pics->len;
	while (at > 0 && ((struct vd_subpicture *)
			g_ptr_array_index(b.pics, at - 1))->start > pic->start + 0.001) {
		at--;
	}
	struct vd_subpicture *before = at > 0 ? g_ptr_array_index(b.pics, at - 1) : NULL;
	if (before && fabs(before->start - pic->start) < 0.001) {
		pic_free(pic);
	} else {
		g_ptr_array_insert(b.pics, at, pic);
		if (b.changed) {
			b.changed(false);
		}
	}
	g_free(a);
	return G_SOURCE_REMOVE;
}

bool bitsubs_open(const char *path, int index, int fallback_w, int fallback_h,
		void (*changed)(bool failed)) {
	bitsubs_close();
	if (path == NULL) {
		return false;
	}
	if (b.pics == NULL) {
		b.pics = g_ptr_array_new_with_free_func((GDestroyNotify)pic_free);
	}
	struct reader *r = g_new0(struct reader, 1);
	r->gen = ++b.gen;
	r->path = g_strdup(path);
	r->index = index;
	r->fallback_w = fallback_w > 0 ? fallback_w : 720;
	r->fallback_h = fallback_h > 0 ? fallback_h : 576;
	g_mutex_init(&r->lock);
	g_cond_init(&r->cond);
	r->from = r->to = 0;
	b.changed = changed;
	b.r = r;
	r->thread = g_thread_new("c8-video-subs", read_thread, r);
	return true;
}

void bitsubs_close(void) {
	struct reader *r = b.r;
	if (r == NULL) {
		return;
	}
	b.r = NULL;
	b.gen++;
	g_mutex_lock(&r->lock);
	r->stop = true;
	g_cond_signal(&r->cond);
	g_mutex_unlock(&r->lock);
	/* The interrupt callback gets it out of a slow read */
	g_thread_join(r->thread);
	g_mutex_clear(&r->lock);
	g_cond_clear(&r->cond);
	g_free(r->path);
	g_free(r);
	if (b.pics) {
		g_ptr_array_set_size(b.pics, 0);
	}
}

bool bitsubs_running(void) {
	return b.r != NULL;
}

/* The one showing at pos: the last to start, unless it has ended */
static guint showing_index(double pos) {
	guint lo = 0, hi = b.pics->len;
	while (lo < hi) {
		guint mid = (lo + hi) / 2;
		if (((struct vd_subpicture *)g_ptr_array_index(b.pics, mid))->start <= pos) {
			lo = mid + 1;
		} else {
			hi = mid;
		}
	}
	return lo; // one past it
}

const struct vd_subpicture *bitsubs_at(double pos) {
	if (b.r == NULL || b.pics->len == 0) {
		return NULL;
	}
	guint i = showing_index(pos);
	if (i == 0) {
		return NULL;
	}
	struct vd_subpicture *pic = g_ptr_array_index(b.pics, i - 1);
	return pos < pic->end && pic->count > 0 ? pic : NULL;
}

void bitsubs_tell(double pos) {
	struct reader *r = b.r;
	if (r == NULL) {
		return;
	}
	g_mutex_lock(&r->lock);
	r->want = pos;
	if (pos + LEAD_S > r->to || pos < r->from) {
		g_cond_signal(&r->cond);
	}
	g_mutex_unlock(&r->lock);
	/* Long gone ones go (ended, or the next began, long ago), but never
	 * the one showing */
	guint keep = showing_index(pos);
	guint drop = 0;
	while (drop + 1 < keep && ((struct vd_subpicture *)
			g_ptr_array_index(b.pics, drop + 1))->start < pos - KEEP_S) {
		drop++;
	}
	if (drop > 0) {
		g_ptr_array_remove_range(b.pics, 0, drop);
	}
}
