From acc6228440ecf235137e8f8af1e54d792cc83d84 Mon Sep 17 00:00:00 2001
From: notaz <notasas@gmail.com>
Date: Sun, 13 Mar 2022 23:40:48 +0200
Subject: [PATCH] cdriso: handle chd subchannels, when available

libretro/pcsx_rearmed#535
only raw mode tested
---
 libpcsxcore/cdriso.c | 25 +++++++++++++++++++++----
 1 file changed, 21 insertions(+), 4 deletions(-)

diff --git a/libpcsxcore/cdriso.c b/libpcsxcore/cdriso.c
index 2dcaf49b..599e1401 100644
--- a/libpcsxcore/cdriso.c
+++ b/libpcsxcore/cdriso.c
@@ -980,8 +980,16 @@ static int handlechd(const char *isofile) {
 		else
 			break;
 
-		if(md.track == 1)
+		SysPrintf("chd: %s\n", meta);
+
+		if (md.track == 1) {
 			md.pregap = 150;
+			if (!strncmp(md.subtype, "RW", 2)) {
+				subChanMixed = TRUE;
+				if (!strcmp(md.subtype, "RW_RAW"))
+					subChanRaw = TRUE;
+			}
+		}
 		else
 			sec2msf(msf2sec(ti[md.track-1].length) + md.pregap, ti[md.track-1].length);
 
@@ -1204,6 +1212,12 @@ static int cdread_chd(FILE *f, unsigned int base, void *dest, int sector)
 	if (dest != cdbuffer) // copy avoid HACK
 		memcpy(dest, chd_img->buffer[chd_img->sector_in_hunk],
 			CD_FRAMESIZE_RAW);
+	if (subChanMixed) {
+		memcpy(subbuffer, chd_img->buffer[chd_img->sector_in_hunk] + CD_FRAMESIZE_RAW,
+			SUB_FRAMESIZE);
+		if (subChanRaw)
+			DecodeRawSubData();
+	}
 	return CD_FRAMESIZE_RAW;
 }
 #endif
@@ -1254,7 +1268,8 @@ static long CALLBACK ISOopen(void) {
 	boolean isMode1ISO = FALSE;
 	char alt_bin_filename[MAXPATHLEN];
 	const char *bin_filename;
-	char image_str[1024] = {0};
+	char image_str[1024];
+	int is_chd = 0;
 
 	if (cdHandle != NULL) {
 		return 0; // it's already open
@@ -1267,7 +1282,8 @@ static long CALLBACK ISOopen(void) {
 		return -1;
 	}
 
-	sprintf(image_str, "Loaded CD Image: %s", GetIsoFile());
+	snprintf(image_str, sizeof(image_str) - 6*4 - 1,
+		"Loaded CD Image: %s", GetIsoFile());
 
 	cddaBigEndian = FALSE;
 	subChanMixed = FALSE;
@@ -1306,6 +1322,7 @@ static long CALLBACK ISOopen(void) {
 		strcat(image_str, "[+chd]");
 		CDR_getBuffer = ISOgetBuffer_chd;
 		cdimg_read_func = cdread_chd;
+		is_chd = 1;
 	}
 #endif
 
@@ -1366,7 +1383,7 @@ static long CALLBACK ISOopen(void) {
 
 	PrintTracks();
 
-	if (subChanMixed)
+	if (subChanMixed && !is_chd)
 		cdimg_read_func = cdread_sub_mixed;
 	else if (isMode1ISO)
 		cdimg_read_func = cdread_2048;
-- 
2.39.5