Repository navigation
Expand file tree
/
Copy pathstickers_lottie.cpp
More file actions
393 lines (365 loc) · 10.2 KB
/
Copy pathstickers_lottie.cpp
File metadata and controls
393 lines (365 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
/*
This file is part of Telegram Desktop,
the official desktop application for the Telegram messaging service.
For license and copyright information please follow this link:
https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
*/
#include "chat_helpers/stickers_lottie.h"
#include "lottie/lottie_single_player.h"
#include "lottie/lottie_multi_player.h"
#include "data/stickers/data_stickers_set.h"
#include "data/data_document.h"
#include "data/data_document_media.h"
#include "data/data_session.h"
#include "data/data_file_origin.h"
#include "storage/cache/storage_cache_database.h"
#include "storage/localimageloader.h"
#include "history/view/media/history_view_media_common.h"
#include "media/clip/media_clip_reader.h"
#include "ui/chat/attach/attach_prepare.h"
#include "ui/effects/path_shift_gradient.h"
#include "ui/image/image_location_factory.h"
#include "ui/painter.h"
#include "main/main_session.h"
#include <xxhash.h>
namespace ChatHelpers {
namespace {
constexpr auto kDontCacheLottieAfterArea = 512 * 512;
[[nodiscard]] uint64 LocalStickerId(QStringView name) {
auto full = u"local_sticker:"_q;
full.append(name);
return XXH64(full.data(), full.size() * sizeof(QChar), 0);
}
} // namespace
uint8 LottieCacheKeyShift(uint8 replacementsTag, StickerLottieSize sizeTag) {
return ((replacementsTag << 4) & 0xF0) | (uint8(sizeTag) & 0x0F);
}
template <typename Method>
auto LottieCachedFromContent(
Method &&method,
Storage::Cache::Key baseKey,
uint8 keyShift,
not_null<Main::Session*> session,
const QByteArray &content,
QSize box) {
const auto key = Storage::Cache::Key{
baseKey.high,
baseKey.low + keyShift
};
const auto get = [=](FnMut<void(QByteArray &&cached)> handler) {
session->data().cacheBigFile().get(
key,
std::move(handler));
};
const auto weak = base::make_weak(session);
const auto put = [=](QByteArray &&cached) {
crl::on_main(weak, [=, data = std::move(cached)]() mutable {
weak->data().cacheBigFile().put(key, std::move(data));
});
};
return method(
get,
put,
content,
Lottie::FrameRequest{ box });
}
template <typename Method>
auto LottieFromDocument(
Method &&method,
not_null<Data::DocumentMedia*> media,
uint8 keyShift,
QSize box) {
const auto document = media->owner();
const auto data = media->bytes();
const auto filepath = document->filepath();
if (box.width() * box.height() > kDontCacheLottieAfterArea) {
// Don't use frame caching for large stickers.
return method(
Lottie::ReadContent(data, filepath),
Lottie::FrameRequest{ box });
}
if (const auto baseKey = document->bigFileBaseCacheKey()) {
return LottieCachedFromContent(
std::forward<Method>(method),
baseKey,
keyShift,
&document->session(),
Lottie::ReadContent(data, filepath),
box);
}
return method(
Lottie::ReadContent(data, filepath),
Lottie::FrameRequest{ box });
}
std::unique_ptr<Lottie::SinglePlayer> LottiePlayerFromDocument(
not_null<Data::DocumentMedia*> media,
StickerLottieSize sizeTag,
QSize box,
Lottie::Quality quality,
std::shared_ptr<Lottie::FrameRenderer> renderer) {
return LottiePlayerFromDocument(
media,
nullptr,
sizeTag,
box,
quality,
std::move(renderer));
}
std::unique_ptr<Lottie::SinglePlayer> LottiePlayerFromDocument(
not_null<Data::DocumentMedia*> media,
const Lottie::ColorReplacements *replacements,
StickerLottieSize sizeTag,
QSize box,
Lottie::Quality quality,
std::shared_ptr<Lottie::FrameRenderer> renderer) {
const auto method = [&](auto &&...args) {
return std::make_unique<Lottie::SinglePlayer>(
std::forward<decltype(args)>(args)...,
quality,
replacements,
std::move(renderer));
};
const auto keyShift = LottieCacheKeyShift(
replacements ? replacements->tag : uint8(0),
sizeTag);
return LottieFromDocument(method, media, uint8(keyShift), box);
}
not_null<Lottie::Animation*> LottieAnimationFromDocument(
not_null<Lottie::MultiPlayer*> player,
not_null<Data::DocumentMedia*> media,
StickerLottieSize sizeTag,
QSize box) {
const auto method = [&](auto &&...args) {
return player->append(std::forward<decltype(args)>(args)...);
};
return LottieFromDocument(method, media, uint8(sizeTag), box);
}
bool HasLottieThumbnail(
StickerType thumbType,
Data::StickersSetThumbnailView *thumb,
Data::DocumentMedia *media) {
if (thumb) {
return (thumbType == StickerType::Tgs)
&& !thumb->content().isEmpty();
} else if (!media) {
return false;
}
const auto document = media->owner();
if (const auto info = document->sticker()) {
if (!info->isLottie()) {
return false;
}
media->automaticLoad(document->stickerSetOrigin(), nullptr);
if (!media->loaded()) {
return false;
}
return document->bigFileBaseCacheKey().valid();
}
return false;
}
std::unique_ptr<Lottie::SinglePlayer> LottieThumbnail(
Data::StickersSetThumbnailView *thumb,
Data::DocumentMedia *media,
StickerLottieSize sizeTag,
QSize box,
std::shared_ptr<Lottie::FrameRenderer> renderer) {
const auto baseKey = thumb
? thumb->owner()->thumbnailBigFileBaseCacheKey()
: media
? media->owner()->bigFileBaseCacheKey()
: Storage::Cache::Key();
if (!baseKey) {
return nullptr;
}
const auto content = thumb
? thumb->content()
: Lottie::ReadContent(media->bytes(), media->owner()->filepath());
if (content.isEmpty()) {
return nullptr;
}
const auto method = [](auto &&...args) {
return std::make_unique<Lottie::SinglePlayer>(
std::forward<decltype(args)>(args)...);
};
const auto session = thumb
? &thumb->owner()->session()
: &media->owner()->session();
return LottieCachedFromContent(
method,
baseKey,
uint8(sizeTag),
session,
content,
box);
}
bool HasWebmThumbnail(
StickerType thumbType,
Data::StickersSetThumbnailView *thumb,
Data::DocumentMedia *media) {
if (thumb) {
return (thumbType == StickerType::Webm)
&& !thumb->content().isEmpty();
} else if (!media) {
return false;
}
const auto document = media->owner();
if (const auto info = document->sticker()) {
if (!info->isWebm()) {
return false;
}
media->automaticLoad(document->stickerSetOrigin(), nullptr);
if (!media->loaded()) {
return false;
}
return document->bigFileBaseCacheKey().valid();
}
return false;
}
Media::Clip::ReaderPointer WebmThumbnail(
Data::StickersSetThumbnailView *thumb,
Data::DocumentMedia *media,
Fn<void(Media::Clip::Notification)> callback) {
return thumb
? ::Media::Clip::MakeReader(
thumb->content(),
std::move(callback))
: ::Media::Clip::MakeReader(
media->owner()->location(),
media->bytes(),
std::move(callback));
}
bool PaintStickerThumbnailPath(
QPainter &p,
not_null<Data::DocumentMedia*> media,
QRect target,
QLinearGradient *gradient,
bool mirrorHorizontal) {
const auto &path = media->thumbnailPath();
const auto dimensions = media->owner()->dimensions;
if (path.isEmpty() || dimensions.isEmpty() || target.isEmpty()) {
return false;
}
p.save();
auto hq = PainterHighQualityEnabler(p);
p.setPen(Qt::NoPen);
p.translate(target.topLeft());
if (gradient) {
const auto scale = dimensions.width() / float64(target.width());
const auto shift = p.worldTransform().dx();
gradient->setStart((gradient->start().x() - shift) * scale, 0);
gradient->setFinalStop(
(gradient->finalStop().x() - shift) * scale,
0);
p.setBrush(*gradient);
}
if (mirrorHorizontal) {
const auto c = QPointF(target.width() / 2., target.height() / 2.);
p.translate(c);
p.scale(-1., 1.);
p.translate(-c);
}
p.scale(
target.width() / float64(dimensions.width()),
target.height() / float64(dimensions.height()));
p.drawPath(path);
p.restore();
return true;
}
bool PaintStickerThumbnailPath(
QPainter &p,
not_null<Data::DocumentMedia*> media,
QRect target,
not_null<Ui::PathShiftGradient*> gradient,
bool mirrorHorizontal) {
return gradient->paint([&](const Ui::PathShiftGradient::Background &bg) {
if (const auto color = std::get_if<style::color>(&bg)) {
p.setBrush(*color);
return PaintStickerThumbnailPath(
p,
media,
target,
nullptr,
mirrorHorizontal);
}
const auto gradient = v::get<QLinearGradient*>(bg);
return PaintStickerThumbnailPath(
p,
media,
target,
gradient,
mirrorHorizontal);
});
}
QSize ComputeStickerSize(not_null<DocumentData*> document, QSize box) {
const auto sticker = document->sticker();
const auto dimensions = document->dimensions;
if (!sticker || !sticker->isLottie() || dimensions.isEmpty()) {
return HistoryView::DownscaledSize(dimensions, box);
}
const auto ratio = style::DevicePixelRatio();
const auto request = Lottie::FrameRequest{ box * ratio };
return HistoryView::NonEmptySize(request.size(dimensions, 8) / ratio);
}
not_null<DocumentData*> GenerateLocalSticker(
not_null<Main::Session*> session,
const QString &path) {
auto task = FileLoadTask(FileLoadTask::Args{
.session = session,
.filepath = path,
.type = SendMediaType::File,
.to = FileLoadTo(0, {}, {}, 0),
.caption = {},
.idOverride = LocalStickerId(path),
});
task.process({ .generateGoodThumbnail = false });
const auto result = task.peekResult();
Assert(result != nullptr);
const auto document = session->data().processDocument(
result->document,
Images::FromImageInMemory(
result->thumb,
"WEBP",
result->thumbbytes));
document->setLocation(Core::FileLocation(path));
Ensures(document->sticker());
return document;
}
not_null<DocumentData*> GenerateLocalTgsSticker(
not_null<Main::Session*> session,
const QString &name,
bool useTextColor) {
const auto cache = [&] {
struct Session {
base::weak_ptr<Main::Session> session;
base::flat_map<QString, not_null<DocumentData*>> cache;
};
static auto Map = std::vector<Session>();
for (auto i = begin(Map); i != end(Map);) {
if (const auto strong = i->session.get()) {
if (strong == session) {
return &i->cache;
}
++i;
} else {
i = Map.erase(i);
}
}
Map.push_back({ .session = session });
return &Map.back().cache;
}();
const auto key = useTextColor ? (name + u"/:/1"_q) : name;
const auto i = cache->find(key);
if (i != end(*cache)) {
return i->second;
}
const auto result = GenerateLocalSticker(
session,
u":/animations/"_q + name + u".tgs"_q);
if (useTextColor) {
result->overrideEmojiUsesTextColor(true);
}
cache->emplace(key, result);
Ensures(result->sticker()->isLottie());
return result;
}
} // namespace ChatHelpers