/* Copyright  (C) 2010-2020 The RetroArch team
*
* ---------------------------------------------------------------------------------------
* The following license statement only applies to this file (vfs_implementation.h).
* ---------------------------------------------------------------------------------------
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#ifndef __LIBRETRO_SDK_VFS_H
#define __LIBRETRO_SDK_VFS_H

#include <retro_common_api.h>
#include <boolean.h>
#include <stdint.h>

#ifdef RARCH_INTERNAL
#ifndef VFS_FRONTEND
#define VFS_FRONTEND
#endif
#endif

RETRO_BEGIN_DECLS

#ifdef _WIN32
typedef void* HANDLE;
#endif

#ifdef HAVE_CDROM
typedef struct
{
   int64_t byte_pos;
   char *cue_buf;
   size_t cue_len;
   unsigned cur_lba;
   unsigned last_frame_lba;
   unsigned char cur_min;
   unsigned char cur_sec;
   unsigned char cur_frame;
   unsigned char cur_track;
   unsigned char last_frame[2352];
   char drive;
   bool last_frame_valid;
} vfs_cdrom_t;
#endif

/* File mapping is available through POSIX mmap (HAVE_MMAP, chosen by
 * the build) or through Win32 file mappings (always available there).
 * Consumers gate on this umbrella so the two backends stay one code
 * path everywhere except the actual map/unmap calls. */
#if defined(HAVE_MMAP) || (defined(_WIN32) && !defined(_XBOX))
#define VFS_HAVE_FILE_MAPPING 1
#endif

/* Descriptor-backed I/O: open()/read()/close() with no stdio layer in
 * between.  The code for it is compiled on every target - it is the
 * path a file mapping falls back to - but until this existed it was
 * only ever *reached* where VFS_HAVE_FILE_MAPPING was defined, since
 * that was the sole gate on the hint that selects it.  Everything
 * else was pinned to stdio no matter what the caller asked for.
 *
 * That matters most on the targets that were excluded.  With newlib,
 * fread() on a buffered stream refills through the stream buffer and
 * memcpy()s each refill into the caller's buffer (see _fread_r), so a
 * whole-file read costs one read() per buffer-full plus a second copy
 * of every byte; glibc's fread() bypasses its buffer once the request
 * reaches a block, which is why this is invisible on desktop.
 *
 * Listed rather than assumed: the descriptor path compiles everywhere
 * but has only ever run on the mapping targets, so a platform joins
 * this list once its open()/read()/lseek() have been exercised.  A
 * target that is not listed keeps the behaviour it has today. */
#ifndef VFS_HAVE_DESCRIPTOR_IO
#if defined(VFS_HAVE_FILE_MAPPING) \
 || defined(VITA) \
 || defined(_3DS) \
 || defined(WIIU) \
 || defined(__SWITCH__)
#define VFS_HAVE_DESCRIPTOR_IO 1
#endif
#endif

/* Descriptor-backed I/O for one-shot writers as well: a stream opened
 * for writing with RETRO_VFS_FILE_ACCESS_HINT_SEQUENTIAL_BULK hands its
 * bytes straight to the descriptor, so a whole-file write is one open,
 * one write and one close.  Same listing discipline as above: a
 * platform joins once its descriptor write path has been exercised.
 *
 * On Vita the descriptor path is sceIo* itself rather than newlib's
 * open()/write(), which sit on top of those calls and add a realpath
 * allocation, a directory stat, a strdup of the path into the fd
 * table and a mutex round-trip per call; stdio adds a FILE, a buffer
 * and an fstat on top of that.  On an SD card every extra stat is a
 * directory lookup, so a bulk extraction pays for all of it per
 * member. */
#ifndef VFS_HAVE_DESCRIPTOR_WRITE
#if defined(VITA)
#define VFS_HAVE_DESCRIPTOR_WRITE 1
#endif
#endif

enum vfs_scheme
{
   VFS_SCHEME_NONE = 0,
   VFS_SCHEME_CDROM,
   VFS_SCHEME_SAF,
   VFS_SCHEME_SMB
};

#if !(defined(__WINRT__) && defined(__cplusplus_winrt))
#ifdef VFS_FRONTEND
struct retro_vfs_file_handle
#else
struct libretro_vfs_implementation_file
#endif
{
   int64_t size;
   uint64_t mappos;
   uint64_t mapsize;
   FILE *fp;
#ifdef _WIN32
   HANDLE fh;
   /* CreateFileMapping handle backing `mapped`; NULL when unmapped */
   HANDLE map_handle;
#endif
   char *buf;
   char* orig_path;
   uint8_t *mapped;
   int fd;
   unsigned hints;
   enum vfs_scheme scheme;
#ifdef HAVE_CDROM
   /* Allocated by retro_vfs_file_open_impl() only when the path
    * carries the cdrom:// scheme, and freed by
    * retro_vfs_file_close_impl(). It used to be an inline member at
    * the head of this struct, which is a poor trade: vfs_cdrom_t
    * embeds a 2352-byte sector cache, so every open file handle in a
    * build with HAVE_CDROM cost 2464 bytes instead of 72, and the
    * fields the read/seek paths actually touch (mappos, mapsize,
    * mapped, hints) were pushed past offset 2392 and split across two
    * cache lines instead of sharing one. Every consumer already gates
    * on 'scheme == VFS_SCHEME_CDROM' before reaching for it, so a
    * NULL here is unreachable on those paths. */
   vfs_cdrom_t *cdrom;
#endif
#ifdef HAVE_SMBCLIENT
   intptr_t smb_fh;
   intptr_t smb_ctx;
#endif
#if defined(HAVE_CDROM) && defined(__APPLE__)
   void *iokit_plugin;   /* IOCFPlugInInterface ** */
   void *iokit_mmc;      /* MMCDeviceInterface ** */
#endif
};
#endif

/* Replace the following symbol with something appropriate
 * to signify the file is being compiled for a front end instead of a core.
 * This allows the same code to act as reference implementation
 * for VFS and as fallbacks for when the front end does not provide VFS functionality.
 */

#ifdef VFS_FRONTEND
typedef struct retro_vfs_file_handle libretro_vfs_implementation_file;
#else
typedef struct libretro_vfs_implementation_file libretro_vfs_implementation_file;
#endif

#ifdef VFS_FRONTEND
typedef struct retro_vfs_dir_handle libretro_vfs_implementation_dir;
#else
typedef struct libretro_vfs_implementation_dir libretro_vfs_implementation_dir;
#endif

RETRO_END_DECLS

#endif
