blob: e6dc7ad33f24618b45ff7f1f6d38fbb37130e42d [file] [log] [blame]
Chong Zhang6d58e4b2020-03-31 09:41:10 -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
Chong Zhangacb33502020-04-20 11:04:48 -070017//#define LOG_NDEBUG 0
Chong Zhang6d58e4b2020-03-31 09:41:10 -070018#define LOG_TAG "TranscodingJobScheduler"
19
20#define VALIDATE_STATE 1
21
22#include <inttypes.h>
23#include <media/TranscodingJobScheduler.h>
24#include <utils/Log.h>
25
26#include <utility>
27
28namespace android {
29
Chong Zhang15c192a2020-05-05 16:24:00 -070030static_assert((JobIdType)-1 < 0, "JobIdType should be signed");
31
Chong Zhang7ae4e2f2020-04-17 15:24:34 -070032constexpr static uid_t OFFLINE_UID = -1;
Chong Zhang6d58e4b2020-03-31 09:41:10 -070033
34//static
35String8 TranscodingJobScheduler::jobToString(const JobKeyType& jobKey) {
36 return String8::format("{client:%lld, job:%d}", (long long)jobKey.first, jobKey.second);
37}
38
39TranscodingJobScheduler::TranscodingJobScheduler(
40 const std::shared_ptr<TranscoderInterface>& transcoder,
Chong Zhang7ae4e2f2020-04-17 15:24:34 -070041 const std::shared_ptr<UidPolicyInterface>& uidPolicy)
42 : mTranscoder(transcoder), mUidPolicy(uidPolicy), mCurrentJob(nullptr), mResourceLost(false) {
Chong Zhang6d58e4b2020-03-31 09:41:10 -070043 // Only push empty offline queue initially. Realtime queues are added when requests come in.
Chong Zhang7ae4e2f2020-04-17 15:24:34 -070044 mUidSortedList.push_back(OFFLINE_UID);
45 mOfflineUidIterator = mUidSortedList.begin();
46 mJobQueues.emplace(OFFLINE_UID, JobQueueType());
Chong Zhang6d58e4b2020-03-31 09:41:10 -070047}
48
49TranscodingJobScheduler::~TranscodingJobScheduler() {}
50
51TranscodingJobScheduler::Job* TranscodingJobScheduler::getTopJob_l() {
52 if (mJobMap.empty()) {
53 return nullptr;
54 }
Chong Zhang7ae4e2f2020-04-17 15:24:34 -070055 uid_t topUid = *mUidSortedList.begin();
56 JobKeyType topJobKey = *mJobQueues[topUid].begin();
Chong Zhang6d58e4b2020-03-31 09:41:10 -070057 return &mJobMap[topJobKey];
58}
59
60void TranscodingJobScheduler::updateCurrentJob_l() {
61 Job* topJob = getTopJob_l();
62 Job* curJob = mCurrentJob;
63 ALOGV("updateCurrentJob: topJob is %s, curJob is %s",
64 topJob == nullptr ? "null" : jobToString(topJob->key).c_str(),
65 curJob == nullptr ? "null" : jobToString(curJob->key).c_str());
66
67 // If we found a topJob that should be run, and it's not already running,
68 // take some actions to ensure it's running.
69 if (topJob != nullptr && (topJob != curJob || topJob->state != Job::RUNNING)) {
70 // If another job is currently running, pause it first.
71 if (curJob != nullptr && curJob->state == Job::RUNNING) {
72 mTranscoder->pause(curJob->key.first, curJob->key.second);
73 curJob->state = Job::PAUSED;
74 }
75 // If we are not experiencing resource loss, we can start or resume
76 // the topJob now.
77 if (!mResourceLost) {
78 if (topJob->state == Job::NOT_STARTED) {
Chong Zhang9087f772020-06-10 11:58:40 -070079 mTranscoder->start(topJob->key.first, topJob->key.second, topJob->request);
Chong Zhang6d58e4b2020-03-31 09:41:10 -070080 } else if (topJob->state == Job::PAUSED) {
81 mTranscoder->resume(topJob->key.first, topJob->key.second);
82 }
83 topJob->state = Job::RUNNING;
84 }
85 }
86 mCurrentJob = topJob;
87}
88
89void TranscodingJobScheduler::removeJob_l(const JobKeyType& jobKey) {
90 ALOGV("%s: job %s", __FUNCTION__, jobToString(jobKey).c_str());
91
92 if (mJobMap.count(jobKey) == 0) {
93 ALOGE("job %s doesn't exist", jobToString(jobKey).c_str());
94 return;
95 }
96
Chong Zhang7ae4e2f2020-04-17 15:24:34 -070097 // Remove job from uid's queue.
98 const uid_t uid = mJobMap[jobKey].uid;
99 JobQueueType& jobQueue = mJobQueues[uid];
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700100 auto it = std::find(jobQueue.begin(), jobQueue.end(), jobKey);
101 if (it == jobQueue.end()) {
Chong Zhang7ae4e2f2020-04-17 15:24:34 -0700102 ALOGE("couldn't find job %s in queue for uid %d", jobToString(jobKey).c_str(), uid);
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700103 return;
104 }
105 jobQueue.erase(it);
106
Chong Zhang7ae4e2f2020-04-17 15:24:34 -0700107 // If this is the last job in a real-time queue, remove this uid's queue.
108 if (uid != OFFLINE_UID && jobQueue.empty()) {
109 mUidSortedList.remove(uid);
110 mJobQueues.erase(uid);
Chong Zhangacb33502020-04-20 11:04:48 -0700111 mUidPolicy->unregisterMonitorUid(uid);
112
113 std::unordered_set<uid_t> topUids = mUidPolicy->getTopUids();
114 moveUidsToTop_l(topUids, false /*preserveTopUid*/);
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700115 }
116
117 // Clear current job.
118 if (mCurrentJob == &mJobMap[jobKey]) {
119 mCurrentJob = nullptr;
120 }
121
122 // Remove job from job map.
123 mJobMap.erase(jobKey);
124}
125
Chong Zhangacb33502020-04-20 11:04:48 -0700126/**
127 * Moves the set of uids to the front of mUidSortedList (which is used to pick
128 * the next job to run).
129 *
130 * This is called when 1) we received a onTopUidsChanged() callbcak from UidPolicy,
131 * or 2) we removed the job queue for a uid because it becomes empty.
132 *
133 * In case of 1), if there are multiple uids in the set, and the current front
134 * uid in mUidSortedList is still in the set, we try to keep that uid at front
135 * so that current job run is not interrupted. (This is not a concern for case 2)
136 * because the queue for a uid was just removed entirely.)
137 */
138void TranscodingJobScheduler::moveUidsToTop_l(const std::unordered_set<uid_t>& uids,
139 bool preserveTopUid) {
140 // If uid set is empty, nothing to do. Do not change the queue status.
141 if (uids.empty()) {
142 return;
143 }
144
145 // Save the current top uid.
146 uid_t curTopUid = *mUidSortedList.begin();
147 bool pushCurTopToFront = false;
148 int32_t numUidsMoved = 0;
149
150 // Go through the sorted uid list once, and move the ones in top set to front.
151 for (auto it = mUidSortedList.begin(); it != mUidSortedList.end();) {
152 uid_t uid = *it;
153
154 if (uid != OFFLINE_UID && uids.count(uid) > 0) {
155 it = mUidSortedList.erase(it);
156
157 // If this is the top we're preserving, don't push it here, push
158 // it after the for-loop.
159 if (uid == curTopUid && preserveTopUid) {
160 pushCurTopToFront = true;
161 } else {
162 mUidSortedList.push_front(uid);
163 }
164
165 // If we found all uids in the set, break out.
166 if (++numUidsMoved == uids.size()) {
167 break;
168 }
169 } else {
170 ++it;
171 }
172 }
173
174 if (pushCurTopToFront) {
175 mUidSortedList.push_front(curTopUid);
176 }
177}
178
Chong Zhang3fa408f2020-04-30 11:04:28 -0700179bool TranscodingJobScheduler::submit(ClientIdType clientId, JobIdType jobId, uid_t uid,
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700180 const TranscodingRequestParcel& request,
181 const std::weak_ptr<ITranscodingClientCallback>& callback) {
182 JobKeyType jobKey = std::make_pair(clientId, jobId);
183
Chong Zhang7ae4e2f2020-04-17 15:24:34 -0700184 ALOGV("%s: job %s, uid %d, prioirty %d", __FUNCTION__, jobToString(jobKey).c_str(), uid,
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700185 (int32_t)request.priority);
186
187 std::scoped_lock lock{mLock};
188
189 if (mJobMap.count(jobKey) > 0) {
190 ALOGE("job %s already exists", jobToString(jobKey).c_str());
191 return false;
192 }
193
194 // TODO(chz): only support offline vs real-time for now. All kUnspecified jobs
195 // go to offline queue.
196 if (request.priority == TranscodingJobPriority::kUnspecified) {
Chong Zhang7ae4e2f2020-04-17 15:24:34 -0700197 uid = OFFLINE_UID;
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700198 }
199
200 // Add job to job map.
201 mJobMap[jobKey].key = jobKey;
Chong Zhang7ae4e2f2020-04-17 15:24:34 -0700202 mJobMap[jobKey].uid = uid;
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700203 mJobMap[jobKey].state = Job::NOT_STARTED;
204 mJobMap[jobKey].request = request;
205 mJobMap[jobKey].callback = callback;
206
207 // If it's an offline job, the queue was already added in constructor.
Chong Zhang7ae4e2f2020-04-17 15:24:34 -0700208 // If it's a real-time jobs, check if a queue is already present for the uid,
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700209 // and add a new queue if needed.
Chong Zhang7ae4e2f2020-04-17 15:24:34 -0700210 if (uid != OFFLINE_UID) {
211 if (mJobQueues.count(uid) == 0) {
Chong Zhangacb33502020-04-20 11:04:48 -0700212 mUidPolicy->registerMonitorUid(uid);
Chong Zhang7ae4e2f2020-04-17 15:24:34 -0700213 if (mUidPolicy->isUidOnTop(uid)) {
214 mUidSortedList.push_front(uid);
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700215 } else {
216 // Shouldn't be submitting real-time requests from non-top app,
217 // put it in front of the offline queue.
Chong Zhang7ae4e2f2020-04-17 15:24:34 -0700218 mUidSortedList.insert(mOfflineUidIterator, uid);
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700219 }
Chong Zhang7ae4e2f2020-04-17 15:24:34 -0700220 } else if (uid != *mUidSortedList.begin()) {
221 if (mUidPolicy->isUidOnTop(uid)) {
222 mUidSortedList.remove(uid);
223 mUidSortedList.push_front(uid);
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700224 }
225 }
226 }
Chong Zhang7ae4e2f2020-04-17 15:24:34 -0700227 // Append this job to the uid's queue.
228 mJobQueues[uid].push_back(jobKey);
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700229
230 updateCurrentJob_l();
231
232 validateState_l();
233 return true;
234}
235
Chong Zhang3fa408f2020-04-30 11:04:28 -0700236bool TranscodingJobScheduler::cancel(ClientIdType clientId, JobIdType jobId) {
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700237 JobKeyType jobKey = std::make_pair(clientId, jobId);
238
239 ALOGV("%s: job %s", __FUNCTION__, jobToString(jobKey).c_str());
240
Chong Zhang15c192a2020-05-05 16:24:00 -0700241 std::list<JobKeyType> jobsToRemove;
242
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700243 std::scoped_lock lock{mLock};
244
Chong Zhang15c192a2020-05-05 16:24:00 -0700245 if (jobId < 0) {
246 for (auto it = mJobMap.begin(); it != mJobMap.end(); ++it) {
247 if (it->first.first == clientId && it->second.uid != OFFLINE_UID) {
248 jobsToRemove.push_back(it->first);
249 }
250 }
251 } else {
252 if (mJobMap.count(jobKey) == 0) {
253 ALOGE("job %s doesn't exist", jobToString(jobKey).c_str());
254 return false;
255 }
256 jobsToRemove.push_back(jobKey);
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700257 }
258
Chong Zhang15c192a2020-05-05 16:24:00 -0700259 for (auto it = jobsToRemove.begin(); it != jobsToRemove.end(); ++it) {
Chong Zhang00feca22020-05-08 15:02:06 -0700260 // If the job has ever been started, stop it now.
261 // Note that stop() is needed even if the job is currently paused. This instructs
262 // the transcoder to discard any states for the job, otherwise the states may
263 // never be discarded.
264 if (mJobMap[*it].state != Job::NOT_STARTED) {
265 mTranscoder->stop(it->first, it->second);
Chong Zhang15c192a2020-05-05 16:24:00 -0700266 }
267
268 // Remove the job.
269 removeJob_l(*it);
270 }
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700271
272 // Start next job.
273 updateCurrentJob_l();
274
275 validateState_l();
276 return true;
277}
278
Chong Zhang3fa408f2020-04-30 11:04:28 -0700279bool TranscodingJobScheduler::getJob(ClientIdType clientId, JobIdType jobId,
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700280 TranscodingRequestParcel* request) {
281 JobKeyType jobKey = std::make_pair(clientId, jobId);
282
283 std::scoped_lock lock{mLock};
284
285 if (mJobMap.count(jobKey) == 0) {
286 ALOGE("job %s doesn't exist", jobToString(jobKey).c_str());
287 return false;
288 }
289
290 *(TranscodingRequest*)request = mJobMap[jobKey].request;
291 return true;
292}
293
Chong Zhang3fa408f2020-04-30 11:04:28 -0700294void TranscodingJobScheduler::onFinish(ClientIdType clientId, JobIdType jobId) {
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700295 JobKeyType jobKey = std::make_pair(clientId, jobId);
296
297 ALOGV("%s: job %s", __FUNCTION__, jobToString(jobKey).c_str());
298
299 std::scoped_lock lock{mLock};
300
301 if (mJobMap.count(jobKey) == 0) {
Chong Zhangacb33502020-04-20 11:04:48 -0700302 ALOGW("ignoring finish for non-existent job");
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700303 return;
304 }
305
306 // Only ignore if job was never started. In particular, propagate the status
307 // to client if the job is paused. Transcoder could have posted finish when
308 // we're pausing it, and the finish arrived after we changed current job.
309 if (mJobMap[jobKey].state == Job::NOT_STARTED) {
Chong Zhangacb33502020-04-20 11:04:48 -0700310 ALOGW("ignoring finish for job that was never started");
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700311 return;
312 }
313
314 {
315 auto clientCallback = mJobMap[jobKey].callback.lock();
316 if (clientCallback != nullptr) {
317 clientCallback->onTranscodingFinished(jobId, TranscodingResultParcel({jobId, 0}));
318 }
319 }
320
321 // Remove the job.
322 removeJob_l(jobKey);
323
324 // Start next job.
325 updateCurrentJob_l();
326
327 validateState_l();
328}
329
Chong Zhang3fa408f2020-04-30 11:04:28 -0700330void TranscodingJobScheduler::onError(ClientIdType clientId, JobIdType jobId,
331 TranscodingErrorCode err) {
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700332 JobKeyType jobKey = std::make_pair(clientId, jobId);
333
334 ALOGV("%s: job %s, err %d", __FUNCTION__, jobToString(jobKey).c_str(), (int32_t)err);
335
336 std::scoped_lock lock{mLock};
337
338 if (mJobMap.count(jobKey) == 0) {
Chong Zhangacb33502020-04-20 11:04:48 -0700339 ALOGW("ignoring error for non-existent job");
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700340 return;
341 }
342
343 // Only ignore if job was never started. In particular, propagate the status
344 // to client if the job is paused. Transcoder could have posted finish when
345 // we're pausing it, and the finish arrived after we changed current job.
346 if (mJobMap[jobKey].state == Job::NOT_STARTED) {
Chong Zhangacb33502020-04-20 11:04:48 -0700347 ALOGW("ignoring error for job that was never started");
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700348 return;
349 }
350
351 {
352 auto clientCallback = mJobMap[jobKey].callback.lock();
353 if (clientCallback != nullptr) {
354 clientCallback->onTranscodingFailed(jobId, err);
355 }
356 }
357
358 // Remove the job.
359 removeJob_l(jobKey);
360
361 // Start next job.
362 updateCurrentJob_l();
363
364 validateState_l();
365}
366
Chong Zhang3fa408f2020-04-30 11:04:28 -0700367void TranscodingJobScheduler::onProgressUpdate(ClientIdType clientId, JobIdType jobId,
368 int32_t progress) {
Chong Zhangacb33502020-04-20 11:04:48 -0700369 JobKeyType jobKey = std::make_pair(clientId, jobId);
370
371 ALOGV("%s: job %s, progress %d", __FUNCTION__, jobToString(jobKey).c_str(), progress);
372
373 std::scoped_lock lock{mLock};
374
375 if (mJobMap.count(jobKey) == 0) {
376 ALOGW("ignoring progress for non-existent job");
377 return;
378 }
379
380 // Only ignore if job was never started. In particular, propagate the status
381 // to client if the job is paused. Transcoder could have posted finish when
382 // we're pausing it, and the finish arrived after we changed current job.
383 if (mJobMap[jobKey].state == Job::NOT_STARTED) {
384 ALOGW("ignoring progress for job that was never started");
385 return;
386 }
387
388 {
389 auto clientCallback = mJobMap[jobKey].callback.lock();
390 if (clientCallback != nullptr) {
391 clientCallback->onProgressUpdate(jobId, progress);
392 }
393 }
394}
395
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700396void TranscodingJobScheduler::onResourceLost() {
397 ALOGV("%s", __FUNCTION__);
398
399 std::scoped_lock lock{mLock};
400
401 // If we receive a resource loss event, the TranscoderLibrary already paused
402 // the transcoding, so we don't need to call onPaused to notify it to pause.
403 // Only need to update the job state here.
404 if (mCurrentJob != nullptr && mCurrentJob->state == Job::RUNNING) {
405 mCurrentJob->state = Job::PAUSED;
406 }
407 mResourceLost = true;
408
409 validateState_l();
410}
411
Chong Zhangacb33502020-04-20 11:04:48 -0700412void TranscodingJobScheduler::onTopUidsChanged(const std::unordered_set<uid_t>& uids) {
413 if (uids.empty()) {
414 ALOGW("%s: ignoring empty uids", __FUNCTION__);
415 return;
416 }
417
418 std::string uidStr;
419 for (auto it = uids.begin(); it != uids.end(); it++) {
420 if (!uidStr.empty()) {
421 uidStr += ", ";
422 }
423 uidStr += std::to_string(*it);
424 }
425
426 ALOGD("%s: topUids: size %zu, uids: %s", __FUNCTION__, uids.size(), uidStr.c_str());
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700427
428 std::scoped_lock lock{mLock};
429
Chong Zhangacb33502020-04-20 11:04:48 -0700430 moveUidsToTop_l(uids, true /*preserveTopUid*/);
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700431
432 updateCurrentJob_l();
433
434 validateState_l();
435}
436
437void TranscodingJobScheduler::onResourceAvailable() {
438 ALOGV("%s", __FUNCTION__);
439
440 std::scoped_lock lock{mLock};
441
442 mResourceLost = false;
443 updateCurrentJob_l();
444
445 validateState_l();
446}
447
448void TranscodingJobScheduler::validateState_l() {
449#ifdef VALIDATE_STATE
Chong Zhang7ae4e2f2020-04-17 15:24:34 -0700450 LOG_ALWAYS_FATAL_IF(mJobQueues.count(OFFLINE_UID) != 1,
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700451 "mJobQueues offline queue number is not 1");
Chong Zhang7ae4e2f2020-04-17 15:24:34 -0700452 LOG_ALWAYS_FATAL_IF(*mOfflineUidIterator != OFFLINE_UID,
453 "mOfflineUidIterator not pointing to offline uid");
454 LOG_ALWAYS_FATAL_IF(mUidSortedList.size() != mJobQueues.size(),
455 "mUidList and mJobQueues size mismatch");
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700456
457 int32_t totalJobs = 0;
Chong Zhang7ae4e2f2020-04-17 15:24:34 -0700458 for (auto uidIt = mUidSortedList.begin(); uidIt != mUidSortedList.end(); uidIt++) {
459 LOG_ALWAYS_FATAL_IF(mJobQueues.count(*uidIt) != 1, "mJobQueues count for uid %d is not 1",
460 *uidIt);
461 for (auto jobIt = mJobQueues[*uidIt].begin(); jobIt != mJobQueues[*uidIt].end(); jobIt++) {
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700462 LOG_ALWAYS_FATAL_IF(mJobMap.count(*jobIt) != 1, "mJobs count for job %s is not 1",
463 jobToString(*jobIt).c_str());
464 }
465
Chong Zhang7ae4e2f2020-04-17 15:24:34 -0700466 totalJobs += mJobQueues[*uidIt].size();
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700467 }
468 LOG_ALWAYS_FATAL_IF(mJobMap.size() != totalJobs,
Chong Zhang7ae4e2f2020-04-17 15:24:34 -0700469 "mJobs size doesn't match total jobs counted from uid queues");
Chong Zhang6d58e4b2020-03-31 09:41:10 -0700470#endif // VALIDATE_STATE
471}
472
473} // namespace android