summaryrefslogtreecommitdiffstats
path: root/dom/media/platforms/android/RemoteDataDecoder.cpp
blob: 56af2601fc948b62cb3d1b8e8fdfcd124091fc15 (plain)
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "AndroidDecoderModule.h"
#include "AndroidBridge.h"
#include "AndroidSurfaceTexture.h"
#include "FennecJNINatives.h"
#include "GLImages.h"

#include "MediaData.h"
#include "MediaInfo.h"
#include "VideoUtils.h"
#include "VPXDecoder.h"

#include "nsThreadUtils.h"
#include "nsPromiseFlatString.h"
#include "nsIGfxInfo.h"

#include "prlog.h"

#include <jni.h>

#include <deque>

#undef LOG
#define LOG(arg, ...) MOZ_LOG(sAndroidDecoderModuleLog, \
    mozilla::LogLevel::Debug, ("RemoteDataDecoder(%p)::%s: " arg, \
      this, __func__, ##__VA_ARGS__))

using namespace mozilla;
using namespace mozilla::gl;
using namespace mozilla::java;
using namespace mozilla::java::sdk;
using media::TimeUnit;

namespace mozilla {

class JavaCallbacksSupport
  : public CodecProxy::NativeCallbacks::Natives<JavaCallbacksSupport>
{
public:
  typedef CodecProxy::NativeCallbacks::Natives<JavaCallbacksSupport> Base;
  using Base::AttachNative;

  JavaCallbacksSupport(MediaDataDecoderCallback* aDecoderCallback)
    : mDecoderCallback(aDecoderCallback)
  {
    MOZ_ASSERT(aDecoderCallback);
  }

  virtual ~JavaCallbacksSupport() {}

  void OnInputExhausted()
  {
    if (mDecoderCallback) {
      mDecoderCallback->InputExhausted();
    }
  }

  virtual void HandleOutput(Sample::Param aSample) = 0;

  void OnOutput(jni::Object::Param aSample)
  {
    if (mDecoderCallback) {
      HandleOutput(Sample::Ref::From(aSample));
    }
  }

  virtual void HandleOutputFormatChanged(MediaFormat::Param aFormat) {};

  void OnOutputFormatChanged(jni::Object::Param aFormat)
  {
    if (mDecoderCallback) {
      HandleOutputFormatChanged(MediaFormat::Ref::From(aFormat));
    }
  }

  void OnError(bool aIsFatal)
  {
    if (mDecoderCallback) {
      mDecoderCallback->Error(aIsFatal ?
        MediaResult(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__) :
        MediaResult(NS_ERROR_DOM_MEDIA_DECODE_ERR, __func__));
    }
  }

  void DisposeNative()
  {
    // TODO
  }

  void Cancel()
  {
    mDecoderCallback = nullptr;
  }

protected:
  MediaDataDecoderCallback* mDecoderCallback;
};

struct SampleTime final
{
  SampleTime(int64_t aStart, int64_t aDuration)
    : mStart(aStart)
    , mDuration(aDuration)
  {}

  int64_t mStart;
  int64_t mDuration;
};


class RemoteVideoDecoder final : public RemoteDataDecoder
{
public:
  class CallbacksSupport final : public JavaCallbacksSupport
  {
  public:
    CallbacksSupport(RemoteVideoDecoder* aDecoder, MediaDataDecoderCallback* aCallback)
      : JavaCallbacksSupport(aCallback)
      , mDecoder(aDecoder)
    {}

    virtual ~CallbacksSupport() {}

    void HandleOutput(Sample::Param aSample) override
    {
      Maybe<int64_t> durationUs = mDecoder->mInputDurations.Get();
      if (!durationUs) {
        return;
      }

      BufferInfo::LocalRef info = aSample->Info();

      int32_t flags;
      bool ok = NS_SUCCEEDED(info->Flags(&flags));
      MOZ_ASSERT(ok);

      int32_t offset;
      ok |= NS_SUCCEEDED(info->Offset(&offset));
      MOZ_ASSERT(ok);

      int64_t presentationTimeUs;
      ok |= NS_SUCCEEDED(info->PresentationTimeUs(&presentationTimeUs));
      MOZ_ASSERT(ok);

      int32_t size;
      ok |= NS_SUCCEEDED(info->Size(&size));
      MOZ_ASSERT(ok);

      NS_ENSURE_TRUE_VOID(ok);

      if (size > 0) {
        RefPtr<layers::Image> img =
          new SurfaceTextureImage(mDecoder->mSurfaceTexture.get(), mDecoder->mConfig.mDisplay,
                                  gl::OriginPos::BottomLeft);

        RefPtr<VideoData> v =
          VideoData::CreateFromImage(mDecoder->mConfig,
                                    offset,
                                    presentationTimeUs,
                                    durationUs.value(),
                                    img,
                                    !!(flags & MediaCodec::BUFFER_FLAG_SYNC_FRAME),
                                    presentationTimeUs,
                                    gfx::IntRect(0, 0,
                                                  mDecoder->mConfig.mDisplay.width,
                                                  mDecoder->mConfig.mDisplay.height));

        mDecoderCallback->Output(v);
      }

      if ((flags & MediaCodec::BUFFER_FLAG_END_OF_STREAM) != 0) {
        mDecoderCallback->DrainComplete();
      }
    }

    friend class RemoteDataDecoder;

  private:
    RemoteVideoDecoder* mDecoder;
  };

  RemoteVideoDecoder(const VideoInfo& aConfig,
                   MediaFormat::Param aFormat,
                   MediaDataDecoderCallback* aCallback,
                   layers::ImageContainer* aImageContainer)
    : RemoteDataDecoder(MediaData::Type::VIDEO_DATA, aConfig.mMimeType,
                        aFormat, aCallback)
    , mImageContainer(aImageContainer)
    , mConfig(aConfig)
  {
  }

  RefPtr<InitPromise> Init() override
  {
    mSurfaceTexture = AndroidSurfaceTexture::Create();
    if (!mSurfaceTexture) {
      NS_WARNING("Failed to create SurfaceTexture for video decode\n");
      return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
    }

    if (!jni::IsFennec()) {
      NS_WARNING("Remote decoding not supported in non-Fennec environment\n");
      return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
    }

    // Register native methods.
    JavaCallbacksSupport::Init();

    mJavaCallbacks = CodecProxy::NativeCallbacks::New();
    JavaCallbacksSupport::AttachNative(mJavaCallbacks,
                                       mozilla::MakeUnique<CallbacksSupport>(this, mCallback));

    mJavaDecoder = CodecProxy::Create(mFormat, mSurfaceTexture->JavaSurface(), mJavaCallbacks);
    if (mJavaDecoder == nullptr) {
      return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
    }

    mInputDurations.Clear();

    return InitPromise::CreateAndResolve(TrackInfo::kVideoTrack, __func__);
  }

  void Flush() override
  {
    mInputDurations.Clear();
    RemoteDataDecoder::Flush();
  }

  void Drain() override
  {
    RemoteDataDecoder::Drain();
    mInputDurations.Put(0);
  }

  void Input(MediaRawData* aSample) override
  {
    RemoteDataDecoder::Input(aSample);
    mInputDurations.Put(aSample->mDuration);
  }

private:
  class DurationQueue {
  public:

    void Clear()
    {
      mValues.clear();
    }

    void Put(int64_t aDurationUs)
    {
      mValues.emplace_back(aDurationUs);
    }

    Maybe<int64_t> Get()
    {
      if (mValues.empty()) {
        return Nothing();
      }

      auto value = Some(mValues.front());
      mValues.pop_front();

      return value;
    }

  private:
    std::deque<int64_t> mValues;
  };

  layers::ImageContainer* mImageContainer;
  const VideoInfo& mConfig;
  RefPtr<AndroidSurfaceTexture> mSurfaceTexture;
  DurationQueue mInputDurations;
};

class RemoteAudioDecoder final : public RemoteDataDecoder
{
public:
  RemoteAudioDecoder(const AudioInfo& aConfig,
                   MediaFormat::Param aFormat,
                   MediaDataDecoderCallback* aCallback)
    : RemoteDataDecoder(MediaData::Type::AUDIO_DATA, aConfig.mMimeType,
                        aFormat, aCallback)
    , mConfig(aConfig)
  {
    JNIEnv* const env = jni::GetEnvForThread();

    bool formatHasCSD = false;
    NS_ENSURE_SUCCESS_VOID(aFormat->ContainsKey(NS_LITERAL_STRING("csd-0"), &formatHasCSD));

    if (!formatHasCSD && aConfig.mCodecSpecificConfig->Length() >= 2) {
      jni::ByteBuffer::LocalRef buffer(env);
      buffer = jni::ByteBuffer::New(
          aConfig.mCodecSpecificConfig->Elements(),
          aConfig.mCodecSpecificConfig->Length());
      NS_ENSURE_SUCCESS_VOID(aFormat->SetByteBuffer(NS_LITERAL_STRING("csd-0"),
                                                    buffer));
    }
  }

  RefPtr<InitPromise> Init() override
  {
    // Register native methods.
    JavaCallbacksSupport::Init();

    mJavaCallbacks = CodecProxy::NativeCallbacks::New();
    JavaCallbacksSupport::AttachNative(mJavaCallbacks,
                                       mozilla::MakeUnique<CallbacksSupport>(this, mCallback));

    mJavaDecoder = CodecProxy::Create(mFormat, nullptr, mJavaCallbacks);
    if (mJavaDecoder == nullptr) {
      return InitPromise::CreateAndReject(NS_ERROR_DOM_MEDIA_FATAL_ERR, __func__);
    }

    return InitPromise::CreateAndResolve(TrackInfo::kAudioTrack, __func__);
  }

private:
  class CallbacksSupport final : public JavaCallbacksSupport
  {
  public:
    CallbacksSupport(RemoteAudioDecoder* aDecoder, MediaDataDecoderCallback* aCallback)
      : JavaCallbacksSupport(aCallback)
      , mDecoder(aDecoder)
    {}

    virtual ~CallbacksSupport() {}

    void HandleOutput(Sample::Param aSample) override
    {
      BufferInfo::LocalRef info = aSample->Info();

      int32_t flags;
      bool ok = NS_SUCCEEDED(info->Flags(&flags));
      MOZ_ASSERT(ok);

      int32_t offset;
      ok |= NS_SUCCEEDED(info->Offset(&offset));
      MOZ_ASSERT(ok);

      int64_t presentationTimeUs;
      ok |= NS_SUCCEEDED(info->PresentationTimeUs(&presentationTimeUs));
      MOZ_ASSERT(ok);

      int32_t size;
      ok |= NS_SUCCEEDED(info->Size(&size));
      MOZ_ASSERT(ok);

      NS_ENSURE_TRUE_VOID(ok);

      if (size > 0) {
#ifdef MOZ_SAMPLE_TYPE_S16
        const int32_t numSamples = size / 2;
#else
#error We only support 16-bit integer PCM
#endif

        const int32_t numFrames = numSamples / mOutputChannels;
        AlignedAudioBuffer audio(numSamples);
        if (!audio) {
          return;
        }

        jni::ByteBuffer::LocalRef dest = jni::ByteBuffer::New(audio.get(), size);
        aSample->WriteToByteBuffer(dest);

        RefPtr<AudioData> data = new AudioData(0, presentationTimeUs,
                                              FramesToUsecs(numFrames, mOutputSampleRate).value(),
                                              numFrames,
                                              Move(audio),
                                              mOutputChannels,
                                              mOutputSampleRate);

        mDecoderCallback->Output(data);
      }

      if ((flags & MediaCodec::BUFFER_FLAG_END_OF_STREAM) != 0) {
        mDecoderCallback->DrainComplete();
        return;
      }
    }

    void HandleOutputFormatChanged(MediaFormat::Param aFormat) override
    {
      aFormat->GetInteger(NS_LITERAL_STRING("channel-count"), &mOutputChannels);
      AudioConfig::ChannelLayout layout(mOutputChannels);
      if (!layout.IsValid()) {
        mDecoderCallback->Error(MediaResult(
          NS_ERROR_DOM_MEDIA_FATAL_ERR,
          RESULT_DETAIL("Invalid channel layout:%d", mOutputChannels)));
        return;
      }
      aFormat->GetInteger(NS_LITERAL_STRING("sample-rate"), &mOutputSampleRate);
      LOG("Audio output format changed: channels:%d sample rate:%d", mOutputChannels, mOutputSampleRate);
    }

  private:
    RemoteAudioDecoder* mDecoder;
    int32_t mOutputChannels;
    int32_t mOutputSampleRate;
  };

  const AudioInfo& mConfig;
};

MediaDataDecoder*
RemoteDataDecoder::CreateAudioDecoder(const AudioInfo& aConfig,
                                          MediaFormat::Param aFormat,
                                          MediaDataDecoderCallback* aCallback)
{
  return new RemoteAudioDecoder(aConfig, aFormat, aCallback);
}

MediaDataDecoder*
RemoteDataDecoder::CreateVideoDecoder(const VideoInfo& aConfig,
                                          MediaFormat::Param aFormat,
                                          MediaDataDecoderCallback* aCallback,
                                          layers::ImageContainer* aImageContainer)
{
  return new RemoteVideoDecoder(aConfig, aFormat, aCallback, aImageContainer);
}

RemoteDataDecoder::RemoteDataDecoder(MediaData::Type aType,
                                     const nsACString& aMimeType,
                                     MediaFormat::Param aFormat,
                                     MediaDataDecoderCallback* aCallback)
  : mType(aType)
  , mMimeType(aMimeType)
  , mFormat(aFormat)
  , mCallback(aCallback)
{
}

void
RemoteDataDecoder::Flush()
{
  mJavaDecoder->Flush();
}

void
RemoteDataDecoder::Drain()
{
  BufferInfo::LocalRef bufferInfo;
  nsresult rv = BufferInfo::New(&bufferInfo);
  NS_ENSURE_SUCCESS_VOID(rv);
  bufferInfo->Set(0, 0, -1, MediaCodec::BUFFER_FLAG_END_OF_STREAM);

  mJavaDecoder->Input(nullptr, bufferInfo, nullptr);
}

void
RemoteDataDecoder::Shutdown()
{
  LOG("");
  MOZ_ASSERT(mJavaDecoder && mJavaCallbacks);

  mJavaDecoder->Release();
  mJavaDecoder = nullptr;

  JavaCallbacksSupport::GetNative(mJavaCallbacks)->Cancel();
  mJavaCallbacks = nullptr;

  mFormat = nullptr;
}

void
RemoteDataDecoder::Input(MediaRawData* aSample)
{
  MOZ_ASSERT(aSample != nullptr);

  jni::ByteBuffer::LocalRef bytes = jni::ByteBuffer::New(const_cast<uint8_t*>(aSample->Data()),
                                                         aSample->Size());

  BufferInfo::LocalRef bufferInfo;
  nsresult rv = BufferInfo::New(&bufferInfo);
  if (NS_FAILED(rv)) {
    mCallback->Error(MediaResult(NS_ERROR_OUT_OF_MEMORY, __func__));
    return;
  }
  bufferInfo->Set(0, aSample->Size(), aSample->mTime, 0);

  mJavaDecoder->Input(bytes, bufferInfo, GetCryptoInfoFromSample(aSample));
}

} // mozilla