NuPlayer2Decoder.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315
  1. /*
  2. * Copyright 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. //#define LOG_NDEBUG 0
  17. #define LOG_TAG "NuPlayer2Decoder"
  18. #include <utils/Log.h>
  19. #include <inttypes.h>
  20. #include <algorithm>
  21. #include "NuPlayer2CCDecoder.h"
  22. #include "NuPlayer2Decoder.h"
  23. #include "NuPlayer2Drm.h"
  24. #include "NuPlayer2Renderer.h"
  25. #include "NuPlayer2Source.h"
  26. #include <cutils/properties.h>
  27. #include <media/MediaBufferHolder.h>
  28. #include <media/MediaCodecBuffer.h>
  29. #include <media/NdkMediaCodec.h>
  30. #include <media/NdkWrapper.h>
  31. #include <media/stagefright/foundation/ABuffer.h>
  32. #include <media/stagefright/foundation/ADebug.h>
  33. #include <media/stagefright/foundation/AMessage.h>
  34. #include <media/stagefright/foundation/avc_utils.h>
  35. #include <media/stagefright/MediaBuffer.h>
  36. #include <media/stagefright/MediaDefs.h>
  37. #include <media/stagefright/MediaErrors.h>
  38. #include <media/stagefright/SurfaceUtils.h>
  39. #include <system/window.h>
  40. #include "ATSParser.h"
  41. namespace android {
  42. static float kDisplayRefreshingRate = 60.f; // TODO: get this from the display
  43. // The default total video frame rate of a stream when that info is not available from
  44. // the source.
  45. static float kDefaultVideoFrameRateTotal = 30.f;
  46. static inline bool getAudioDeepBufferSetting() {
  47. return property_get_bool("media.stagefright.audio.deep", false /* default_value */);
  48. }
  49. NuPlayer2::Decoder::Decoder(
  50. const sp<AMessage> &notify,
  51. const sp<Source> &source,
  52. pid_t pid,
  53. uid_t uid,
  54. const sp<Renderer> &renderer,
  55. const sp<ANativeWindowWrapper> &nww,
  56. const sp<CCDecoder> &ccDecoder)
  57. : DecoderBase(notify),
  58. mNativeWindow(nww),
  59. mSource(source),
  60. mRenderer(renderer),
  61. mCCDecoder(ccDecoder),
  62. mPid(pid),
  63. mUid(uid),
  64. mSkipRenderingUntilMediaTimeUs(-1LL),
  65. mNumFramesTotal(0LL),
  66. mNumInputFramesDropped(0LL),
  67. mNumOutputFramesDropped(0LL),
  68. mVideoWidth(0),
  69. mVideoHeight(0),
  70. mIsAudio(true),
  71. mIsVideoAVC(false),
  72. mIsSecure(false),
  73. mIsEncrypted(false),
  74. mIsEncryptedObservedEarlier(false),
  75. mFormatChangePending(false),
  76. mTimeChangePending(false),
  77. mFrameRateTotal(kDefaultVideoFrameRateTotal),
  78. mPlaybackSpeed(1.0f),
  79. mNumVideoTemporalLayerTotal(1), // decode all layers
  80. mNumVideoTemporalLayerAllowed(1),
  81. mCurrentMaxVideoTemporalLayerId(0),
  82. mResumePending(false),
  83. mComponentName("decoder") {
  84. mVideoTemporalLayerAggregateFps[0] = mFrameRateTotal;
  85. }
  86. NuPlayer2::Decoder::~Decoder() {
  87. // Need to stop looper first since mCodec could be accessed on the mDecoderLooper.
  88. stopLooper();
  89. if (mCodec != NULL) {
  90. mCodec->release();
  91. }
  92. releaseAndResetMediaBuffers();
  93. }
  94. sp<AMessage> NuPlayer2::Decoder::getStats() const {
  95. mStats->setInt64("frames-total", mNumFramesTotal);
  96. mStats->setInt64("frames-dropped-input", mNumInputFramesDropped);
  97. mStats->setInt64("frames-dropped-output", mNumOutputFramesDropped);
  98. mStats->setFloat("frame-rate-total", mFrameRateTotal);
  99. // i'm mutexed right now.
  100. // make our own copy, so we aren't victim to any later changes.
  101. sp<AMessage> copiedStats = mStats->dup();
  102. return copiedStats;
  103. }
  104. status_t NuPlayer2::Decoder::setVideoSurface(const sp<ANativeWindowWrapper> &nww) {
  105. if (nww == NULL || nww->getANativeWindow() == NULL
  106. || ADebug::isExperimentEnabled("legacy-setsurface")) {
  107. return BAD_VALUE;
  108. }
  109. sp<AMessage> msg = new AMessage(kWhatSetVideoSurface, this);
  110. msg->setObject("surface", nww);
  111. sp<AMessage> response;
  112. status_t err = msg->postAndAwaitResponse(&response);
  113. if (err == OK && response != NULL) {
  114. CHECK(response->findInt32("err", &err));
  115. }
  116. return err;
  117. }
  118. void NuPlayer2::Decoder::onMessageReceived(const sp<AMessage> &msg) {
  119. ALOGV("[%s] onMessage: %s", mComponentName.c_str(), msg->debugString().c_str());
  120. switch (msg->what()) {
  121. case kWhatCodecNotify:
  122. {
  123. int32_t cbID;
  124. CHECK(msg->findInt32("callbackID", &cbID));
  125. ALOGV("[%s] kWhatCodecNotify: cbID = %d, paused = %d",
  126. mIsAudio ? "audio" : "video", cbID, mPaused);
  127. if (mPaused) {
  128. break;
  129. }
  130. switch (cbID) {
  131. case AMediaCodecWrapper::CB_INPUT_AVAILABLE:
  132. {
  133. int32_t index;
  134. CHECK(msg->findInt32("index", &index));
  135. handleAnInputBuffer(index);
  136. break;
  137. }
  138. case AMediaCodecWrapper::CB_OUTPUT_AVAILABLE:
  139. {
  140. int32_t index;
  141. size_t offset;
  142. size_t size;
  143. int64_t timeUs;
  144. int32_t flags;
  145. CHECK(msg->findInt32("index", &index));
  146. CHECK(msg->findSize("offset", &offset));
  147. CHECK(msg->findSize("size", &size));
  148. CHECK(msg->findInt64("timeUs", &timeUs));
  149. CHECK(msg->findInt32("flags", &flags));
  150. handleAnOutputBuffer(index, offset, size, timeUs, flags);
  151. break;
  152. }
  153. case AMediaCodecWrapper::CB_OUTPUT_FORMAT_CHANGED:
  154. {
  155. sp<AMessage> format;
  156. CHECK(msg->findMessage("format", &format));
  157. handleOutputFormatChange(format);
  158. break;
  159. }
  160. case AMediaCodecWrapper::CB_ERROR:
  161. {
  162. status_t err;
  163. CHECK(msg->findInt32("err", &err));
  164. ALOGE("Decoder (%s) reported error : 0x%x",
  165. mIsAudio ? "audio" : "video", err);
  166. handleError(err);
  167. break;
  168. }
  169. default:
  170. {
  171. TRESPASS();
  172. break;
  173. }
  174. }
  175. break;
  176. }
  177. case kWhatRenderBuffer:
  178. {
  179. if (!isStaleReply(msg)) {
  180. onRenderBuffer(msg);
  181. }
  182. break;
  183. }
  184. case kWhatAudioOutputFormatChanged:
  185. {
  186. if (!isStaleReply(msg)) {
  187. status_t err;
  188. if (msg->findInt32("err", &err) && err != OK) {
  189. ALOGE("Renderer reported 0x%x when changing audio output format", err);
  190. handleError(err);
  191. }
  192. }
  193. break;
  194. }
  195. case kWhatSetVideoSurface:
  196. {
  197. sp<AReplyToken> replyID;
  198. CHECK(msg->senderAwaitsResponse(&replyID));
  199. sp<RefBase> obj;
  200. CHECK(msg->findObject("surface", &obj));
  201. sp<ANativeWindowWrapper> nww =
  202. static_cast<ANativeWindowWrapper *>(obj.get()); // non-null
  203. if (nww == NULL || nww->getANativeWindow() == NULL) {
  204. break;
  205. }
  206. int32_t err = INVALID_OPERATION;
  207. // NOTE: in practice mNativeWindow is always non-null,
  208. // but checking here for completeness
  209. if (mCodec != NULL
  210. && mNativeWindow != NULL && mNativeWindow->getANativeWindow() != NULL) {
  211. // TODO: once AwesomePlayer is removed, remove this automatic connecting
  212. // to the surface by MediaPlayerService.
  213. //
  214. // at this point MediaPlayer2Manager::client has already connected to the
  215. // surface, which MediaCodec does not expect
  216. err = native_window_api_disconnect(nww->getANativeWindow(),
  217. NATIVE_WINDOW_API_MEDIA);
  218. if (err == OK) {
  219. err = mCodec->setOutputSurface(nww);
  220. ALOGI_IF(err, "codec setOutputSurface returned: %d", err);
  221. if (err == OK) {
  222. // reconnect to the old surface as MPS::Client will expect to
  223. // be able to disconnect from it.
  224. (void)native_window_api_connect(mNativeWindow->getANativeWindow(),
  225. NATIVE_WINDOW_API_MEDIA);
  226. mNativeWindow = nww;
  227. }
  228. }
  229. if (err != OK) {
  230. // reconnect to the new surface on error as MPS::Client will expect to
  231. // be able to disconnect from it.
  232. (void)native_window_api_connect(nww->getANativeWindow(),
  233. NATIVE_WINDOW_API_MEDIA);
  234. }
  235. }
  236. sp<AMessage> response = new AMessage;
  237. response->setInt32("err", err);
  238. response->postReply(replyID);
  239. break;
  240. }
  241. case kWhatDrmReleaseCrypto:
  242. {
  243. ALOGV("kWhatDrmReleaseCrypto");
  244. onReleaseCrypto(msg);
  245. break;
  246. }
  247. default:
  248. DecoderBase::onMessageReceived(msg);
  249. break;
  250. }
  251. }
  252. void NuPlayer2::Decoder::onConfigure(const sp<AMessage> &format) {
  253. ALOGV("[%s] onConfigure (format=%s)", mComponentName.c_str(), format->debugString().c_str());
  254. CHECK(mCodec == NULL);
  255. mFormatChangePending = false;
  256. mTimeChangePending = false;
  257. ++mBufferGeneration;
  258. AString mime;
  259. CHECK(format->findString("mime", &mime));
  260. mIsAudio = !strncasecmp("audio/", mime.c_str(), 6);
  261. mIsVideoAVC = !strcasecmp(MEDIA_MIMETYPE_VIDEO_AVC, mime.c_str());
  262. mComponentName = mime;
  263. mComponentName.append(" decoder");
  264. ALOGV("[%s] onConfigure (nww=%p)", mComponentName.c_str(),
  265. (mNativeWindow == NULL ? NULL : mNativeWindow->getANativeWindow()));
  266. mCodec = AMediaCodecWrapper::CreateDecoderByType(mime);
  267. int32_t secure = 0;
  268. if (format->findInt32("secure", &secure) && secure != 0) {
  269. if (mCodec != NULL) {
  270. if (mCodec->getName(&mComponentName) == OK) {
  271. mComponentName.append(".secure");
  272. mCodec->release();
  273. ALOGI("[%s] creating", mComponentName.c_str());
  274. mCodec = AMediaCodecWrapper::CreateCodecByName(mComponentName);
  275. } else {
  276. mCodec = NULL;
  277. }
  278. }
  279. }
  280. if (mCodec == NULL) {
  281. ALOGE("Failed to create %s%s decoder",
  282. (secure ? "secure " : ""), mime.c_str());
  283. handleError(NO_INIT);
  284. return;
  285. }
  286. mIsSecure = secure;
  287. mCodec->getName(&mComponentName);
  288. status_t err;
  289. if (mNativeWindow != NULL && mNativeWindow->getANativeWindow() != NULL) {
  290. // disconnect from surface as MediaCodec will reconnect
  291. err = native_window_api_disconnect(mNativeWindow->getANativeWindow(),
  292. NATIVE_WINDOW_API_MEDIA);
  293. // We treat this as a warning, as this is a preparatory step.
  294. // Codec will try to connect to the surface, which is where
  295. // any error signaling will occur.
  296. ALOGW_IF(err != OK, "failed to disconnect from surface: %d", err);
  297. }
  298. // Modular DRM
  299. sp<RefBase> objCrypto;
  300. format->findObject("crypto", &objCrypto);
  301. sp<AMediaCryptoWrapper> crypto = static_cast<AMediaCryptoWrapper *>(objCrypto.get());
  302. // non-encrypted source won't have a crypto
  303. mIsEncrypted = (crypto != NULL);
  304. // configure is called once; still using OR in case the behavior changes.
  305. mIsEncryptedObservedEarlier = mIsEncryptedObservedEarlier || mIsEncrypted;
  306. ALOGV("onConfigure mCrypto: %p, mIsSecure: %d", crypto.get(), mIsSecure);
  307. err = mCodec->configure(
  308. AMediaFormatWrapper::Create(format),
  309. mNativeWindow,
  310. crypto,
  311. 0 /* flags */);
  312. if (err != OK) {
  313. ALOGE("Failed to configure [%s] decoder (err=%d)", mComponentName.c_str(), err);
  314. mCodec->release();
  315. mCodec.clear();
  316. handleError(err);
  317. return;
  318. }
  319. rememberCodecSpecificData(format);
  320. // the following should work in configured state
  321. sp<AMediaFormatWrapper> outputFormat = mCodec->getOutputFormat();
  322. if (outputFormat == NULL) {
  323. handleError(INVALID_OPERATION);
  324. return;
  325. }
  326. mInputFormat = mCodec->getInputFormat();
  327. if (mInputFormat == NULL) {
  328. handleError(INVALID_OPERATION);
  329. return;
  330. }
  331. mStats->setString("mime", mime.c_str());
  332. mStats->setString("component-name", mComponentName.c_str());
  333. if (!mIsAudio) {
  334. int32_t width, height;
  335. if (outputFormat->getInt32("width", &width)
  336. && outputFormat->getInt32("height", &height)) {
  337. mStats->setInt32("width", width);
  338. mStats->setInt32("height", height);
  339. }
  340. }
  341. sp<AMessage> reply = new AMessage(kWhatCodecNotify, this);
  342. mCodec->setCallback(reply);
  343. err = mCodec->start();
  344. if (err != OK) {
  345. ALOGE("Failed to start [%s] decoder (err=%d)", mComponentName.c_str(), err);
  346. mCodec->release();
  347. mCodec.clear();
  348. handleError(err);
  349. return;
  350. }
  351. releaseAndResetMediaBuffers();
  352. mPaused = false;
  353. mResumePending = false;
  354. }
  355. void NuPlayer2::Decoder::onSetParameters(const sp<AMessage> &params) {
  356. bool needAdjustLayers = false;
  357. float frameRateTotal;
  358. if (params->findFloat("frame-rate-total", &frameRateTotal)
  359. && mFrameRateTotal != frameRateTotal) {
  360. needAdjustLayers = true;
  361. mFrameRateTotal = frameRateTotal;
  362. }
  363. int32_t numVideoTemporalLayerTotal;
  364. if (params->findInt32("temporal-layer-count", &numVideoTemporalLayerTotal)
  365. && numVideoTemporalLayerTotal >= 0
  366. && numVideoTemporalLayerTotal <= kMaxNumVideoTemporalLayers
  367. && mNumVideoTemporalLayerTotal != numVideoTemporalLayerTotal) {
  368. needAdjustLayers = true;
  369. mNumVideoTemporalLayerTotal = std::max(numVideoTemporalLayerTotal, 1);
  370. }
  371. if (needAdjustLayers && mNumVideoTemporalLayerTotal > 1) {
  372. // TODO: For now, layer fps is calculated for some specific architectures.
  373. // But it really should be extracted from the stream.
  374. mVideoTemporalLayerAggregateFps[0] =
  375. mFrameRateTotal / (float)(1LL << (mNumVideoTemporalLayerTotal - 1));
  376. for (int32_t i = 1; i < mNumVideoTemporalLayerTotal; ++i) {
  377. mVideoTemporalLayerAggregateFps[i] =
  378. mFrameRateTotal / (float)(1LL << (mNumVideoTemporalLayerTotal - i))
  379. + mVideoTemporalLayerAggregateFps[i - 1];
  380. }
  381. }
  382. float playbackSpeed;
  383. if (params->findFloat("playback-speed", &playbackSpeed)
  384. && mPlaybackSpeed != playbackSpeed) {
  385. needAdjustLayers = true;
  386. mPlaybackSpeed = playbackSpeed;
  387. }
  388. if (needAdjustLayers) {
  389. float decodeFrameRate = mFrameRateTotal;
  390. // enable temporal layering optimization only if we know the layering depth
  391. if (mNumVideoTemporalLayerTotal > 1) {
  392. int32_t layerId;
  393. for (layerId = 0; layerId < mNumVideoTemporalLayerTotal - 1; ++layerId) {
  394. if (mVideoTemporalLayerAggregateFps[layerId] * mPlaybackSpeed
  395. >= kDisplayRefreshingRate * 0.9) {
  396. break;
  397. }
  398. }
  399. mNumVideoTemporalLayerAllowed = layerId + 1;
  400. decodeFrameRate = mVideoTemporalLayerAggregateFps[layerId];
  401. }
  402. ALOGV("onSetParameters: allowed layers=%d, decodeFps=%g",
  403. mNumVideoTemporalLayerAllowed, decodeFrameRate);
  404. if (mCodec == NULL) {
  405. ALOGW("onSetParameters called before codec is created.");
  406. return;
  407. }
  408. sp<AMediaFormatWrapper> codecParams = new AMediaFormatWrapper();
  409. codecParams->setFloat("operating-rate", decodeFrameRate * mPlaybackSpeed);
  410. mCodec->setParameters(codecParams);
  411. }
  412. }
  413. void NuPlayer2::Decoder::onSetRenderer(const sp<Renderer> &renderer) {
  414. mRenderer = renderer;
  415. }
  416. void NuPlayer2::Decoder::onResume(bool notifyComplete) {
  417. mPaused = false;
  418. if (notifyComplete) {
  419. mResumePending = true;
  420. }
  421. if (mCodec == NULL) {
  422. ALOGE("[%s] onResume without a valid codec", mComponentName.c_str());
  423. handleError(NO_INIT);
  424. return;
  425. }
  426. mCodec->start();
  427. }
  428. void NuPlayer2::Decoder::doFlush(bool notifyComplete) {
  429. if (mCCDecoder != NULL) {
  430. mCCDecoder->flush();
  431. }
  432. if (mRenderer != NULL) {
  433. mRenderer->flush(mIsAudio, notifyComplete);
  434. mRenderer->signalTimeDiscontinuity();
  435. }
  436. status_t err = OK;
  437. if (mCodec != NULL) {
  438. err = mCodec->flush();
  439. mCSDsToSubmit = mCSDsForCurrentFormat; // copy operator
  440. ++mBufferGeneration;
  441. }
  442. if (err != OK) {
  443. ALOGE("failed to flush [%s] (err=%d)", mComponentName.c_str(), err);
  444. handleError(err);
  445. // finish with posting kWhatFlushCompleted.
  446. // we attempt to release the buffers even if flush fails.
  447. }
  448. releaseAndResetMediaBuffers();
  449. mPaused = true;
  450. }
  451. void NuPlayer2::Decoder::onFlush() {
  452. doFlush(true);
  453. if (isDiscontinuityPending()) {
  454. // This could happen if the client starts seeking/shutdown
  455. // after we queued an EOS for discontinuities.
  456. // We can consider discontinuity handled.
  457. finishHandleDiscontinuity(false /* flushOnTimeChange */);
  458. }
  459. sp<AMessage> notify = mNotify->dup();
  460. notify->setInt32("what", kWhatFlushCompleted);
  461. notify->post();
  462. }
  463. void NuPlayer2::Decoder::onShutdown(bool notifyComplete) {
  464. status_t err = OK;
  465. // if there is a pending resume request, notify complete now
  466. notifyResumeCompleteIfNecessary();
  467. if (mCodec != NULL) {
  468. err = mCodec->release();
  469. mCodec = NULL;
  470. ++mBufferGeneration;
  471. if (mNativeWindow != NULL && mNativeWindow->getANativeWindow() != NULL) {
  472. // reconnect to surface as MediaCodec disconnected from it
  473. status_t error = native_window_api_connect(mNativeWindow->getANativeWindow(),
  474. NATIVE_WINDOW_API_MEDIA);
  475. ALOGW_IF(error != NO_ERROR,
  476. "[%s] failed to connect to native window, error=%d",
  477. mComponentName.c_str(), error);
  478. }
  479. mComponentName = "decoder";
  480. }
  481. releaseAndResetMediaBuffers();
  482. if (err != OK) {
  483. ALOGE("failed to release [%s] (err=%d)", mComponentName.c_str(), err);
  484. handleError(err);
  485. // finish with posting kWhatShutdownCompleted.
  486. }
  487. if (notifyComplete) {
  488. sp<AMessage> notify = mNotify->dup();
  489. notify->setInt32("what", kWhatShutdownCompleted);
  490. notify->post();
  491. mPaused = true;
  492. }
  493. }
  494. /*
  495. * returns true if we should request more data
  496. */
  497. bool NuPlayer2::Decoder::doRequestBuffers() {
  498. if (isDiscontinuityPending()) {
  499. return false;
  500. }
  501. status_t err = OK;
  502. while (err == OK && !mDequeuedInputBuffers.empty()) {
  503. size_t bufferIx = *mDequeuedInputBuffers.begin();
  504. sp<AMessage> msg = new AMessage();
  505. msg->setSize("buffer-ix", bufferIx);
  506. err = fetchInputData(msg);
  507. if (err != OK && err != ERROR_END_OF_STREAM) {
  508. // if EOS, need to queue EOS buffer
  509. break;
  510. }
  511. mDequeuedInputBuffers.erase(mDequeuedInputBuffers.begin());
  512. if (!mPendingInputMessages.empty()
  513. || !onInputBufferFetched(msg)) {
  514. mPendingInputMessages.push_back(msg);
  515. }
  516. }
  517. return err == -EWOULDBLOCK
  518. && mSource->feedMoreTSData() == OK;
  519. }
  520. void NuPlayer2::Decoder::handleError(int32_t err)
  521. {
  522. // We cannot immediately release the codec due to buffers still outstanding
  523. // in the renderer. We signal to the player the error so it can shutdown/release the
  524. // decoder after flushing and increment the generation to discard unnecessary messages.
  525. ++mBufferGeneration;
  526. sp<AMessage> notify = mNotify->dup();
  527. notify->setInt32("what", kWhatError);
  528. notify->setInt32("err", err);
  529. notify->post();
  530. }
  531. status_t NuPlayer2::Decoder::releaseCrypto()
  532. {
  533. ALOGV("releaseCrypto");
  534. sp<AMessage> msg = new AMessage(kWhatDrmReleaseCrypto, this);
  535. sp<AMessage> response;
  536. status_t status = msg->postAndAwaitResponse(&response);
  537. if (status == OK && response != NULL) {
  538. CHECK(response->findInt32("status", &status));
  539. ALOGV("releaseCrypto ret: %d ", status);
  540. } else {
  541. ALOGE("releaseCrypto err: %d", status);
  542. }
  543. return status;
  544. }
  545. void NuPlayer2::Decoder::onReleaseCrypto(const sp<AMessage>& msg)
  546. {
  547. status_t status = INVALID_OPERATION;
  548. if (mCodec != NULL) {
  549. status = mCodec->releaseCrypto();
  550. } else {
  551. // returning OK if the codec has been already released
  552. status = OK;
  553. ALOGE("onReleaseCrypto No mCodec. err: %d", status);
  554. }
  555. sp<AMessage> response = new AMessage;
  556. response->setInt32("status", status);
  557. // Clearing the state as it's tied to crypto. mIsEncryptedObservedEarlier is sticky though
  558. // and lasts for the lifetime of this codec. See its use in fetchInputData.
  559. mIsEncrypted = false;
  560. sp<AReplyToken> replyID;
  561. CHECK(msg->senderAwaitsResponse(&replyID));
  562. response->postReply(replyID);
  563. }
  564. bool NuPlayer2::Decoder::handleAnInputBuffer(size_t index) {
  565. if (isDiscontinuityPending()) {
  566. return false;
  567. }
  568. if (mCodec == NULL) {
  569. ALOGE("[%s] handleAnInputBuffer without a valid codec", mComponentName.c_str());
  570. handleError(NO_INIT);
  571. return false;
  572. }
  573. size_t bufferSize = 0;
  574. uint8_t *bufferBase = mCodec->getInputBuffer(index, &bufferSize);
  575. if (bufferBase == NULL) {
  576. ALOGE("[%s] handleAnInputBuffer, failed to get input buffer", mComponentName.c_str());
  577. handleError(UNKNOWN_ERROR);
  578. return false;
  579. }
  580. sp<MediaCodecBuffer> buffer =
  581. new MediaCodecBuffer(NULL /* format */, new ABuffer(bufferBase, bufferSize));
  582. if (index >= mInputBuffers.size()) {
  583. for (size_t i = mInputBuffers.size(); i <= index; ++i) {
  584. mInputBuffers.add();
  585. mMediaBuffers.add();
  586. mInputBufferIsDequeued.add();
  587. mMediaBuffers.editItemAt(i) = NULL;
  588. mInputBufferIsDequeued.editItemAt(i) = false;
  589. }
  590. }
  591. mInputBuffers.editItemAt(index) = buffer;
  592. //CHECK_LT(bufferIx, mInputBuffers.size());
  593. if (mMediaBuffers[index] != NULL) {
  594. mMediaBuffers[index]->release();
  595. mMediaBuffers.editItemAt(index) = NULL;
  596. }
  597. mInputBufferIsDequeued.editItemAt(index) = true;
  598. if (!mCSDsToSubmit.isEmpty()) {
  599. sp<AMessage> msg = new AMessage();
  600. msg->setSize("buffer-ix", index);
  601. sp<ABuffer> buffer = mCSDsToSubmit.itemAt(0);
  602. ALOGI("[%s] resubmitting CSD", mComponentName.c_str());
  603. msg->setBuffer("buffer", buffer);
  604. mCSDsToSubmit.removeAt(0);
  605. if (!onInputBufferFetched(msg)) {
  606. handleError(UNKNOWN_ERROR);
  607. return false;
  608. }
  609. return true;
  610. }
  611. while (!mPendingInputMessages.empty()) {
  612. sp<AMessage> msg = *mPendingInputMessages.begin();
  613. if (!onInputBufferFetched(msg)) {
  614. break;
  615. }
  616. mPendingInputMessages.erase(mPendingInputMessages.begin());
  617. }
  618. if (!mInputBufferIsDequeued.editItemAt(index)) {
  619. return true;
  620. }
  621. mDequeuedInputBuffers.push_back(index);
  622. onRequestInputBuffers();
  623. return true;
  624. }
  625. bool NuPlayer2::Decoder::handleAnOutputBuffer(
  626. size_t index,
  627. size_t offset,
  628. size_t size,
  629. int64_t timeUs,
  630. int32_t flags) {
  631. if (mCodec == NULL) {
  632. ALOGE("[%s] handleAnOutputBuffer without a valid codec", mComponentName.c_str());
  633. handleError(NO_INIT);
  634. return false;
  635. }
  636. // CHECK_LT(bufferIx, mOutputBuffers.size());
  637. size_t bufferSize = 0;
  638. uint8_t *bufferBase = mCodec->getOutputBuffer(index, &bufferSize);
  639. if (bufferBase == NULL) {
  640. ALOGE("[%s] handleAnOutputBuffer, failed to get output buffer", mComponentName.c_str());
  641. handleError(UNKNOWN_ERROR);
  642. return false;
  643. }
  644. sp<MediaCodecBuffer> buffer =
  645. new MediaCodecBuffer(NULL /* format */, new ABuffer(bufferBase, bufferSize));
  646. if (index >= mOutputBuffers.size()) {
  647. for (size_t i = mOutputBuffers.size(); i <= index; ++i) {
  648. mOutputBuffers.add();
  649. }
  650. }
  651. mOutputBuffers.editItemAt(index) = buffer;
  652. buffer->setRange(offset, size);
  653. buffer->meta()->clear();
  654. buffer->meta()->setInt64("timeUs", timeUs);
  655. bool eos = flags & AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM;
  656. // we do not expect CODECCONFIG or SYNCFRAME for decoder
  657. sp<AMessage> reply = new AMessage(kWhatRenderBuffer, this);
  658. reply->setSize("buffer-ix", index);
  659. reply->setInt32("generation", mBufferGeneration);
  660. if (eos) {
  661. ALOGI("[%s] saw output EOS", mIsAudio ? "audio" : "video");
  662. buffer->meta()->setInt32("eos", true);
  663. reply->setInt32("eos", true);
  664. }
  665. mNumFramesTotal += !mIsAudio;
  666. if (mSkipRenderingUntilMediaTimeUs >= 0) {
  667. if (timeUs < mSkipRenderingUntilMediaTimeUs) {
  668. ALOGV("[%s] dropping buffer at time %lld as requested.",
  669. mComponentName.c_str(), (long long)timeUs);
  670. reply->post();
  671. if (eos) {
  672. notifyResumeCompleteIfNecessary();
  673. if (mRenderer != NULL && !isDiscontinuityPending()) {
  674. mRenderer->queueEOS(mIsAudio, ERROR_END_OF_STREAM);
  675. }
  676. }
  677. return true;
  678. }
  679. mSkipRenderingUntilMediaTimeUs = -1;
  680. }
  681. // wait until 1st frame comes out to signal resume complete
  682. notifyResumeCompleteIfNecessary();
  683. if (mRenderer != NULL) {
  684. // send the buffer to renderer.
  685. mRenderer->queueBuffer(mIsAudio, buffer, reply);
  686. if (eos && !isDiscontinuityPending()) {
  687. mRenderer->queueEOS(mIsAudio, ERROR_END_OF_STREAM);
  688. }
  689. }
  690. return true;
  691. }
  692. void NuPlayer2::Decoder::handleOutputFormatChange(const sp<AMessage> &format) {
  693. if (!mIsAudio) {
  694. int32_t width, height;
  695. if (format->findInt32("width", &width)
  696. && format->findInt32("height", &height)) {
  697. mStats->setInt32("width", width);
  698. mStats->setInt32("height", height);
  699. }
  700. sp<AMessage> notify = mNotify->dup();
  701. notify->setInt32("what", kWhatVideoSizeChanged);
  702. notify->setMessage("format", format);
  703. notify->post();
  704. } else if (mRenderer != NULL) {
  705. uint32_t flags;
  706. int64_t durationUs;
  707. bool hasVideo = (mSource->getFormat(false /* audio */) != NULL);
  708. if (getAudioDeepBufferSetting() // override regardless of source duration
  709. || (mSource->getDuration(&durationUs) == OK
  710. && durationUs > AUDIO_SINK_MIN_DEEP_BUFFER_DURATION_US)) {
  711. flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
  712. } else {
  713. flags = AUDIO_OUTPUT_FLAG_NONE;
  714. }
  715. sp<AMessage> reply = new AMessage(kWhatAudioOutputFormatChanged, this);
  716. reply->setInt32("generation", mBufferGeneration);
  717. mRenderer->changeAudioFormat(
  718. format, false /* offloadOnly */, hasVideo,
  719. flags, mSource->isStreaming(), reply);
  720. }
  721. }
  722. void NuPlayer2::Decoder::releaseAndResetMediaBuffers() {
  723. for (size_t i = 0; i < mMediaBuffers.size(); i++) {
  724. if (mMediaBuffers[i] != NULL) {
  725. mMediaBuffers[i]->release();
  726. mMediaBuffers.editItemAt(i) = NULL;
  727. }
  728. }
  729. mMediaBuffers.resize(mInputBuffers.size());
  730. for (size_t i = 0; i < mMediaBuffers.size(); i++) {
  731. mMediaBuffers.editItemAt(i) = NULL;
  732. }
  733. mInputBufferIsDequeued.clear();
  734. mInputBufferIsDequeued.resize(mInputBuffers.size());
  735. for (size_t i = 0; i < mInputBufferIsDequeued.size(); i++) {
  736. mInputBufferIsDequeued.editItemAt(i) = false;
  737. }
  738. mPendingInputMessages.clear();
  739. mDequeuedInputBuffers.clear();
  740. mSkipRenderingUntilMediaTimeUs = -1;
  741. }
  742. bool NuPlayer2::Decoder::isStaleReply(const sp<AMessage> &msg) {
  743. int32_t generation;
  744. CHECK(msg->findInt32("generation", &generation));
  745. return generation != mBufferGeneration;
  746. }
  747. status_t NuPlayer2::Decoder::fetchInputData(sp<AMessage> &reply) {
  748. sp<ABuffer> accessUnit;
  749. bool dropAccessUnit = true;
  750. do {
  751. status_t err = mSource->dequeueAccessUnit(mIsAudio, &accessUnit);
  752. if (err == -EWOULDBLOCK) {
  753. return err;
  754. } else if (err != OK) {
  755. if (err == INFO_DISCONTINUITY) {
  756. int32_t type;
  757. CHECK(accessUnit->meta()->findInt32("discontinuity", &type));
  758. bool formatChange =
  759. (mIsAudio &&
  760. (type & ATSParser::DISCONTINUITY_AUDIO_FORMAT))
  761. || (!mIsAudio &&
  762. (type & ATSParser::DISCONTINUITY_VIDEO_FORMAT));
  763. bool timeChange = (type & ATSParser::DISCONTINUITY_TIME) != 0;
  764. ALOGI("%s discontinuity (format=%d, time=%d)",
  765. mIsAudio ? "audio" : "video", formatChange, timeChange);
  766. bool seamlessFormatChange = false;
  767. sp<AMessage> newFormat = mSource->getFormat(mIsAudio);
  768. if (formatChange) {
  769. seamlessFormatChange =
  770. supportsSeamlessFormatChange(newFormat);
  771. // treat seamless format change separately
  772. formatChange = !seamlessFormatChange;
  773. }
  774. // For format or time change, return EOS to queue EOS input,
  775. // then wait for EOS on output.
  776. if (formatChange /* not seamless */) {
  777. mFormatChangePending = true;
  778. err = ERROR_END_OF_STREAM;
  779. } else if (timeChange) {
  780. rememberCodecSpecificData(newFormat);
  781. mTimeChangePending = true;
  782. err = ERROR_END_OF_STREAM;
  783. } else if (seamlessFormatChange) {
  784. // reuse existing decoder and don't flush
  785. rememberCodecSpecificData(newFormat);
  786. continue;
  787. } else {
  788. // This stream is unaffected by the discontinuity
  789. return -EWOULDBLOCK;
  790. }
  791. }
  792. // reply should only be returned without a buffer set
  793. // when there is an error (including EOS)
  794. CHECK(err != OK);
  795. reply->setInt32("err", err);
  796. return ERROR_END_OF_STREAM;
  797. }
  798. dropAccessUnit = false;
  799. if (!mIsAudio && !mIsEncrypted) {
  800. // Extra safeguard if higher-level behavior changes. Otherwise, not required now.
  801. // Preventing the buffer from being processed (and sent to codec) if this is a later
  802. // round of playback but this time without prepareDrm. Or if there is a race between
  803. // stop (which is not blocking) and releaseDrm allowing buffers being processed after
  804. // Crypto has been released (GenericSource currently prevents this race though).
  805. // Particularly doing this check before IsAVCReferenceFrame call to prevent parsing
  806. // of encrypted data.
  807. if (mIsEncryptedObservedEarlier) {
  808. ALOGE("fetchInputData: mismatched mIsEncrypted/mIsEncryptedObservedEarlier (0/1)");
  809. return INVALID_OPERATION;
  810. }
  811. int32_t layerId = 0;
  812. bool haveLayerId = accessUnit->meta()->findInt32("temporal-layer-id", &layerId);
  813. if (mRenderer->getVideoLateByUs() > 100000LL
  814. && mIsVideoAVC
  815. && !IsAVCReferenceFrame(accessUnit)) {
  816. dropAccessUnit = true;
  817. } else if (haveLayerId && mNumVideoTemporalLayerTotal > 1) {
  818. // Add only one layer each time.
  819. if (layerId > mCurrentMaxVideoTemporalLayerId + 1
  820. || layerId >= mNumVideoTemporalLayerAllowed) {
  821. dropAccessUnit = true;
  822. ALOGV("dropping layer(%d), speed=%g, allowed layer count=%d, max layerId=%d",
  823. layerId, mPlaybackSpeed, mNumVideoTemporalLayerAllowed,
  824. mCurrentMaxVideoTemporalLayerId);
  825. } else if (layerId > mCurrentMaxVideoTemporalLayerId) {
  826. mCurrentMaxVideoTemporalLayerId = layerId;
  827. } else if (layerId == 0 && mNumVideoTemporalLayerTotal > 1
  828. && IsIDR(accessUnit->data(), accessUnit->size())) {
  829. mCurrentMaxVideoTemporalLayerId = mNumVideoTemporalLayerTotal - 1;
  830. }
  831. }
  832. if (dropAccessUnit) {
  833. if (layerId <= mCurrentMaxVideoTemporalLayerId && layerId > 0) {
  834. mCurrentMaxVideoTemporalLayerId = layerId - 1;
  835. }
  836. ++mNumInputFramesDropped;
  837. }
  838. }
  839. } while (dropAccessUnit);
  840. // ALOGV("returned a valid buffer of %s data", mIsAudio ? "mIsAudio" : "video");
  841. #if 0
  842. int64_t mediaTimeUs;
  843. CHECK(accessUnit->meta()->findInt64("timeUs", &mediaTimeUs));
  844. ALOGV("[%s] feeding input buffer at media time %.3f",
  845. mIsAudio ? "audio" : "video",
  846. mediaTimeUs / 1E6);
  847. #endif
  848. if (mCCDecoder != NULL) {
  849. mCCDecoder->decode(accessUnit);
  850. }
  851. reply->setBuffer("buffer", accessUnit);
  852. return OK;
  853. }
  854. bool NuPlayer2::Decoder::onInputBufferFetched(const sp<AMessage> &msg) {
  855. if (mCodec == NULL) {
  856. ALOGE("[%s] onInputBufferFetched without a valid codec", mComponentName.c_str());
  857. handleError(NO_INIT);
  858. return false;
  859. }
  860. size_t bufferIx;
  861. CHECK(msg->findSize("buffer-ix", &bufferIx));
  862. CHECK_LT(bufferIx, mInputBuffers.size());
  863. sp<MediaCodecBuffer> codecBuffer = mInputBuffers[bufferIx];
  864. sp<ABuffer> buffer;
  865. bool hasBuffer = msg->findBuffer("buffer", &buffer);
  866. bool needsCopy = true;
  867. if (buffer == NULL /* includes !hasBuffer */) {
  868. int32_t streamErr = ERROR_END_OF_STREAM;
  869. CHECK(msg->findInt32("err", &streamErr) || !hasBuffer);
  870. CHECK(streamErr != OK);
  871. // attempt to queue EOS
  872. status_t err = mCodec->queueInputBuffer(
  873. bufferIx,
  874. 0,
  875. 0,
  876. 0,
  877. AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM);
  878. if (err == OK) {
  879. mInputBufferIsDequeued.editItemAt(bufferIx) = false;
  880. } else if (streamErr == ERROR_END_OF_STREAM) {
  881. streamErr = err;
  882. // err will not be ERROR_END_OF_STREAM
  883. }
  884. if (streamErr != ERROR_END_OF_STREAM) {
  885. ALOGE("Stream error for [%s] (err=%d), EOS %s queued",
  886. mComponentName.c_str(),
  887. streamErr,
  888. err == OK ? "successfully" : "unsuccessfully");
  889. handleError(streamErr);
  890. }
  891. } else {
  892. sp<AMessage> extra;
  893. if (buffer->meta()->findMessage("extra", &extra) && extra != NULL) {
  894. int64_t resumeAtMediaTimeUs;
  895. if (extra->findInt64(
  896. "resume-at-mediaTimeUs", &resumeAtMediaTimeUs)) {
  897. ALOGI("[%s] suppressing rendering until %lld us",
  898. mComponentName.c_str(), (long long)resumeAtMediaTimeUs);
  899. mSkipRenderingUntilMediaTimeUs = resumeAtMediaTimeUs;
  900. }
  901. }
  902. int64_t timeUs = 0;
  903. uint32_t flags = 0;
  904. CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
  905. int32_t eos, csd;
  906. // we do not expect SYNCFRAME for decoder
  907. if (buffer->meta()->findInt32("eos", &eos) && eos) {
  908. flags |= AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM;
  909. } else if (buffer->meta()->findInt32("csd", &csd) && csd) {
  910. flags |= AMEDIACODEC_BUFFER_FLAG_CODEC_CONFIG;
  911. }
  912. // Modular DRM
  913. MediaBufferBase *mediaBuf = NULL;
  914. sp<AMediaCodecCryptoInfoWrapper> cryptInfo;
  915. // copy into codec buffer
  916. if (needsCopy) {
  917. if (buffer->size() > codecBuffer->capacity()) {
  918. handleError(ERROR_BUFFER_TOO_SMALL);
  919. mDequeuedInputBuffers.push_back(bufferIx);
  920. return false;
  921. }
  922. if (buffer->data() != NULL) {
  923. codecBuffer->setRange(0, buffer->size());
  924. memcpy(codecBuffer->data(), buffer->data(), buffer->size());
  925. } else { // No buffer->data()
  926. //Modular DRM
  927. sp<RefBase> holder;
  928. if (buffer->meta()->findObject("mediaBufferHolder", &holder)) {
  929. mediaBuf = (holder != nullptr) ?
  930. static_cast<MediaBufferHolder*>(holder.get())->mediaBuffer() : nullptr;
  931. }
  932. if (mediaBuf != NULL) {
  933. if (mediaBuf->size() > codecBuffer->capacity()) {
  934. handleError(ERROR_BUFFER_TOO_SMALL);
  935. mDequeuedInputBuffers.push_back(bufferIx);
  936. return false;
  937. }
  938. codecBuffer->setRange(0, mediaBuf->size());
  939. memcpy(codecBuffer->data(), mediaBuf->data(), mediaBuf->size());
  940. MetaDataBase &meta_data = mediaBuf->meta_data();
  941. cryptInfo = AMediaCodecCryptoInfoWrapper::Create(meta_data);
  942. } else { // No mediaBuf
  943. ALOGE("onInputBufferFetched: buffer->data()/mediaBuf are NULL for %p",
  944. buffer.get());
  945. handleError(UNKNOWN_ERROR);
  946. return false;
  947. }
  948. } // buffer->data()
  949. } // needsCopy
  950. sp<RefBase> cryptInfoObj;
  951. if (buffer->meta()->findObject("cryptInfo", &cryptInfoObj)) {
  952. cryptInfo = static_cast<AMediaCodecCryptoInfoWrapper *>(cryptInfoObj.get());
  953. }
  954. status_t err;
  955. if (cryptInfo != NULL) {
  956. err = mCodec->queueSecureInputBuffer(
  957. bufferIx,
  958. codecBuffer->offset(),
  959. cryptInfo,
  960. timeUs,
  961. flags);
  962. // synchronous call so done with cryptInfo here
  963. } else {
  964. err = mCodec->queueInputBuffer(
  965. bufferIx,
  966. codecBuffer->offset(),
  967. codecBuffer->size(),
  968. timeUs,
  969. flags);
  970. } // no cryptInfo
  971. if (err != OK) {
  972. ALOGE("onInputBufferFetched: queue%sInputBuffer failed for [%s] (err=%d)",
  973. (cryptInfo != NULL ? "Secure" : ""),
  974. mComponentName.c_str(), err);
  975. handleError(err);
  976. } else {
  977. mInputBufferIsDequeued.editItemAt(bufferIx) = false;
  978. }
  979. } // buffer != NULL
  980. return true;
  981. }
  982. void NuPlayer2::Decoder::onRenderBuffer(const sp<AMessage> &msg) {
  983. status_t err;
  984. int32_t render;
  985. size_t bufferIx;
  986. int32_t eos;
  987. CHECK(msg->findSize("buffer-ix", &bufferIx));
  988. if (!mIsAudio) {
  989. int64_t timeUs;
  990. sp<MediaCodecBuffer> buffer = mOutputBuffers[bufferIx];
  991. buffer->meta()->findInt64("timeUs", &timeUs);
  992. if (mCCDecoder != NULL && mCCDecoder->isSelected()) {
  993. mCCDecoder->display(timeUs);
  994. }
  995. }
  996. if (mCodec == NULL) {
  997. err = NO_INIT;
  998. } else if (msg->findInt32("render", &render) && render) {
  999. int64_t timestampNs;
  1000. CHECK(msg->findInt64("timestampNs", &timestampNs));
  1001. err = mCodec->releaseOutputBufferAtTime(bufferIx, timestampNs);
  1002. } else {
  1003. mNumOutputFramesDropped += !mIsAudio;
  1004. err = mCodec->releaseOutputBuffer(bufferIx, false /* render */);
  1005. }
  1006. if (err != OK) {
  1007. ALOGE("failed to release output buffer for [%s] (err=%d)",
  1008. mComponentName.c_str(), err);
  1009. handleError(err);
  1010. }
  1011. if (msg->findInt32("eos", &eos) && eos
  1012. && isDiscontinuityPending()) {
  1013. finishHandleDiscontinuity(true /* flushOnTimeChange */);
  1014. }
  1015. }
  1016. bool NuPlayer2::Decoder::isDiscontinuityPending() const {
  1017. return mFormatChangePending || mTimeChangePending;
  1018. }
  1019. void NuPlayer2::Decoder::finishHandleDiscontinuity(bool flushOnTimeChange) {
  1020. ALOGV("finishHandleDiscontinuity: format %d, time %d, flush %d",
  1021. mFormatChangePending, mTimeChangePending, flushOnTimeChange);
  1022. // If we have format change, pause and wait to be killed;
  1023. // If we have time change only, flush and restart fetching.
  1024. if (mFormatChangePending) {
  1025. mPaused = true;
  1026. } else if (mTimeChangePending) {
  1027. if (flushOnTimeChange) {
  1028. doFlush(false /* notifyComplete */);
  1029. signalResume(false /* notifyComplete */);
  1030. }
  1031. }
  1032. // Notify NuPlayer2 to either shutdown decoder, or rescan sources
  1033. sp<AMessage> msg = mNotify->dup();
  1034. msg->setInt32("what", kWhatInputDiscontinuity);
  1035. msg->setInt32("formatChange", mFormatChangePending);
  1036. msg->post();
  1037. mFormatChangePending = false;
  1038. mTimeChangePending = false;
  1039. }
  1040. bool NuPlayer2::Decoder::supportsSeamlessAudioFormatChange(
  1041. const sp<AMessage> &targetFormat) const {
  1042. if (targetFormat == NULL) {
  1043. return true;
  1044. }
  1045. AString mime;
  1046. if (!targetFormat->findString("mime", &mime)) {
  1047. return false;
  1048. }
  1049. if (!strcasecmp(mime.c_str(), MEDIA_MIMETYPE_AUDIO_AAC)) {
  1050. // field-by-field comparison
  1051. const char * keys[] = { "channel-count", "sample-rate", "is-adts" };
  1052. for (unsigned int i = 0; i < sizeof(keys) / sizeof(keys[0]); i++) {
  1053. int32_t oldVal, newVal;
  1054. if (!mInputFormat->getInt32(keys[i], &oldVal) ||
  1055. !targetFormat->findInt32(keys[i], &newVal) ||
  1056. oldVal != newVal) {
  1057. return false;
  1058. }
  1059. }
  1060. sp<ABuffer> newBuf;
  1061. uint8_t *oldBufData = NULL;
  1062. size_t oldBufSize = 0;
  1063. if (mInputFormat->getBuffer("csd-0", (void**)&oldBufData, &oldBufSize) &&
  1064. targetFormat->findBuffer("csd-0", &newBuf)) {
  1065. if (oldBufSize != newBuf->size()) {
  1066. return false;
  1067. }
  1068. return !memcmp(oldBufData, newBuf->data(), oldBufSize);
  1069. }
  1070. }
  1071. return false;
  1072. }
  1073. bool NuPlayer2::Decoder::supportsSeamlessFormatChange(const sp<AMessage> &targetFormat) const {
  1074. if (mInputFormat == NULL) {
  1075. return false;
  1076. }
  1077. if (targetFormat == NULL) {
  1078. return true;
  1079. }
  1080. AString oldMime, newMime;
  1081. if (!mInputFormat->getString("mime", &oldMime)
  1082. || !targetFormat->findString("mime", &newMime)
  1083. || !(oldMime == newMime)) {
  1084. return false;
  1085. }
  1086. bool audio = !strncasecmp(oldMime.c_str(), "audio/", strlen("audio/"));
  1087. bool seamless;
  1088. if (audio) {
  1089. seamless = supportsSeamlessAudioFormatChange(targetFormat);
  1090. } else {
  1091. int32_t isAdaptive;
  1092. seamless = (mCodec != NULL &&
  1093. mInputFormat->getInt32("adaptive-playback", &isAdaptive) &&
  1094. isAdaptive);
  1095. }
  1096. ALOGV("%s seamless support for %s", seamless ? "yes" : "no", oldMime.c_str());
  1097. return seamless;
  1098. }
  1099. void NuPlayer2::Decoder::rememberCodecSpecificData(const sp<AMessage> &format) {
  1100. if (format == NULL) {
  1101. return;
  1102. }
  1103. mCSDsForCurrentFormat.clear();
  1104. for (int32_t i = 0; ; ++i) {
  1105. AString tag = "csd-";
  1106. tag.append(i);
  1107. sp<ABuffer> buffer;
  1108. if (!format->findBuffer(tag.c_str(), &buffer)) {
  1109. break;
  1110. }
  1111. mCSDsForCurrentFormat.push(buffer);
  1112. }
  1113. }
  1114. void NuPlayer2::Decoder::notifyResumeCompleteIfNecessary() {
  1115. if (mResumePending) {
  1116. mResumePending = false;
  1117. sp<AMessage> notify = mNotify->dup();
  1118. notify->setInt32("what", kWhatResumeCompleted);
  1119. notify->post();
  1120. }
  1121. }
  1122. } // namespace android