1 /*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "snapshot/TextureSaver.h"
18
19 #include "aemu/base/files/CompressingStream.h"
20 #include "aemu/base/system/System.h"
21
22 #include <algorithm>
23 #include <cassert>
24 #include <iterator>
25 #include <utility>
26
27 using android::base::CompressingStream;
28
29 namespace android {
30 namespace snapshot {
31
TextureSaver(android::base::StdioStream && stream)32 TextureSaver::TextureSaver(android::base::StdioStream&& stream)
33 : mStream(std::move(stream)) {
34 // Put a placeholder for the index offset right now.
35 mStream.putBe64(0);
36 }
37
~TextureSaver()38 TextureSaver::~TextureSaver() {
39 done();
40 }
41
saveTexture(uint32_t texId,const saver_t & saver)42 void TextureSaver::saveTexture(uint32_t texId, const saver_t& saver) {
43
44 if (!mStartTime) {
45 mStartTime = base::getHighResTimeUs();
46 }
47
48 assert(mIndex.textures.end() ==
49 std::find_if(mIndex.textures.begin(), mIndex.textures.end(),
50 [texId](FileIndex::Texture& tex) {
51 return tex.texId == texId;
52 }));
53 mIndex.textures.push_back({texId, ftello64(mStream.get())});
54
55 CompressingStream stream(mStream);
56 saver(&stream, &mBuffer);
57 }
58
done()59 void TextureSaver::done() {
60 if (mFinished) {
61 return;
62 }
63 mIndex.startPosInFile = ftello64(mStream.get());
64 writeIndex();
65 mEndTime = base::getHighResTimeUs();
66 #if SNAPSHOT_PROFILE > 1
67 printf("Texture saving time: %.03f\n",
68 (mEndTime - mStartTime) / 1000.0);
69 #endif
70 mHasError = ferror(mStream.get()) != 0;
71 mFinished = true;
72 mStream.close();
73 }
74
writeIndex()75 void TextureSaver::writeIndex() {
76 #if SNAPSHOT_PROFILE > 1
77 auto start = ftello64(mStream.get());
78 #endif
79
80 mStream.putBe32(static_cast<uint32_t>(mIndex.version));
81 mStream.putBe32(static_cast<uint32_t>(mIndex.textures.size()));
82 for (const FileIndex::Texture& b : mIndex.textures) {
83 mStream.putBe32(b.texId);
84 mStream.putBe64(static_cast<uint64_t>(b.filePos));
85 }
86 auto end = ftello64(mStream.get());
87 mDiskSize = uint64_t(end);
88 #if SNAPSHOT_PROFILE > 1
89 printf("texture: index size: %d\n", int(end - start));
90 #endif
91
92 fseeko64(mStream.get(), 0, SEEK_SET);
93 mStream.putBe64(static_cast<uint64_t>(mIndex.startPosInFile));
94 }
95
96 } // namespace snapshot
97 } // namespace android
98