1 /*
2  * The contents of this file are subject to the Mozilla Public
3  * License Version 1.1 (the "License"); you may not use this file
4  * except in compliance with the License. You may obtain a copy of
5  * the License at http://www.mozilla.org/MPL/
6  *
7  * Software distributed under the License is distributed on an "AS
8  * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
9  * implied. See the License for the specific language governing
10  * rights and limitations under the License.
11  *
12  * The Original Code is MPEG4IP.
13  *
14  * The Initial Developer of the Original Code is Cisco Systems Inc.
15  * Portions created by Cisco Systems Inc. are
16  * Copyright (C) Cisco Systems Inc. 2001 - 2005.  All Rights Reserved.
17  *
18  * Contributor(s):
19  *		Ben Allison			benski at nullsoft.com
20  *
21  * Virtual I/O support, for file support other than fopen/fread/fwrite
22  */
23 
24 #include "mp4common.h"
25 #include "virtual_io.h"
26 
27 /* --------- Virtual IO for FILE * --------- */
28 
FILE_GetFileLength(void * user)29 u_int64_t FILE_GetFileLength(void *user)
30 {
31 	FILE *fp = (FILE *)user;
32 	struct stat s;
33 	if (fstat(fileno(fp), &s) < 0) {
34 		throw new MP4Error(errno, "stat failed", "MP4Open");
35 	}
36 	return s.st_size;
37 }
38 
FILE_SetPosition(void * user,u_int64_t position)39 int FILE_SetPosition(void *user, u_int64_t position)
40 {
41 	FILE *fp = (FILE *)user;
42 	fpos_t fpos;
43 	VAR_TO_FPOS(fpos, position);
44 	return fsetpos(fp, &fpos);
45 }
46 
FILE_GetPosition(void * user,u_int64_t * position)47 int FILE_GetPosition(void *user, u_int64_t *position)
48 {
49 	FILE *fp = (FILE *)user;
50 	fpos_t fpos;
51 	if (fgetpos(fp, &fpos) < 0) {
52 		throw new MP4Error(errno, "MP4GetPosition");
53 	}
54 
55 	FPOS_TO_VAR(fpos, u_int64_t, *position);
56 	return 0;
57 }
58 
FILE_Read(void * user,void * buffer,size_t size)59 size_t FILE_Read(void *user, void *buffer, size_t size)
60 {
61 	FILE *fp = (FILE *)user;
62 	return fread(buffer, 1, size, fp);
63 }
64 
FILE_Write(void * user,void * buffer,size_t size)65 size_t FILE_Write(void *user, void *buffer, size_t size)
66 {
67 	FILE *fp = (FILE *)user;
68 	return fwrite(buffer, 1, size, fp);
69 }
70 
FILE_EndOfFile(void * user)71 int FILE_EndOfFile(void *user)
72 {
73 	FILE *fp = (FILE *)user;
74 	return feof(fp);
75 }
76 
FILE_Close(void * user)77 int FILE_Close(void *user)
78 {
79 	FILE *fp = (FILE *)user;
80 	return fclose(fp);
81 }
82 
83 Virtual_IO FILE_virtual_IO =
84 {
85 	FILE_GetFileLength,
86 		FILE_SetPosition,
87 		FILE_GetPosition,
88 		FILE_Read,
89 		FILE_Write,
90 		FILE_EndOfFile,
91 		FILE_Close,
92 };
93