NuPlayer2.cpp 109 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308
  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 "NuPlayer2"
  18. #include <inttypes.h>
  19. #include <utils/Log.h>
  20. #include "NuPlayer2.h"
  21. #include "HTTPLiveSource2.h"
  22. #include "JMediaPlayer2Utils.h"
  23. #include "NuPlayer2CCDecoder.h"
  24. #include "NuPlayer2Decoder.h"
  25. #include "NuPlayer2DecoderBase.h"
  26. #include "NuPlayer2DecoderPassThrough.h"
  27. #include "NuPlayer2Driver.h"
  28. #include "NuPlayer2Renderer.h"
  29. #include "NuPlayer2Source.h"
  30. #include "RTSPSource2.h"
  31. #include "GenericSource2.h"
  32. #include "TextDescriptions2.h"
  33. #include "ATSParser.h"
  34. #include <cutils/properties.h>
  35. #include <media/AudioParameter.h>
  36. #include <media/AudioResamplerPublic.h>
  37. #include <media/AVSyncSettings.h>
  38. #include <media/DataSourceDesc.h>
  39. #include <media/MediaCodecBuffer.h>
  40. #include <media/NdkWrapper.h>
  41. #include <media/stagefright/foundation/hexdump.h>
  42. #include <media/stagefright/foundation/ABuffer.h>
  43. #include <media/stagefright/foundation/ADebug.h>
  44. #include <media/stagefright/foundation/AMessage.h>
  45. #include <media/stagefright/foundation/avc_utils.h>
  46. #include <media/stagefright/MediaBuffer.h>
  47. #include <media/stagefright/MediaClock.h>
  48. #include <media/stagefright/MediaDefs.h>
  49. #include <media/stagefright/MediaErrors.h>
  50. #include <media/stagefright/MetaData.h>
  51. #include "ESDS.h"
  52. #include <media/stagefright/Utils.h>
  53. #include <system/window.h>
  54. namespace android {
  55. static status_t sendMetaDataToHal(sp<MediaPlayer2Interface::AudioSink>& sink,
  56. const sp<MetaData>& meta) {
  57. int32_t sampleRate = 0;
  58. int32_t bitRate = 0;
  59. int32_t channelMask = 0;
  60. int32_t delaySamples = 0;
  61. int32_t paddingSamples = 0;
  62. AudioParameter param = AudioParameter();
  63. if (meta->findInt32(kKeySampleRate, &sampleRate)) {
  64. param.addInt(String8(AUDIO_OFFLOAD_CODEC_SAMPLE_RATE), sampleRate);
  65. }
  66. if (meta->findInt32(kKeyChannelMask, &channelMask)) {
  67. param.addInt(String8(AUDIO_OFFLOAD_CODEC_NUM_CHANNEL), channelMask);
  68. }
  69. if (meta->findInt32(kKeyBitRate, &bitRate)) {
  70. param.addInt(String8(AUDIO_OFFLOAD_CODEC_AVG_BIT_RATE), bitRate);
  71. }
  72. if (meta->findInt32(kKeyEncoderDelay, &delaySamples)) {
  73. param.addInt(String8(AUDIO_OFFLOAD_CODEC_DELAY_SAMPLES), delaySamples);
  74. }
  75. if (meta->findInt32(kKeyEncoderPadding, &paddingSamples)) {
  76. param.addInt(String8(AUDIO_OFFLOAD_CODEC_PADDING_SAMPLES), paddingSamples);
  77. }
  78. ALOGV("sendMetaDataToHal: bitRate %d, sampleRate %d, chanMask %d,"
  79. "delaySample %d, paddingSample %d", bitRate, sampleRate,
  80. channelMask, delaySamples, paddingSamples);
  81. sink->setParameters(param.toString());
  82. return OK;
  83. }
  84. struct NuPlayer2::Action : public RefBase {
  85. Action() {}
  86. virtual void execute(NuPlayer2 *player) = 0;
  87. private:
  88. DISALLOW_EVIL_CONSTRUCTORS(Action);
  89. };
  90. struct NuPlayer2::SeekAction : public Action {
  91. explicit SeekAction(int64_t seekTimeUs, MediaPlayer2SeekMode mode)
  92. : mSeekTimeUs(seekTimeUs),
  93. mMode(mode) {
  94. }
  95. virtual void execute(NuPlayer2 *player) {
  96. player->performSeek(mSeekTimeUs, mMode);
  97. }
  98. private:
  99. int64_t mSeekTimeUs;
  100. MediaPlayer2SeekMode mMode;
  101. DISALLOW_EVIL_CONSTRUCTORS(SeekAction);
  102. };
  103. struct NuPlayer2::ResumeDecoderAction : public Action {
  104. explicit ResumeDecoderAction(bool needNotify)
  105. : mNeedNotify(needNotify) {
  106. }
  107. virtual void execute(NuPlayer2 *player) {
  108. player->performResumeDecoders(mNeedNotify);
  109. }
  110. private:
  111. bool mNeedNotify;
  112. DISALLOW_EVIL_CONSTRUCTORS(ResumeDecoderAction);
  113. };
  114. struct NuPlayer2::SetSurfaceAction : public Action {
  115. explicit SetSurfaceAction(const sp<ANativeWindowWrapper> &nww)
  116. : mNativeWindow(nww) {
  117. }
  118. virtual void execute(NuPlayer2 *player) {
  119. player->performSetSurface(mNativeWindow);
  120. }
  121. private:
  122. sp<ANativeWindowWrapper> mNativeWindow;
  123. DISALLOW_EVIL_CONSTRUCTORS(SetSurfaceAction);
  124. };
  125. struct NuPlayer2::FlushDecoderAction : public Action {
  126. FlushDecoderAction(FlushCommand audio, FlushCommand video)
  127. : mAudio(audio),
  128. mVideo(video) {
  129. }
  130. virtual void execute(NuPlayer2 *player) {
  131. player->performDecoderFlush(mAudio, mVideo);
  132. }
  133. private:
  134. FlushCommand mAudio;
  135. FlushCommand mVideo;
  136. DISALLOW_EVIL_CONSTRUCTORS(FlushDecoderAction);
  137. };
  138. struct NuPlayer2::PostMessageAction : public Action {
  139. explicit PostMessageAction(const sp<AMessage> &msg)
  140. : mMessage(msg) {
  141. }
  142. virtual void execute(NuPlayer2 *) {
  143. mMessage->post();
  144. }
  145. private:
  146. sp<AMessage> mMessage;
  147. DISALLOW_EVIL_CONSTRUCTORS(PostMessageAction);
  148. };
  149. // Use this if there's no state necessary to save in order to execute
  150. // the action.
  151. struct NuPlayer2::SimpleAction : public Action {
  152. typedef void (NuPlayer2::*ActionFunc)();
  153. explicit SimpleAction(ActionFunc func)
  154. : mFunc(func) {
  155. }
  156. virtual void execute(NuPlayer2 *player) {
  157. (player->*mFunc)();
  158. }
  159. private:
  160. ActionFunc mFunc;
  161. DISALLOW_EVIL_CONSTRUCTORS(SimpleAction);
  162. };
  163. ////////////////////////////////////////////////////////////////////////////////
  164. NuPlayer2::NuPlayer2(
  165. pid_t pid, uid_t uid, const sp<MediaClock> &mediaClock, const sp<JObjectHolder> &context)
  166. : mPID(pid),
  167. mUID(uid),
  168. mMediaClock(mediaClock),
  169. mOffloadAudio(false),
  170. mAudioDecoderGeneration(0),
  171. mVideoDecoderGeneration(0),
  172. mRendererGeneration(0),
  173. mEOSMonitorGeneration(0),
  174. mLastStartedPlayingTimeNs(0),
  175. mPreviousSeekTimeUs(0),
  176. mAudioEOS(false),
  177. mVideoEOS(false),
  178. mScanSourcesPending(false),
  179. mScanSourcesGeneration(0),
  180. mPollDurationGeneration(0),
  181. mTimedTextGeneration(0),
  182. mFlushingAudio(NONE),
  183. mFlushingVideo(NONE),
  184. mResumePending(false),
  185. mVideoScalingMode(NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW),
  186. mPlaybackSettings(AUDIO_PLAYBACK_RATE_DEFAULT),
  187. mVideoFpsHint(-1.f),
  188. mStarted(false),
  189. mPrepared(false),
  190. mResetting(false),
  191. mSourceStarted(false),
  192. mAudioDecoderError(false),
  193. mVideoDecoderError(false),
  194. mPaused(false),
  195. mPausedByClient(true),
  196. mPausedForBuffering(false),
  197. mContext(context) {
  198. CHECK(mediaClock != NULL);
  199. clearFlushComplete();
  200. }
  201. NuPlayer2::~NuPlayer2() {
  202. }
  203. void NuPlayer2::setDriver(const wp<NuPlayer2Driver> &driver) {
  204. mDriver = driver;
  205. }
  206. static bool IsHTTPLiveURL(const char *url) {
  207. if (!strncasecmp("http://", url, 7)
  208. || !strncasecmp("https://", url, 8)
  209. || !strncasecmp("file://", url, 7)) {
  210. size_t len = strlen(url);
  211. if (len >= 5 && !strcasecmp(".m3u8", &url[len - 5])) {
  212. return true;
  213. }
  214. if (strstr(url,"m3u8")) {
  215. return true;
  216. }
  217. }
  218. return false;
  219. }
  220. status_t NuPlayer2::createNuPlayer2Source(const sp<DataSourceDesc> &dsd,
  221. sp<Source> *source,
  222. DATA_SOURCE_TYPE *dataSourceType) {
  223. status_t err = NO_ERROR;
  224. sp<AMessage> notify = new AMessage(kWhatSourceNotify, this);
  225. notify->setInt64("srcId", dsd->mId);
  226. switch (dsd->mType) {
  227. case DataSourceDesc::TYPE_URL:
  228. {
  229. const char *url = dsd->mUrl.c_str();
  230. size_t len = strlen(url);
  231. const sp<MediaHTTPService> &httpService = dsd->mHttpService;
  232. KeyedVector<String8, String8> *headers = &(dsd->mHeaders);
  233. if (IsHTTPLiveURL(url)) {
  234. *source = new HTTPLiveSource2(notify, httpService, url, headers);
  235. ALOGV("createNuPlayer2Source HTTPLiveSource2 %s", url);
  236. *dataSourceType = DATA_SOURCE_TYPE_HTTP_LIVE;
  237. } else if (!strncasecmp(url, "rtsp://", 7)) {
  238. *source = new RTSPSource2(
  239. notify, httpService, url, headers, mUID);
  240. ALOGV("createNuPlayer2Source RTSPSource2 %s", url);
  241. *dataSourceType = DATA_SOURCE_TYPE_RTSP;
  242. } else if ((!strncasecmp(url, "http://", 7)
  243. || !strncasecmp(url, "https://", 8))
  244. && ((len >= 4 && !strcasecmp(".sdp", &url[len - 4]))
  245. || strstr(url, ".sdp?"))) {
  246. *source = new RTSPSource2(
  247. notify, httpService, url, headers, mUID, true);
  248. ALOGV("createNuPlayer2Source RTSPSource2 http/https/.sdp %s", url);
  249. *dataSourceType = DATA_SOURCE_TYPE_RTSP;
  250. } else {
  251. ALOGV("createNuPlayer2Source GenericSource2 %s", url);
  252. sp<GenericSource2> genericSource =
  253. new GenericSource2(notify, mUID, mMediaClock);
  254. err = genericSource->setDataSource(url, headers);
  255. if (err == OK) {
  256. *source = genericSource;
  257. } else {
  258. *source = NULL;
  259. ALOGE("Failed to create NuPlayer2Source!");
  260. }
  261. // regardless of success/failure
  262. *dataSourceType = DATA_SOURCE_TYPE_GENERIC_URL;
  263. }
  264. break;
  265. }
  266. case DataSourceDesc::TYPE_FD:
  267. {
  268. sp<GenericSource2> genericSource =
  269. new GenericSource2(notify, mUID, mMediaClock);
  270. ALOGV("createNuPlayer2Source fd %d/%lld/%lld source: %p",
  271. dsd->mFD, (long long)dsd->mFDOffset, (long long)dsd->mFDLength,
  272. genericSource.get());
  273. err = genericSource->setDataSource(dsd->mFD, dsd->mFDOffset, dsd->mFDLength);
  274. if (err != OK) {
  275. ALOGE("Failed to create NuPlayer2Source!");
  276. *source = NULL;
  277. } else {
  278. *source = genericSource;
  279. }
  280. *dataSourceType = DATA_SOURCE_TYPE_GENERIC_FD;
  281. break;
  282. }
  283. case DataSourceDesc::TYPE_CALLBACK:
  284. {
  285. sp<GenericSource2> genericSource =
  286. new GenericSource2(notify, mUID, mMediaClock);
  287. err = genericSource->setDataSource(dsd->mCallbackSource);
  288. if (err != OK) {
  289. ALOGE("Failed to create NuPlayer2Source!");
  290. *source = NULL;
  291. } else {
  292. *source = genericSource;
  293. }
  294. *dataSourceType = DATA_SOURCE_TYPE_MEDIA;
  295. break;
  296. }
  297. default:
  298. err = BAD_TYPE;
  299. *source = NULL;
  300. *dataSourceType = DATA_SOURCE_TYPE_NONE;
  301. ALOGE("invalid data source type!");
  302. break;
  303. }
  304. return err;
  305. }
  306. void NuPlayer2::setDataSourceAsync(const sp<DataSourceDesc> &dsd) {
  307. DATA_SOURCE_TYPE dataSourceType;
  308. sp<Source> source;
  309. createNuPlayer2Source(dsd, &source, &dataSourceType);
  310. // TODO: currently NuPlayer2Driver makes blocking call to setDataSourceAsync
  311. // and expects notifySetDataSourceCompleted regardless of success or failure.
  312. // This will be changed since setDataSource should be asynchronous at JAVA level.
  313. // When it succeeds, app will get onInfo notification. Otherwise, onError
  314. // will be called.
  315. /*
  316. if (err != OK) {
  317. notifyListener(dsd->mId, MEDIA2_ERROR, MEDIA2_ERROR_FAILED_TO_SET_DATA_SOURCE, err);
  318. return;
  319. }
  320. // Now, source != NULL.
  321. */
  322. mCurrentSourceInfo.mDataSourceType = dataSourceType;
  323. sp<AMessage> msg = new AMessage(kWhatSetDataSource, this);
  324. msg->setObject("source", source);
  325. msg->setInt64("srcId", dsd->mId);
  326. msg->setInt64("startTimeUs", dsd->mStartPositionMs * 1000);
  327. msg->setInt64("endTimeUs", dsd->mEndPositionMs * 1000);
  328. msg->post();
  329. }
  330. void NuPlayer2::prepareNextDataSourceAsync(const sp<DataSourceDesc> &dsd) {
  331. DATA_SOURCE_TYPE dataSourceType;
  332. sp<Source> source;
  333. createNuPlayer2Source(dsd, &source, &dataSourceType);
  334. /*
  335. if (err != OK) {
  336. notifyListener(dsd->mId, MEDIA2_ERROR, MEDIA2_ERROR_FAILED_TO_SET_DATA_SOURCE, err);
  337. return;
  338. }
  339. // Now, source != NULL.
  340. */
  341. mNextSourceInfo.mDataSourceType = dataSourceType;
  342. sp<AMessage> msg = new AMessage(kWhatPrepareNextDataSource, this);
  343. msg->setObject("source", source);
  344. msg->setInt64("srcId", dsd->mId);
  345. msg->setInt64("startTimeUs", dsd->mStartPositionMs * 1000);
  346. msg->setInt64("endTimeUs", dsd->mEndPositionMs * 1000);
  347. msg->post();
  348. }
  349. void NuPlayer2::playNextDataSource(int64_t srcId) {
  350. disconnectSource();
  351. sp<AMessage> msg = new AMessage(kWhatPlayNextDataSource, this);
  352. msg->setInt64("srcId", srcId);
  353. msg->post();
  354. }
  355. status_t NuPlayer2::getBufferingSettings(
  356. BufferingSettings *buffering /* nonnull */) {
  357. sp<AMessage> msg = new AMessage(kWhatGetBufferingSettings, this);
  358. sp<AMessage> response;
  359. status_t err = msg->postAndAwaitResponse(&response);
  360. if (err == OK && response != NULL) {
  361. CHECK(response->findInt32("err", &err));
  362. if (err == OK) {
  363. readFromAMessage(response, buffering);
  364. }
  365. }
  366. return err;
  367. }
  368. status_t NuPlayer2::setBufferingSettings(const BufferingSettings& buffering) {
  369. sp<AMessage> msg = new AMessage(kWhatSetBufferingSettings, this);
  370. writeToAMessage(msg, buffering);
  371. sp<AMessage> response;
  372. status_t err = msg->postAndAwaitResponse(&response);
  373. if (err == OK && response != NULL) {
  374. CHECK(response->findInt32("err", &err));
  375. }
  376. return err;
  377. }
  378. void NuPlayer2::prepareAsync() {
  379. ALOGV("prepareAsync");
  380. (new AMessage(kWhatPrepare, this))->post();
  381. }
  382. void NuPlayer2::setVideoSurfaceTextureAsync(const sp<ANativeWindowWrapper> &nww) {
  383. sp<AMessage> msg = new AMessage(kWhatSetVideoSurface, this);
  384. if (nww == NULL || nww->getANativeWindow() == NULL) {
  385. msg->setObject("surface", NULL);
  386. } else {
  387. msg->setObject("surface", nww);
  388. }
  389. msg->post();
  390. }
  391. void NuPlayer2::setAudioSink(const sp<MediaPlayer2Interface::AudioSink> &sink) {
  392. sp<AMessage> msg = new AMessage(kWhatSetAudioSink, this);
  393. msg->setObject("sink", sink);
  394. msg->post();
  395. }
  396. void NuPlayer2::start() {
  397. (new AMessage(kWhatStart, this))->post();
  398. }
  399. status_t NuPlayer2::setPlaybackSettings(const AudioPlaybackRate &rate) {
  400. // do some cursory validation of the settings here. audio modes are
  401. // only validated when set on the audiosink.
  402. if (rate.mSpeed < AUDIO_TIMESTRETCH_SPEED_MIN
  403. || rate.mSpeed > AUDIO_TIMESTRETCH_SPEED_MAX
  404. || rate.mPitch < AUDIO_TIMESTRETCH_SPEED_MIN
  405. || rate.mPitch > AUDIO_TIMESTRETCH_SPEED_MAX) {
  406. return BAD_VALUE;
  407. }
  408. sp<AMessage> msg = new AMessage(kWhatConfigPlayback, this);
  409. writeToAMessage(msg, rate);
  410. sp<AMessage> response;
  411. status_t err = msg->postAndAwaitResponse(&response);
  412. if (err == OK && response != NULL) {
  413. CHECK(response->findInt32("err", &err));
  414. }
  415. return err;
  416. }
  417. status_t NuPlayer2::getPlaybackSettings(AudioPlaybackRate *rate /* nonnull */) {
  418. sp<AMessage> msg = new AMessage(kWhatGetPlaybackSettings, this);
  419. sp<AMessage> response;
  420. status_t err = msg->postAndAwaitResponse(&response);
  421. if (err == OK && response != NULL) {
  422. CHECK(response->findInt32("err", &err));
  423. if (err == OK) {
  424. readFromAMessage(response, rate);
  425. }
  426. }
  427. return err;
  428. }
  429. status_t NuPlayer2::setSyncSettings(const AVSyncSettings &sync, float videoFpsHint) {
  430. sp<AMessage> msg = new AMessage(kWhatConfigSync, this);
  431. writeToAMessage(msg, sync, videoFpsHint);
  432. sp<AMessage> response;
  433. status_t err = msg->postAndAwaitResponse(&response);
  434. if (err == OK && response != NULL) {
  435. CHECK(response->findInt32("err", &err));
  436. }
  437. return err;
  438. }
  439. status_t NuPlayer2::getSyncSettings(
  440. AVSyncSettings *sync /* nonnull */, float *videoFps /* nonnull */) {
  441. sp<AMessage> msg = new AMessage(kWhatGetSyncSettings, this);
  442. sp<AMessage> response;
  443. status_t err = msg->postAndAwaitResponse(&response);
  444. if (err == OK && response != NULL) {
  445. CHECK(response->findInt32("err", &err));
  446. if (err == OK) {
  447. readFromAMessage(response, sync, videoFps);
  448. }
  449. }
  450. return err;
  451. }
  452. void NuPlayer2::pause() {
  453. (new AMessage(kWhatPause, this))->post();
  454. }
  455. void NuPlayer2::resetAsync() {
  456. disconnectSource();
  457. (new AMessage(kWhatReset, this))->post();
  458. }
  459. void NuPlayer2::disconnectSource() {
  460. sp<Source> source;
  461. {
  462. Mutex::Autolock autoLock(mSourceLock);
  463. source = mCurrentSourceInfo.mSource;
  464. }
  465. if (source != NULL) {
  466. // During a reset, the data source might be unresponsive already, we need to
  467. // disconnect explicitly so that reads exit promptly.
  468. // We can't queue the disconnect request to the looper, as it might be
  469. // queued behind a stuck read and never gets processed.
  470. // Doing a disconnect outside the looper to allows the pending reads to exit
  471. // (either successfully or with error).
  472. source->disconnect();
  473. }
  474. }
  475. status_t NuPlayer2::notifyAt(int64_t mediaTimeUs) {
  476. sp<AMessage> notify = new AMessage(kWhatNotifyTime, this);
  477. notify->setInt64("timerUs", mediaTimeUs);
  478. mMediaClock->addTimer(notify, mediaTimeUs);
  479. return OK;
  480. }
  481. void NuPlayer2::seekToAsync(int64_t seekTimeUs, MediaPlayer2SeekMode mode, bool needNotify) {
  482. sp<AMessage> msg = new AMessage(kWhatSeek, this);
  483. msg->setInt64("seekTimeUs", seekTimeUs);
  484. msg->setInt32("mode", mode);
  485. msg->setInt32("needNotify", needNotify);
  486. msg->post();
  487. }
  488. void NuPlayer2::rewind() {
  489. sp<AMessage> msg = new AMessage(kWhatRewind, this);
  490. msg->post();
  491. }
  492. void NuPlayer2::writeTrackInfo(
  493. PlayerMessage* reply, const sp<AMessage>& format) const {
  494. if (format == NULL) {
  495. ALOGE("NULL format");
  496. return;
  497. }
  498. int32_t trackType;
  499. if (!format->findInt32("type", &trackType)) {
  500. ALOGE("no track type");
  501. return;
  502. }
  503. AString mime;
  504. if (!format->findString("mime", &mime)) {
  505. // Java MediaPlayer only uses mimetype for subtitle and timedtext tracks.
  506. // If we can't find the mimetype here it means that we wouldn't be needing
  507. // the mimetype on the Java end. We still write a placeholder mime to keep the
  508. // (de)serialization logic simple.
  509. if (trackType == MEDIA_TRACK_TYPE_AUDIO) {
  510. mime = "audio/";
  511. } else if (trackType == MEDIA_TRACK_TYPE_VIDEO) {
  512. mime = "video/";
  513. } else {
  514. ALOGE("unknown track type: %d", trackType);
  515. return;
  516. }
  517. }
  518. AString lang;
  519. if (!format->findString("language", &lang)) {
  520. ALOGE("no language");
  521. return;
  522. }
  523. reply->add_values()->set_int32_value(trackType);
  524. reply->add_values()->set_string_value(mime.c_str());
  525. reply->add_values()->set_string_value(lang.c_str());
  526. if (trackType == MEDIA_TRACK_TYPE_SUBTITLE) {
  527. int32_t isAuto, isDefault, isForced;
  528. CHECK(format->findInt32("auto", &isAuto));
  529. CHECK(format->findInt32("default", &isDefault));
  530. CHECK(format->findInt32("forced", &isForced));
  531. reply->add_values()->set_int32_value(isAuto);
  532. reply->add_values()->set_int32_value(isDefault);
  533. reply->add_values()->set_int32_value(isForced);
  534. }
  535. }
  536. void NuPlayer2::onMessageReceived(const sp<AMessage> &msg) {
  537. switch (msg->what()) {
  538. case kWhatSetDataSource:
  539. {
  540. ALOGV("kWhatSetDataSource");
  541. CHECK(mCurrentSourceInfo.mSource == NULL);
  542. status_t err = OK;
  543. sp<RefBase> obj;
  544. CHECK(msg->findObject("source", &obj));
  545. if (obj != NULL) {
  546. Mutex::Autolock autoLock(mSourceLock);
  547. CHECK(msg->findInt64("srcId", &mCurrentSourceInfo.mSrcId));
  548. CHECK(msg->findInt64("startTimeUs", &mCurrentSourceInfo.mStartTimeUs));
  549. CHECK(msg->findInt64("endTimeUs", &mCurrentSourceInfo.mEndTimeUs));
  550. mCurrentSourceInfo.mSource = static_cast<Source *>(obj.get());
  551. } else {
  552. err = UNKNOWN_ERROR;
  553. ALOGE("kWhatSetDataSource, source should not be NULL");
  554. }
  555. CHECK(mDriver != NULL);
  556. sp<NuPlayer2Driver> driver = mDriver.promote();
  557. if (driver != NULL) {
  558. driver->notifySetDataSourceCompleted(mCurrentSourceInfo.mSrcId, err);
  559. }
  560. break;
  561. }
  562. case kWhatPrepareNextDataSource:
  563. {
  564. ALOGV("kWhatPrepareNextDataSource");
  565. status_t err = OK;
  566. sp<RefBase> obj;
  567. CHECK(msg->findObject("source", &obj));
  568. if (obj != NULL) {
  569. Mutex::Autolock autoLock(mSourceLock);
  570. CHECK(msg->findInt64("srcId", &mNextSourceInfo.mSrcId));
  571. CHECK(msg->findInt64("startTimeUs", &mNextSourceInfo.mStartTimeUs));
  572. CHECK(msg->findInt64("endTimeUs", &mNextSourceInfo.mEndTimeUs));
  573. mNextSourceInfo.mSource = static_cast<Source *>(obj.get());
  574. mNextSourceInfo.mSource->prepareAsync(mNextSourceInfo.mStartTimeUs);
  575. } else {
  576. err = UNKNOWN_ERROR;
  577. }
  578. break;
  579. }
  580. case kWhatPlayNextDataSource:
  581. {
  582. ALOGV("kWhatPlayNextDataSource");
  583. int64_t srcId;
  584. CHECK(msg->findInt64("srcId", &srcId));
  585. if (srcId != mNextSourceInfo.mSrcId) {
  586. notifyListener(srcId, MEDIA2_ERROR, MEDIA2_ERROR_UNKNOWN, 0);
  587. return;
  588. }
  589. mResetting = true;
  590. stopPlaybackTimer("kWhatPlayNextDataSource");
  591. stopRebufferingTimer(true);
  592. mDeferredActions.push_back(
  593. new FlushDecoderAction(
  594. FLUSH_CMD_SHUTDOWN /* audio */,
  595. FLUSH_CMD_SHUTDOWN /* video */));
  596. mDeferredActions.push_back(
  597. new SimpleAction(&NuPlayer2::performPlayNextDataSource));
  598. processDeferredActions();
  599. break;
  600. }
  601. case kWhatEOSMonitor:
  602. {
  603. int32_t generation;
  604. CHECK(msg->findInt32("generation", &generation));
  605. int32_t reason;
  606. CHECK(msg->findInt32("reason", &reason));
  607. if (generation != mEOSMonitorGeneration || reason != MediaClock::TIMER_REASON_REACHED) {
  608. break; // stale or reset
  609. }
  610. ALOGV("kWhatEOSMonitor");
  611. notifyListener(mCurrentSourceInfo.mSrcId, MEDIA2_PLAYBACK_COMPLETE, 0, 0);
  612. break;
  613. }
  614. case kWhatGetBufferingSettings:
  615. {
  616. sp<AReplyToken> replyID;
  617. CHECK(msg->senderAwaitsResponse(&replyID));
  618. ALOGV("kWhatGetBufferingSettings");
  619. BufferingSettings buffering;
  620. status_t err = OK;
  621. if (mCurrentSourceInfo.mSource != NULL) {
  622. err = mCurrentSourceInfo.mSource->getBufferingSettings(&buffering);
  623. } else {
  624. err = INVALID_OPERATION;
  625. }
  626. sp<AMessage> response = new AMessage;
  627. if (err == OK) {
  628. writeToAMessage(response, buffering);
  629. }
  630. response->setInt32("err", err);
  631. response->postReply(replyID);
  632. break;
  633. }
  634. case kWhatSetBufferingSettings:
  635. {
  636. sp<AReplyToken> replyID;
  637. CHECK(msg->senderAwaitsResponse(&replyID));
  638. ALOGV("kWhatSetBufferingSettings");
  639. BufferingSettings buffering;
  640. readFromAMessage(msg, &buffering);
  641. status_t err = OK;
  642. if (mCurrentSourceInfo.mSource != NULL) {
  643. err = mCurrentSourceInfo.mSource->setBufferingSettings(buffering);
  644. } else {
  645. err = INVALID_OPERATION;
  646. }
  647. sp<AMessage> response = new AMessage;
  648. response->setInt32("err", err);
  649. response->postReply(replyID);
  650. break;
  651. }
  652. case kWhatPrepare:
  653. {
  654. ALOGV("onMessageReceived kWhatPrepare");
  655. mCurrentSourceInfo.mSource->prepareAsync(mCurrentSourceInfo.mStartTimeUs);
  656. break;
  657. }
  658. case kWhatGetTrackInfo:
  659. {
  660. sp<AReplyToken> replyID;
  661. CHECK(msg->senderAwaitsResponse(&replyID));
  662. int64_t srcId;
  663. CHECK(msg->findInt64("srcId", (int64_t*)&srcId));
  664. PlayerMessage* reply;
  665. CHECK(msg->findPointer("reply", (void**)&reply));
  666. // TODO: use correct source info based on srcId.
  667. size_t inbandTracks = 0;
  668. if (mCurrentSourceInfo.mSource != NULL) {
  669. inbandTracks = mCurrentSourceInfo.mSource->getTrackCount();
  670. }
  671. size_t ccTracks = 0;
  672. if (mCCDecoder != NULL) {
  673. ccTracks = mCCDecoder->getTrackCount();
  674. }
  675. // total track count
  676. reply->add_values()->set_int32_value(inbandTracks + ccTracks);
  677. // write inband tracks
  678. for (size_t i = 0; i < inbandTracks; ++i) {
  679. writeTrackInfo(reply, mCurrentSourceInfo.mSource->getTrackInfo(i));
  680. }
  681. // write CC track
  682. for (size_t i = 0; i < ccTracks; ++i) {
  683. writeTrackInfo(reply, mCCDecoder->getTrackInfo(i));
  684. }
  685. sp<AMessage> response = new AMessage;
  686. response->postReply(replyID);
  687. break;
  688. }
  689. case kWhatGetSelectedTrack:
  690. {
  691. int64_t srcId;
  692. CHECK(msg->findInt64("srcId", (int64_t*)&srcId));
  693. int32_t type32;
  694. CHECK(msg->findInt32("type", (int32_t*)&type32));
  695. media_track_type type = (media_track_type)type32;
  696. // TODO: use correct source info based on srcId.
  697. size_t inbandTracks = 0;
  698. status_t err = INVALID_OPERATION;
  699. ssize_t selectedTrack = -1;
  700. if (mCurrentSourceInfo.mSource != NULL) {
  701. err = OK;
  702. inbandTracks = mCurrentSourceInfo.mSource->getTrackCount();
  703. selectedTrack = mCurrentSourceInfo.mSource->getSelectedTrack(type);
  704. }
  705. if (selectedTrack == -1 && mCCDecoder != NULL) {
  706. err = OK;
  707. selectedTrack = mCCDecoder->getSelectedTrack(type);
  708. if (selectedTrack != -1) {
  709. selectedTrack += inbandTracks;
  710. }
  711. }
  712. PlayerMessage* reply;
  713. CHECK(msg->findPointer("reply", (void**)&reply));
  714. reply->add_values()->set_int32_value(selectedTrack);
  715. sp<AMessage> response = new AMessage;
  716. response->setInt32("err", err);
  717. sp<AReplyToken> replyID;
  718. CHECK(msg->senderAwaitsResponse(&replyID));
  719. response->postReply(replyID);
  720. break;
  721. }
  722. case kWhatSelectTrack:
  723. {
  724. sp<AReplyToken> replyID;
  725. CHECK(msg->senderAwaitsResponse(&replyID));
  726. int64_t srcId;
  727. size_t trackIndex;
  728. int32_t select;
  729. int64_t timeUs;
  730. CHECK(msg->findInt64("srcId", (int64_t*)&srcId));
  731. CHECK(msg->findSize("trackIndex", &trackIndex));
  732. CHECK(msg->findInt32("select", &select));
  733. CHECK(msg->findInt64("timeUs", &timeUs));
  734. status_t err = INVALID_OPERATION;
  735. // TODO: use correct source info based on srcId.
  736. size_t inbandTracks = 0;
  737. if (mCurrentSourceInfo.mSource != NULL) {
  738. inbandTracks = mCurrentSourceInfo.mSource->getTrackCount();
  739. }
  740. size_t ccTracks = 0;
  741. if (mCCDecoder != NULL) {
  742. ccTracks = mCCDecoder->getTrackCount();
  743. }
  744. if (trackIndex < inbandTracks) {
  745. err = mCurrentSourceInfo.mSource->selectTrack(trackIndex, select, timeUs);
  746. if (!select && err == OK) {
  747. int32_t type;
  748. sp<AMessage> info = mCurrentSourceInfo.mSource->getTrackInfo(trackIndex);
  749. if (info != NULL
  750. && info->findInt32("type", &type)
  751. && type == MEDIA_TRACK_TYPE_TIMEDTEXT) {
  752. ++mTimedTextGeneration;
  753. }
  754. }
  755. } else {
  756. trackIndex -= inbandTracks;
  757. if (trackIndex < ccTracks) {
  758. err = mCCDecoder->selectTrack(trackIndex, select);
  759. }
  760. }
  761. sp<AMessage> response = new AMessage;
  762. response->setInt32("err", err);
  763. response->postReply(replyID);
  764. break;
  765. }
  766. case kWhatPollDuration:
  767. {
  768. int32_t generation;
  769. CHECK(msg->findInt32("generation", &generation));
  770. if (generation != mPollDurationGeneration) {
  771. // stale
  772. break;
  773. }
  774. int64_t durationUs;
  775. if (mDriver != NULL && mCurrentSourceInfo.mSource->getDuration(&durationUs) == OK) {
  776. sp<NuPlayer2Driver> driver = mDriver.promote();
  777. if (driver != NULL) {
  778. driver->notifyDuration(mCurrentSourceInfo.mSrcId, durationUs);
  779. }
  780. }
  781. msg->post(1000000LL); // poll again in a second.
  782. break;
  783. }
  784. case kWhatSetVideoSurface:
  785. {
  786. sp<RefBase> obj;
  787. CHECK(msg->findObject("surface", &obj));
  788. sp<ANativeWindowWrapper> nww = static_cast<ANativeWindowWrapper *>(obj.get());
  789. ALOGD("onSetVideoSurface(%p, %s video decoder)",
  790. (nww == NULL ? NULL : nww->getANativeWindow()),
  791. (mCurrentSourceInfo.mSource != NULL && mStarted
  792. && mCurrentSourceInfo.mSource->getFormat(false /* audio */) != NULL
  793. && mVideoDecoder != NULL) ? "have" : "no");
  794. // Need to check mStarted before calling mCurrentSourceInfo.mSource->getFormat
  795. // because NuPlayer2 might be in preparing state and it could take long time.
  796. // When mStarted is true, mCurrentSourceInfo.mSource must have been set.
  797. if (mCurrentSourceInfo.mSource == NULL || !mStarted
  798. || mCurrentSourceInfo.mSource->getFormat(false /* audio */) == NULL
  799. // NOTE: mVideoDecoder's mNativeWindow is always non-null
  800. || (mVideoDecoder != NULL && mVideoDecoder->setVideoSurface(nww) == OK)) {
  801. performSetSurface(nww);
  802. break;
  803. }
  804. mDeferredActions.push_back(
  805. new FlushDecoderAction(
  806. (obj != NULL ? FLUSH_CMD_FLUSH : FLUSH_CMD_NONE) /* audio */,
  807. FLUSH_CMD_SHUTDOWN /* video */));
  808. mDeferredActions.push_back(new SetSurfaceAction(nww));
  809. if (obj != NULL) {
  810. if (mStarted) {
  811. // Issue a seek to refresh the video screen only if started otherwise
  812. // the extractor may not yet be started and will assert.
  813. // If the video decoder is not set (perhaps audio only in this case)
  814. // do not perform a seek as it is not needed.
  815. int64_t currentPositionUs = 0;
  816. if (getCurrentPosition(&currentPositionUs) == OK) {
  817. mDeferredActions.push_back(
  818. new SeekAction(currentPositionUs,
  819. MediaPlayer2SeekMode::SEEK_PREVIOUS_SYNC /* mode */));
  820. }
  821. }
  822. // If there is a new surface texture, instantiate decoders
  823. // again if possible.
  824. mDeferredActions.push_back(
  825. new SimpleAction(&NuPlayer2::performScanSources));
  826. // After a flush without shutdown, decoder is paused.
  827. // Don't resume it until source seek is done, otherwise it could
  828. // start pulling stale data too soon.
  829. mDeferredActions.push_back(
  830. new ResumeDecoderAction(false /* needNotify */));
  831. }
  832. processDeferredActions();
  833. break;
  834. }
  835. case kWhatSetAudioSink:
  836. {
  837. ALOGV("kWhatSetAudioSink");
  838. sp<RefBase> obj;
  839. CHECK(msg->findObject("sink", &obj));
  840. mAudioSink = static_cast<MediaPlayer2Interface::AudioSink *>(obj.get());
  841. break;
  842. }
  843. case kWhatStart:
  844. {
  845. ALOGV("kWhatStart");
  846. if (mStarted) {
  847. // do not resume yet if the source is still buffering
  848. if (!mPausedForBuffering) {
  849. onResume();
  850. }
  851. } else {
  852. onStart(true /* play */);
  853. }
  854. mPausedByClient = false;
  855. notifyListener(mCurrentSourceInfo.mSrcId, MEDIA2_STARTED, 0, 0);
  856. break;
  857. }
  858. case kWhatConfigPlayback:
  859. {
  860. sp<AReplyToken> replyID;
  861. CHECK(msg->senderAwaitsResponse(&replyID));
  862. AudioPlaybackRate rate /* sanitized */;
  863. readFromAMessage(msg, &rate);
  864. status_t err = OK;
  865. if (mRenderer != NULL) {
  866. // AudioSink allows only 1.f and 0.f for offload mode.
  867. // For other speed, switch to non-offload mode.
  868. if (mOffloadAudio && (rate.mSpeed != 1.f || rate.mPitch != 1.f)) {
  869. int64_t currentPositionUs;
  870. if (getCurrentPosition(&currentPositionUs) != OK) {
  871. currentPositionUs = mPreviousSeekTimeUs;
  872. }
  873. // Set mPlaybackSettings so that the new audio decoder can
  874. // be created correctly.
  875. mPlaybackSettings = rate;
  876. if (!mPaused) {
  877. mRenderer->pause();
  878. }
  879. restartAudio(
  880. currentPositionUs, true /* forceNonOffload */,
  881. true /* needsToCreateAudioDecoder */);
  882. if (!mPaused) {
  883. mRenderer->resume();
  884. }
  885. }
  886. err = mRenderer->setPlaybackSettings(rate);
  887. }
  888. if (err == OK) {
  889. mPlaybackSettings = rate;
  890. if (mVideoDecoder != NULL) {
  891. sp<AMessage> params = new AMessage();
  892. params->setFloat("playback-speed", mPlaybackSettings.mSpeed);
  893. mVideoDecoder->setParameters(params);
  894. }
  895. }
  896. sp<AMessage> response = new AMessage;
  897. response->setInt32("err", err);
  898. response->postReply(replyID);
  899. break;
  900. }
  901. case kWhatGetPlaybackSettings:
  902. {
  903. sp<AReplyToken> replyID;
  904. CHECK(msg->senderAwaitsResponse(&replyID));
  905. AudioPlaybackRate rate = mPlaybackSettings;
  906. status_t err = OK;
  907. if (mRenderer != NULL) {
  908. err = mRenderer->getPlaybackSettings(&rate);
  909. }
  910. if (err == OK) {
  911. // get playback settings used by renderer, as it may be
  912. // slightly off due to audiosink not taking small changes.
  913. mPlaybackSettings = rate;
  914. }
  915. sp<AMessage> response = new AMessage;
  916. if (err == OK) {
  917. writeToAMessage(response, rate);
  918. }
  919. response->setInt32("err", err);
  920. response->postReply(replyID);
  921. break;
  922. }
  923. case kWhatConfigSync:
  924. {
  925. sp<AReplyToken> replyID;
  926. CHECK(msg->senderAwaitsResponse(&replyID));
  927. ALOGV("kWhatConfigSync");
  928. AVSyncSettings sync;
  929. float videoFpsHint;
  930. readFromAMessage(msg, &sync, &videoFpsHint);
  931. status_t err = OK;
  932. if (mRenderer != NULL) {
  933. err = mRenderer->setSyncSettings(sync, videoFpsHint);
  934. }
  935. if (err == OK) {
  936. mSyncSettings = sync;
  937. mVideoFpsHint = videoFpsHint;
  938. }
  939. sp<AMessage> response = new AMessage;
  940. response->setInt32("err", err);
  941. response->postReply(replyID);
  942. break;
  943. }
  944. case kWhatGetSyncSettings:
  945. {
  946. sp<AReplyToken> replyID;
  947. CHECK(msg->senderAwaitsResponse(&replyID));
  948. AVSyncSettings sync = mSyncSettings;
  949. float videoFps = mVideoFpsHint;
  950. status_t err = OK;
  951. if (mRenderer != NULL) {
  952. err = mRenderer->getSyncSettings(&sync, &videoFps);
  953. if (err == OK) {
  954. mSyncSettings = sync;
  955. mVideoFpsHint = videoFps;
  956. }
  957. }
  958. sp<AMessage> response = new AMessage;
  959. if (err == OK) {
  960. writeToAMessage(response, sync, videoFps);
  961. }
  962. response->setInt32("err", err);
  963. response->postReply(replyID);
  964. break;
  965. }
  966. case kWhatScanSources:
  967. {
  968. int32_t generation;
  969. CHECK(msg->findInt32("generation", &generation));
  970. if (generation != mScanSourcesGeneration) {
  971. // Drop obsolete msg.
  972. break;
  973. }
  974. mScanSourcesPending = false;
  975. ALOGV("scanning sources haveAudio=%d, haveVideo=%d",
  976. mAudioDecoder != NULL, mVideoDecoder != NULL);
  977. bool mHadAnySourcesBefore =
  978. (mAudioDecoder != NULL) || (mVideoDecoder != NULL);
  979. bool rescan = false;
  980. // initialize video before audio because successful initialization of
  981. // video may change deep buffer mode of audio.
  982. if (mNativeWindow != NULL && mNativeWindow->getANativeWindow() != NULL) {
  983. if (instantiateDecoder(false, &mVideoDecoder) == -EWOULDBLOCK) {
  984. rescan = true;
  985. }
  986. }
  987. // Don't try to re-open audio sink if there's an existing decoder.
  988. if (mAudioSink != NULL && mAudioDecoder == NULL) {
  989. if (instantiateDecoder(true, &mAudioDecoder) == -EWOULDBLOCK) {
  990. rescan = true;
  991. }
  992. }
  993. if (!mHadAnySourcesBefore
  994. && (mAudioDecoder != NULL || mVideoDecoder != NULL)) {
  995. // This is the first time we've found anything playable.
  996. if (mCurrentSourceInfo.mSourceFlags & Source::FLAG_DYNAMIC_DURATION) {
  997. schedulePollDuration();
  998. }
  999. }
  1000. status_t err;
  1001. if ((err = mCurrentSourceInfo.mSource->feedMoreTSData()) != OK) {
  1002. if (mAudioDecoder == NULL && mVideoDecoder == NULL) {
  1003. // We're not currently decoding anything (no audio or
  1004. // video tracks found) and we just ran out of input data.
  1005. if (err == ERROR_END_OF_STREAM) {
  1006. notifyListener(mCurrentSourceInfo.mSrcId, MEDIA2_PLAYBACK_COMPLETE, 0, 0);
  1007. } else {
  1008. notifyListener(
  1009. mCurrentSourceInfo.mSrcId, MEDIA2_ERROR, MEDIA2_ERROR_UNKNOWN, err);
  1010. }
  1011. }
  1012. break;
  1013. }
  1014. if (rescan) {
  1015. msg->post(100000LL);
  1016. mScanSourcesPending = true;
  1017. }
  1018. break;
  1019. }
  1020. case kWhatVideoNotify:
  1021. case kWhatAudioNotify:
  1022. {
  1023. bool audio = msg->what() == kWhatAudioNotify;
  1024. int32_t currentDecoderGeneration =
  1025. (audio? mAudioDecoderGeneration : mVideoDecoderGeneration);
  1026. int32_t requesterGeneration = currentDecoderGeneration - 1;
  1027. CHECK(msg->findInt32("generation", &requesterGeneration));
  1028. if (requesterGeneration != currentDecoderGeneration) {
  1029. ALOGV("got message from old %s decoder, generation(%d:%d)",
  1030. audio ? "audio" : "video", requesterGeneration,
  1031. currentDecoderGeneration);
  1032. sp<AMessage> reply;
  1033. if (!(msg->findMessage("reply", &reply))) {
  1034. return;
  1035. }
  1036. reply->setInt32("err", INFO_DISCONTINUITY);
  1037. reply->post();
  1038. return;
  1039. }
  1040. int32_t what;
  1041. CHECK(msg->findInt32("what", &what));
  1042. if (what == DecoderBase::kWhatInputDiscontinuity) {
  1043. int32_t formatChange;
  1044. CHECK(msg->findInt32("formatChange", &formatChange));
  1045. ALOGV("%s discontinuity: formatChange %d",
  1046. audio ? "audio" : "video", formatChange);
  1047. if (formatChange) {
  1048. mDeferredActions.push_back(
  1049. new FlushDecoderAction(
  1050. audio ? FLUSH_CMD_SHUTDOWN : FLUSH_CMD_NONE,
  1051. audio ? FLUSH_CMD_NONE : FLUSH_CMD_SHUTDOWN));
  1052. }
  1053. mDeferredActions.push_back(
  1054. new SimpleAction(
  1055. &NuPlayer2::performScanSources));
  1056. processDeferredActions();
  1057. } else if (what == DecoderBase::kWhatEOS) {
  1058. int32_t err;
  1059. CHECK(msg->findInt32("err", &err));
  1060. if (err == ERROR_END_OF_STREAM) {
  1061. ALOGV("got %s decoder EOS", audio ? "audio" : "video");
  1062. } else {
  1063. ALOGV("got %s decoder EOS w/ error %d",
  1064. audio ? "audio" : "video",
  1065. err);
  1066. }
  1067. mRenderer->queueEOS(audio, err);
  1068. } else if (what == DecoderBase::kWhatFlushCompleted) {
  1069. ALOGV("decoder %s flush completed", audio ? "audio" : "video");
  1070. handleFlushComplete(audio, true /* isDecoder */);
  1071. finishFlushIfPossible();
  1072. } else if (what == DecoderBase::kWhatVideoSizeChanged) {
  1073. sp<AMessage> format;
  1074. CHECK(msg->findMessage("format", &format));
  1075. sp<AMessage> inputFormat =
  1076. mCurrentSourceInfo.mSource->getFormat(false /* audio */);
  1077. setVideoScalingMode(mVideoScalingMode);
  1078. updateVideoSize(mCurrentSourceInfo.mSrcId, inputFormat, format);
  1079. } else if (what == DecoderBase::kWhatShutdownCompleted) {
  1080. ALOGV("%s shutdown completed", audio ? "audio" : "video");
  1081. if (audio) {
  1082. Mutex::Autolock autoLock(mDecoderLock);
  1083. mAudioDecoder.clear();
  1084. mAudioDecoderError = false;
  1085. ++mAudioDecoderGeneration;
  1086. CHECK_EQ((int)mFlushingAudio, (int)SHUTTING_DOWN_DECODER);
  1087. mFlushingAudio = SHUT_DOWN;
  1088. } else {
  1089. Mutex::Autolock autoLock(mDecoderLock);
  1090. mVideoDecoder.clear();
  1091. mVideoDecoderError = false;
  1092. ++mVideoDecoderGeneration;
  1093. CHECK_EQ((int)mFlushingVideo, (int)SHUTTING_DOWN_DECODER);
  1094. mFlushingVideo = SHUT_DOWN;
  1095. }
  1096. finishFlushIfPossible();
  1097. } else if (what == DecoderBase::kWhatResumeCompleted) {
  1098. finishResume();
  1099. } else if (what == DecoderBase::kWhatError) {
  1100. status_t err;
  1101. if (!msg->findInt32("err", &err) || err == OK) {
  1102. err = UNKNOWN_ERROR;
  1103. }
  1104. // Decoder errors can be due to Source (e.g. from streaming),
  1105. // or from decoding corrupted bitstreams, or from other decoder
  1106. // MediaCodec operations (e.g. from an ongoing reset or seek).
  1107. // They may also be due to openAudioSink failure at
  1108. // decoder start or after a format change.
  1109. //
  1110. // We try to gracefully shut down the affected decoder if possible,
  1111. // rather than trying to force the shutdown with something
  1112. // similar to performReset(). This method can lead to a hang
  1113. // if MediaCodec functions block after an error, but they should
  1114. // typically return INVALID_OPERATION instead of blocking.
  1115. FlushStatus *flushing = audio ? &mFlushingAudio : &mFlushingVideo;
  1116. ALOGE("received error(%#x) from %s decoder, flushing(%d), now shutting down",
  1117. err, audio ? "audio" : "video", *flushing);
  1118. switch (*flushing) {
  1119. case NONE:
  1120. mDeferredActions.push_back(
  1121. new FlushDecoderAction(
  1122. audio ? FLUSH_CMD_SHUTDOWN : FLUSH_CMD_NONE,
  1123. audio ? FLUSH_CMD_NONE : FLUSH_CMD_SHUTDOWN));
  1124. processDeferredActions();
  1125. break;
  1126. case FLUSHING_DECODER:
  1127. *flushing = FLUSHING_DECODER_SHUTDOWN; // initiate shutdown after flush.
  1128. break; // Wait for flush to complete.
  1129. case FLUSHING_DECODER_SHUTDOWN:
  1130. break; // Wait for flush to complete.
  1131. case SHUTTING_DOWN_DECODER:
  1132. break; // Wait for shutdown to complete.
  1133. case FLUSHED:
  1134. getDecoder(audio)->initiateShutdown(); // In the middle of a seek.
  1135. *flushing = SHUTTING_DOWN_DECODER; // Shut down.
  1136. break;
  1137. case SHUT_DOWN:
  1138. finishFlushIfPossible(); // Should not occur.
  1139. break; // Finish anyways.
  1140. }
  1141. if (mCurrentSourceInfo.mSource != nullptr) {
  1142. if (audio) {
  1143. if (mVideoDecoderError
  1144. || mCurrentSourceInfo.mSource->getFormat(false /* audio */) == NULL
  1145. || mNativeWindow == NULL
  1146. || mNativeWindow->getANativeWindow() == NULL
  1147. || mVideoDecoder == NULL) {
  1148. // When both audio and video have error, or this stream has only audio
  1149. // which has error, notify client of error.
  1150. notifyListener(
  1151. mCurrentSourceInfo.mSrcId, MEDIA2_ERROR,
  1152. MEDIA2_ERROR_UNKNOWN, err);
  1153. } else {
  1154. // Only audio track has error. Video track could be still good to play.
  1155. notifyListener(
  1156. mCurrentSourceInfo.mSrcId, MEDIA2_INFO,
  1157. MEDIA2_INFO_PLAY_AUDIO_ERROR, err);
  1158. }
  1159. mAudioDecoderError = true;
  1160. } else {
  1161. if (mAudioDecoderError
  1162. || mCurrentSourceInfo.mSource->getFormat(true /* audio */) == NULL
  1163. || mAudioSink == NULL || mAudioDecoder == NULL) {
  1164. // When both audio and video have error, or this stream has only video
  1165. // which has error, notify client of error.
  1166. notifyListener(
  1167. mCurrentSourceInfo.mSrcId, MEDIA2_ERROR,
  1168. MEDIA2_ERROR_UNKNOWN, err);
  1169. } else {
  1170. // Only video track has error. Audio track could be still good to play.
  1171. notifyListener(
  1172. mCurrentSourceInfo.mSrcId, MEDIA2_INFO,
  1173. MEDIA2_INFO_PLAY_VIDEO_ERROR, err);
  1174. }
  1175. mVideoDecoderError = true;
  1176. }
  1177. }
  1178. } else {
  1179. ALOGV("Unhandled decoder notification %d '%c%c%c%c'.",
  1180. what,
  1181. what >> 24,
  1182. (what >> 16) & 0xff,
  1183. (what >> 8) & 0xff,
  1184. what & 0xff);
  1185. }
  1186. break;
  1187. }
  1188. case kWhatRendererNotify:
  1189. {
  1190. int32_t requesterGeneration = mRendererGeneration - 1;
  1191. CHECK(msg->findInt32("generation", &requesterGeneration));
  1192. if (requesterGeneration != mRendererGeneration) {
  1193. ALOGV("got message from old renderer, generation(%d:%d)",
  1194. requesterGeneration, mRendererGeneration);
  1195. return;
  1196. }
  1197. int32_t what;
  1198. CHECK(msg->findInt32("what", &what));
  1199. if (what == Renderer::kWhatEOS) {
  1200. int32_t audio;
  1201. CHECK(msg->findInt32("audio", &audio));
  1202. int32_t finalResult;
  1203. CHECK(msg->findInt32("finalResult", &finalResult));
  1204. if (audio) {
  1205. mAudioEOS = true;
  1206. } else {
  1207. mVideoEOS = true;
  1208. }
  1209. if (finalResult == ERROR_END_OF_STREAM) {
  1210. ALOGV("reached %s EOS", audio ? "audio" : "video");
  1211. } else {
  1212. ALOGE("%s track encountered an error (%d)",
  1213. audio ? "audio" : "video", finalResult);
  1214. notifyListener(
  1215. mCurrentSourceInfo.mSrcId, MEDIA2_ERROR,
  1216. MEDIA2_ERROR_UNKNOWN, finalResult);
  1217. }
  1218. if ((mAudioEOS || mAudioDecoder == NULL)
  1219. && (mVideoEOS || mVideoDecoder == NULL)) {
  1220. notifyListener(mCurrentSourceInfo.mSrcId, MEDIA2_PLAYBACK_COMPLETE, 0, 0);
  1221. }
  1222. } else if (what == Renderer::kWhatFlushComplete) {
  1223. int32_t audio;
  1224. CHECK(msg->findInt32("audio", &audio));
  1225. if (audio) {
  1226. mAudioEOS = false;
  1227. } else {
  1228. mVideoEOS = false;
  1229. }
  1230. ALOGV("renderer %s flush completed.", audio ? "audio" : "video");
  1231. if (audio && (mFlushingAudio == NONE || mFlushingAudio == FLUSHED
  1232. || mFlushingAudio == SHUT_DOWN)) {
  1233. // Flush has been handled by tear down.
  1234. break;
  1235. }
  1236. handleFlushComplete(audio, false /* isDecoder */);
  1237. finishFlushIfPossible();
  1238. } else if (what == Renderer::kWhatVideoRenderingStart) {
  1239. notifyListener(mCurrentSourceInfo.mSrcId, MEDIA2_INFO,
  1240. MEDIA2_INFO_VIDEO_RENDERING_START, 0);
  1241. } else if (what == Renderer::kWhatMediaRenderingStart) {
  1242. ALOGV("media rendering started");
  1243. notifyListener(mCurrentSourceInfo.mSrcId, MEDIA2_STARTED, 0, 0);
  1244. } else if (what == Renderer::kWhatAudioTearDown) {
  1245. int32_t reason;
  1246. CHECK(msg->findInt32("reason", &reason));
  1247. ALOGV("Tear down audio with reason %d.", reason);
  1248. if (reason == Renderer::kDueToTimeout && !(mPaused && mOffloadAudio)) {
  1249. // TimeoutWhenPaused is only for offload mode.
  1250. ALOGW("Receive a stale message for teardown.");
  1251. break;
  1252. }
  1253. int64_t positionUs;
  1254. if (!msg->findInt64("positionUs", &positionUs)) {
  1255. positionUs = mPreviousSeekTimeUs;
  1256. }
  1257. restartAudio(
  1258. positionUs, reason == Renderer::kForceNonOffload /* forceNonOffload */,
  1259. reason != Renderer::kDueToTimeout /* needsToCreateAudioDecoder */);
  1260. }
  1261. break;
  1262. }
  1263. case kWhatMoreDataQueued:
  1264. {
  1265. break;
  1266. }
  1267. case kWhatReset:
  1268. {
  1269. ALOGV("kWhatReset");
  1270. mResetting = true;
  1271. stopPlaybackTimer("kWhatReset");
  1272. stopRebufferingTimer(true);
  1273. mDeferredActions.push_back(
  1274. new FlushDecoderAction(
  1275. FLUSH_CMD_SHUTDOWN /* audio */,
  1276. FLUSH_CMD_SHUTDOWN /* video */));
  1277. mDeferredActions.push_back(
  1278. new SimpleAction(&NuPlayer2::performReset));
  1279. processDeferredActions();
  1280. break;
  1281. }
  1282. case kWhatNotifyTime:
  1283. {
  1284. ALOGV("kWhatNotifyTime");
  1285. int64_t timerUs;
  1286. CHECK(msg->findInt64("timerUs", &timerUs));
  1287. notifyListener(mCurrentSourceInfo.mSrcId, MEDIA2_NOTIFY_TIME, timerUs, 0);
  1288. break;
  1289. }
  1290. case kWhatSeek:
  1291. {
  1292. int64_t seekTimeUs;
  1293. int32_t mode;
  1294. int32_t needNotify;
  1295. CHECK(msg->findInt64("seekTimeUs", &seekTimeUs));
  1296. CHECK(msg->findInt32("mode", &mode));
  1297. CHECK(msg->findInt32("needNotify", &needNotify));
  1298. ALOGV("kWhatSeek seekTimeUs=%lld us, mode=%d, needNotify=%d",
  1299. (long long)seekTimeUs, mode, needNotify);
  1300. if (!mStarted) {
  1301. if (!mSourceStarted) {
  1302. mSourceStarted = true;
  1303. mCurrentSourceInfo.mSource->start();
  1304. }
  1305. if (seekTimeUs > 0) {
  1306. performSeek(seekTimeUs, (MediaPlayer2SeekMode)mode);
  1307. }
  1308. if (needNotify) {
  1309. notifyDriverSeekComplete(mCurrentSourceInfo.mSrcId);
  1310. }
  1311. break;
  1312. }
  1313. // seeks can take a while, so we essentially paused
  1314. notifyListener(mCurrentSourceInfo.mSrcId, MEDIA2_PAUSED, 0, 0);
  1315. mDeferredActions.push_back(
  1316. new FlushDecoderAction(FLUSH_CMD_FLUSH /* audio */,
  1317. FLUSH_CMD_FLUSH /* video */));
  1318. mDeferredActions.push_back(
  1319. new SeekAction(seekTimeUs, (MediaPlayer2SeekMode)mode));
  1320. // After a flush without shutdown, decoder is paused.
  1321. // Don't resume it until source seek is done, otherwise it could
  1322. // start pulling stale data too soon.
  1323. mDeferredActions.push_back(
  1324. new ResumeDecoderAction(needNotify));
  1325. processDeferredActions();
  1326. break;
  1327. }
  1328. case kWhatRewind:
  1329. {
  1330. ALOGV("kWhatRewind");
  1331. int64_t seekTimeUs = mCurrentSourceInfo.mStartTimeUs;
  1332. int32_t mode = MediaPlayer2SeekMode::SEEK_CLOSEST;
  1333. if (!mStarted) {
  1334. if (!mSourceStarted) {
  1335. mSourceStarted = true;
  1336. mCurrentSourceInfo.mSource->start();
  1337. }
  1338. performSeek(seekTimeUs, (MediaPlayer2SeekMode)mode);
  1339. break;
  1340. }
  1341. // seeks can take a while, so we essentially paused
  1342. notifyListener(mCurrentSourceInfo.mSrcId, MEDIA2_PAUSED, 0, 0);
  1343. mDeferredActions.push_back(
  1344. new FlushDecoderAction(FLUSH_CMD_FLUSH /* audio */,
  1345. FLUSH_CMD_FLUSH /* video */));
  1346. mDeferredActions.push_back(
  1347. new SeekAction(seekTimeUs, (MediaPlayer2SeekMode)mode));
  1348. // After a flush without shutdown, decoder is paused.
  1349. // Don't resume it until source seek is done, otherwise it could
  1350. // start pulling stale data too soon.
  1351. mDeferredActions.push_back(
  1352. new ResumeDecoderAction(false /* needNotify */));
  1353. processDeferredActions();
  1354. break;
  1355. }
  1356. case kWhatPause:
  1357. {
  1358. if (!mStarted) {
  1359. onStart(false /* play */);
  1360. }
  1361. onPause();
  1362. notifyListener(mCurrentSourceInfo.mSrcId, MEDIA2_PAUSED, 0, 0);
  1363. mPausedByClient = true;
  1364. break;
  1365. }
  1366. case kWhatSourceNotify:
  1367. {
  1368. onSourceNotify(msg);
  1369. break;
  1370. }
  1371. case kWhatClosedCaptionNotify:
  1372. {
  1373. onClosedCaptionNotify(msg);
  1374. break;
  1375. }
  1376. case kWhatPrepareDrm:
  1377. {
  1378. status_t status = onPrepareDrm(msg);
  1379. sp<AMessage> response = new AMessage;
  1380. response->setInt32("status", status);
  1381. sp<AReplyToken> replyID;
  1382. CHECK(msg->senderAwaitsResponse(&replyID));
  1383. response->postReply(replyID);
  1384. break;
  1385. }
  1386. case kWhatReleaseDrm:
  1387. {
  1388. status_t status = onReleaseDrm(msg);
  1389. sp<AMessage> response = new AMessage;
  1390. response->setInt32("status", status);
  1391. sp<AReplyToken> replyID;
  1392. CHECK(msg->senderAwaitsResponse(&replyID));
  1393. response->postReply(replyID);
  1394. break;
  1395. }
  1396. default:
  1397. TRESPASS();
  1398. break;
  1399. }
  1400. }
  1401. void NuPlayer2::onResume() {
  1402. if (!mPaused || mResetting) {
  1403. ALOGD_IF(mResetting, "resetting, onResume discarded");
  1404. return;
  1405. }
  1406. mPaused = false;
  1407. if (mCurrentSourceInfo.mSource != NULL) {
  1408. mCurrentSourceInfo.mSource->resume();
  1409. } else {
  1410. ALOGW("resume called when source is gone or not set");
  1411. }
  1412. // |mAudioDecoder| may have been released due to the pause timeout, so re-create it if
  1413. // needed.
  1414. if (audioDecoderStillNeeded() && mAudioDecoder == NULL) {
  1415. instantiateDecoder(true /* audio */, &mAudioDecoder);
  1416. }
  1417. if (mRenderer != NULL) {
  1418. mRenderer->resume();
  1419. } else {
  1420. ALOGW("resume called when renderer is gone or not set");
  1421. }
  1422. startPlaybackTimer("onresume");
  1423. }
  1424. void NuPlayer2::onStart(bool play) {
  1425. ALOGV("onStart: mCrypto: %p", mCurrentSourceInfo.mCrypto.get());
  1426. if (!mSourceStarted) {
  1427. mSourceStarted = true;
  1428. mCurrentSourceInfo.mSource->start();
  1429. }
  1430. mOffloadAudio = false;
  1431. mAudioEOS = false;
  1432. mVideoEOS = false;
  1433. mStarted = true;
  1434. mPaused = false;
  1435. uint32_t flags = 0;
  1436. if (mCurrentSourceInfo.mSource->isRealTime()) {
  1437. flags |= Renderer::FLAG_REAL_TIME;
  1438. }
  1439. bool hasAudio = (mCurrentSourceInfo.mSource->getFormat(true /* audio */) != NULL);
  1440. bool hasVideo = (mCurrentSourceInfo.mSource->getFormat(false /* audio */) != NULL);
  1441. if (!hasAudio && !hasVideo) {
  1442. ALOGE("no metadata for either audio or video source");
  1443. mCurrentSourceInfo.mSource->stop();
  1444. mSourceStarted = false;
  1445. notifyListener(mCurrentSourceInfo.mSrcId, MEDIA2_ERROR,
  1446. MEDIA2_ERROR_UNKNOWN, ERROR_MALFORMED);
  1447. return;
  1448. }
  1449. ALOGV_IF(!hasAudio, "no metadata for audio source"); // video only stream
  1450. sp<MetaData> audioMeta = mCurrentSourceInfo.mSource->getFormatMeta(true /* audio */);
  1451. audio_stream_type_t streamType = AUDIO_STREAM_MUSIC;
  1452. if (mAudioSink != NULL) {
  1453. streamType = mAudioSink->getAudioStreamType();
  1454. }
  1455. mOffloadAudio =
  1456. JMediaPlayer2Utils::isOffloadedAudioPlaybackSupported(
  1457. audioMeta, hasVideo, mCurrentSourceInfo.mSource->isStreaming(), streamType)
  1458. && (mPlaybackSettings.mSpeed == 1.f && mPlaybackSettings.mPitch == 1.f);
  1459. // Modular DRM: Disabling audio offload if the source is protected
  1460. if (mOffloadAudio && mCurrentSourceInfo.mIsDrmProtected) {
  1461. mOffloadAudio = false;
  1462. ALOGV("onStart: Disabling mOffloadAudio now that the source is protected.");
  1463. }
  1464. if (mOffloadAudio) {
  1465. flags |= Renderer::FLAG_OFFLOAD_AUDIO;
  1466. }
  1467. sp<AMessage> notify = new AMessage(kWhatRendererNotify, this);
  1468. ++mRendererGeneration;
  1469. notify->setInt32("generation", mRendererGeneration);
  1470. mRenderer = new Renderer(mAudioSink, mMediaClock, notify, mContext, flags);
  1471. mRendererLooper = new ALooper;
  1472. mRendererLooper->setName("NuPlayer2Renderer");
  1473. mRendererLooper->start(false, true, ANDROID_PRIORITY_AUDIO);
  1474. mRendererLooper->registerHandler(mRenderer);
  1475. status_t err = mRenderer->setPlaybackSettings(mPlaybackSettings);
  1476. if (err != OK) {
  1477. mCurrentSourceInfo.mSource->stop();
  1478. mSourceStarted = false;
  1479. notifyListener(mCurrentSourceInfo.mSrcId, MEDIA2_ERROR, MEDIA2_ERROR_UNKNOWN, err);
  1480. return;
  1481. }
  1482. float rate = getFrameRate();
  1483. if (rate > 0) {
  1484. mRenderer->setVideoFrameRate(rate);
  1485. }
  1486. addEndTimeMonitor();
  1487. // Renderer is created in paused state.
  1488. if (play) {
  1489. mRenderer->resume();
  1490. }
  1491. if (mVideoDecoder != NULL) {
  1492. mVideoDecoder->setRenderer(mRenderer);
  1493. }
  1494. if (mAudioDecoder != NULL) {
  1495. mAudioDecoder->setRenderer(mRenderer);
  1496. }
  1497. startPlaybackTimer("onstart");
  1498. notifyListener(mCurrentSourceInfo.mSrcId, MEDIA2_INFO, MEDIA2_INFO_DATA_SOURCE_START, 0);
  1499. postScanSources();
  1500. }
  1501. void NuPlayer2::addEndTimeMonitor() {
  1502. ++mEOSMonitorGeneration;
  1503. if (mCurrentSourceInfo.mEndTimeUs == DataSourceDesc::kMaxTimeUs) {
  1504. return;
  1505. }
  1506. sp<AMessage> msg = new AMessage(kWhatEOSMonitor, this);
  1507. msg->setInt32("generation", mEOSMonitorGeneration);
  1508. mMediaClock->addTimer(msg, mCurrentSourceInfo.mEndTimeUs);
  1509. }
  1510. void NuPlayer2::startPlaybackTimer(const char *where) {
  1511. Mutex::Autolock autoLock(mPlayingTimeLock);
  1512. if (mLastStartedPlayingTimeNs == 0) {
  1513. mLastStartedPlayingTimeNs = systemTime();
  1514. ALOGV("startPlaybackTimer() time %20" PRId64 " (%s)", mLastStartedPlayingTimeNs, where);
  1515. }
  1516. }
  1517. void NuPlayer2::stopPlaybackTimer(const char *where) {
  1518. Mutex::Autolock autoLock(mPlayingTimeLock);
  1519. ALOGV("stopPlaybackTimer() time %20" PRId64 " (%s)", mLastStartedPlayingTimeNs, where);
  1520. if (mLastStartedPlayingTimeNs != 0) {
  1521. sp<NuPlayer2Driver> driver = mDriver.promote();
  1522. if (driver != NULL) {
  1523. int64_t now = systemTime();
  1524. int64_t played = now - mLastStartedPlayingTimeNs;
  1525. ALOGV("stopPlaybackTimer() log %20" PRId64 "", played);
  1526. if (played > 0) {
  1527. driver->notifyMorePlayingTimeUs(mCurrentSourceInfo.mSrcId, (played+500)/1000);
  1528. }
  1529. }
  1530. mLastStartedPlayingTimeNs = 0;
  1531. }
  1532. }
  1533. void NuPlayer2::startRebufferingTimer() {
  1534. Mutex::Autolock autoLock(mPlayingTimeLock);
  1535. if (mLastStartedRebufferingTimeNs == 0) {
  1536. mLastStartedRebufferingTimeNs = systemTime();
  1537. ALOGV("startRebufferingTimer() time %20" PRId64 "", mLastStartedRebufferingTimeNs);
  1538. }
  1539. }
  1540. void NuPlayer2::stopRebufferingTimer(bool exitingPlayback) {
  1541. Mutex::Autolock autoLock(mPlayingTimeLock);
  1542. ALOGV("stopRebufferTimer() time %20" PRId64 " (exiting %d)",
  1543. mLastStartedRebufferingTimeNs, exitingPlayback);
  1544. if (mLastStartedRebufferingTimeNs != 0) {
  1545. sp<NuPlayer2Driver> driver = mDriver.promote();
  1546. if (driver != NULL) {
  1547. int64_t now = systemTime();
  1548. int64_t rebuffered = now - mLastStartedRebufferingTimeNs;
  1549. ALOGV("stopRebufferingTimer() log %20" PRId64 "", rebuffered);
  1550. if (rebuffered > 0) {
  1551. driver->notifyMoreRebufferingTimeUs(
  1552. mCurrentSourceInfo.mSrcId, (rebuffered+500)/1000);
  1553. if (exitingPlayback) {
  1554. driver->notifyRebufferingWhenExit(mCurrentSourceInfo.mSrcId, true);
  1555. }
  1556. }
  1557. }
  1558. mLastStartedRebufferingTimeNs = 0;
  1559. }
  1560. }
  1561. void NuPlayer2::onPause() {
  1562. stopPlaybackTimer("onPause");
  1563. if (mPaused) {
  1564. return;
  1565. }
  1566. mPaused = true;
  1567. if (mCurrentSourceInfo.mSource != NULL) {
  1568. mCurrentSourceInfo.mSource->pause();
  1569. } else {
  1570. ALOGW("pause called when source is gone or not set");
  1571. }
  1572. if (mRenderer != NULL) {
  1573. mRenderer->pause();
  1574. } else {
  1575. ALOGW("pause called when renderer is gone or not set");
  1576. }
  1577. }
  1578. bool NuPlayer2::audioDecoderStillNeeded() {
  1579. // Audio decoder is no longer needed if it's in shut/shutting down status.
  1580. return ((mFlushingAudio != SHUT_DOWN) && (mFlushingAudio != SHUTTING_DOWN_DECODER));
  1581. }
  1582. void NuPlayer2::handleFlushComplete(bool audio, bool isDecoder) {
  1583. // We wait for both the decoder flush and the renderer flush to complete
  1584. // before entering either the FLUSHED or the SHUTTING_DOWN_DECODER state.
  1585. mFlushComplete[audio][isDecoder] = true;
  1586. if (!mFlushComplete[audio][!isDecoder]) {
  1587. return;
  1588. }
  1589. FlushStatus *state = audio ? &mFlushingAudio : &mFlushingVideo;
  1590. switch (*state) {
  1591. case FLUSHING_DECODER:
  1592. {
  1593. *state = FLUSHED;
  1594. break;
  1595. }
  1596. case FLUSHING_DECODER_SHUTDOWN:
  1597. {
  1598. *state = SHUTTING_DOWN_DECODER;
  1599. ALOGV("initiating %s decoder shutdown", audio ? "audio" : "video");
  1600. getDecoder(audio)->initiateShutdown();
  1601. break;
  1602. }
  1603. default:
  1604. // decoder flush completes only occur in a flushing state.
  1605. LOG_ALWAYS_FATAL_IF(isDecoder, "decoder flush in invalid state %d", *state);
  1606. break;
  1607. }
  1608. }
  1609. void NuPlayer2::finishFlushIfPossible() {
  1610. if (mFlushingAudio != NONE && mFlushingAudio != FLUSHED
  1611. && mFlushingAudio != SHUT_DOWN) {
  1612. return;
  1613. }
  1614. if (mFlushingVideo != NONE && mFlushingVideo != FLUSHED
  1615. && mFlushingVideo != SHUT_DOWN) {
  1616. return;
  1617. }
  1618. ALOGV("both audio and video are flushed now.");
  1619. mFlushingAudio = NONE;
  1620. mFlushingVideo = NONE;
  1621. clearFlushComplete();
  1622. processDeferredActions();
  1623. }
  1624. void NuPlayer2::postScanSources() {
  1625. if (mScanSourcesPending) {
  1626. return;
  1627. }
  1628. sp<AMessage> msg = new AMessage(kWhatScanSources, this);
  1629. msg->setInt32("generation", mScanSourcesGeneration);
  1630. msg->post();
  1631. mScanSourcesPending = true;
  1632. }
  1633. void NuPlayer2::tryOpenAudioSinkForOffload(
  1634. const sp<AMessage> &format, const sp<MetaData> &audioMeta, bool hasVideo) {
  1635. // Note: This is called early in NuPlayer2 to determine whether offloading
  1636. // is possible; otherwise the decoders call the renderer openAudioSink directly.
  1637. status_t err = mRenderer->openAudioSink(
  1638. format, true /* offloadOnly */, hasVideo,
  1639. AUDIO_OUTPUT_FLAG_NONE, &mOffloadAudio, mCurrentSourceInfo.mSource->isStreaming());
  1640. if (err != OK) {
  1641. // Any failure we turn off mOffloadAudio.
  1642. mOffloadAudio = false;
  1643. } else if (mOffloadAudio) {
  1644. sendMetaDataToHal(mAudioSink, audioMeta);
  1645. }
  1646. }
  1647. void NuPlayer2::closeAudioSink() {
  1648. mRenderer->closeAudioSink();
  1649. }
  1650. void NuPlayer2::restartAudio(
  1651. int64_t currentPositionUs, bool forceNonOffload, bool needsToCreateAudioDecoder) {
  1652. if (mAudioDecoder != NULL) {
  1653. mAudioDecoder->pause();
  1654. Mutex::Autolock autoLock(mDecoderLock);
  1655. mAudioDecoder.clear();
  1656. mAudioDecoderError = false;
  1657. ++mAudioDecoderGeneration;
  1658. }
  1659. if (mFlushingAudio == FLUSHING_DECODER) {
  1660. mFlushComplete[1 /* audio */][1 /* isDecoder */] = true;
  1661. mFlushingAudio = FLUSHED;
  1662. finishFlushIfPossible();
  1663. } else if (mFlushingAudio == FLUSHING_DECODER_SHUTDOWN
  1664. || mFlushingAudio == SHUTTING_DOWN_DECODER) {
  1665. mFlushComplete[1 /* audio */][1 /* isDecoder */] = true;
  1666. mFlushingAudio = SHUT_DOWN;
  1667. finishFlushIfPossible();
  1668. needsToCreateAudioDecoder = false;
  1669. }
  1670. if (mRenderer == NULL) {
  1671. return;
  1672. }
  1673. closeAudioSink();
  1674. mRenderer->flush(true /* audio */, false /* notifyComplete */);
  1675. if (mVideoDecoder != NULL) {
  1676. mDeferredActions.push_back(
  1677. new FlushDecoderAction(FLUSH_CMD_NONE /* audio */,
  1678. FLUSH_CMD_FLUSH /* video */));
  1679. mDeferredActions.push_back(
  1680. new SeekAction(currentPositionUs,
  1681. MediaPlayerSeekMode::SEEK_PREVIOUS_SYNC /* mode */));
  1682. // After a flush without shutdown, decoder is paused.
  1683. // Don't resume it until source seek is done, otherwise it could
  1684. // start pulling stale data too soon.
  1685. mDeferredActions.push_back(new ResumeDecoderAction(false));
  1686. processDeferredActions();
  1687. } else {
  1688. performSeek(currentPositionUs, MediaPlayerSeekMode::SEEK_PREVIOUS_SYNC /* mode */);
  1689. }
  1690. if (forceNonOffload) {
  1691. mRenderer->signalDisableOffloadAudio();
  1692. mOffloadAudio = false;
  1693. }
  1694. if (needsToCreateAudioDecoder) {
  1695. instantiateDecoder(true /* audio */, &mAudioDecoder, !forceNonOffload);
  1696. }
  1697. }
  1698. void NuPlayer2::determineAudioModeChange(const sp<AMessage> &audioFormat) {
  1699. if (mCurrentSourceInfo.mSource == NULL || mAudioSink == NULL) {
  1700. return;
  1701. }
  1702. if (mRenderer == NULL) {
  1703. ALOGW("No renderer can be used to determine audio mode. Use non-offload for safety.");
  1704. mOffloadAudio = false;
  1705. return;
  1706. }
  1707. sp<MetaData> audioMeta = mCurrentSourceInfo.mSource->getFormatMeta(true /* audio */);
  1708. sp<AMessage> videoFormat = mCurrentSourceInfo.mSource->getFormat(false /* audio */);
  1709. audio_stream_type_t streamType = mAudioSink->getAudioStreamType();
  1710. const bool hasVideo = (videoFormat != NULL);
  1711. bool canOffload = JMediaPlayer2Utils::isOffloadedAudioPlaybackSupported(
  1712. audioMeta, hasVideo, mCurrentSourceInfo.mSource->isStreaming(), streamType)
  1713. && (mPlaybackSettings.mSpeed == 1.f && mPlaybackSettings.mPitch == 1.f);
  1714. // Modular DRM: Disabling audio offload if the source is protected
  1715. if (canOffload && mCurrentSourceInfo.mIsDrmProtected) {
  1716. canOffload = false;
  1717. ALOGV("determineAudioModeChange: Disabling mOffloadAudio b/c the source is protected.");
  1718. }
  1719. if (canOffload) {
  1720. if (!mOffloadAudio) {
  1721. mRenderer->signalEnableOffloadAudio();
  1722. }
  1723. // open audio sink early under offload mode.
  1724. tryOpenAudioSinkForOffload(audioFormat, audioMeta, hasVideo);
  1725. } else {
  1726. if (mOffloadAudio) {
  1727. mRenderer->signalDisableOffloadAudio();
  1728. mOffloadAudio = false;
  1729. }
  1730. }
  1731. }
  1732. status_t NuPlayer2::instantiateDecoder(
  1733. bool audio, sp<DecoderBase> *decoder, bool checkAudioModeChange) {
  1734. // The audio decoder could be cleared by tear down. If still in shut down
  1735. // process, no need to create a new audio decoder.
  1736. if (*decoder != NULL || (audio && mFlushingAudio == SHUT_DOWN)) {
  1737. return OK;
  1738. }
  1739. sp<AMessage> format = mCurrentSourceInfo.mSource->getFormat(audio);
  1740. if (format == NULL) {
  1741. return UNKNOWN_ERROR;
  1742. } else {
  1743. status_t err;
  1744. if (format->findInt32("err", &err) && err) {
  1745. return err;
  1746. }
  1747. }
  1748. format->setInt32("priority", 0 /* realtime */);
  1749. if (!audio) {
  1750. AString mime;
  1751. CHECK(format->findString("mime", &mime));
  1752. sp<AMessage> ccNotify = new AMessage(kWhatClosedCaptionNotify, this);
  1753. if (mCCDecoder == NULL) {
  1754. mCCDecoder = new CCDecoder(ccNotify);
  1755. }
  1756. if (mCurrentSourceInfo.mSourceFlags & Source::FLAG_SECURE) {
  1757. format->setInt32("secure", true);
  1758. }
  1759. if (mCurrentSourceInfo.mSourceFlags & Source::FLAG_PROTECTED) {
  1760. format->setInt32("protected", true);
  1761. }
  1762. float rate = getFrameRate();
  1763. if (rate > 0) {
  1764. format->setFloat("operating-rate", rate * mPlaybackSettings.mSpeed);
  1765. }
  1766. }
  1767. Mutex::Autolock autoLock(mDecoderLock);
  1768. if (audio) {
  1769. sp<AMessage> notify = new AMessage(kWhatAudioNotify, this);
  1770. ++mAudioDecoderGeneration;
  1771. notify->setInt32("generation", mAudioDecoderGeneration);
  1772. if (checkAudioModeChange) {
  1773. determineAudioModeChange(format);
  1774. }
  1775. if (mOffloadAudio) {
  1776. mCurrentSourceInfo.mSource->setOffloadAudio(true /* offload */);
  1777. const bool hasVideo = (mCurrentSourceInfo.mSource->getFormat(false /*audio */) != NULL);
  1778. format->setInt32("has-video", hasVideo);
  1779. *decoder = new DecoderPassThrough(notify, mCurrentSourceInfo.mSource, mRenderer);
  1780. ALOGV("instantiateDecoder audio DecoderPassThrough hasVideo: %d", hasVideo);
  1781. } else {
  1782. mCurrentSourceInfo.mSource->setOffloadAudio(false /* offload */);
  1783. *decoder = new Decoder(notify, mCurrentSourceInfo.mSource, mPID, mUID, mRenderer);
  1784. ALOGV("instantiateDecoder audio Decoder");
  1785. }
  1786. mAudioDecoderError = false;
  1787. } else {
  1788. sp<AMessage> notify = new AMessage(kWhatVideoNotify, this);
  1789. ++mVideoDecoderGeneration;
  1790. notify->setInt32("generation", mVideoDecoderGeneration);
  1791. *decoder = new Decoder(
  1792. notify, mCurrentSourceInfo.mSource, mPID, mUID, mRenderer, mNativeWindow,
  1793. mCCDecoder);
  1794. mVideoDecoderError = false;
  1795. // enable FRC if high-quality AV sync is requested, even if not
  1796. // directly queuing to display, as this will even improve textureview
  1797. // playback.
  1798. {
  1799. if (property_get_bool("persist.sys.media.avsync", false)) {
  1800. format->setInt32("auto-frc", 1);
  1801. }
  1802. }
  1803. }
  1804. (*decoder)->init();
  1805. // Modular DRM
  1806. if (mCurrentSourceInfo.mIsDrmProtected) {
  1807. format->setObject("crypto", mCurrentSourceInfo.mCrypto);
  1808. ALOGV("instantiateDecoder: mCrypto: %p isSecure: %d",
  1809. mCurrentSourceInfo.mCrypto.get(),
  1810. (mCurrentSourceInfo.mSourceFlags & Source::FLAG_SECURE) != 0);
  1811. }
  1812. (*decoder)->configure(format);
  1813. if (!audio) {
  1814. sp<AMessage> params = new AMessage();
  1815. float rate = getFrameRate();
  1816. if (rate > 0) {
  1817. params->setFloat("frame-rate-total", rate);
  1818. }
  1819. sp<MetaData> fileMeta = getFileMeta();
  1820. if (fileMeta != NULL) {
  1821. int32_t videoTemporalLayerCount;
  1822. if (fileMeta->findInt32(kKeyTemporalLayerCount, &videoTemporalLayerCount)
  1823. && videoTemporalLayerCount > 0) {
  1824. params->setInt32("temporal-layer-count", videoTemporalLayerCount);
  1825. }
  1826. }
  1827. if (params->countEntries() > 0) {
  1828. (*decoder)->setParameters(params);
  1829. }
  1830. }
  1831. return OK;
  1832. }
  1833. void NuPlayer2::updateVideoSize(
  1834. int64_t srcId,
  1835. const sp<AMessage> &inputFormat,
  1836. const sp<AMessage> &outputFormat) {
  1837. if (inputFormat == NULL) {
  1838. ALOGW("Unknown video size, reporting 0x0!");
  1839. notifyListener(srcId, MEDIA2_SET_VIDEO_SIZE, 0, 0);
  1840. return;
  1841. }
  1842. int32_t err = OK;
  1843. inputFormat->findInt32("err", &err);
  1844. if (err == -EWOULDBLOCK) {
  1845. ALOGW("Video meta is not available yet!");
  1846. return;
  1847. }
  1848. if (err != OK) {
  1849. ALOGW("Something is wrong with video meta!");
  1850. return;
  1851. }
  1852. int32_t displayWidth, displayHeight;
  1853. if (outputFormat != NULL) {
  1854. int32_t width, height;
  1855. CHECK(outputFormat->findInt32("width", &width));
  1856. CHECK(outputFormat->findInt32("height", &height));
  1857. int32_t cropLeft, cropTop, cropRight, cropBottom;
  1858. CHECK(outputFormat->findRect(
  1859. "crop",
  1860. &cropLeft, &cropTop, &cropRight, &cropBottom));
  1861. displayWidth = cropRight - cropLeft + 1;
  1862. displayHeight = cropBottom - cropTop + 1;
  1863. ALOGV("Video output format changed to %d x %d "
  1864. "(crop: %d x %d @ (%d, %d))",
  1865. width, height,
  1866. displayWidth,
  1867. displayHeight,
  1868. cropLeft, cropTop);
  1869. } else {
  1870. CHECK(inputFormat->findInt32("width", &displayWidth));
  1871. CHECK(inputFormat->findInt32("height", &displayHeight));
  1872. ALOGV("Video input format %d x %d", displayWidth, displayHeight);
  1873. }
  1874. // Take into account sample aspect ratio if necessary:
  1875. int32_t sarWidth, sarHeight;
  1876. if (inputFormat->findInt32("sar-width", &sarWidth)
  1877. && inputFormat->findInt32("sar-height", &sarHeight)
  1878. && sarWidth > 0 && sarHeight > 0) {
  1879. ALOGV("Sample aspect ratio %d : %d", sarWidth, sarHeight);
  1880. displayWidth = (displayWidth * sarWidth) / sarHeight;
  1881. ALOGV("display dimensions %d x %d", displayWidth, displayHeight);
  1882. } else {
  1883. int32_t width, height;
  1884. if (inputFormat->findInt32("display-width", &width)
  1885. && inputFormat->findInt32("display-height", &height)
  1886. && width > 0 && height > 0
  1887. && displayWidth > 0 && displayHeight > 0) {
  1888. if (displayHeight * (int64_t)width / height > (int64_t)displayWidth) {
  1889. displayHeight = (int32_t)(displayWidth * (int64_t)height / width);
  1890. } else {
  1891. displayWidth = (int32_t)(displayHeight * (int64_t)width / height);
  1892. }
  1893. ALOGV("Video display width and height are overridden to %d x %d",
  1894. displayWidth, displayHeight);
  1895. }
  1896. }
  1897. int32_t rotationDegrees;
  1898. if (!inputFormat->findInt32("rotation-degrees", &rotationDegrees)) {
  1899. rotationDegrees = 0;
  1900. }
  1901. if (rotationDegrees == 90 || rotationDegrees == 270) {
  1902. int32_t tmp = displayWidth;
  1903. displayWidth = displayHeight;
  1904. displayHeight = tmp;
  1905. }
  1906. notifyListener(
  1907. srcId,
  1908. MEDIA2_SET_VIDEO_SIZE,
  1909. displayWidth,
  1910. displayHeight);
  1911. }
  1912. void NuPlayer2::notifyListener(
  1913. int64_t srcId, int msg, int ext1, int ext2, const PlayerMessage *in) {
  1914. if (mDriver == NULL) {
  1915. return;
  1916. }
  1917. sp<NuPlayer2Driver> driver = mDriver.promote();
  1918. if (driver == NULL) {
  1919. return;
  1920. }
  1921. driver->notifyListener(srcId, msg, ext1, ext2, in);
  1922. }
  1923. void NuPlayer2::flushDecoder(bool audio, bool needShutdown) {
  1924. ALOGV("[%s] flushDecoder needShutdown=%d",
  1925. audio ? "audio" : "video", needShutdown);
  1926. const sp<DecoderBase> &decoder = getDecoder(audio);
  1927. if (decoder == NULL) {
  1928. ALOGI("flushDecoder %s without decoder present",
  1929. audio ? "audio" : "video");
  1930. return;
  1931. }
  1932. // Make sure we don't continue to scan sources until we finish flushing.
  1933. ++mScanSourcesGeneration;
  1934. if (mScanSourcesPending) {
  1935. if (!needShutdown) {
  1936. mDeferredActions.push_back(
  1937. new SimpleAction(&NuPlayer2::performScanSources));
  1938. }
  1939. mScanSourcesPending = false;
  1940. }
  1941. decoder->signalFlush();
  1942. FlushStatus newStatus =
  1943. needShutdown ? FLUSHING_DECODER_SHUTDOWN : FLUSHING_DECODER;
  1944. mFlushComplete[audio][false /* isDecoder */] = (mRenderer == NULL);
  1945. mFlushComplete[audio][true /* isDecoder */] = false;
  1946. if (audio) {
  1947. ALOGE_IF(mFlushingAudio != NONE,
  1948. "audio flushDecoder() is called in state %d", mFlushingAudio);
  1949. mFlushingAudio = newStatus;
  1950. } else {
  1951. ALOGE_IF(mFlushingVideo != NONE,
  1952. "video flushDecoder() is called in state %d", mFlushingVideo);
  1953. mFlushingVideo = newStatus;
  1954. }
  1955. }
  1956. void NuPlayer2::queueDecoderShutdown(
  1957. bool audio, bool video, const sp<AMessage> &reply) {
  1958. ALOGI("queueDecoderShutdown audio=%d, video=%d", audio, video);
  1959. mDeferredActions.push_back(
  1960. new FlushDecoderAction(
  1961. audio ? FLUSH_CMD_SHUTDOWN : FLUSH_CMD_NONE,
  1962. video ? FLUSH_CMD_SHUTDOWN : FLUSH_CMD_NONE));
  1963. mDeferredActions.push_back(
  1964. new SimpleAction(&NuPlayer2::performScanSources));
  1965. mDeferredActions.push_back(new PostMessageAction(reply));
  1966. processDeferredActions();
  1967. }
  1968. status_t NuPlayer2::setVideoScalingMode(int32_t mode) {
  1969. mVideoScalingMode = mode;
  1970. if (mNativeWindow != NULL && mNativeWindow->getANativeWindow() != NULL) {
  1971. status_t ret = native_window_set_scaling_mode(
  1972. mNativeWindow->getANativeWindow(), mVideoScalingMode);
  1973. if (ret != OK) {
  1974. ALOGE("Failed to set scaling mode (%d): %s",
  1975. -ret, strerror(-ret));
  1976. return ret;
  1977. }
  1978. }
  1979. return OK;
  1980. }
  1981. status_t NuPlayer2::getTrackInfo(int64_t srcId, PlayerMessage* reply) const {
  1982. sp<AMessage> msg = new AMessage(kWhatGetTrackInfo, this);
  1983. msg->setInt64("srcId", srcId);
  1984. msg->setPointer("reply", reply);
  1985. sp<AMessage> response;
  1986. status_t err = msg->postAndAwaitResponse(&response);
  1987. return err;
  1988. }
  1989. status_t NuPlayer2::getSelectedTrack(int64_t srcId, int32_t type, PlayerMessage* reply) const {
  1990. sp<AMessage> msg = new AMessage(kWhatGetSelectedTrack, this);
  1991. msg->setPointer("reply", reply);
  1992. msg->setInt64("srcId", srcId);
  1993. msg->setInt32("type", type);
  1994. sp<AMessage> response;
  1995. status_t err = msg->postAndAwaitResponse(&response);
  1996. if (err == OK && response != NULL) {
  1997. CHECK(response->findInt32("err", &err));
  1998. }
  1999. return err;
  2000. }
  2001. status_t NuPlayer2::selectTrack(int64_t srcId, size_t trackIndex, bool select, int64_t timeUs) {
  2002. sp<AMessage> msg = new AMessage(kWhatSelectTrack, this);
  2003. msg->setInt64("srcId", srcId);
  2004. msg->setSize("trackIndex", trackIndex);
  2005. msg->setInt32("select", select);
  2006. msg->setInt64("timeUs", timeUs);
  2007. sp<AMessage> response;
  2008. status_t err = msg->postAndAwaitResponse(&response);
  2009. if (err != OK) {
  2010. return err;
  2011. }
  2012. if (!response->findInt32("err", &err)) {
  2013. err = OK;
  2014. }
  2015. return err;
  2016. }
  2017. status_t NuPlayer2::getCurrentPosition(int64_t *mediaUs) {
  2018. sp<Renderer> renderer = mRenderer;
  2019. if (renderer == NULL) {
  2020. return NO_INIT;
  2021. }
  2022. return renderer->getCurrentPosition(mediaUs);
  2023. }
  2024. void NuPlayer2::getStats(Vector<sp<AMessage> > *mTrackStats) {
  2025. CHECK(mTrackStats != NULL);
  2026. mTrackStats->clear();
  2027. Mutex::Autolock autoLock(mDecoderLock);
  2028. if (mVideoDecoder != NULL) {
  2029. mTrackStats->push_back(mVideoDecoder->getStats());
  2030. }
  2031. if (mAudioDecoder != NULL) {
  2032. mTrackStats->push_back(mAudioDecoder->getStats());
  2033. }
  2034. }
  2035. sp<MetaData> NuPlayer2::getFileMeta() {
  2036. return mCurrentSourceInfo.mSource->getFileFormatMeta();
  2037. }
  2038. float NuPlayer2::getFrameRate() {
  2039. sp<MetaData> meta = mCurrentSourceInfo.mSource->getFormatMeta(false /* audio */);
  2040. if (meta == NULL) {
  2041. return 0;
  2042. }
  2043. int32_t rate;
  2044. if (!meta->findInt32(kKeyFrameRate, &rate)) {
  2045. // fall back to try file meta
  2046. sp<MetaData> fileMeta = getFileMeta();
  2047. if (fileMeta == NULL) {
  2048. ALOGW("source has video meta but not file meta");
  2049. return -1;
  2050. }
  2051. int32_t fileMetaRate;
  2052. if (!fileMeta->findInt32(kKeyFrameRate, &fileMetaRate)) {
  2053. return -1;
  2054. }
  2055. return fileMetaRate;
  2056. }
  2057. return rate;
  2058. }
  2059. void NuPlayer2::schedulePollDuration() {
  2060. sp<AMessage> msg = new AMessage(kWhatPollDuration, this);
  2061. msg->setInt32("generation", mPollDurationGeneration);
  2062. msg->post();
  2063. }
  2064. void NuPlayer2::cancelPollDuration() {
  2065. ++mPollDurationGeneration;
  2066. }
  2067. void NuPlayer2::processDeferredActions() {
  2068. while (!mDeferredActions.empty()) {
  2069. // We won't execute any deferred actions until we're no longer in
  2070. // an intermediate state, i.e. one more more decoders are currently
  2071. // flushing or shutting down.
  2072. if (mFlushingAudio != NONE || mFlushingVideo != NONE) {
  2073. // We're currently flushing, postpone the reset until that's
  2074. // completed.
  2075. ALOGV("postponing action mFlushingAudio=%d, mFlushingVideo=%d",
  2076. mFlushingAudio, mFlushingVideo);
  2077. break;
  2078. }
  2079. sp<Action> action = *mDeferredActions.begin();
  2080. mDeferredActions.erase(mDeferredActions.begin());
  2081. action->execute(this);
  2082. }
  2083. }
  2084. void NuPlayer2::performSeek(int64_t seekTimeUs, MediaPlayer2SeekMode mode) {
  2085. ALOGV("performSeek seekTimeUs=%lld us (%.2f secs), mode=%d",
  2086. (long long)seekTimeUs, seekTimeUs / 1E6, mode);
  2087. if (mCurrentSourceInfo.mSource == NULL) {
  2088. // This happens when reset occurs right before the loop mode
  2089. // asynchronously seeks to the start of the stream.
  2090. LOG_ALWAYS_FATAL_IF(mAudioDecoder != NULL || mVideoDecoder != NULL,
  2091. "mCurrentSourceInfo.mSource is NULL and decoders not NULL audio(%p) video(%p)",
  2092. mAudioDecoder.get(), mVideoDecoder.get());
  2093. return;
  2094. }
  2095. mPreviousSeekTimeUs = seekTimeUs;
  2096. mCurrentSourceInfo.mSource->seekTo(seekTimeUs, mode);
  2097. ++mTimedTextGeneration;
  2098. // everything's flushed, continue playback.
  2099. }
  2100. void NuPlayer2::performDecoderFlush(FlushCommand audio, FlushCommand video) {
  2101. ALOGV("performDecoderFlush audio=%d, video=%d", audio, video);
  2102. if ((audio == FLUSH_CMD_NONE || mAudioDecoder == NULL)
  2103. && (video == FLUSH_CMD_NONE || mVideoDecoder == NULL)) {
  2104. return;
  2105. }
  2106. if (audio != FLUSH_CMD_NONE && mAudioDecoder != NULL) {
  2107. flushDecoder(true /* audio */, (audio == FLUSH_CMD_SHUTDOWN));
  2108. }
  2109. if (video != FLUSH_CMD_NONE && mVideoDecoder != NULL) {
  2110. flushDecoder(false /* audio */, (video == FLUSH_CMD_SHUTDOWN));
  2111. }
  2112. }
  2113. void NuPlayer2::performReset() {
  2114. ALOGV("performReset");
  2115. CHECK(mAudioDecoder == NULL);
  2116. CHECK(mVideoDecoder == NULL);
  2117. stopPlaybackTimer("performReset");
  2118. stopRebufferingTimer(true);
  2119. cancelPollDuration();
  2120. ++mScanSourcesGeneration;
  2121. mScanSourcesPending = false;
  2122. if (mRendererLooper != NULL) {
  2123. if (mRenderer != NULL) {
  2124. mRendererLooper->unregisterHandler(mRenderer->id());
  2125. }
  2126. mRendererLooper->stop();
  2127. mRendererLooper.clear();
  2128. }
  2129. mRenderer.clear();
  2130. ++mRendererGeneration;
  2131. resetSourceInfo(mCurrentSourceInfo);
  2132. resetSourceInfo(mNextSourceInfo);
  2133. if (mDriver != NULL) {
  2134. sp<NuPlayer2Driver> driver = mDriver.promote();
  2135. if (driver != NULL) {
  2136. driver->notifyResetComplete(mCurrentSourceInfo.mSrcId);
  2137. }
  2138. }
  2139. mStarted = false;
  2140. mPrepared = false;
  2141. mResetting = false;
  2142. mSourceStarted = false;
  2143. }
  2144. void NuPlayer2::performPlayNextDataSource() {
  2145. ALOGV("performPlayNextDataSource");
  2146. CHECK(mAudioDecoder == NULL);
  2147. CHECK(mVideoDecoder == NULL);
  2148. stopPlaybackTimer("performPlayNextDataSource");
  2149. stopRebufferingTimer(true);
  2150. cancelPollDuration();
  2151. ++mScanSourcesGeneration;
  2152. mScanSourcesPending = false;
  2153. ++mRendererGeneration;
  2154. if (mCurrentSourceInfo.mSource != NULL) {
  2155. mCurrentSourceInfo.mSource->stop();
  2156. }
  2157. long previousSrcId;
  2158. {
  2159. Mutex::Autolock autoLock(mSourceLock);
  2160. previousSrcId = mCurrentSourceInfo.mSrcId;
  2161. mCurrentSourceInfo = mNextSourceInfo;
  2162. mNextSourceInfo = SourceInfo();
  2163. mNextSourceInfo.mSrcId = ~mCurrentSourceInfo.mSrcId; // to distinguish the two sources.
  2164. }
  2165. if (mDriver != NULL) {
  2166. sp<NuPlayer2Driver> driver = mDriver.promote();
  2167. if (driver != NULL) {
  2168. notifyListener(previousSrcId, MEDIA2_INFO, MEDIA2_INFO_DATA_SOURCE_END, 0);
  2169. int64_t durationUs;
  2170. if (mCurrentSourceInfo.mSource->getDuration(&durationUs) == OK) {
  2171. driver->notifyDuration(mCurrentSourceInfo.mSrcId, durationUs);
  2172. }
  2173. notifyListener(
  2174. mCurrentSourceInfo.mSrcId, MEDIA2_INFO, MEDIA2_INFO_DATA_SOURCE_START, 0);
  2175. }
  2176. }
  2177. mStarted = false;
  2178. mPrepared = true; // TODO: what if it's not prepared
  2179. mResetting = false;
  2180. mSourceStarted = false;
  2181. addEndTimeMonitor();
  2182. if (mRenderer != NULL) {
  2183. mRenderer->resume();
  2184. }
  2185. onStart(true /* play */);
  2186. mPausedByClient = false;
  2187. notifyListener(mCurrentSourceInfo.mSrcId, MEDIA2_STARTED, 0, 0);
  2188. }
  2189. void NuPlayer2::performScanSources() {
  2190. ALOGV("performScanSources");
  2191. if (!mStarted) {
  2192. return;
  2193. }
  2194. if (mAudioDecoder == NULL || mVideoDecoder == NULL) {
  2195. postScanSources();
  2196. }
  2197. }
  2198. void NuPlayer2::performSetSurface(const sp<ANativeWindowWrapper> &nww) {
  2199. ALOGV("performSetSurface");
  2200. mNativeWindow = nww;
  2201. // XXX - ignore error from setVideoScalingMode for now
  2202. setVideoScalingMode(mVideoScalingMode);
  2203. if (mDriver != NULL) {
  2204. sp<NuPlayer2Driver> driver = mDriver.promote();
  2205. if (driver != NULL) {
  2206. driver->notifySetSurfaceComplete(mCurrentSourceInfo.mSrcId);
  2207. }
  2208. }
  2209. }
  2210. void NuPlayer2::performResumeDecoders(bool needNotify) {
  2211. if (needNotify) {
  2212. mResumePending = true;
  2213. if (mVideoDecoder == NULL) {
  2214. // if audio-only, we can notify seek complete now,
  2215. // as the resume operation will be relatively fast.
  2216. finishResume();
  2217. }
  2218. }
  2219. if (mVideoDecoder != NULL) {
  2220. // When there is continuous seek, MediaPlayer will cache the seek
  2221. // position, and send down new seek request when previous seek is
  2222. // complete. Let's wait for at least one video output frame before
  2223. // notifying seek complete, so that the video thumbnail gets updated
  2224. // when seekbar is dragged.
  2225. mVideoDecoder->signalResume(needNotify);
  2226. }
  2227. if (mAudioDecoder != NULL) {
  2228. mAudioDecoder->signalResume(false /* needNotify */);
  2229. }
  2230. }
  2231. void NuPlayer2::finishResume() {
  2232. if (mResumePending) {
  2233. mResumePending = false;
  2234. notifyDriverSeekComplete(mCurrentSourceInfo.mSrcId);
  2235. }
  2236. }
  2237. void NuPlayer2::notifyDriverSeekComplete(int64_t srcId) {
  2238. if (mDriver != NULL) {
  2239. sp<NuPlayer2Driver> driver = mDriver.promote();
  2240. if (driver != NULL) {
  2241. driver->notifySeekComplete(srcId);
  2242. }
  2243. }
  2244. }
  2245. void NuPlayer2::onSourceNotify(const sp<AMessage> &msg) {
  2246. int32_t what;
  2247. CHECK(msg->findInt32("what", &what));
  2248. int64_t srcId;
  2249. CHECK(msg->findInt64("srcId", &srcId));
  2250. switch (what) {
  2251. case Source::kWhatPrepared:
  2252. {
  2253. ALOGV("NuPlayer2::onSourceNotify Source::kWhatPrepared source:%p, Id(%lld)",
  2254. mCurrentSourceInfo.mSource.get(), (long long)srcId);
  2255. if (srcId == mCurrentSourceInfo.mSrcId) {
  2256. if (mCurrentSourceInfo.mSource == NULL) {
  2257. // This is a stale notification from a source that was
  2258. // asynchronously preparing when the client called reset().
  2259. // We handled the reset, the source is gone.
  2260. break;
  2261. }
  2262. int32_t err;
  2263. CHECK(msg->findInt32("err", &err));
  2264. if (err != OK) {
  2265. // shut down potential secure codecs in case client never calls reset
  2266. mDeferredActions.push_back(
  2267. new FlushDecoderAction(FLUSH_CMD_SHUTDOWN /* audio */,
  2268. FLUSH_CMD_SHUTDOWN /* video */));
  2269. processDeferredActions();
  2270. } else {
  2271. mPrepared = true;
  2272. }
  2273. sp<NuPlayer2Driver> driver = mDriver.promote();
  2274. if (driver != NULL) {
  2275. // notify duration first, so that it's definitely set when
  2276. // the app received the "prepare complete" callback.
  2277. int64_t durationUs;
  2278. if (mCurrentSourceInfo.mSource->getDuration(&durationUs) == OK) {
  2279. driver->notifyDuration(srcId, durationUs);
  2280. }
  2281. driver->notifyPrepareCompleted(srcId, err);
  2282. }
  2283. } else if (srcId == mNextSourceInfo.mSrcId) {
  2284. if (mNextSourceInfo.mSource == NULL) {
  2285. break; // stale
  2286. }
  2287. sp<NuPlayer2Driver> driver = mDriver.promote();
  2288. if (driver != NULL) {
  2289. int32_t err;
  2290. CHECK(msg->findInt32("err", &err));
  2291. driver->notifyPrepareCompleted(srcId, err);
  2292. }
  2293. }
  2294. break;
  2295. }
  2296. // Modular DRM
  2297. case Source::kWhatDrmInfo:
  2298. {
  2299. PlayerMessage playerMsg;
  2300. sp<ABuffer> drmInfo;
  2301. CHECK(msg->findBuffer("drmInfo", &drmInfo));
  2302. playerMsg.ParseFromArray(drmInfo->data(), drmInfo->size());
  2303. ALOGV("onSourceNotify() kWhatDrmInfo MEDIA2_DRM_INFO drmInfo: %p playerMsg size: %d",
  2304. drmInfo.get(), playerMsg.ByteSize());
  2305. notifyListener(srcId, MEDIA2_DRM_INFO, 0 /* ext1 */, 0 /* ext2 */, &playerMsg);
  2306. break;
  2307. }
  2308. case Source::kWhatFlagsChanged:
  2309. {
  2310. uint32_t flags;
  2311. CHECK(msg->findInt32("flags", (int32_t *)&flags));
  2312. sp<NuPlayer2Driver> driver = mDriver.promote();
  2313. if (driver != NULL) {
  2314. ALOGV("onSourceNotify() kWhatFlagsChanged FLAG_CAN_PAUSE: %d "
  2315. "FLAG_CAN_SEEK_BACKWARD: %d \n\t\t\t\t FLAG_CAN_SEEK_FORWARD: %d "
  2316. "FLAG_CAN_SEEK: %d FLAG_DYNAMIC_DURATION: %d \n"
  2317. "\t\t\t\t FLAG_SECURE: %d FLAG_PROTECTED: %d",
  2318. (flags & Source::FLAG_CAN_PAUSE) != 0,
  2319. (flags & Source::FLAG_CAN_SEEK_BACKWARD) != 0,
  2320. (flags & Source::FLAG_CAN_SEEK_FORWARD) != 0,
  2321. (flags & Source::FLAG_CAN_SEEK) != 0,
  2322. (flags & Source::FLAG_DYNAMIC_DURATION) != 0,
  2323. (flags & Source::FLAG_SECURE) != 0,
  2324. (flags & Source::FLAG_PROTECTED) != 0);
  2325. if ((flags & NuPlayer2::Source::FLAG_CAN_SEEK) == 0) {
  2326. driver->notifyListener(
  2327. srcId, MEDIA2_INFO, MEDIA2_INFO_NOT_SEEKABLE, 0);
  2328. }
  2329. if (srcId == mCurrentSourceInfo.mSrcId) {
  2330. driver->notifyFlagsChanged(srcId, flags);
  2331. }
  2332. }
  2333. if (srcId == mCurrentSourceInfo.mSrcId) {
  2334. if ((mCurrentSourceInfo.mSourceFlags & Source::FLAG_DYNAMIC_DURATION)
  2335. && (!(flags & Source::FLAG_DYNAMIC_DURATION))) {
  2336. cancelPollDuration();
  2337. } else if (!(mCurrentSourceInfo.mSourceFlags & Source::FLAG_DYNAMIC_DURATION)
  2338. && (flags & Source::FLAG_DYNAMIC_DURATION)
  2339. && (mAudioDecoder != NULL || mVideoDecoder != NULL)) {
  2340. schedulePollDuration();
  2341. }
  2342. mCurrentSourceInfo.mSourceFlags = flags;
  2343. } else if (srcId == mNextSourceInfo.mSrcId) {
  2344. // TODO: handle duration polling for next source.
  2345. mNextSourceInfo.mSourceFlags = flags;
  2346. }
  2347. break;
  2348. }
  2349. case Source::kWhatVideoSizeChanged:
  2350. {
  2351. sp<AMessage> format;
  2352. CHECK(msg->findMessage("format", &format));
  2353. updateVideoSize(srcId, format);
  2354. break;
  2355. }
  2356. case Source::kWhatBufferingUpdate:
  2357. {
  2358. int32_t percentage;
  2359. CHECK(msg->findInt32("percentage", &percentage));
  2360. notifyListener(srcId, MEDIA2_BUFFERING_UPDATE, percentage, 0);
  2361. break;
  2362. }
  2363. case Source::kWhatPauseOnBufferingStart:
  2364. {
  2365. // ignore if not playing
  2366. if (mStarted) {
  2367. ALOGI("buffer low, pausing...");
  2368. startRebufferingTimer();
  2369. mPausedForBuffering = true;
  2370. onPause();
  2371. }
  2372. notifyListener(srcId, MEDIA2_INFO, MEDIA2_INFO_BUFFERING_START, 0);
  2373. break;
  2374. }
  2375. case Source::kWhatResumeOnBufferingEnd:
  2376. {
  2377. // ignore if not playing
  2378. if (mStarted) {
  2379. ALOGI("buffer ready, resuming...");
  2380. stopRebufferingTimer(false);
  2381. mPausedForBuffering = false;
  2382. // do not resume yet if client didn't unpause
  2383. if (!mPausedByClient) {
  2384. onResume();
  2385. }
  2386. }
  2387. notifyListener(srcId, MEDIA2_INFO, MEDIA2_INFO_BUFFERING_END, 0);
  2388. break;
  2389. }
  2390. case Source::kWhatCacheStats:
  2391. {
  2392. int32_t kbps;
  2393. CHECK(msg->findInt32("bandwidth", &kbps));
  2394. notifyListener(srcId, MEDIA2_INFO, MEDIA2_INFO_NETWORK_BANDWIDTH, kbps);
  2395. break;
  2396. }
  2397. case Source::kWhatSubtitleData:
  2398. {
  2399. sp<ABuffer> buffer;
  2400. CHECK(msg->findBuffer("buffer", &buffer));
  2401. sendSubtitleData(buffer, 0 /* baseIndex */);
  2402. break;
  2403. }
  2404. case Source::kWhatTimedMetaData:
  2405. {
  2406. sp<ABuffer> buffer;
  2407. if (!msg->findBuffer("buffer", &buffer)) {
  2408. notifyListener(srcId, MEDIA2_INFO, MEDIA2_INFO_METADATA_UPDATE, 0);
  2409. } else {
  2410. sendTimedMetaData(buffer);
  2411. }
  2412. break;
  2413. }
  2414. case Source::kWhatTimedTextData:
  2415. {
  2416. int32_t generation;
  2417. if (msg->findInt32("generation", &generation)
  2418. && generation != mTimedTextGeneration) {
  2419. break;
  2420. }
  2421. sp<ABuffer> buffer;
  2422. CHECK(msg->findBuffer("buffer", &buffer));
  2423. sp<NuPlayer2Driver> driver = mDriver.promote();
  2424. if (driver == NULL) {
  2425. break;
  2426. }
  2427. int64_t posMs;
  2428. int64_t timeUs, posUs;
  2429. driver->getCurrentPosition(&posMs);
  2430. posUs = posMs * 1000LL;
  2431. CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
  2432. if (posUs < timeUs) {
  2433. if (!msg->findInt32("generation", &generation)) {
  2434. msg->setInt32("generation", mTimedTextGeneration);
  2435. }
  2436. msg->post(timeUs - posUs);
  2437. } else {
  2438. sendTimedTextData(buffer);
  2439. }
  2440. break;
  2441. }
  2442. case Source::kWhatQueueDecoderShutdown:
  2443. {
  2444. int32_t audio, video;
  2445. CHECK(msg->findInt32("audio", &audio));
  2446. CHECK(msg->findInt32("video", &video));
  2447. sp<AMessage> reply;
  2448. CHECK(msg->findMessage("reply", &reply));
  2449. queueDecoderShutdown(audio, video, reply);
  2450. break;
  2451. }
  2452. case Source::kWhatDrmNoLicense:
  2453. {
  2454. notifyListener(srcId, MEDIA2_ERROR, MEDIA2_ERROR_UNKNOWN, ERROR_DRM_NO_LICENSE);
  2455. break;
  2456. }
  2457. default:
  2458. TRESPASS();
  2459. }
  2460. }
  2461. void NuPlayer2::onClosedCaptionNotify(const sp<AMessage> &msg) {
  2462. int32_t what;
  2463. CHECK(msg->findInt32("what", &what));
  2464. switch (what) {
  2465. case NuPlayer2::CCDecoder::kWhatClosedCaptionData:
  2466. {
  2467. sp<ABuffer> buffer;
  2468. CHECK(msg->findBuffer("buffer", &buffer));
  2469. size_t inbandTracks = 0;
  2470. if (mCurrentSourceInfo.mSource != NULL) {
  2471. inbandTracks = mCurrentSourceInfo.mSource->getTrackCount();
  2472. }
  2473. sendSubtitleData(buffer, inbandTracks);
  2474. break;
  2475. }
  2476. case NuPlayer2::CCDecoder::kWhatTrackAdded:
  2477. {
  2478. notifyListener(mCurrentSourceInfo.mSrcId, MEDIA2_INFO, MEDIA2_INFO_METADATA_UPDATE, 0);
  2479. break;
  2480. }
  2481. default:
  2482. TRESPASS();
  2483. }
  2484. }
  2485. void NuPlayer2::sendSubtitleData(const sp<ABuffer> &buffer, int32_t baseIndex) {
  2486. int32_t trackIndex;
  2487. int64_t timeUs, durationUs;
  2488. CHECK(buffer->meta()->findInt32(AMEDIAFORMAT_KEY_TRACK_INDEX, &trackIndex));
  2489. CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
  2490. CHECK(buffer->meta()->findInt64("durationUs", &durationUs));
  2491. PlayerMessage playerMsg;
  2492. playerMsg.add_values()->set_int32_value(trackIndex + baseIndex);
  2493. playerMsg.add_values()->set_int64_value(timeUs);
  2494. playerMsg.add_values()->set_int64_value(durationUs);
  2495. playerMsg.add_values()->set_bytes_value(buffer->data(), buffer->size());
  2496. notifyListener(mCurrentSourceInfo.mSrcId, MEDIA2_SUBTITLE_DATA, 0, 0, &playerMsg);
  2497. }
  2498. void NuPlayer2::sendTimedMetaData(const sp<ABuffer> &buffer) {
  2499. int64_t timeUs;
  2500. CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
  2501. PlayerMessage playerMsg;
  2502. playerMsg.add_values()->set_int64_value(timeUs);
  2503. playerMsg.add_values()->set_bytes_value(buffer->data(), buffer->size());
  2504. notifyListener(mCurrentSourceInfo.mSrcId, MEDIA2_META_DATA, 0, 0, &playerMsg);
  2505. }
  2506. void NuPlayer2::sendTimedTextData(const sp<ABuffer> &buffer) {
  2507. const void *data;
  2508. size_t size = 0;
  2509. int64_t timeUs;
  2510. int32_t flag = TextDescriptions2::IN_BAND_TEXT_3GPP;
  2511. AString mime;
  2512. CHECK(buffer->meta()->findString("mime", &mime));
  2513. CHECK(strcasecmp(mime.c_str(), MEDIA_MIMETYPE_TEXT_3GPP) == 0);
  2514. data = buffer->data();
  2515. size = buffer->size();
  2516. PlayerMessage playerMsg;
  2517. if (size > 0) {
  2518. CHECK(buffer->meta()->findInt64("timeUs", &timeUs));
  2519. int32_t global = 0;
  2520. if (buffer->meta()->findInt32("global", &global) && global) {
  2521. flag |= TextDescriptions2::GLOBAL_DESCRIPTIONS;
  2522. } else {
  2523. flag |= TextDescriptions2::LOCAL_DESCRIPTIONS;
  2524. }
  2525. TextDescriptions2::getPlayerMessageOfDescriptions(
  2526. (const uint8_t *)data, size, flag, timeUs / 1000, &playerMsg);
  2527. }
  2528. if (playerMsg.values_size() > 0) {
  2529. notifyListener(mCurrentSourceInfo.mSrcId, MEDIA2_TIMED_TEXT, 0, 0, &playerMsg);
  2530. } else { // send an empty timed text
  2531. notifyListener(mCurrentSourceInfo.mSrcId, MEDIA2_TIMED_TEXT, 0, 0);
  2532. }
  2533. }
  2534. const char *NuPlayer2::getDataSourceType() {
  2535. switch (mCurrentSourceInfo.mDataSourceType) {
  2536. case DATA_SOURCE_TYPE_HTTP_LIVE:
  2537. return "HTTPLive";
  2538. case DATA_SOURCE_TYPE_RTSP:
  2539. return "RTSP";
  2540. case DATA_SOURCE_TYPE_GENERIC_URL:
  2541. return "GenURL";
  2542. case DATA_SOURCE_TYPE_GENERIC_FD:
  2543. return "GenFD";
  2544. case DATA_SOURCE_TYPE_MEDIA:
  2545. return "Media";
  2546. case DATA_SOURCE_TYPE_NONE:
  2547. default:
  2548. return "None";
  2549. }
  2550. }
  2551. NuPlayer2::SourceInfo* NuPlayer2::getSourceInfoByIdInMsg(const sp<AMessage> &msg) {
  2552. int64_t srcId;
  2553. CHECK(msg->findInt64("srcId", &srcId));
  2554. if (mCurrentSourceInfo.mSrcId == srcId) {
  2555. return &mCurrentSourceInfo;
  2556. } else if (mNextSourceInfo.mSrcId == srcId) {
  2557. return &mNextSourceInfo;
  2558. } else {
  2559. return NULL;
  2560. }
  2561. }
  2562. void NuPlayer2::resetSourceInfo(NuPlayer2::SourceInfo &srcInfo) {
  2563. if (srcInfo.mSource != NULL) {
  2564. srcInfo.mSource->stop();
  2565. Mutex::Autolock autoLock(mSourceLock);
  2566. srcInfo.mSource.clear();
  2567. }
  2568. // Modular DRM
  2569. ALOGD("performReset mCrypto: %p", srcInfo.mCrypto.get());
  2570. srcInfo.mCrypto.clear();
  2571. srcInfo.mIsDrmProtected = false;
  2572. }
  2573. // Modular DRM begin
  2574. status_t NuPlayer2::prepareDrm(
  2575. int64_t srcId, const uint8_t uuid[16], const Vector<uint8_t> &drmSessionId)
  2576. {
  2577. ALOGV("prepareDrm ");
  2578. // Passing to the looper anyway; called in a pre-config prepared state so no race on mCrypto
  2579. sp<AMessage> msg = new AMessage(kWhatPrepareDrm, this);
  2580. // synchronous call so just passing the address but with local copies of "const" args
  2581. uint8_t UUID[16];
  2582. memcpy(UUID, uuid, sizeof(UUID));
  2583. Vector<uint8_t> sessionId = drmSessionId;
  2584. msg->setInt64("srcId", srcId);
  2585. msg->setPointer("uuid", (void*)UUID);
  2586. msg->setPointer("drmSessionId", (void*)&sessionId);
  2587. sp<AMessage> response;
  2588. status_t status = msg->postAndAwaitResponse(&response);
  2589. if (status == OK && response != NULL) {
  2590. CHECK(response->findInt32("status", &status));
  2591. ALOGV("prepareDrm ret: %d ", status);
  2592. } else {
  2593. ALOGE("prepareDrm err: %d", status);
  2594. }
  2595. return status;
  2596. }
  2597. status_t NuPlayer2::releaseDrm(int64_t srcId)
  2598. {
  2599. ALOGV("releaseDrm ");
  2600. sp<AMessage> msg = new AMessage(kWhatReleaseDrm, this);
  2601. msg->setInt64("srcId", srcId);
  2602. sp<AMessage> response;
  2603. status_t status = msg->postAndAwaitResponse(&response);
  2604. if (status == OK && response != NULL) {
  2605. CHECK(response->findInt32("status", &status));
  2606. ALOGV("releaseDrm ret: %d ", status);
  2607. } else {
  2608. ALOGE("releaseDrm err: %d", status);
  2609. }
  2610. return status;
  2611. }
  2612. status_t NuPlayer2::onPrepareDrm(const sp<AMessage> &msg)
  2613. {
  2614. // TODO change to ALOGV
  2615. ALOGD("onPrepareDrm ");
  2616. status_t status = INVALID_OPERATION;
  2617. SourceInfo *srcInfo = getSourceInfoByIdInMsg(msg);
  2618. if (srcInfo == NULL) {
  2619. return status;
  2620. }
  2621. int64_t srcId = srcInfo->mSrcId;
  2622. if (srcInfo->mSource == NULL) {
  2623. ALOGE("onPrepareDrm: srcInfo(%lld) No source. onPrepareDrm failed with %d.",
  2624. (long long)srcId, status);
  2625. return status;
  2626. }
  2627. uint8_t *uuid;
  2628. Vector<uint8_t> *drmSessionId;
  2629. CHECK(msg->findPointer("uuid", (void**)&uuid));
  2630. CHECK(msg->findPointer("drmSessionId", (void**)&drmSessionId));
  2631. status = OK;
  2632. sp<AMediaCryptoWrapper> crypto = NULL;
  2633. status = srcInfo->mSource->prepareDrm(uuid, *drmSessionId, &crypto);
  2634. if (crypto == NULL) {
  2635. ALOGE("onPrepareDrm: srcInfo(%lld).mSource->prepareDrm failed. status: %d",
  2636. (long long)srcId, status);
  2637. return status;
  2638. }
  2639. ALOGV("onPrepareDrm: srcInfo(%lld).mSource->prepareDrm succeeded", (long long)srcId);
  2640. if (srcInfo->mCrypto != NULL) {
  2641. ALOGE("onPrepareDrm: srcInfo(%lld) Unexpected. Already having mCrypto: %p",
  2642. (long long)srcId, srcInfo->mCrypto.get());
  2643. srcInfo->mCrypto.clear();
  2644. }
  2645. srcInfo->mCrypto = crypto;
  2646. srcInfo->mIsDrmProtected = true;
  2647. // TODO change to ALOGV
  2648. ALOGD("onPrepareDrm: mCrypto: %p", srcInfo->mCrypto.get());
  2649. return status;
  2650. }
  2651. status_t NuPlayer2::onReleaseDrm(const sp<AMessage> &msg)
  2652. {
  2653. // TODO change to ALOGV
  2654. ALOGD("onReleaseDrm ");
  2655. SourceInfo *srcInfo = getSourceInfoByIdInMsg(msg);;
  2656. if (srcInfo == NULL) {
  2657. return INVALID_OPERATION;
  2658. }
  2659. int64_t srcId = srcInfo->mSrcId;
  2660. if (!srcInfo->mIsDrmProtected) {
  2661. ALOGW("onReleaseDrm: srcInfo(%lld) Unexpected. mIsDrmProtected is already false.",
  2662. (long long)srcId);
  2663. }
  2664. srcInfo->mIsDrmProtected = false;
  2665. status_t status;
  2666. if (srcInfo->mCrypto != NULL) {
  2667. // notifying the source first before removing crypto from codec
  2668. if (srcInfo->mSource != NULL) {
  2669. srcInfo->mSource->releaseDrm();
  2670. }
  2671. status=OK;
  2672. // first making sure the codecs have released their crypto reference
  2673. const sp<DecoderBase> &videoDecoder = getDecoder(false/*audio*/);
  2674. if (videoDecoder != NULL) {
  2675. status = videoDecoder->releaseCrypto();
  2676. ALOGV("onReleaseDrm: video decoder ret: %d", status);
  2677. }
  2678. const sp<DecoderBase> &audioDecoder = getDecoder(true/*audio*/);
  2679. if (audioDecoder != NULL) {
  2680. status_t status_audio = audioDecoder->releaseCrypto();
  2681. if (status == OK) { // otherwise, returning the first error
  2682. status = status_audio;
  2683. }
  2684. ALOGV("onReleaseDrm: audio decoder ret: %d", status_audio);
  2685. }
  2686. // TODO change to ALOGV
  2687. ALOGD("onReleaseDrm: mCrypto: %p", srcInfo->mCrypto.get());
  2688. srcInfo->mCrypto.clear();
  2689. } else { // srcInfo->mCrypto == NULL
  2690. ALOGE("onReleaseDrm: Unexpected. There is no crypto.");
  2691. status = INVALID_OPERATION;
  2692. }
  2693. return status;
  2694. }
  2695. // Modular DRM end
  2696. ////////////////////////////////////////////////////////////////////////////////
  2697. sp<AMessage> NuPlayer2::Source::getFormat(bool audio) {
  2698. sp<MetaData> meta = getFormatMeta(audio);
  2699. if (meta == NULL) {
  2700. return NULL;
  2701. }
  2702. sp<AMessage> msg = new AMessage;
  2703. if(convertMetaDataToMessage(meta, &msg) == OK) {
  2704. return msg;
  2705. }
  2706. return NULL;
  2707. }
  2708. void NuPlayer2::Source::notifyFlagsChanged(uint32_t flags) {
  2709. sp<AMessage> notify = dupNotify();
  2710. notify->setInt32("what", kWhatFlagsChanged);
  2711. notify->setInt32("flags", flags);
  2712. notify->post();
  2713. }
  2714. void NuPlayer2::Source::notifyVideoSizeChanged(const sp<AMessage> &format) {
  2715. sp<AMessage> notify = dupNotify();
  2716. notify->setInt32("what", kWhatVideoSizeChanged);
  2717. notify->setMessage("format", format);
  2718. notify->post();
  2719. }
  2720. void NuPlayer2::Source::notifyPrepared(status_t err) {
  2721. ALOGV("Source::notifyPrepared %d", err);
  2722. sp<AMessage> notify = dupNotify();
  2723. notify->setInt32("what", kWhatPrepared);
  2724. notify->setInt32("err", err);
  2725. notify->post();
  2726. }
  2727. void NuPlayer2::Source::notifyDrmInfo(const sp<ABuffer> &drmInfoBuffer)
  2728. {
  2729. ALOGV("Source::notifyDrmInfo");
  2730. sp<AMessage> notify = dupNotify();
  2731. notify->setInt32("what", kWhatDrmInfo);
  2732. notify->setBuffer("drmInfo", drmInfoBuffer);
  2733. notify->post();
  2734. }
  2735. void NuPlayer2::Source::onMessageReceived(const sp<AMessage> & /* msg */) {
  2736. TRESPASS();
  2737. }
  2738. NuPlayer2::SourceInfo::SourceInfo()
  2739. : mDataSourceType(DATA_SOURCE_TYPE_NONE),
  2740. mSrcId(0),
  2741. mSourceFlags(0),
  2742. mStartTimeUs(0),
  2743. mEndTimeUs(DataSourceDesc::kMaxTimeUs) {
  2744. }
  2745. NuPlayer2::SourceInfo & NuPlayer2::SourceInfo::operator=(const NuPlayer2::SourceInfo &other) {
  2746. mSource = other.mSource;
  2747. mCrypto = other.mCrypto;
  2748. mDataSourceType = (DATA_SOURCE_TYPE)other.mDataSourceType;
  2749. mSrcId = other.mSrcId;
  2750. mSourceFlags = other.mSourceFlags;
  2751. mStartTimeUs = other.mStartTimeUs;
  2752. mEndTimeUs = other.mEndTimeUs;
  2753. mIsDrmProtected = other.mIsDrmProtected;
  2754. return *this;
  2755. }
  2756. } // namespace android