+
+/* Functions for handling memory-mapped input frames */
+int x264_cli_mmap_init( cli_mmap_t *h, FILE *fh )
+{
+#ifdef _WIN32
+ HANDLE osfhandle = (HANDLE)_get_osfhandle( _fileno( fh ) );
+ if( osfhandle != INVALID_HANDLE_VALUE )
+ {
+ SYSTEM_INFO si;
+ GetSystemInfo( &si );
+ h->align_mask = si.dwAllocationGranularity - 1;
+ h->map_handle = CreateFileMappingW( osfhandle, NULL, PAGE_READONLY, 0, 0, NULL );
+ return !h->map_handle;
+ }
+#elif HAVE_MMAP && defined(_SC_PAGESIZE)
+ h->align_mask = sysconf( _SC_PAGESIZE ) - 1;
+ h->fd = fileno( fh );
+ return h->align_mask < 0 || h->fd < 0;
+#endif
+ return -1;
+}
+
+void *x264_cli_mmap( cli_mmap_t *h, int64_t offset, size_t size )
+{
+#if defined(_WIN32) || HAVE_MMAP
+ int align = offset & h->align_mask;
+ offset -= align;
+ size += align;
+#ifdef _WIN32
+ uint8_t *base = MapViewOfFile( h->map_handle, FILE_MAP_READ, offset >> 32, offset, size );
+ /* TODO: Would PrefetchVirtualMemory() (only available on Win8+) be beneficial? */
+ if( base )
+ return base + align;
+#else
+ uint8_t *base = mmap( NULL, size, PROT_READ, MAP_PRIVATE, h->fd, offset );
+ if( base != MAP_FAILED )
+ {
+ /* Ask the OS to readahead pages. This improves performance whereas
+ * forcing page faults by manually accessing every page does not.
+ * Some systems have implemented madvise() but not posix_madvise()
+ * and vice versa, so check both to see if either is available. */
+#ifdef MADV_WILLNEED
+ madvise( base, size, MADV_WILLNEED );
+#elif defined(POSIX_MADV_WILLNEED)
+ posix_madvise( base, size, POSIX_MADV_WILLNEED );
+#endif
+ return base + align;
+ }
+#endif
+#endif
+ return NULL;
+}
+
+int x264_cli_munmap( cli_mmap_t *h, void *addr, size_t size )
+{
+#if defined(_WIN32) || HAVE_MMAP
+ void *base = (void*)((intptr_t)addr & ~h->align_mask);
+#ifdef _WIN32
+ return !UnmapViewOfFile( base );
+#else
+ return munmap( base, size + (intptr_t)addr - (intptr_t)base );
+#endif
+#endif
+ return -1;
+}
+
+void x264_cli_mmap_close( cli_mmap_t *h )
+{
+#ifdef _WIN32
+ CloseHandle( h->map_handle );
+#endif
+}