blob: 2306395a1c044a54612f940822326e79e8a37202 [file] [log] [blame]
Chong Zhangbc062482020-10-14 16:43:53 -07001/*
2 * Copyright (C) 2020 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//#define LOG_NDEBUG 0
18#define LOG_TAG "TranscodingSessionController"
19
20#define VALIDATE_STATE 1
21
22#include <inttypes.h>
23#include <media/TranscodingSessionController.h>
24#include <media/TranscodingUidPolicy.h>
25#include <utils/Log.h>
26
27#include <utility>
28
29namespace android {
30
31static_assert((SessionIdType)-1 < 0, "SessionIdType should be signed");
32
33constexpr static uid_t OFFLINE_UID = -1;
34
35//static
36String8 TranscodingSessionController::sessionToString(const SessionKeyType& sessionKey) {
37 return String8::format("{client:%lld, session:%d}", (long long)sessionKey.first,
38 sessionKey.second);
39}
40
41//static
42const char* TranscodingSessionController::sessionStateToString(const Session::State sessionState) {
43 switch (sessionState) {
44 case Session::State::NOT_STARTED:
45 return "NOT_STARTED";
46 case Session::State::RUNNING:
47 return "RUNNING";
48 case Session::State::PAUSED:
49 return "PAUSED";
50 default:
51 break;
52 }
53 return "(unknown)";
54}
55
56TranscodingSessionController::TranscodingSessionController(
57 const std::shared_ptr<TranscoderInterface>& transcoder,
58 const std::shared_ptr<UidPolicyInterface>& uidPolicy,
59 const std::shared_ptr<ResourcePolicyInterface>& resourcePolicy)
60 : mTranscoder(transcoder),
61 mUidPolicy(uidPolicy),
62 mResourcePolicy(resourcePolicy),
63 mCurrentSession(nullptr),
64 mResourceLost(false) {
65 // Only push empty offline queue initially. Realtime queues are added when requests come in.
66 mUidSortedList.push_back(OFFLINE_UID);
67 mOfflineUidIterator = mUidSortedList.begin();
68 mSessionQueues.emplace(OFFLINE_UID, SessionQueueType());
69}
70
71TranscodingSessionController::~TranscodingSessionController() {}
72
73void TranscodingSessionController::dumpAllSessions(int fd, const Vector<String16>& args __unused) {
74 String8 result;
75
76 const size_t SIZE = 256;
77 char buffer[SIZE];
78 std::scoped_lock lock{mLock};
79
80 snprintf(buffer, SIZE, "\n========== Dumping all sessions queues =========\n");
81 result.append(buffer);
82 snprintf(buffer, SIZE, " Total num of Sessions: %zu\n", mSessionMap.size());
83 result.append(buffer);
84
85 std::vector<int32_t> uids(mUidSortedList.begin(), mUidSortedList.end());
86 // Exclude last uid, which is for offline queue
87 uids.pop_back();
88 std::vector<std::string> packageNames;
89 if (TranscodingUidPolicy::getNamesForUids(uids, &packageNames)) {
90 uids.push_back(OFFLINE_UID);
91 packageNames.push_back("(offline)");
92 }
93
94 for (int32_t i = 0; i < uids.size(); i++) {
95 const uid_t uid = uids[i];
96
97 if (mSessionQueues[uid].empty()) {
98 continue;
99 }
100 snprintf(buffer, SIZE, " Uid: %d, pkg: %s\n", uid,
101 packageNames.empty() ? "(unknown)" : packageNames[i].c_str());
102 result.append(buffer);
103 snprintf(buffer, SIZE, " Num of sessions: %zu\n", mSessionQueues[uid].size());
104 result.append(buffer);
105 for (auto& sessionKey : mSessionQueues[uid]) {
106 auto sessionIt = mSessionMap.find(sessionKey);
107 if (sessionIt == mSessionMap.end()) {
108 snprintf(buffer, SIZE, "Failed to look up Session %s \n",
109 sessionToString(sessionKey).c_str());
110 result.append(buffer);
111 continue;
112 }
113 Session& session = sessionIt->second;
114 TranscodingRequestParcel& request = session.request;
115 snprintf(buffer, SIZE, " Session: %s, %s, %d%%\n",
116 sessionToString(sessionKey).c_str(), sessionStateToString(session.state),
117 session.lastProgress);
118 result.append(buffer);
119 snprintf(buffer, SIZE, " Src: %s\n", request.sourceFilePath.c_str());
120 result.append(buffer);
121 snprintf(buffer, SIZE, " Dst: %s\n", request.destinationFilePath.c_str());
122 result.append(buffer);
123 }
124 }
125
126 write(fd, result.string(), result.size());
127}
128
129TranscodingSessionController::Session* TranscodingSessionController::getTopSession_l() {
130 if (mSessionMap.empty()) {
131 return nullptr;
132 }
133 uid_t topUid = *mUidSortedList.begin();
134 SessionKeyType topSessionKey = *mSessionQueues[topUid].begin();
135 return &mSessionMap[topSessionKey];
136}
137
138void TranscodingSessionController::updateCurrentSession_l() {
139 Session* topSession = getTopSession_l();
140 Session* curSession = mCurrentSession;
141 ALOGV("updateCurrentSession: topSession is %s, curSession is %s",
142 topSession == nullptr ? "null" : sessionToString(topSession->key).c_str(),
143 curSession == nullptr ? "null" : sessionToString(curSession->key).c_str());
144
145 // If we found a topSession that should be run, and it's not already running,
146 // take some actions to ensure it's running.
147 if (topSession != nullptr &&
148 (topSession != curSession || topSession->state != Session::RUNNING)) {
149 // If another session is currently running, pause it first.
150 if (curSession != nullptr && curSession->state == Session::RUNNING) {
151 mTranscoder->pause(curSession->key.first, curSession->key.second);
152 curSession->state = Session::PAUSED;
153 }
154 // If we are not experiencing resource loss, we can start or resume
155 // the topSession now.
156 if (!mResourceLost) {
157 if (topSession->state == Session::NOT_STARTED) {
158 mTranscoder->start(topSession->key.first, topSession->key.second,
159 topSession->request, topSession->callback.lock());
160 } else if (topSession->state == Session::PAUSED) {
161 mTranscoder->resume(topSession->key.first, topSession->key.second,
162 topSession->request, topSession->callback.lock());
163 }
164 topSession->state = Session::RUNNING;
165 }
166 }
167 mCurrentSession = topSession;
168}
169
170void TranscodingSessionController::removeSession_l(const SessionKeyType& sessionKey) {
171 ALOGV("%s: session %s", __FUNCTION__, sessionToString(sessionKey).c_str());
172
173 if (mSessionMap.count(sessionKey) == 0) {
174 ALOGE("session %s doesn't exist", sessionToString(sessionKey).c_str());
175 return;
176 }
177
178 // Remove session from uid's queue.
179 const uid_t uid = mSessionMap[sessionKey].uid;
180 SessionQueueType& sessionQueue = mSessionQueues[uid];
181 auto it = std::find(sessionQueue.begin(), sessionQueue.end(), sessionKey);
182 if (it == sessionQueue.end()) {
183 ALOGE("couldn't find session %s in queue for uid %d", sessionToString(sessionKey).c_str(),
184 uid);
185 return;
186 }
187 sessionQueue.erase(it);
188
189 // If this is the last session in a real-time queue, remove this uid's queue.
190 if (uid != OFFLINE_UID && sessionQueue.empty()) {
191 mUidSortedList.remove(uid);
192 mSessionQueues.erase(uid);
193 mUidPolicy->unregisterMonitorUid(uid);
194
195 std::unordered_set<uid_t> topUids = mUidPolicy->getTopUids();
196 moveUidsToTop_l(topUids, false /*preserveTopUid*/);
197 }
198
199 // Clear current session.
200 if (mCurrentSession == &mSessionMap[sessionKey]) {
201 mCurrentSession = nullptr;
202 }
203
204 // Remove session from session map.
205 mSessionMap.erase(sessionKey);
206}
207
208/**
209 * Moves the set of uids to the front of mUidSortedList (which is used to pick
210 * the next session to run).
211 *
212 * This is called when 1) we received a onTopUidsChanged() callback from UidPolicy,
213 * or 2) we removed the session queue for a uid because it becomes empty.
214 *
215 * In case of 1), if there are multiple uids in the set, and the current front
216 * uid in mUidSortedList is still in the set, we try to keep that uid at front
217 * so that current session run is not interrupted. (This is not a concern for case 2)
218 * because the queue for a uid was just removed entirely.)
219 */
220void TranscodingSessionController::moveUidsToTop_l(const std::unordered_set<uid_t>& uids,
221 bool preserveTopUid) {
222 // If uid set is empty, nothing to do. Do not change the queue status.
223 if (uids.empty()) {
224 return;
225 }
226
227 // Save the current top uid.
228 uid_t curTopUid = *mUidSortedList.begin();
229 bool pushCurTopToFront = false;
230 int32_t numUidsMoved = 0;
231
232 // Go through the sorted uid list once, and move the ones in top set to front.
233 for (auto it = mUidSortedList.begin(); it != mUidSortedList.end();) {
234 uid_t uid = *it;
235
236 if (uid != OFFLINE_UID && uids.count(uid) > 0) {
237 it = mUidSortedList.erase(it);
238
239 // If this is the top we're preserving, don't push it here, push
240 // it after the for-loop.
241 if (uid == curTopUid && preserveTopUid) {
242 pushCurTopToFront = true;
243 } else {
244 mUidSortedList.push_front(uid);
245 }
246
247 // If we found all uids in the set, break out.
248 if (++numUidsMoved == uids.size()) {
249 break;
250 }
251 } else {
252 ++it;
253 }
254 }
255
256 if (pushCurTopToFront) {
257 mUidSortedList.push_front(curTopUid);
258 }
259}
260
261bool TranscodingSessionController::submit(
262 ClientIdType clientId, SessionIdType sessionId, uid_t uid,
263 const TranscodingRequestParcel& request,
264 const std::weak_ptr<ITranscodingClientCallback>& callback) {
265 SessionKeyType sessionKey = std::make_pair(clientId, sessionId);
266
267 ALOGV("%s: session %s, uid %d, prioirty %d", __FUNCTION__, sessionToString(sessionKey).c_str(),
268 uid, (int32_t)request.priority);
269
270 std::scoped_lock lock{mLock};
271
272 if (mSessionMap.count(sessionKey) > 0) {
273 ALOGE("session %s already exists", sessionToString(sessionKey).c_str());
274 return false;
275 }
276
277 // TODO(chz): only support offline vs real-time for now. All kUnspecified sessions
278 // go to offline queue.
279 if (request.priority == TranscodingSessionPriority::kUnspecified) {
280 uid = OFFLINE_UID;
281 }
282
283 // Add session to session map.
284 mSessionMap[sessionKey].key = sessionKey;
285 mSessionMap[sessionKey].uid = uid;
286 mSessionMap[sessionKey].state = Session::NOT_STARTED;
287 mSessionMap[sessionKey].lastProgress = 0;
288 mSessionMap[sessionKey].request = request;
289 mSessionMap[sessionKey].callback = callback;
290
291 // If it's an offline session, the queue was already added in constructor.
292 // If it's a real-time sessions, check if a queue is already present for the uid,
293 // and add a new queue if needed.
294 if (uid != OFFLINE_UID) {
295 if (mSessionQueues.count(uid) == 0) {
296 mUidPolicy->registerMonitorUid(uid);
297 if (mUidPolicy->isUidOnTop(uid)) {
298 mUidSortedList.push_front(uid);
299 } else {
300 // Shouldn't be submitting real-time requests from non-top app,
301 // put it in front of the offline queue.
302 mUidSortedList.insert(mOfflineUidIterator, uid);
303 }
304 } else if (uid != *mUidSortedList.begin()) {
305 if (mUidPolicy->isUidOnTop(uid)) {
306 mUidSortedList.remove(uid);
307 mUidSortedList.push_front(uid);
308 }
309 }
310 }
311 // Append this session to the uid's queue.
312 mSessionQueues[uid].push_back(sessionKey);
313
314 updateCurrentSession_l();
315
316 validateState_l();
317 return true;
318}
319
320bool TranscodingSessionController::cancel(ClientIdType clientId, SessionIdType sessionId) {
321 SessionKeyType sessionKey = std::make_pair(clientId, sessionId);
322
323 ALOGV("%s: session %s", __FUNCTION__, sessionToString(sessionKey).c_str());
324
325 std::list<SessionKeyType> sessionsToRemove;
326
327 std::scoped_lock lock{mLock};
328
329 if (sessionId < 0) {
330 for (auto it = mSessionMap.begin(); it != mSessionMap.end(); ++it) {
331 if (it->first.first == clientId && it->second.uid != OFFLINE_UID) {
332 sessionsToRemove.push_back(it->first);
333 }
334 }
335 } else {
336 if (mSessionMap.count(sessionKey) == 0) {
337 ALOGE("session %s doesn't exist", sessionToString(sessionKey).c_str());
338 return false;
339 }
340 sessionsToRemove.push_back(sessionKey);
341 }
342
343 for (auto it = sessionsToRemove.begin(); it != sessionsToRemove.end(); ++it) {
344 // If the session has ever been started, stop it now.
345 // Note that stop() is needed even if the session is currently paused. This instructs
346 // the transcoder to discard any states for the session, otherwise the states may
347 // never be discarded.
348 if (mSessionMap[*it].state != Session::NOT_STARTED) {
349 mTranscoder->stop(it->first, it->second);
350 }
351
352 // Remove the session.
353 removeSession_l(*it);
354 }
355
356 // Start next session.
357 updateCurrentSession_l();
358
359 validateState_l();
360 return true;
361}
362
363bool TranscodingSessionController::getSession(ClientIdType clientId, SessionIdType sessionId,
364 TranscodingRequestParcel* request) {
365 SessionKeyType sessionKey = std::make_pair(clientId, sessionId);
366
367 std::scoped_lock lock{mLock};
368
369 if (mSessionMap.count(sessionKey) == 0) {
370 ALOGE("session %s doesn't exist", sessionToString(sessionKey).c_str());
371 return false;
372 }
373
374 *(TranscodingRequest*)request = mSessionMap[sessionKey].request;
375 return true;
376}
377
378void TranscodingSessionController::notifyClient(ClientIdType clientId, SessionIdType sessionId,
379 const char* reason,
380 std::function<void(const SessionKeyType&)> func) {
381 SessionKeyType sessionKey = std::make_pair(clientId, sessionId);
382
383 std::scoped_lock lock{mLock};
384
385 if (mSessionMap.count(sessionKey) == 0) {
386 ALOGW("%s: ignoring %s for session %s that doesn't exist", __FUNCTION__, reason,
387 sessionToString(sessionKey).c_str());
388 return;
389 }
390
391 // Only ignore if session was never started. In particular, propagate the status
392 // to client if the session is paused. Transcoder could have posted finish when
393 // we're pausing it, and the finish arrived after we changed current session.
394 if (mSessionMap[sessionKey].state == Session::NOT_STARTED) {
395 ALOGW("%s: ignoring %s for session %s that was never started", __FUNCTION__, reason,
396 sessionToString(sessionKey).c_str());
397 return;
398 }
399
400 ALOGV("%s: session %s %s", __FUNCTION__, sessionToString(sessionKey).c_str(), reason);
401 func(sessionKey);
402}
403
404void TranscodingSessionController::onStarted(ClientIdType clientId, SessionIdType sessionId) {
405 notifyClient(clientId, sessionId, "started", [=](const SessionKeyType& sessionKey) {
406 auto callback = mSessionMap[sessionKey].callback.lock();
407 if (callback != nullptr) {
408 callback->onTranscodingStarted(sessionId);
409 }
410 });
411}
412
413void TranscodingSessionController::onPaused(ClientIdType clientId, SessionIdType sessionId) {
414 notifyClient(clientId, sessionId, "paused", [=](const SessionKeyType& sessionKey) {
415 auto callback = mSessionMap[sessionKey].callback.lock();
416 if (callback != nullptr) {
417 callback->onTranscodingPaused(sessionId);
418 }
419 });
420}
421
422void TranscodingSessionController::onResumed(ClientIdType clientId, SessionIdType sessionId) {
423 notifyClient(clientId, sessionId, "resumed", [=](const SessionKeyType& sessionKey) {
424 auto callback = mSessionMap[sessionKey].callback.lock();
425 if (callback != nullptr) {
426 callback->onTranscodingResumed(sessionId);
427 }
428 });
429}
430
431void TranscodingSessionController::onFinish(ClientIdType clientId, SessionIdType sessionId) {
432 notifyClient(clientId, sessionId, "finish", [=](const SessionKeyType& sessionKey) {
433 {
434 auto clientCallback = mSessionMap[sessionKey].callback.lock();
435 if (clientCallback != nullptr) {
436 clientCallback->onTranscodingFinished(
437 sessionId, TranscodingResultParcel({sessionId, -1 /*actualBitrateBps*/,
438 std::nullopt /*sessionStats*/}));
439 }
440 }
441
442 // Remove the session.
443 removeSession_l(sessionKey);
444
445 // Start next session.
446 updateCurrentSession_l();
447
448 validateState_l();
449 });
450}
451
452void TranscodingSessionController::onError(ClientIdType clientId, SessionIdType sessionId,
453 TranscodingErrorCode err) {
454 notifyClient(clientId, sessionId, "error", [=](const SessionKeyType& sessionKey) {
455 {
456 auto clientCallback = mSessionMap[sessionKey].callback.lock();
457 if (clientCallback != nullptr) {
458 clientCallback->onTranscodingFailed(sessionId, err);
459 }
460 }
461
462 // Remove the session.
463 removeSession_l(sessionKey);
464
465 // Start next session.
466 updateCurrentSession_l();
467
468 validateState_l();
469 });
470}
471
472void TranscodingSessionController::onProgressUpdate(ClientIdType clientId, SessionIdType sessionId,
473 int32_t progress) {
474 notifyClient(clientId, sessionId, "progress", [=](const SessionKeyType& sessionKey) {
475 auto callback = mSessionMap[sessionKey].callback.lock();
476 if (callback != nullptr) {
477 callback->onProgressUpdate(sessionId, progress);
478 }
479 mSessionMap[sessionKey].lastProgress = progress;
480 });
481}
482
483void TranscodingSessionController::onResourceLost() {
484 ALOGI("%s", __FUNCTION__);
485
486 std::scoped_lock lock{mLock};
487
488 if (mResourceLost) {
489 return;
490 }
491
492 // If we receive a resource loss event, the TranscoderLibrary already paused
493 // the transcoding, so we don't need to call onPaused to notify it to pause.
494 // Only need to update the session state here.
495 if (mCurrentSession != nullptr && mCurrentSession->state == Session::RUNNING) {
496 mCurrentSession->state = Session::PAUSED;
497 // Notify the client as a paused event.
498 auto clientCallback = mCurrentSession->callback.lock();
499 if (clientCallback != nullptr) {
500 clientCallback->onTranscodingPaused(mCurrentSession->key.second);
501 }
502 }
503 mResourceLost = true;
504
505 validateState_l();
506}
507
508void TranscodingSessionController::onTopUidsChanged(const std::unordered_set<uid_t>& uids) {
509 if (uids.empty()) {
510 ALOGW("%s: ignoring empty uids", __FUNCTION__);
511 return;
512 }
513
514 std::string uidStr;
515 for (auto it = uids.begin(); it != uids.end(); it++) {
516 if (!uidStr.empty()) {
517 uidStr += ", ";
518 }
519 uidStr += std::to_string(*it);
520 }
521
522 ALOGD("%s: topUids: size %zu, uids: %s", __FUNCTION__, uids.size(), uidStr.c_str());
523
524 std::scoped_lock lock{mLock};
525
526 moveUidsToTop_l(uids, true /*preserveTopUid*/);
527
528 updateCurrentSession_l();
529
530 validateState_l();
531}
532
533void TranscodingSessionController::onResourceAvailable() {
534 std::scoped_lock lock{mLock};
535
536 if (!mResourceLost) {
537 return;
538 }
539
540 ALOGI("%s", __FUNCTION__);
541
542 mResourceLost = false;
543 updateCurrentSession_l();
544
545 validateState_l();
546}
547
548void TranscodingSessionController::validateState_l() {
549#ifdef VALIDATE_STATE
550 LOG_ALWAYS_FATAL_IF(mSessionQueues.count(OFFLINE_UID) != 1,
551 "mSessionQueues offline queue number is not 1");
552 LOG_ALWAYS_FATAL_IF(*mOfflineUidIterator != OFFLINE_UID,
553 "mOfflineUidIterator not pointing to offline uid");
554 LOG_ALWAYS_FATAL_IF(mUidSortedList.size() != mSessionQueues.size(),
555 "mUidList and mSessionQueues size mismatch");
556
557 int32_t totalSessions = 0;
558 for (auto uid : mUidSortedList) {
559 LOG_ALWAYS_FATAL_IF(mSessionQueues.count(uid) != 1,
560 "mSessionQueues count for uid %d is not 1", uid);
561 for (auto& sessionKey : mSessionQueues[uid]) {
562 LOG_ALWAYS_FATAL_IF(mSessionMap.count(sessionKey) != 1,
563 "mSessions count for session %s is not 1",
564 sessionToString(sessionKey).c_str());
565 }
566
567 totalSessions += mSessionQueues[uid].size();
568 }
569 LOG_ALWAYS_FATAL_IF(mSessionMap.size() != totalSessions,
570 "mSessions size doesn't match total sessions counted from uid queues");
571#endif // VALIDATE_STATE
572}
573
574} // namespace android