/** * Xtc.cpp * * Main XTC ebook class implementation * XTC ebook support for CrossPoint Reader */ #include "Xtc.h" #include #include #include bool Xtc::load() { LOG_DBG("XTC", "Loading XTC: %s", filepath.c_str()); // Initialize parser parser.reset(new xtc::XtcParser()); // Open XTC file xtc::XtcError err = parser->open(filepath.c_str()); if (err != xtc::XtcError::OK) { LOG_ERR("XTC", "Failed to load: %s", xtc::errorToString(err)); parser.reset(); return false; } loaded = true; LOG_DBG("XTC", "Loaded XTC: %s (%lu pages)", filepath.c_str(), parser->getPageCount()); return true; } bool Xtc::clearCache() const { if (!Storage.exists(cachePath.c_str())) { LOG_DBG("XTC", "Cache does not exist, no action needed"); return true; } if (!Storage.removeDir(cachePath.c_str())) { LOG_ERR("XTC", "Failed to clear cache"); return false; } LOG_DBG("XTC", "Cache cleared successfully"); return true; } void Xtc::setupCacheDir() const { if (Storage.exists(cachePath.c_str())) { return; } // Create directories recursively for (size_t i = 1; i < cachePath.length(); i++) { if (cachePath[i] == '/') { Storage.mkdir(cachePath.substr(0, i).c_str()); } } Storage.mkdir(cachePath.c_str()); } std::string Xtc::getTitle() const { if (!loaded || !parser) { return ""; } // Try to get title from XTC metadata first std::string title = parser->getTitle(); if (!title.empty()) { return title; } // Fallback: extract filename from path as title size_t lastSlash = filepath.find_last_of('/'); size_t lastDot = filepath.find_last_of('.'); if (lastSlash == std::string::npos) { lastSlash = 0; } else { lastSlash++; } if (lastDot == std::string::npos || lastDot <= lastSlash) { return filepath.substr(lastSlash); } return filepath.substr(lastSlash, lastDot - lastSlash); } std::string Xtc::getAuthor() const { if (!loaded || !parser) { return ""; } // Try to get author from XTC metadata return parser->getAuthor(); } bool Xtc::hasChapters() const { if (!loaded || !parser) { return false; } return parser->hasChapters(); } const std::vector& Xtc::getChapters() { static const std::vector kEmpty; if (!loaded || !parser) { return kEmpty; } return parser->getChapters(); } std::string Xtc::getCoverBmpPath() const { return cachePath + "/cover.bmp"; } bool Xtc::generateCoverBmp() const { // Already generated if (Storage.exists(getCoverBmpPath().c_str())) { return true; } if (!loaded || !parser) { LOG_ERR("XTC", "Cannot generate cover BMP, file not loaded"); return false; } if (parser->getPageCount() == 0) { LOG_ERR("XTC", "No pages in XTC file"); return false; } // Setup cache directory setupCacheDir(); // Get first page info for cover xtc::PageInfo pageInfo; if (!parser->getPageInfo(0, pageInfo)) { LOG_DBG("XTC", "Failed to get first page info"); return false; } // Get bit depth const uint8_t bitDepth = parser->getBitDepth(); // Allocate buffer for page data // XTG (1-bit): Row-major, ((width+7)/8) * height bytes // XTH (2-bit): Two bit planes, column-major, ((width * height + 7) / 8) * 2 bytes size_t bitmapSize; if (bitDepth == 2) { bitmapSize = ((static_cast(pageInfo.width) * pageInfo.height + 7) / 8) * 2; } else { bitmapSize = ((pageInfo.width + 7) / 8) * pageInfo.height; } uint8_t* pageBuffer = static_cast(malloc(bitmapSize)); if (!pageBuffer) { LOG_ERR("XTC", "Failed to allocate page buffer (%lu bytes)", bitmapSize); return false; } // Load first page (cover) size_t bytesRead = const_cast(parser.get())->loadPage(0, pageBuffer, bitmapSize); if (bytesRead == 0) { LOG_ERR("XTC", "Failed to load cover page"); free(pageBuffer); return false; } // Create BMP file FsFile coverBmp; if (!Storage.openFileForWrite("XTC", getCoverBmpPath(), coverBmp)) { LOG_DBG("XTC", "Failed to create cover BMP file"); free(pageBuffer); return false; } // Write 1-bit BMP header (top-down row order) BmpHeader bmpHeader; createBmpHeader(&bmpHeader, pageInfo.width, pageInfo.height, BmpRowOrder::TopDown); coverBmp.write(reinterpret_cast(&bmpHeader), sizeof(bmpHeader)); const uint32_t rowSize = ((pageInfo.width + 31) / 32) * 4; // Write bitmap data // BMP requires 4-byte row alignment const size_t dstRowSize = (pageInfo.width + 7) / 8; // 1-bit destination row size if (bitDepth == 2) { // XTH 2-bit mode: Two bit planes, column-major order // - Columns scanned right to left (x = width-1 down to 0) // - 8 vertical pixels per byte (MSB = topmost pixel in group) // - First plane: Bit1, Second plane: Bit2 // - Pixel value = (bit1 << 1) | bit2 const size_t planeSize = (static_cast(pageInfo.width) * pageInfo.height + 7) / 8; const uint8_t* plane1 = pageBuffer; // Bit1 plane const uint8_t* plane2 = pageBuffer + planeSize; // Bit2 plane const size_t colBytes = (pageInfo.height + 7) / 8; // Bytes per column // Allocate a row buffer for 1-bit output uint8_t* rowBuffer = static_cast(malloc(dstRowSize)); if (!rowBuffer) { free(pageBuffer); return false; } for (uint16_t y = 0; y < pageInfo.height; y++) { memset(rowBuffer, 0xFF, dstRowSize); // Start with all white for (uint16_t x = 0; x < pageInfo.width; x++) { // Column-major, right to left: column index = (width - 1 - x) const size_t colIndex = pageInfo.width - 1 - x; const size_t byteInCol = y / 8; const size_t bitInByte = 7 - (y % 8); // MSB = topmost pixel const size_t byteOffset = colIndex * colBytes + byteInCol; const uint8_t bit1 = (plane1[byteOffset] >> bitInByte) & 1; const uint8_t bit2 = (plane2[byteOffset] >> bitInByte) & 1; const uint8_t pixelValue = (bit1 << 1) | bit2; // Threshold: 0=white (1); 1,2,3=black (0) if (pixelValue >= 1) { // Set bit to 0 (black) in BMP format const size_t dstByte = x / 8; const size_t dstBit = 7 - (x % 8); rowBuffer[dstByte] &= ~(1 << dstBit); } } // Write converted row coverBmp.write(rowBuffer, dstRowSize); // Pad to 4-byte boundary uint8_t padding[4] = {0, 0, 0, 0}; size_t paddingSize = rowSize - dstRowSize; if (paddingSize > 0) { coverBmp.write(padding, paddingSize); } } free(rowBuffer); } else { // 1-bit source: write directly with proper padding const size_t srcRowSize = (pageInfo.width + 7) / 8; for (uint16_t y = 0; y < pageInfo.height; y++) { // Write source row coverBmp.write(pageBuffer + y * srcRowSize, srcRowSize); // Pad to 4-byte boundary uint8_t padding[4] = {0, 0, 0, 0}; size_t paddingSize = rowSize - srcRowSize; if (paddingSize > 0) { coverBmp.write(padding, paddingSize); } } } free(pageBuffer); LOG_DBG("XTC", "Generated cover BMP: %s", getCoverBmpPath().c_str()); return true; } std::string Xtc::getThumbBmpPath() const { return cachePath + "/thumb_[HEIGHT].bmp"; } std::string Xtc::getThumbBmpPath(int height) const { return cachePath + "/thumb_" + std::to_string(height) + ".bmp"; } std::string Xtc::getThumbBmpPath(int width, int height) const { return cachePath + "/thumb_" + std::to_string(width) + "x" + std::to_string(height) + ".bmp"; } bool Xtc::generateThumbBmp(int height) const { const std::string destPath = getThumbBmpPath(height); if (Storage.exists(destPath.c_str())) return true; const int width = static_cast(height * 0.6f); if (!generateThumbBmp(width, height)) return false; const std::string srcPath = getThumbBmpPath(width, height); Storage.rename(srcPath.c_str(), destPath.c_str()); return Storage.exists(destPath.c_str()); } bool Xtc::generateThumbBmp(int width, int height) const { if (Storage.exists(getThumbBmpPath(width, height).c_str())) return true; if (!loaded || !parser) { LOG_ERR("XTC", "Cannot generate thumb BMP, file not loaded"); return false; } if (parser->getPageCount() == 0) { LOG_ERR("XTC", "No pages in XTC file"); return false; } setupCacheDir(); xtc::PageInfo pageInfo; if (!parser->getPageInfo(0, pageInfo)) { LOG_DBG("XTC", "Failed to get first page info"); return false; } const uint8_t bitDepth = parser->getBitDepth(); const int THUMB_TARGET_WIDTH = width; const int THUMB_TARGET_HEIGHT = height; float scaleX = static_cast(THUMB_TARGET_WIDTH) / pageInfo.width; float scaleY = static_cast(THUMB_TARGET_HEIGHT) / pageInfo.height; float scale = (scaleX < scaleY) ? scaleX : scaleY; if (scale >= 1.0f) { if (generateCoverBmp()) { FsFile src, dst; if (Storage.openFileForRead("XTC", getCoverBmpPath(), src)) { if (Storage.openFileForWrite("XTC", getThumbBmpPath(width, height), dst)) { uint8_t buffer[512]; while (src.available()) { size_t bytesRead = src.read(buffer, sizeof(buffer)); dst.write(buffer, bytesRead); } dst.close(); } src.close(); } return Storage.exists(getThumbBmpPath(width, height).c_str()); } return false; } uint16_t thumbWidth = static_cast(pageInfo.width * scale); uint16_t thumbHeight = static_cast(pageInfo.height * scale); size_t bitmapSize; if (bitDepth == 2) { bitmapSize = ((static_cast(pageInfo.width) * pageInfo.height + 7) / 8) * 2; } else { bitmapSize = ((pageInfo.width + 7) / 8) * pageInfo.height; } uint8_t* pageBuffer = static_cast(malloc(bitmapSize)); if (!pageBuffer) { LOG_ERR("XTC", "Failed to allocate page buffer (%lu bytes)", bitmapSize); return false; } size_t bytesRead = const_cast(parser.get())->loadPage(0, pageBuffer, bitmapSize); if (bytesRead == 0) { LOG_ERR("XTC", "Failed to load cover page for thumb"); free(pageBuffer); return false; } const std::string thumbPath = getThumbBmpPath(width, height); FsFile thumbBmp; if (!Storage.openFileForWrite("XTC", thumbPath, thumbBmp)) { free(pageBuffer); return false; } const uint32_t rowSize = (thumbWidth + 31) / 32 * 4; BmpHeader bmpHeader; createBmpHeader(&bmpHeader, thumbWidth, thumbHeight, BmpRowOrder::TopDown); thumbBmp.write(reinterpret_cast(&bmpHeader), sizeof(BmpHeader)); uint8_t* rowBuffer = static_cast(malloc(rowSize)); if (!rowBuffer) { free(pageBuffer); thumbBmp.close(); Storage.remove(thumbPath.c_str()); return false; } uint32_t scaleInv_fp = static_cast(65536.0f / scale); const size_t planeSize = (bitDepth == 2) ? ((static_cast(pageInfo.width) * pageInfo.height + 7) / 8) : 0; const uint8_t* plane1 = (bitDepth == 2) ? pageBuffer : nullptr; const uint8_t* plane2 = (bitDepth == 2) ? pageBuffer + planeSize : nullptr; const size_t colBytes = (bitDepth == 2) ? ((pageInfo.height + 7) / 8) : 0; const size_t srcRowBytes = (bitDepth == 1) ? ((pageInfo.width + 7) / 8) : 0; for (uint16_t dstY = 0; dstY < thumbHeight; dstY++) { memset(rowBuffer, 0xFF, rowSize); uint32_t srcYStart = (static_cast(dstY) * scaleInv_fp) >> 16; uint32_t srcYEnd = (static_cast(dstY + 1) * scaleInv_fp) >> 16; if (srcYStart >= pageInfo.height) srcYStart = pageInfo.height - 1; if (srcYEnd > pageInfo.height) srcYEnd = pageInfo.height; if (srcYEnd <= srcYStart) srcYEnd = srcYStart + 1; if (srcYEnd > pageInfo.height) srcYEnd = pageInfo.height; for (uint16_t dstX = 0; dstX < thumbWidth; dstX++) { uint32_t srcXStart = (static_cast(dstX) * scaleInv_fp) >> 16; uint32_t srcXEnd = (static_cast(dstX + 1) * scaleInv_fp) >> 16; if (srcXStart >= pageInfo.width) srcXStart = pageInfo.width - 1; if (srcXEnd > pageInfo.width) srcXEnd = pageInfo.width; if (srcXEnd <= srcXStart) srcXEnd = srcXStart + 1; if (srcXEnd > pageInfo.width) srcXEnd = pageInfo.width; uint32_t graySum = 0, totalCount = 0; for (uint32_t srcY = srcYStart; srcY < srcYEnd && srcY < pageInfo.height; srcY++) { for (uint32_t srcX = srcXStart; srcX < srcXEnd && srcX < pageInfo.width; srcX++) { uint8_t grayValue = 255; if (bitDepth == 2) { if (srcX < pageInfo.width) { const size_t colIndex = pageInfo.width - 1 - srcX; const size_t byteInCol = srcY / 8; const size_t bitInByte = 7 - (srcY % 8); const size_t byteOffset = colIndex * colBytes + byteInCol; if (byteOffset < planeSize) { const uint8_t bit1 = (plane1[byteOffset] >> bitInByte) & 1; const uint8_t bit2 = (plane2[byteOffset] >> bitInByte) & 1; grayValue = (3 - ((bit1 << 1) | bit2)) * 85; } } } else { const size_t byteIdx = srcY * srcRowBytes + srcX / 8; const size_t bitIdx = 7 - (srcX % 8); if (byteIdx < bitmapSize) { grayValue = ((pageBuffer[byteIdx] >> bitIdx) & 1) ? 255 : 0; } } graySum += grayValue; totalCount++; } } uint8_t avgGray = (totalCount > 0) ? static_cast(graySum / totalCount) : 255; uint32_t hash = static_cast(dstX) * 374761393u + static_cast(dstY) * 668265263u; hash = (hash ^ (hash >> 13)) * 1274126177u; const int threshold = static_cast(hash >> 24); const int adjustedThreshold = 128 + ((threshold - 128) / 2); uint8_t oneBit = (avgGray >= adjustedThreshold) ? 1 : 0; const size_t byteIndex = dstX / 8; const size_t bitOffset = 7 - (dstX % 8); if (byteIndex < rowSize) { if (oneBit) rowBuffer[byteIndex] |= (1 << bitOffset); else rowBuffer[byteIndex] &= ~(1 << bitOffset); } } thumbBmp.write(rowBuffer, rowSize); } free(rowBuffer); thumbBmp.close(); free(pageBuffer); LOG_DBG("XTC", "Generated thumb BMP (%dx%d): %s", thumbWidth, thumbHeight, getThumbBmpPath(width, height).c_str()); return true; } uint32_t Xtc::getPageCount() const { if (!loaded || !parser) { return 0; } return parser->getPageCount(); } uint16_t Xtc::getPageWidth() const { if (!loaded || !parser) { return 0; } return parser->getWidth(); } uint16_t Xtc::getPageHeight() const { if (!loaded || !parser) { return 0; } return parser->getHeight(); } uint8_t Xtc::getBitDepth() const { if (!loaded || !parser) { return 1; // Default to 1-bit } return parser->getBitDepth(); } size_t Xtc::loadPage(uint32_t pageIndex, uint8_t* buffer, size_t bufferSize) const { if (!loaded || !parser) { return 0; } return const_cast(parser.get())->loadPage(pageIndex, buffer, bufferSize); } xtc::XtcError Xtc::loadPageStreaming(uint32_t pageIndex, std::function callback, size_t chunkSize) const { if (!loaded || !parser) { return xtc::XtcError::FILE_NOT_FOUND; } return const_cast(parser.get())->loadPageStreaming(pageIndex, callback, chunkSize); } uint8_t Xtc::calculateProgress(uint32_t currentPage) const { if (!loaded || !parser || parser->getPageCount() == 0) { return 0; } return static_cast((currentPage + 1) * 100 / parser->getPageCount()); } xtc::XtcError Xtc::getLastError() const { if (!parser) { return xtc::XtcError::FILE_NOT_FOUND; } return parser->getLastError(); }