summaryrefslogtreecommitdiffstats
path: root/netwerk/protocol/device/AndroidCaptureProvider.cpp
blob: e69766085025bfb8fdf9607ab4e1621a29c68187 (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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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 "base/basictypes.h"
#include "AndroidCaptureProvider.h"
#include "nsXULAppAPI.h"
#include "nsStreamUtils.h"
#include "nsThreadUtils.h"
#include "nsMemory.h"
#include "RawStructs.h"

// The maximum number of frames we keep in our queue. Don't live in the past.
#define MAX_FRAMES_QUEUED 10

using namespace mozilla::net;

NS_IMPL_ISUPPORTS(AndroidCameraInputStream, nsIInputStream, nsIAsyncInputStream)

AndroidCameraInputStream::AndroidCameraInputStream() :
  mWidth(0), mHeight(0), mCamera(0), mHeaderSent(false), mClosed(true), mFrameSize(0),
  mMonitor("AndroidCamera.Monitor")
{
  mAvailable = sizeof(RawVideoHeader);
  mFrameQueue = new nsDeque();
}

AndroidCameraInputStream::~AndroidCameraInputStream() {
  // clear the frame queue
  while (mFrameQueue->GetSize() > 0) {
    free(mFrameQueue->PopFront());
  }
  delete mFrameQueue;
}

NS_IMETHODIMP
AndroidCameraInputStream::Init(nsACString& aContentType, nsCaptureParams* aParams)
{
  if (!XRE_IsParentProcess())
    return NS_ERROR_NOT_IMPLEMENTED;

  mContentType = aContentType;
  mWidth = aParams->width;
  mHeight = aParams->height;
  mCamera = aParams->camera;
  
  CameraStreamImpl *impl = CameraStreamImpl::GetInstance(0);
  if (!impl)
    return NS_ERROR_OUT_OF_MEMORY;
  if (impl->Init(mContentType, mCamera, mWidth, mHeight, this)) {
    mWidth = impl->GetWidth();
    mHeight = impl->GetHeight();
    mClosed = false;
  }
  return NS_OK;
}

void AndroidCameraInputStream::ReceiveFrame(char* frame, uint32_t length) {
  {
    mozilla::ReentrantMonitorAutoEnter autoMonitor(mMonitor);
    if (mFrameQueue->GetSize() > MAX_FRAMES_QUEUED) {
      free(mFrameQueue->PopFront());
      mAvailable -= mFrameSize;
    }
  }
  
  mFrameSize = sizeof(RawPacketHeader) + length;
  
  char* fullFrame = (char*)moz_xmalloc(mFrameSize);

  if (!fullFrame)
    return;
  
  RawPacketHeader* header = (RawPacketHeader*) fullFrame;
  header->packetID = 0xFF;
  header->codecID = 0x595556; // "YUV"
  
  // we copy the Y plane, and de-interlace the CrCb
  
  uint32_t yFrameSize = mWidth * mHeight;
  uint32_t uvFrameSize = yFrameSize / 4;

  memcpy(fullFrame + sizeof(RawPacketHeader), frame, yFrameSize);
  
  char* uFrame = fullFrame + yFrameSize;
  char* vFrame = fullFrame + yFrameSize + uvFrameSize;
  char* yFrame = frame + yFrameSize;
  for (uint32_t i = 0; i < uvFrameSize; i++) {
    uFrame[i] = yFrame[2 * i + 1];
    vFrame[i] = yFrame[2 * i];
  }
  
  {
    mozilla::ReentrantMonitorAutoEnter autoMonitor(mMonitor);
    mAvailable += mFrameSize;
    mFrameQueue->Push((void*)fullFrame);
  }

  NotifyListeners();
}

NS_IMETHODIMP
AndroidCameraInputStream::Available(uint64_t *aAvailable)
{
  mozilla::ReentrantMonitorAutoEnter autoMonitor(mMonitor);

  *aAvailable = mAvailable;

  return NS_OK;
}

NS_IMETHODIMP AndroidCameraInputStream::IsNonBlocking(bool *aNonBlock) {
  *aNonBlock = true;
  return NS_OK;
}

NS_IMETHODIMP AndroidCameraInputStream::Read(char *aBuffer, uint32_t aCount, uint32_t *aRead) {
  return ReadSegments(NS_CopySegmentToBuffer, aBuffer, aCount, aRead);
}

NS_IMETHODIMP AndroidCameraInputStream::ReadSegments(nsWriteSegmentFun aWriter, void *aClosure, uint32_t aCount, uint32_t *aRead) {
  *aRead = 0;
  
  nsresult rv;

  if (mAvailable == 0)
    return NS_BASE_STREAM_WOULD_BLOCK;
  
  if (aCount > mAvailable)
    aCount = mAvailable;

  if (!mHeaderSent) {
    CameraStreamImpl *impl = CameraStreamImpl::GetInstance(0);
    RawVideoHeader header;
    header.headerPacketID = 0;
    header.codecID = 0x595556; // "YUV"
    header.majorVersion = 0;
    header.minorVersion = 1;
    header.options = 1 | 1 << 1; // color, 4:2:2

    header.alphaChannelBpp = 0;
    header.lumaChannelBpp = 8;
    header.chromaChannelBpp = 4;
    header.colorspace = 1;

    header.frameWidth = mWidth;
    header.frameHeight = mHeight;
    header.aspectNumerator = 1;
    header.aspectDenominator = 1;

    header.framerateNumerator = impl->GetFps();
    header.framerateDenominator = 1;

    rv = aWriter(this, aClosure, (const char*)&header, 0, sizeof(RawVideoHeader), aRead);
   
    if (NS_FAILED(rv))
      return NS_OK;
    
    mHeaderSent = true;
    aCount -= sizeof(RawVideoHeader);
    mAvailable -= sizeof(RawVideoHeader);
  }
  
  {
    mozilla::ReentrantMonitorAutoEnter autoMonitor(mMonitor);
    while ((mAvailable > 0) && (aCount >= mFrameSize)) {
      uint32_t readThisTime = 0;

      char* frame = (char*)mFrameQueue->PopFront();
      rv = aWriter(this, aClosure, (const char*)frame, *aRead, mFrameSize, &readThisTime);

      if (readThisTime != mFrameSize) {
        mFrameQueue->PushFront((void*)frame);
        return NS_OK;
      }
  
      // RawReader does a copy when calling VideoData::Create()
      free(frame);
  
      if (NS_FAILED(rv))
        return NS_OK;

      aCount -= readThisTime;
      mAvailable -= readThisTime;
      *aRead += readThisTime;
    }
  }
  return NS_OK;
}

NS_IMETHODIMP AndroidCameraInputStream::Close() {
  return CloseWithStatus(NS_OK);
}


/**
 * must be called on the main (java) thread
 */
void AndroidCameraInputStream::doClose() {
  NS_ASSERTION(!mClosed, "Camera is already closed");

  CameraStreamImpl *impl = CameraStreamImpl::GetInstance(0);
  impl->Close();
  mClosed = true;
}


void AndroidCameraInputStream::NotifyListeners() {
  mozilla::ReentrantMonitorAutoEnter autoMonitor(mMonitor);
  
  if (mCallback && (mAvailable > sizeof(RawVideoHeader))) {
    nsCOMPtr<nsIInputStreamCallback> callback;
    if (mCallbackTarget) {
      callback = NS_NewInputStreamReadyEvent(mCallback, mCallbackTarget);
    } else {
      callback = mCallback;
    }

    NS_ASSERTION(callback, "Shouldn't fail to make the callback!");

    // Null the callback first because OnInputStreamReady may reenter AsyncWait
    mCallback = nullptr;
    mCallbackTarget = nullptr;

    callback->OnInputStreamReady(this);
  }
}

NS_IMETHODIMP AndroidCameraInputStream::AsyncWait(nsIInputStreamCallback *aCallback, uint32_t aFlags, uint32_t aRequestedCount, nsIEventTarget *aTarget)
{
  if (aFlags != 0)
    return NS_ERROR_NOT_IMPLEMENTED;

  if (mCallback || mCallbackTarget)
    return NS_ERROR_UNEXPECTED;

  mCallbackTarget = aTarget;
  mCallback = aCallback;

  // What we are being asked for may be present already
  NotifyListeners();
  return NS_OK;
}


NS_IMETHODIMP AndroidCameraInputStream::CloseWithStatus(nsresult status)
{
  AndroidCameraInputStream::doClose();
  return NS_OK;
}

/**
 * AndroidCaptureProvider implementation
 */

NS_IMPL_ISUPPORTS0(AndroidCaptureProvider)

AndroidCaptureProvider* AndroidCaptureProvider::sInstance = nullptr;

AndroidCaptureProvider::AndroidCaptureProvider() {
}

AndroidCaptureProvider::~AndroidCaptureProvider() {
  AndroidCaptureProvider::sInstance = nullptr;
}

nsresult AndroidCaptureProvider::Init(nsACString& aContentType,
                        nsCaptureParams* aParams,
                        nsIInputStream** aStream) {

  NS_ENSURE_ARG_POINTER(aParams);

  NS_ASSERTION(aParams->frameLimit == 0 || aParams->timeLimit == 0,
    "Cannot set both a frame limit and a time limit!");

  RefPtr<AndroidCameraInputStream> stream;

  if (aContentType.EqualsLiteral("video/x-raw-yuv")) {
    stream = new AndroidCameraInputStream();
    if (stream) {
      nsresult rv = stream->Init(aContentType, aParams);
      if (NS_FAILED(rv))
        return rv;
    }
    else
      return NS_ERROR_OUT_OF_MEMORY;
  } else {
    NS_NOTREACHED("Should not have asked Android for this type!");
  }
  stream.forget(aStream);
  return NS_OK;
}

already_AddRefed<AndroidCaptureProvider> GetAndroidCaptureProvider() {
  if (!AndroidCaptureProvider::sInstance) {
    AndroidCaptureProvider::sInstance = new AndroidCaptureProvider();
  }
  RefPtr<AndroidCaptureProvider> ret = AndroidCaptureProvider::sInstance;
  return ret.forget();
}