-
-
Notifications
You must be signed in to change notification settings - Fork 6.3k
/
DVDVideoCodecAndroidMediaCodec.cpp
1482 lines (1305 loc) · 46 KB
/
DVDVideoCodecAndroidMediaCodec.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2013 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
// http://developer.android.com/reference/android/media/MediaCodec.html
//
// Android MediaCodec class can be used to access low-level media codec,
// i.e. encoder/decoder components. (android.media.MediaCodec). Requires SDK21+
//
#include "DVDVideoCodecAndroidMediaCodec.h"
#include "Application.h"
#include "messaging/ApplicationMessenger.h"
#include "DVDClock.h"
#include "threads/Atomics.h"
#include "utils/BitstreamConverter.h"
#include "utils/CPUInfo.h"
#include "utils/log.h"
#include "settings/AdvancedSettings.h"
#include "platform/android/activity/XBMCApp.h"
#include "cores/VideoPlayer/VideoRenderers/RenderManager.h"
#include "cores/VideoPlayer/VideoRenderers/RenderFlags.h"
#include "platform/android/jni/ByteBuffer.h"
#include "platform/android/jni/MediaCodec.h"
#include "platform/android/jni/MediaCrypto.h"
#include "platform/android/jni/MediaFormat.h"
#include "platform/android/jni/MediaCodecList.h"
#include "platform/android/jni/MediaCodecInfo.h"
#include "platform/android/jni/Surface.h"
#include "platform/android/jni/SurfaceTexture.h"
#include "platform/android/activity/AndroidFeatures.h"
#include "settings/Settings.h"
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <cassert>
using namespace KODI::MESSAGING;
enum MEDIACODEC_STATES
{
MEDIACODEC_STATE_UNINITIALIZED,
MEDIACODEC_STATE_CONFIGURED,
MEDIACODEC_STATE_FLUSHED,
MEDIACODEC_STATE_RUNNING,
MEDIACODEC_STATE_BEFORE_ENDOFSTREAM,
MEDIACODEC_STATE_ENDOFSTREAM,
MEDIACODEC_STATE_ERROR
};
static bool CanSurfaceRenderBlackList(const std::string &name)
{
// All devices 'should' be capiable of surface rendering
// but that seems to be hit or miss as most odd name devices
// cannot surface render.
static const char *cannotsurfacerender_decoders[] = {
NULL
};
for (const char **ptr = cannotsurfacerender_decoders; *ptr; ptr++)
{
if (!strnicmp(*ptr, name.c_str(), strlen(*ptr)))
return true;
}
return false;
}
static bool IsBlacklisted(const std::string &name)
{
static const char *blacklisted_decoders[] = {
// No software decoders
"OMX.google",
// For Rockchip non-standard components
"AVCDecoder",
"AVCDecoder_FLASH",
"FLVDecoder",
"M2VDecoder",
"M4vH263Decoder",
"RVDecoder",
"VC1Decoder",
"VPXDecoder",
// End of Rockchip
NULL
};
for (const char **ptr = blacklisted_decoders; *ptr; ptr++)
{
if (!strnicmp(*ptr, name.c_str(), strlen(*ptr)))
return true;
}
return false;
}
static bool IsSupportedColorFormat(int color_format)
{
static const int supported_colorformats[] = {
CJNIMediaCodecInfoCodecCapabilities::COLOR_FormatYUV420Planar,
CJNIMediaCodecInfoCodecCapabilities::COLOR_TI_FormatYUV420PackedSemiPlanar,
CJNIMediaCodecInfoCodecCapabilities::COLOR_FormatYUV420SemiPlanar,
CJNIMediaCodecInfoCodecCapabilities::COLOR_QCOM_FormatYUV420SemiPlanar,
CJNIMediaCodecInfoCodecCapabilities::OMX_QCOM_COLOR_FormatYVU420SemiPlanarInterlace,
-1
};
for (const int *ptr = supported_colorformats; *ptr != -1; ptr++)
{
if (color_format == *ptr)
return true;
}
return false;
}
/*****************************************************************************/
/*****************************************************************************/
class CNULL_Listener : public CJNISurfaceTextureOnFrameAvailableListener
{
public:
CNULL_Listener() : CJNISurfaceTextureOnFrameAvailableListener(jni::jhobject(NULL)) {};
protected:
virtual void OnFrameAvailable(CJNISurfaceTexture &surface) {};
};
class CDVDMediaCodecOnFrameAvailable : public CEvent, CJNISurfaceTextureOnFrameAvailableListener
{
public:
CDVDMediaCodecOnFrameAvailable(std::shared_ptr<CJNISurfaceTexture> &surfaceTexture)
: m_surfaceTexture(surfaceTexture)
{
m_surfaceTexture->setOnFrameAvailableListener(*this);
}
virtual ~CDVDMediaCodecOnFrameAvailable()
{
// unhook the callback
CNULL_Listener null_listener;
m_surfaceTexture->setOnFrameAvailableListener(null_listener);
}
protected:
virtual void OnFrameAvailable(CJNISurfaceTexture &surface)
{
Set();
}
private:
std::shared_ptr<CJNISurfaceTexture> m_surfaceTexture;
};
/*****************************************************************************/
/*****************************************************************************/
CDVDMediaCodecInfo::CDVDMediaCodecInfo(
int index
, unsigned int texture
, std::shared_ptr<CJNIMediaCodec> &codec
, std::shared_ptr<CJNISurfaceTexture> &surfacetexture
, std::shared_ptr<CDVDMediaCodecOnFrameAvailable> &frameready
)
: m_refs(1)
, m_valid(true)
, m_isReleased(true)
, m_index(index)
, m_texture(texture)
, m_timestamp(0)
, m_codec(codec)
, m_surfacetexture(surfacetexture)
, m_frameready(frameready)
{
// paranoid checks
assert(m_index >= 0);
assert(m_codec != NULL);
}
CDVDMediaCodecInfo::~CDVDMediaCodecInfo()
{
assert(m_refs == 0);
}
CDVDMediaCodecInfo* CDVDMediaCodecInfo::Retain()
{
AtomicIncrement(&m_refs);
m_isReleased = false;
return this;
}
long CDVDMediaCodecInfo::Release()
{
long count = AtomicDecrement(&m_refs);
if (count == 1)
ReleaseOutputBuffer(false);
if (count == 0)
delete this;
return count;
}
void CDVDMediaCodecInfo::Validate(bool state)
{
CSingleLock lock(m_section);
m_valid = state;
}
bool CDVDMediaCodecInfo::WaitForFrame(int millis)
{
return m_frameready->WaitMSec(millis);
}
void CDVDMediaCodecInfo::ReleaseOutputBuffer(bool render)
{
CSingleLock lock(m_section);
if (!m_valid || m_isReleased)
return;
// release OutputBuffer and render if indicated
// then wait for rendered frame to become avaliable.
if (render)
if (m_frameready)
m_frameready->Reset();
m_codec->releaseOutputBuffer(m_index, render);
m_isReleased = true;
if (xbmc_jnienv()->ExceptionCheck())
{
CLog::Log(LOGERROR, "CDVDMediaCodecInfo::ReleaseOutputBuffer "
"ExceptionCheck index(%d), render(%d)", m_index, render);
xbmc_jnienv()->ExceptionDescribe();
xbmc_jnienv()->ExceptionClear();
}
}
ssize_t CDVDMediaCodecInfo::GetIndex() const
{
CSingleLock lock(m_section);
return m_index;
}
int CDVDMediaCodecInfo::GetTextureID() const
{
// since m_texture never changes,
// we do not need a m_section lock here.
return m_texture;
}
void CDVDMediaCodecInfo::GetTransformMatrix(float *textureMatrix)
{
CSingleLock lock(m_section);
if (!m_valid)
return;
m_surfacetexture->getTransformMatrix(textureMatrix);
}
void CDVDMediaCodecInfo::UpdateTexImage()
{
CSingleLock lock(m_section);
if (!m_valid)
return;
// updateTexImage will check and spew any prior gl errors,
// clear them before we call updateTexImage.
glGetError();
// this is key, after calling releaseOutputBuffer, we must
// wait a little for MediaCodec to render to the surface.
// Then we can updateTexImage without delay. If we do not
// wait, then video playback gets jerky. To optomize this,
// we hook the SurfaceTexture OnFrameAvailable callback
// using CJNISurfaceTextureOnFrameAvailableListener and wait
// on a CEvent to fire. 50ms seems to be a good max fallback.
WaitForFrame(50);
m_surfacetexture->updateTexImage();
if (xbmc_jnienv()->ExceptionCheck())
{
CLog::Log(LOGERROR, "CDVDMediaCodecInfo::UpdateTexImage updateTexImage:ExceptionCheck");
xbmc_jnienv()->ExceptionDescribe();
xbmc_jnienv()->ExceptionClear();
}
m_timestamp = m_surfacetexture->getTimestamp();
if (xbmc_jnienv()->ExceptionCheck())
{
CLog::Log(LOGERROR, "CDVDMediaCodecInfo::UpdateTexImage getTimestamp:ExceptionCheck");
xbmc_jnienv()->ExceptionDescribe();
xbmc_jnienv()->ExceptionClear();
}
}
void CDVDMediaCodecInfo::RenderUpdate(const CRect &SrcRect, const CRect &DestRect)
{
CSingleLock lock(m_section);
static CRect cur_rect;
if (!m_valid)
return;
if (DestRect != cur_rect)
{
CRect adjRect = CXBMCApp::MapRenderToDroid(DestRect);
CXBMCApp::get()->setVideoViewSurfaceRect(adjRect.x1, adjRect.y1, adjRect.x2, adjRect.y2);
CLog::Log(LOGDEBUG, "RenderUpdate: Dest - %f+%f-%fx%f", DestRect.x1, DestRect.y1, DestRect.Width(), DestRect.Height());
CLog::Log(LOGDEBUG, "RenderUpdate: Adj - %f+%f-%fx%f", adjRect.x1, adjRect.y1, adjRect.Width(), adjRect.Height());
cur_rect = DestRect;
// setVideoViewSurfaceRect is async, so skip rendering this frame
ReleaseOutputBuffer(false);
}
else
ReleaseOutputBuffer(true);
}
/*****************************************************************************/
/*****************************************************************************/
CDVDVideoCodecAndroidMediaCodec::CDVDVideoCodecAndroidMediaCodec(CProcessInfo &processInfo, bool surface_render)
: CDVDVideoCodec(processInfo)
, m_formatname("mediacodec")
, m_opened(false)
, m_surface(NULL)
, m_textureId(0)
, m_bitstream(NULL)
, m_render_sw(false)
, m_render_surface(surface_render)
{
memset(&m_videobuffer, 0x00, sizeof(DVDVideoPicture));
memset(&m_demux_pkt, 0x00, sizeof(m_demux_pkt));
}
CDVDVideoCodecAndroidMediaCodec::~CDVDVideoCodecAndroidMediaCodec()
{
Dispose();
}
bool CDVDVideoCodecAndroidMediaCodec::Open(CDVDStreamInfo &hints, CDVDCodecOptions &options)
{
// mediacodec crashes with null size. Trap this...
if (!hints.width || !hints.height)
{
CLog::Log(LOGERROR, "CDVDVideoCodecAndroidMediaCodec::Open - %s\n", "null size, cannot handle");
return false;
}
else if (hints.stills)
return false;
else if (!CSettings::GetInstance().GetBool(CSettings::SETTING_VIDEOPLAYER_USEMEDIACODEC) &&
!CSettings::GetInstance().GetBool(CSettings::SETTING_VIDEOPLAYER_USEMEDIACODECSURFACE))
return false;
m_render_surface = CSettings::GetInstance().GetBool(CSettings::SETTING_VIDEOPLAYER_USEMEDIACODECSURFACE);
m_drop = false;
m_state = MEDIACODEC_STATE_UNINITIALIZED;
m_codecControlFlags = 0;
m_hints = hints;
switch(m_hints.codec)
{
case AV_CODEC_ID_MPEG2VIDEO:
m_mime = "video/mpeg2";
m_formatname = "amc-mpeg2";
break;
case AV_CODEC_ID_MPEG4:
if (hints.width <= 800)
return false;
m_mime = "video/mp4v-es";
m_formatname = "amc-mpeg4";
break;
case AV_CODEC_ID_H263:
m_mime = "video/3gpp";
m_formatname = "amc-h263";
break;
case AV_CODEC_ID_VP3:
case AV_CODEC_ID_VP6:
case AV_CODEC_ID_VP6F:
case AV_CODEC_ID_VP8:
//m_mime = "video/x-vp6";
//m_mime = "video/x-vp7";
m_mime = "video/x-vnd.on2.vp8";
m_formatname = "amc-vpX";
break;
case AV_CODEC_ID_VP9:
m_mime = "video/x-vnd.on2.vp9";
m_formatname = "amc-vp9";
break;
case AV_CODEC_ID_AVS:
case AV_CODEC_ID_CAVS:
case AV_CODEC_ID_H264:
switch(hints.profile)
{
case FF_PROFILE_H264_HIGH_10:
case FF_PROFILE_H264_HIGH_10_INTRA:
// No known h/w decoder supporting Hi10P
return false;
}
m_mime = "video/avc";
m_formatname = "amc-h264";
// check for h264-avcC and convert to h264-annex-b
if (m_hints.extradata)
{
m_bitstream = new CBitstreamConverter;
if (!m_bitstream->Open(m_hints.codec, (uint8_t*)m_hints.extradata, m_hints.extrasize, true))
{
SAFE_DELETE(m_bitstream);
}
}
break;
case AV_CODEC_ID_HEVC:
m_mime = "video/hevc";
m_formatname = "amc-h265";
// check for hevc-hvcC and convert to h265-annex-b
if (m_hints.extradata)
{
m_bitstream = new CBitstreamConverter;
if (!m_bitstream->Open(m_hints.codec, (uint8_t*)m_hints.extradata, m_hints.extrasize, true))
{
SAFE_DELETE(m_bitstream);
}
}
break;
case AV_CODEC_ID_WMV3:
if (m_hints.extrasize == 4 || m_hints.extrasize == 5)
{
// Convert to SMPTE 421M-2006 Annex-L
static char annexL_hdr1[] = {0x8e, 0x01, 0x00, 0xc5, 0x04, 0x00, 0x00, 0x00};
static char annexL_hdr2[] = {0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
free(m_hints.extradata);
m_hints.extrasize = 36;
m_hints.extradata = malloc(m_hints.extrasize);
unsigned int offset = 0;
char buf[4];
memcpy(m_hints.extradata, annexL_hdr1, sizeof(annexL_hdr1));
offset += sizeof(annexL_hdr1);
memcpy(&((char *)(m_hints.extradata))[offset], hints.extradata, 4);
offset += 4;
BS_WL32(buf, hints.height);
memcpy(&((char *)(m_hints.extradata))[offset], buf, 4);
offset += 4;
BS_WL32(buf, hints.width);
memcpy(&((char *)(m_hints.extradata))[offset], buf, 4);
offset += 4;
memcpy(&((char *)(m_hints.extradata))[offset], annexL_hdr2, sizeof(annexL_hdr2));
}
m_mime = "video/x-ms-wmv";
m_formatname = "amc-wmv";
break;
case AV_CODEC_ID_VC1:
{
if (m_hints.extrasize < 16)
return false;
// Reduce extradata to first SEQ header
unsigned int seq_offset = 0;
for (; seq_offset <= m_hints.extrasize-4; ++seq_offset)
{
char *ptr = &((char*)m_hints.extradata)[seq_offset];
if (ptr[0] == 0x00 && ptr[1] == 0x00 && ptr[2] == 0x01 && ptr[3] == 0x0f)
break;
}
if (seq_offset > m_hints.extrasize-4)
return false;
if (seq_offset)
{
free(m_hints.extradata);
m_hints.extrasize -= seq_offset;
m_hints.extradata = malloc(m_hints.extrasize);
memcpy(m_hints.extradata, &((char *)(hints.extradata))[seq_offset], m_hints.extrasize);
}
m_mime = "video/wvc1";
m_formatname = "amc-vc1";
break;
}
default:
CLog::Log(LOGDEBUG, "CDVDVideoCodecAndroidMediaCodec:: Unknown hints.codec(%d)", hints.codec);
return false;
break;
}
if (m_render_surface)
{
m_videosurface = CXBMCApp::get()->getVideoViewSurface();
if (!m_videosurface)
return false;
}
// CJNIMediaCodec::createDecoderByXXX doesn't handle errors nicely,
// it crashes if the codec isn't found. This is fixed in latest AOSP,
// but not in current 4.1 devices. So 1st search for a matching codec, then create it.
m_colorFormat = -1;
int num_codecs = CJNIMediaCodecList::getCodecCount();
for (int i = 0; i < num_codecs; i++)
{
CJNIMediaCodecInfo codec_info = CJNIMediaCodecList::getCodecInfoAt(i);
if (codec_info.isEncoder())
continue;
m_codecname = codec_info.getName();
if (IsBlacklisted(m_codecname))
continue;
CJNIMediaCodecInfoCodecCapabilities codec_caps = codec_info.getCapabilitiesForType(m_mime);
if (xbmc_jnienv()->ExceptionCheck())
{
// Unsupported type?
xbmc_jnienv()->ExceptionClear();
continue;
}
std::vector<int> color_formats = codec_caps.colorFormats();
std::vector<std::string> types = codec_info.getSupportedTypes();
// return the 1st one we find, that one is typically 'the best'
for (size_t j = 0; j < types.size(); ++j)
{
if (types[j] == m_mime)
{
m_codec = std::shared_ptr<CJNIMediaCodec>(new CJNIMediaCodec(CJNIMediaCodec::createByCodecName(m_codecname)));
// clear any jni exceptions, jni gets upset if we do not.
if (xbmc_jnienv()->ExceptionCheck())
{
CLog::Log(LOGERROR, "CDVDVideoCodecAndroidMediaCodec::Open ExceptionCheck");
xbmc_jnienv()->ExceptionClear();
m_codec.reset();
continue;
}
for (size_t k = 0; k < color_formats.size(); ++k)
{
CLog::Log(LOGDEBUG, "CDVDVideoCodecAndroidMediaCodec::Open "
"m_codecname(%s), colorFormat(%d)", m_codecname.c_str(), color_formats[k]);
if (IsSupportedColorFormat(color_formats[k]))
m_colorFormat = color_formats[k]; // Save color format for initial output configuration
}
break;
}
}
if (m_codec)
break;
}
if (!m_codec)
{
CLog::Log(LOGERROR, "CDVDVideoCodecAndroidMediaCodec:: Failed to create Android MediaCodec");
SAFE_DELETE(m_bitstream);
return false;
}
// blacklist of devices that cannot surface render.
m_render_sw = CanSurfaceRenderBlackList(m_codecname) || g_advancedSettings.m_mediacodecForceSoftwareRendring;
if (m_render_sw)
{
if (m_colorFormat == -1)
{
CLog::Log(LOGERROR, "CDVDVideoCodecAndroidMediaCodec:: No supported color format");
m_codec.reset();
SAFE_DELETE(m_bitstream);
return false;
}
m_render_surface = false;
}
// setup a YUV420P DVDVideoPicture buffer.
// first make sure all properties are reset.
memset(&m_videobuffer, 0x00, sizeof(DVDVideoPicture));
m_videobuffer.dts = DVD_NOPTS_VALUE;
m_videobuffer.pts = DVD_NOPTS_VALUE;
m_videobuffer.color_range = 0;
m_videobuffer.color_matrix = 4;
m_videobuffer.iFlags = DVP_FLAG_ALLOCATED;
m_videobuffer.iWidth = m_hints.width;
m_videobuffer.iHeight = m_hints.height;
// these will get reset to crop values later
m_videobuffer.iDisplayWidth = m_hints.width;
m_videobuffer.iDisplayHeight = m_hints.height;
if (!ConfigureMediaCodec())
{
m_codec.reset();
SAFE_DELETE(m_bitstream);
return false;
}
CLog::Log(LOGINFO, "CDVDVideoCodecAndroidMediaCodec:: "
"Open Android MediaCodec %s", m_codecname.c_str());
m_opened = true;
memset(&m_demux_pkt, 0, sizeof(m_demux_pkt));
m_processInfo.SetVideoDecoderName(m_formatname, true );
m_processInfo.SetVideoPixelFormat(m_render_surface ? "Surface" : (m_render_sw ? "YUV" : "EGL"));
m_processInfo.SetVideoDimensions(m_hints.width, m_hints.height);
m_processInfo.SetVideoDeintMethod("hardware");
return m_opened;
}
void CDVDVideoCodecAndroidMediaCodec::Dispose()
{
if (!m_opened)
return;
m_opened = false;
// release any retained demux packets
if (m_demux_pkt.pData)
free(m_demux_pkt.pData);
// invalidate any inflight outputbuffers
FlushInternal();
// clear m_videobuffer bits
if (m_render_sw)
{
free(m_videobuffer.data[0]), m_videobuffer.data[0] = NULL;
free(m_videobuffer.data[1]), m_videobuffer.data[1] = NULL;
free(m_videobuffer.data[2]), m_videobuffer.data[2] = NULL;
}
m_videobuffer.iFlags = 0;
// m_videobuffer.mediacodec is unioned with m_videobuffer.data[0]
// so be very careful when and how you touch it.
m_videobuffer.mediacodec = NULL;
if (m_codec)
{
m_codec->stop();
m_state = MEDIACODEC_STATE_UNINITIALIZED;
m_codec->release();
m_codec.reset();
if (xbmc_jnienv()->ExceptionCheck())
xbmc_jnienv()->ExceptionClear();
}
ReleaseSurfaceTexture();
if (m_render_surface)
CXBMCApp::get()->clearVideoView();
SAFE_DELETE(m_bitstream);
}
int CDVDVideoCodecAndroidMediaCodec::Decode(uint8_t *pData, int iSize, double dts, double pts)
{
static int s_rtn = VC_BUFFER;
if (pData && !(s_rtn & VC_BUFFER))
CLog::Log(LOGDEBUG, "CDVDVideoCodecAndroidMediaCodec::Decode Anomaly!! buffer not requested (%d)", iSize);
if (!m_opened)
return VC_ERROR;
if (m_state != MEDIACODEC_STATE_RUNNING)
CLog::Log(LOGDEBUG, "CDVDVideoCodecAndroidMediaCodec::Decode current state (%d)", m_state);
if (m_hints.ptsinvalid)
pts = DVD_NOPTS_VALUE;
bool drain = (m_codecControlFlags & DVD_CODEC_CTRL_DRAIN) ? true : false;
if (drain && (m_state == MEDIACODEC_STATE_RUNNING || m_state == MEDIACODEC_STATE_FLUSHED))
m_state = MEDIACODEC_STATE_BEFORE_ENDOFSTREAM;
// Handle input, add demuxer packet to input queue, we must accept it or
// it will be discarded as VideoPlayerVideo has no concept of "try again".
// we must return VC_BUFFER or VC_PICTURE, default to VC_BUFFER.
s_rtn = (m_state == MEDIACODEC_STATE_BEFORE_ENDOFSTREAM || m_state == MEDIACODEC_STATE_ENDOFSTREAM) ? 0 : VC_BUFFER;
if (!pData)
{
// Check if we have a saved buffer
if (m_demux_pkt.pData && m_state != MEDIACODEC_STATE_ENDOFSTREAM)
{
pData = m_demux_pkt.pData;
iSize = m_demux_pkt.iSize;
pts = m_demux_pkt.pts;
dts = m_demux_pkt.dts;
}
}
else if (m_state == MEDIACODEC_STATE_ENDOFSTREAM)
{
// VideoPlayer sends unasked buffer when going out of drain. Flush...
FlushInternal();
m_codec->flush();
m_state = MEDIACODEC_STATE_FLUSHED;
s_rtn |= VC_BUFFER;
}
// must check for an output picture 1st,
// otherwise, mediacodec can stall on some devices.
int retgp = GetOutputPicture();
if (retgp > 0)
{
s_rtn |= VC_PICTURE;
}
else if (retgp == -1) // EOS
{
m_codec->flush();
m_state = MEDIACODEC_STATE_FLUSHED;
s_rtn |= VC_BUFFER;
}
// If we push EOS, be sure to push a buffer (even empty) to move one
// If we are flushed, be sure to push a buffer (even empty) to go back to Running state
if (pData || m_state == MEDIACODEC_STATE_BEFORE_ENDOFSTREAM || m_state == MEDIACODEC_STATE_FLUSHED)
{
// try to fetch an input buffer
int64_t timeout_us = 5000;
int index = m_codec->dequeueInputBuffer(timeout_us);
if (xbmc_jnienv()->ExceptionCheck())
{
CLog::Log(LOGERROR, "CDVDVideoCodecAndroidMediaCodec::Decode ExceptionCheck");
xbmc_jnienv()->ExceptionDescribe();
xbmc_jnienv()->ExceptionClear();
s_rtn = VC_ERROR;
}
else if (index >= 0)
{
if (m_state == MEDIACODEC_STATE_FLUSHED)
m_state = MEDIACODEC_STATE_RUNNING;
if (!(m_state == MEDIACODEC_STATE_FLUSHED || m_state == MEDIACODEC_STATE_RUNNING || m_state == MEDIACODEC_STATE_BEFORE_ENDOFSTREAM))
CLog::Log(LOGERROR, "CDVDVideoCodecAndroidMediaCodec::Decode Dequeue: Wrong state (%d)", m_state);
// we have an input buffer, fill it.
if (pData && m_bitstream)
{
m_bitstream->Convert(pData, iSize);
iSize = m_bitstream->GetConvertSize();
pData = m_bitstream->GetConvertBuffer();
}
CJNIByteBuffer buffer = m_codec->getInputBuffer(index);
int size = buffer.capacity();
if (iSize > size)
{
CLog::Log(LOGERROR, "CDVDVideoCodecAndroidMediaCodec::Decode, iSize(%d) > size(%d)", iSize, size);
iSize = size;
}
// fetch a pointer to the ByteBuffer backing store
uint8_t *dst_ptr = (uint8_t*)xbmc_jnienv()->GetDirectBufferAddress(buffer.get_raw());
if (pData && dst_ptr)
{
// Codec specifics
switch(m_hints.codec)
{
case AV_CODEC_ID_VC1:
{
if (iSize >= 4 && pData[0] == 0x00 && pData[1] == 0x00 && pData[2] == 0x01 && (pData[3] == 0x0d || pData[3] == 0x0f))
memcpy(dst_ptr, pData, iSize);
else
{
dst_ptr[0] = 0x00;
dst_ptr[1] = 0x00;
dst_ptr[2] = 0x01;
dst_ptr[3] = 0x0d;
memcpy(dst_ptr+4, pData, iSize);
iSize += 4;
}
break;
}
default:
memcpy(dst_ptr, pData, iSize);
break;
}
}
// Translate from VideoPlayer dts/pts to MediaCodec pts,
// pts WILL get re-ordered by MediaCodec if needed.
// Do not try to pass pts as a unioned double/int64_t,
// some android devices will diddle with presentationTimeUs
// and you will get NaN back and VideoPlayerVideo will barf.
int64_t presentationTimeUs = 0;
if (pts != DVD_NOPTS_VALUE)
presentationTimeUs = pts;
else if (dts != DVD_NOPTS_VALUE)
presentationTimeUs = dts;
/*
CLog::Log(LOGDEBUG, "CDVDVideoCodecAndroidMediaCodec:: "
"pts(%f), ipts(%lld), iSize(%d), GetDataSize(%d), loop_cnt(%d)",
presentationTimeUs, pts_dtoi(presentationTimeUs), iSize, GetDataSize(), loop_cnt);
*/
int flags = 0;
if (m_state == MEDIACODEC_STATE_BEFORE_ENDOFSTREAM)
{
flags |= CJNIMediaCodec::BUFFER_FLAG_END_OF_STREAM;
m_state = MEDIACODEC_STATE_ENDOFSTREAM;
}
int offset = 0;
m_codec->queueInputBuffer(index, offset, iSize, presentationTimeUs, flags);
// clear any jni exceptions, jni gets upset if we do not.
if (xbmc_jnienv()->ExceptionCheck())
{
CLog::Log(LOGERROR, "CDVDVideoCodecAndroidMediaCodec::Decode ExceptionCheck");
xbmc_jnienv()->ExceptionClear();
}
// Free saved buffer it there was one
if (m_demux_pkt.pData)
{
free(m_demux_pkt.pData);
memset(&m_demux_pkt, 0, sizeof(m_demux_pkt));
}
}
else
{
// We couldn't get an input buffer. Save the packet for next iteration, if it wasn't already
if (!m_demux_pkt.pData)
{
m_demux_pkt.dts = dts;
m_demux_pkt.pts = pts;
m_demux_pkt.iSize = iSize;
m_demux_pkt.pData = (uint8_t*)malloc(iSize);
memcpy(m_demux_pkt.pData, pData, iSize);
}
s_rtn &= ~VC_BUFFER;
}
}
return s_rtn;
}
void CDVDVideoCodecAndroidMediaCodec::Reset()
{
if (!m_opened)
return;
// dump any pending demux packets
if (m_demux_pkt.pData)
{
free(m_demux_pkt.pData);
memset(&m_demux_pkt, 0, sizeof(m_demux_pkt));
}
if (m_codec)
{
// flush all outputbuffers inflight, they will
// become invalid on m_codec->flush and generate
// a spew of java exceptions if used
FlushInternal();
// now we can flush the actual MediaCodec object
CLog::Log(LOGDEBUG, "CDVDVideoCodecAndroidMediaCodec::Reset Current state (%d)", m_state);
m_codec->flush();
m_state = MEDIACODEC_STATE_FLUSHED;
if (xbmc_jnienv()->ExceptionCheck())
{
CLog::Log(LOGERROR, "CDVDVideoCodecAndroidMediaCodec::Reset ExceptionCheck");
xbmc_jnienv()->ExceptionClear();
}
// Invalidate our local DVDVideoPicture bits
m_videobuffer.pts = DVD_NOPTS_VALUE;
if (!m_render_sw)
m_videobuffer.mediacodec = NULL;
}
}
bool CDVDVideoCodecAndroidMediaCodec::GetPicture(DVDVideoPicture* pDvdVideoPicture)
{
if (!m_opened)
return false;
*pDvdVideoPicture = m_videobuffer;
if (pDvdVideoPicture->mediacodec == nullptr && !(pDvdVideoPicture->iFlags & DVP_FLAG_DROPPED))
CLog::Log(LOGDEBUG, "CDVDVideoCodecAndroidMediaCodec::GetOutputPicture null picture "
"pts(%f), flags(%x)", pDvdVideoPicture->pts, pDvdVideoPicture->iFlags);
// Invalidate our local DVDVideoPicture bits
m_videobuffer.pts = DVD_NOPTS_VALUE;
if (!m_render_sw)
m_videobuffer.mediacodec = NULL;
return true;
}
bool CDVDVideoCodecAndroidMediaCodec::ClearPicture(DVDVideoPicture* pDvdVideoPicture)
{
if (pDvdVideoPicture->format == RENDER_FMT_MEDIACODEC || pDvdVideoPicture->format == RENDER_FMT_MEDIACODECSURFACE)
SAFE_RELEASE(pDvdVideoPicture->mediacodec);
memset(pDvdVideoPicture, 0x00, sizeof(DVDVideoPicture));
return true;
}
void CDVDVideoCodecAndroidMediaCodec::SetDropState(bool bDrop)
{
if (bDrop == m_drop)
return;
if (g_advancedSettings.CanLogComponent(LOGVIDEO))
CLog::Log(LOGDEBUG, "%s::%s %s->%s", "CDVDVideoCodecAndroidMediaCodec", __func__, m_drop ? "true" : "false", bDrop ? "true" : "false");
m_drop = bDrop;
if (m_drop)
m_videobuffer.iFlags |= DVP_FLAG_DROPPED;
else
m_videobuffer.iFlags &= ~DVP_FLAG_DROPPED;
}
void CDVDVideoCodecAndroidMediaCodec::SetCodecControl(int flags)
{
if (m_codecControlFlags != flags)
{
if (g_advancedSettings.CanLogComponent(LOGVIDEO))
CLog::Log(LOGDEBUG, "%s::%s %x->%x", "CDVDVideoCodecAndroidMediaCodec", __func__, m_codecControlFlags, flags);
m_codecControlFlags = flags;
}
}
int CDVDVideoCodecAndroidMediaCodec::GetDataSize(void)
{
// just ignore internal buffering contribution.
return 0;
}
double CDVDVideoCodecAndroidMediaCodec::GetTimeSize(void)
{
// just ignore internal buffering contribution.
return 0.0;
}
unsigned CDVDVideoCodecAndroidMediaCodec::GetAllowedReferences()
{
return 4;
}
void CDVDVideoCodecAndroidMediaCodec::FlushInternal()
{
// invalidate any existing inflight buffers and create
// new ones to match the number of output buffers
if (m_render_sw)
return;
for (size_t i = 0; i < m_inflight.size(); i++)
{
m_inflight[i]->Validate(false);
m_inflight[i]->Release();
}
m_inflight.clear();
}
bool CDVDVideoCodecAndroidMediaCodec::ConfigureMediaCodec(void)
{
// setup a MediaFormat to match the video content,
// used by codec during configure
CJNIMediaFormat mediaformat = CJNIMediaFormat::createVideoFormat(
m_mime.c_str(), m_hints.width, m_hints.height);
// some android devices forget to default the demux input max size
mediaformat.setInteger(CJNIMediaFormat::KEY_MAX_INPUT_SIZE, 0);
// handle codec extradata
if (m_hints.extrasize)
{
size_t size = m_hints.extrasize;
void *src_ptr = m_hints.extradata;
if (m_bitstream)
{
size = m_bitstream->GetExtraSize();
src_ptr = m_bitstream->GetExtraData();
}
// Allocate a byte buffer via allocateDirect in java instead of NewDirectByteBuffer,
// since the latter doesn't allocate storage of its own, and we don't know how long
// the codec uses the buffer.
CJNIByteBuffer bytebuffer = CJNIByteBuffer::allocateDirect(size);
void *dts_ptr = xbmc_jnienv()->GetDirectBufferAddress(bytebuffer.get_raw());
memcpy(dts_ptr, src_ptr, size);
// codec will automatically handle buffers as extradata
// using entries with keys "csd-0", "csd-1", etc.
mediaformat.setByteBuffer("csd-0", bytebuffer);
}
InitSurfaceTexture();
// configure and start the codec.