1 /*-------------------------------------------------------------------------
2 * drawElements Quality Program Execution Server
3 * ---------------------------------------------
4 *
5 * Copyright 2014 The Android Open Source Project
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 *
19 *//*!
20 * \file
21 * \brief File Reader.
22 *//*--------------------------------------------------------------------*/
23
24 #include "xsPosixFileReader.hpp"
25
26 #include <vector>
27
28 namespace xs
29 {
30 namespace posix
31 {
32
FileReader(int blockSize,int numBlocks)33 FileReader::FileReader(int blockSize, int numBlocks) : m_file(DE_NULL), m_buf(blockSize, numBlocks), m_isRunning(false)
34 {
35 }
36
~FileReader(void)37 FileReader::~FileReader(void)
38 {
39 }
40
start(const char * filename)41 void FileReader::start(const char *filename)
42 {
43 DE_ASSERT(!m_isRunning);
44
45 m_file = deFile_create(filename, DE_FILEMODE_OPEN | DE_FILEMODE_READ);
46 XS_CHECK(m_file);
47
48 #if (DE_OS != DE_OS_IOS)
49 // Set to non-blocking mode.
50 if (!deFile_setFlags(m_file, DE_FILE_NONBLOCKING))
51 {
52 deFile_destroy(m_file);
53 m_file = DE_NULL;
54 XS_FAIL("Failed to set non-blocking mode");
55 }
56 #endif
57
58 m_isRunning = true;
59
60 de::Thread::start();
61 }
62
run(void)63 void FileReader::run(void)
64 {
65 std::vector<uint8_t> tmpBuf(FILEREADER_TMP_BUFFER_SIZE);
66 int64_t numRead = 0;
67
68 while (!m_buf.isCanceled())
69 {
70 deFileResult result = deFile_read(m_file, &tmpBuf[0], (int64_t)tmpBuf.size(), &numRead);
71
72 if (result == DE_FILERESULT_SUCCESS)
73 {
74 // Write to buffer.
75 try
76 {
77 m_buf.write((int)numRead, &tmpBuf[0]);
78 m_buf.flush();
79 }
80 catch (const ThreadedByteBuffer::CanceledException &)
81 {
82 // Canceled.
83 break;
84 }
85 }
86 else if (result == DE_FILERESULT_END_OF_FILE || result == DE_FILERESULT_WOULD_BLOCK)
87 {
88 // Wait for more data.
89 deSleep(FILEREADER_IDLE_SLEEP);
90 }
91 else
92 break; // Error.
93 }
94 }
95
stop(void)96 void FileReader::stop(void)
97 {
98 if (!m_isRunning)
99 return; // Nothing to do.
100
101 m_buf.cancel();
102
103 // Join thread.
104 join();
105
106 // Destroy file.
107 deFile_destroy(m_file);
108 m_file = DE_NULL;
109
110 // Reset buffer.
111 m_buf.clear();
112
113 m_isRunning = false;
114 }
115
116 } // namespace posix
117 } // namespace xs
118