summaryrefslogtreecommitdiff
path: root/chromium/media/gpu/v4l2/v4l2_image_processor_backend.cc
blob: bbf7959e21a9a9362171a5478c4bce34d3b07867 (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "media/gpu/v4l2/v4l2_image_processor_backend.h"

#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <string.h>
#include <sys/eventfd.h>
#include <sys/ioctl.h>
#include <sys/mman.h>

#include <limits>
#include <memory>
#include <utility>

#include "base/bind.h"
#include "base/callback.h"
#include "base/numerics/safe_conversions.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/trace_event/trace_event.h"
#include "media/base/color_plane_layout.h"
#include "media/base/scopedfd_helper.h"
#include "media/base/status.h"
#include "media/gpu/chromeos/fourcc.h"
#include "media/gpu/chromeos/platform_video_frame_utils.h"
#include "media/gpu/macros.h"
#include "media/gpu/v4l2/v4l2_utils.h"

namespace media {

namespace {

const char kImageProcessorTraceName[] = "V4L2ImageProcessorBackend";

absl::optional<gfx::GpuMemoryBufferHandle> CreateHandle(
    const VideoFrame* frame) {
  gfx::GpuMemoryBufferHandle handle = CreateGpuMemoryBufferHandle(frame);

  if (handle.is_null() || handle.type != gfx::NATIVE_PIXMAP)
    return absl::nullopt;
  return handle;
}

void FillV4L2BufferByGpuMemoryBufferHandle(
    const Fourcc& fourcc,
    const gfx::Size& coded_size,
    const gfx::GpuMemoryBufferHandle& gmb_handle,
    V4L2WritableBufferRef* buffer) {
  DCHECK_EQ(buffer->Memory(), V4L2_MEMORY_DMABUF);
  const size_t num_planes =
      V4L2Device::GetNumPlanesOfV4L2PixFmt(fourcc.ToV4L2PixFmt());
  const std::vector<gfx::NativePixmapPlane>& planes =
      gmb_handle.native_pixmap_handle.planes;

  for (size_t i = 0; i < num_planes; ++i) {
    if (fourcc.IsMultiPlanar()) {
      // TODO(crbug.com/901264): The way to pass an offset within a DMA-buf
      // is not defined in V4L2 specification, so we abuse data_offset for
      // now. Fix it when we have the right interface, including any
      // necessary validation and potential alignment
      buffer->SetPlaneDataOffset(i, planes[i].offset);

      // V4L2 counts data_offset as used bytes
      buffer->SetPlaneSize(i, planes[i].size + planes[i].offset);
      // Workaround: filling length should not be needed. This is a bug of
      // videobuf2 library.
      buffer->SetPlaneBytesUsed(i, planes[i].size + planes[i].offset);
    } else {
      // There is no need of filling data_offset for a single-planar format.
      buffer->SetPlaneBytesUsed(i, planes[i].size);
    }
  }
}

bool AllocateV4L2Buffers(V4L2Queue* queue,
                         const size_t num_buffers,
                         v4l2_memory memory_type) {
  DCHECK(queue);

  size_t requested_buffers = num_buffers;

  // If we are using DMABUFs, then we will try to keep using the same V4L2
  // buffer for a given input or output frame. In that case, allocate as many
  // V4L2 buffers as we can to avoid running out of them. Unused buffers won't
  // use backed memory and are thus virtually free.
  if (memory_type == V4L2_MEMORY_DMABUF)
    requested_buffers = VIDEO_MAX_FRAME;

  // Note that MDP does not support incoherent buffer allocations.
  if (queue->AllocateBuffers(requested_buffers, memory_type,
                             /*incoherent=*/false) == 0u)
    return false;

  if (queue->AllocatedBuffersCount() < num_buffers) {
    VLOGF(1) << "Failed to allocate buffers. Allocated number="
             << queue->AllocatedBuffersCount()
             << ", Requested number=" << num_buffers;
    return false;
  }

  return true;
}
}  // namespace

V4L2ImageProcessorBackend::JobRecord::JobRecord()
    : output_buffer_id(std::numeric_limits<size_t>::max()) {}

V4L2ImageProcessorBackend::JobRecord::~JobRecord() = default;

V4L2ImageProcessorBackend::V4L2ImageProcessorBackend(
    scoped_refptr<base::SequencedTaskRunner> backend_task_runner,
    scoped_refptr<V4L2Device> device,
    const PortConfig& input_config,
    const PortConfig& output_config,
    v4l2_memory input_memory_type,
    v4l2_memory output_memory_type,
    OutputMode output_mode,
    VideoRotation relative_rotation,
    size_t num_buffers,
    ErrorCB error_cb)
    : ImageProcessorBackend(input_config,
                            output_config,
                            output_mode,
                            relative_rotation,
                            std::move(error_cb),
                            std::move(backend_task_runner)),
      input_memory_type_(input_memory_type),
      output_memory_type_(output_memory_type),
      device_(device),
      num_buffers_(num_buffers),
      // We poll V4L2 device on this task runner, which blocks the task runner.
      // Therefore we use dedicated SingleThreadTaskRunner here.
      poll_task_runner_(base::ThreadPool::CreateSingleThreadTaskRunner(
          {},
          base::SingleThreadTaskRunnerThreadMode::DEDICATED)) {
  DVLOGF(2);
  DETACH_FROM_SEQUENCE(poll_sequence_checker_);
  DCHECK_NE(output_memory_type_, V4L2_MEMORY_USERPTR);

  backend_weak_this_ = backend_weak_this_factory_.GetWeakPtr();
  poll_weak_this_ = poll_weak_this_factory_.GetWeakPtr();
}

void V4L2ImageProcessorBackend::Destroy() {
  DVLOGF(3);
  DCHECK_CALLED_ON_VALID_SEQUENCE(backend_sequence_checker_);

  backend_weak_this_factory_.InvalidateWeakPtrs();

  if (input_queue_) {
    if (!input_queue_->Streamoff())
      VLOGF(1) << "Failed to turn stream off";
    if (!input_queue_->DeallocateBuffers())
      VLOGF(1) << "Failed to deallocate buffers";
    input_queue_ = nullptr;
  }
  if (output_queue_) {
    if (!output_queue_->Streamoff())
      VLOGF(1) << "Failed to turn stream off";
    if (!output_queue_->DeallocateBuffers())
      VLOGF(1) << "Failed to deallocate buffers";
    output_queue_ = nullptr;
  }

  // Reset all our accounting info.
  input_job_queue_ = {};
  running_jobs_ = {};

  // Stop the running DevicePollTask() if it exists.
  if (!device_->SetDevicePollInterrupt())
    NotifyError();

  // After stopping queue, we don't schedule new DevicePollTask() to
  // |poll_task_runner_|. Now clean up |poll_task_runner_|.
  poll_task_runner_->PostTask(
      FROM_HERE,
      base::BindOnce(&V4L2ImageProcessorBackend::DestroyOnPollSequence,
                     poll_weak_this_));
}

void V4L2ImageProcessorBackend::DestroyOnPollSequence() {
  VLOGF(2);
  DCHECK_CALLED_ON_VALID_SEQUENCE(poll_sequence_checker_);

  poll_weak_this_factory_.InvalidateWeakPtrs();

  delete this;
}

V4L2ImageProcessorBackend::~V4L2ImageProcessorBackend() {
  VLOGF(3);
  DCHECK_CALLED_ON_VALID_SEQUENCE(poll_sequence_checker_);
}

void V4L2ImageProcessorBackend::NotifyError() {
  VLOGF(1);

  error_cb_.Run();
}

namespace {

v4l2_memory InputStorageTypeToV4L2Memory(VideoFrame::StorageType storage_type) {
  switch (storage_type) {
    case VideoFrame::STORAGE_OWNED_MEMORY:
    case VideoFrame::STORAGE_UNOWNED_MEMORY:
    case VideoFrame::STORAGE_SHMEM:
      return V4L2_MEMORY_USERPTR;
    case VideoFrame::STORAGE_DMABUFS:
    case VideoFrame::STORAGE_GPU_MEMORY_BUFFER:
      return V4L2_MEMORY_DMABUF;
    default:
      return static_cast<v4l2_memory>(0);
  }
}

}  // namespace

// static
std::unique_ptr<ImageProcessorBackend> V4L2ImageProcessorBackend::Create(
    scoped_refptr<V4L2Device> device,
    size_t num_buffers,
    const PortConfig& input_config,
    const PortConfig& output_config,
    OutputMode output_mode,
    VideoRotation relative_rotation,
    ErrorCB error_cb,
    scoped_refptr<base::SequencedTaskRunner> backend_task_runner) {
  VLOGF(2);
  DCHECK_GT(num_buffers, 0u);

  // Most of the users of this class are decoders that only want a pixel format
  // conversion (with the same coded dimensions and visible rectangles). Video
  // encoding, however, can try and ask for cropping (this is common for camera
  // capture for example). Although the V4L2 ImageProcessor might support it,
  // it's a better idea to use libyuv instead.
  if (input_config.size != output_config.size ||
      input_config.visible_rect != output_config.visible_rect) {
    VLOGF(2) << "V4L2ImageProcessor cannot adapt size/visible_rects, input "
             << input_config.ToString() << ", output "
             << output_config.ToString();
    return nullptr;
  }

  if (!device) {
    VLOGF(2) << "Failed creating V4L2Device";
    return nullptr;
  }

  VideoFrame::StorageType input_storage_type = VideoFrame::STORAGE_UNKNOWN;
  for (auto input_type : input_config.preferred_storage_types) {
    v4l2_memory v4l2_memory_type = InputStorageTypeToV4L2Memory(input_type);
    if (v4l2_memory_type == V4L2_MEMORY_USERPTR ||
        v4l2_memory_type == V4L2_MEMORY_DMABUF) {
      input_storage_type = input_type;
      break;
    }
  }
  if (input_storage_type == VideoFrame::STORAGE_UNKNOWN) {
    VLOGF(2) << "Unsupported input storage type";
    return nullptr;
  }

  VideoFrame::StorageType output_storage_type = VideoFrame::STORAGE_UNKNOWN;
  for (auto output_type : output_config.preferred_storage_types) {
    v4l2_memory v4l2_memory_type = InputStorageTypeToV4L2Memory(output_type);
    if (v4l2_memory_type == V4L2_MEMORY_MMAP ||
        v4l2_memory_type == V4L2_MEMORY_DMABUF) {
      output_storage_type = output_type;
      break;
    }
  }
  if (output_storage_type == VideoFrame::STORAGE_UNKNOWN) {
    VLOGF(2) << "Unsupported output storage type";
    return nullptr;
  }

  const v4l2_memory input_memory_type =
      InputStorageTypeToV4L2Memory(input_storage_type);
  if (input_memory_type == 0) {
    VLOGF(1) << "Unsupported input storage type: " << input_storage_type;
    return nullptr;
  }

  if (!device->IsImageProcessingSupported()) {
    VLOGF(1) << "V4L2ImageProcessorBackend not supported in this platform";
    return nullptr;
  }

  // V4L2IP now doesn't support rotation case, so return nullptr.
  if (relative_rotation != VIDEO_ROTATION_0) {
    VLOGF(1) << "Currently V4L2IP doesn't support rotation";
    return nullptr;
  }

  if (!device->Open(V4L2Device::Type::kImageProcessor,
                    input_config.fourcc.ToV4L2PixFmt())) {
    VLOGF(1) << "Failed to open device with input fourcc: "
             << input_config.fourcc.ToString();
    return nullptr;
  }

  // Try to set input format.
  struct v4l2_format format;
  memset(&format, 0, sizeof(format));
  format.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
  format.fmt.pix_mp.width = input_config.size.width();
  format.fmt.pix_mp.height = input_config.size.height();
  format.fmt.pix_mp.pixelformat = input_config.fourcc.ToV4L2PixFmt();
  if (device->Ioctl(VIDIOC_S_FMT, &format) != 0 ||
      format.fmt.pix_mp.pixelformat != input_config.fourcc.ToV4L2PixFmt()) {
    VLOGF(1) << "Failed to negotiate input format";
    return nullptr;
  }

  const v4l2_pix_format_mplane& pix_mp = format.fmt.pix_mp;
  const gfx::Size negotiated_input_size(pix_mp.width, pix_mp.height);
  if (!gfx::Rect(negotiated_input_size).Contains(input_config.visible_rect)) {
    VLOGF(1) << "Negotiated input allocated size: "
             << negotiated_input_size.ToString()
             << " should contain visible size: "
             << input_config.visible_rect.size().ToString();
    return nullptr;
  }
  std::vector<ColorPlaneLayout> input_planes(pix_mp.num_planes);
  for (size_t i = 0; i < pix_mp.num_planes; ++i) {
    input_planes[i].stride = pix_mp.plane_fmt[i].bytesperline;
    // offset will be specified for a buffer in each VIDIOC_QBUF.
    input_planes[i].offset = 0;
    input_planes[i].size = pix_mp.plane_fmt[i].sizeimage;
  }

  // Try to set output format.
  memset(&format, 0, sizeof(format));
  format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
  v4l2_pix_format_mplane& out_pix_mp = format.fmt.pix_mp;
  out_pix_mp.width = output_config.size.width();
  out_pix_mp.height = output_config.size.height();
  out_pix_mp.pixelformat = output_config.fourcc.ToV4L2PixFmt();
  out_pix_mp.num_planes = output_config.planes.size();
  for (size_t i = 0; i < output_config.planes.size(); ++i) {
    out_pix_mp.plane_fmt[i].sizeimage = output_config.planes[i].size;
    out_pix_mp.plane_fmt[i].bytesperline = output_config.planes[i].stride;
  }
  if (device->Ioctl(VIDIOC_S_FMT, &format) != 0 ||
      format.fmt.pix_mp.pixelformat != output_config.fourcc.ToV4L2PixFmt()) {
    VLOGF(1) << "Failed to negotiate output format";
    return nullptr;
  }

  out_pix_mp = format.fmt.pix_mp;
  const gfx::Size negotiated_output_size(out_pix_mp.width, out_pix_mp.height);
  if (!gfx::Rect(negotiated_output_size)
           .Contains(gfx::Rect(output_config.size))) {
    VLOGF(1) << "Negotiated output allocated size: "
             << negotiated_output_size.ToString()
             << " should contain original output allocated size: "
             << output_config.size.ToString();
    return nullptr;
  }
  std::vector<ColorPlaneLayout> output_planes(out_pix_mp.num_planes);
  for (size_t i = 0; i < pix_mp.num_planes; ++i) {
    output_planes[i].stride = pix_mp.plane_fmt[i].bytesperline;
    // offset will be specified for a buffer in each VIDIOC_QBUF.
    output_planes[i].offset = 0;
    output_planes[i].size = pix_mp.plane_fmt[i].sizeimage;
  }

  // Capabilities check.
  struct v4l2_capability caps {};
  const __u32 kCapsRequired = V4L2_CAP_VIDEO_M2M_MPLANE | V4L2_CAP_STREAMING;
  if (device->Ioctl(VIDIOC_QUERYCAP, &caps) != 0) {
    VPLOGF(1) << "VIDIOC_QUERYCAP failed";
    return nullptr;
  }
  if ((caps.capabilities & kCapsRequired) != kCapsRequired) {
    VLOGF(1) << "VIDIOC_QUERYCAP failed: "
             << "caps check failed: 0x" << std::hex << caps.capabilities;
    return nullptr;
  }

  // Set a few standard controls to default values.
  struct v4l2_control rotation = {.id = V4L2_CID_ROTATE, .value = 0};
  if (device->Ioctl(VIDIOC_S_CTRL, &rotation) != 0) {
    VPLOGF(1) << "V4L2_CID_ROTATE failed";
    return nullptr;
  }

  struct v4l2_control hflip = {.id = V4L2_CID_HFLIP, .value = 0};
  if (device->Ioctl(VIDIOC_S_CTRL, &hflip) != 0) {
    VPLOGF(1) << "V4L2_CID_HFLIP failed";
    return nullptr;
  }

  struct v4l2_control vflip = {.id = V4L2_CID_VFLIP, .value = 0};
  if (device->Ioctl(VIDIOC_S_CTRL, &vflip) != 0) {
    VPLOGF(1) << "V4L2_CID_VFLIP failed";
    return nullptr;
  }

  struct v4l2_control alpha = {.id = V4L2_CID_ALPHA_COMPONENT, .value = 255};
  if (device->Ioctl(VIDIOC_S_CTRL, &alpha) != 0)
    VPLOGF(1) << "V4L2_CID_ALPHA_COMPONENT failed";

  const v4l2_memory output_memory_type =
      output_mode == OutputMode::ALLOCATE
          ? V4L2_MEMORY_MMAP
          : InputStorageTypeToV4L2Memory(output_storage_type);
  std::unique_ptr<V4L2ImageProcessorBackend> image_processor(
      new V4L2ImageProcessorBackend(
          backend_task_runner, std::move(device),
          PortConfig(input_config.fourcc, negotiated_input_size, input_planes,
                     input_config.visible_rect, {input_storage_type}),
          PortConfig(output_config.fourcc, negotiated_output_size,
                     output_planes, output_config.visible_rect,
                     {output_storage_type}),
          input_memory_type, output_memory_type, output_mode, relative_rotation,
          num_buffers, std::move(error_cb)));

  // Initialize at |backend_task_runner|.
  bool success = false;
  base::WaitableEvent done;
  auto init_cb = base::BindOnce(
      [](base::WaitableEvent* done, bool* success, bool value) {
        *success = value;
        done->Signal();
      },
      base::Unretained(&done), base::Unretained(&success));
  // Using base::Unretained() is safe because it is blocking call.
  backend_task_runner->PostTask(
      FROM_HERE, base::BindOnce(&V4L2ImageProcessorBackend::Initialize,
                                base::Unretained(image_processor.get()),
                                std::move(init_cb)));
  done.Wait();
  if (!success) {
    // This needs to be destroyed on |backend_task_runner|.
    backend_task_runner->DeleteSoon(FROM_HERE, std::move(image_processor));
    return nullptr;
  }

  return image_processor;
}

void V4L2ImageProcessorBackend::Initialize(InitCB init_cb) {
  DVLOGF(2);
  DCHECK_CALLED_ON_VALID_SEQUENCE(backend_sequence_checker_);

  if (!CreateInputBuffers() || !CreateOutputBuffers()) {
    std::move(init_cb).Run(false);
    return;
  }

  // Enqueue a poll task with no devices to poll on - will wait only for the
  // poll interrupt.
  DVLOGF(3) << "starting device poll";
  poll_task_runner_->PostTask(
      FROM_HERE, base::BindOnce(&V4L2ImageProcessorBackend::DevicePollTask,
                                poll_weak_this_, false));

  VLOGF(2) << "V4L2ImageProcessorBackend initialized for "
           << "input: " << input_config_.ToString()
           << ", output: " << output_config_.ToString();

  std::move(init_cb).Run(true);
}

// static
bool V4L2ImageProcessorBackend::IsSupported() {
  scoped_refptr<V4L2Device> device = V4L2Device::Create();
  if (!device)
    return false;

  return device->IsImageProcessingSupported();
}

// static
std::vector<uint32_t> V4L2ImageProcessorBackend::GetSupportedInputFormats() {
  scoped_refptr<V4L2Device> device = V4L2Device::Create();
  if (!device)
    return std::vector<uint32_t>();

  return device->GetSupportedImageProcessorPixelformats(
      V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE);
}

// static
std::vector<uint32_t> V4L2ImageProcessorBackend::GetSupportedOutputFormats() {
  scoped_refptr<V4L2Device> device = V4L2Device::Create();
  if (!device)
    return std::vector<uint32_t>();

  return device->GetSupportedImageProcessorPixelformats(
      V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE);
}

// static
bool V4L2ImageProcessorBackend::TryOutputFormat(uint32_t input_pixelformat,
                                                uint32_t output_pixelformat,
                                                const gfx::Size& input_size,
                                                gfx::Size* output_size,
                                                size_t* num_planes) {
  DVLOGF(3) << "input_format=" << FourccToString(input_pixelformat)
            << " input_size=" << input_size.ToString()
            << " output_format=" << FourccToString(output_pixelformat)
            << " output_size=" << output_size->ToString();
  scoped_refptr<V4L2Device> device = V4L2Device::Create();
  if (!device ||
      !device->Open(V4L2Device::Type::kImageProcessor, input_pixelformat))
    return false;

  // Set input format.
  struct v4l2_format format;
  memset(&format, 0, sizeof(format));
  format.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
  format.fmt.pix_mp.width = input_size.width();
  format.fmt.pix_mp.height = input_size.height();
  format.fmt.pix_mp.pixelformat = input_pixelformat;
  if (device->Ioctl(VIDIOC_S_FMT, &format) != 0 ||
      format.fmt.pix_mp.pixelformat != input_pixelformat) {
    DVLOGF(4) << "Failed to set image processor input format: "
              << V4L2FormatToString(format);
    return false;
  }

  // Try output format.
  memset(&format, 0, sizeof(format));
  format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
  format.fmt.pix_mp.width = output_size->width();
  format.fmt.pix_mp.height = output_size->height();
  format.fmt.pix_mp.pixelformat = output_pixelformat;
  if (device->Ioctl(VIDIOC_TRY_FMT, &format) != 0 ||
      format.fmt.pix_mp.pixelformat != output_pixelformat) {
    return false;
  }

  *num_planes = format.fmt.pix_mp.num_planes;
  *output_size = V4L2Device::AllocatedSizeFromV4L2Format(format);
  DVLOGF(3) << "Adjusted output_size=" << output_size->ToString()
            << ", num_planes=" << *num_planes;
  return true;
}

void V4L2ImageProcessorBackend::ProcessLegacy(scoped_refptr<VideoFrame> frame,
                                              LegacyFrameReadyCB cb) {
  DVLOGF(4) << "ts=" << frame->timestamp().InMilliseconds();
  DCHECK_CALLED_ON_VALID_SEQUENCE(backend_sequence_checker_);

  if (output_memory_type_ != V4L2_MEMORY_MMAP) {
    NOTREACHED();
    return;
  }

  auto job_record = std::make_unique<JobRecord>();
  job_record->input_frame = frame;
  job_record->legacy_ready_cb = std::move(cb);

  input_job_queue_.emplace(std::move(job_record));
  ProcessJobsTask();
}

void V4L2ImageProcessorBackend::Process(scoped_refptr<VideoFrame> input_frame,
                                        scoped_refptr<VideoFrame> output_frame,
                                        FrameReadyCB cb) {
  DVLOGF(4) << "ts=" << input_frame->timestamp().InMilliseconds();
  DCHECK_CALLED_ON_VALID_SEQUENCE(backend_sequence_checker_);

  auto job_record = std::make_unique<JobRecord>();
  job_record->input_frame = std::move(input_frame);
  job_record->output_frame = std::move(output_frame);
  job_record->ready_cb = std::move(cb);

  input_job_queue_.emplace(std::move(job_record));
  ProcessJobsTask();
}

void V4L2ImageProcessorBackend::ProcessJobsTask() {
  DVLOGF(4);
  DCHECK_CALLED_ON_VALID_SEQUENCE(backend_sequence_checker_);

  while (!input_job_queue_.empty()) {
    if (!input_queue_->IsStreaming()) {
      const VideoFrame& input_frame =
          *(input_job_queue_.front()->input_frame.get());
      const gfx::Size input_buffer_size(input_frame.stride(0),
                                        input_frame.coded_size().height());
      if (!ReconfigureV4L2Format(input_buffer_size,
                                 V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE)) {
        NotifyError();
        return;
      }
    }

    if (input_job_queue_.front()
            ->output_frame &&  // output_frame is nullptr in ALLOCATE mode.
        !output_queue_->IsStreaming()) {
      const VideoFrame& output_frame =
          *(input_job_queue_.front()->output_frame.get());
      const gfx::Size output_buffer_size(output_frame.stride(0),
                                         output_frame.coded_size().height());
      if (!ReconfigureV4L2Format(output_buffer_size,
                                 V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE)) {
        NotifyError();
        return;
      }
    }

    // We need one input and one output buffer to schedule the job
    absl::optional<V4L2WritableBufferRef> input_buffer;
    // If we are using DMABUF frames, try to always obtain the same V4L2 buffer.
    if (input_memory_type_ == V4L2_MEMORY_DMABUF) {
      const VideoFrame& input_frame =
          *(input_job_queue_.front()->input_frame.get());
      input_buffer = input_queue_->GetFreeBufferForFrame(input_frame);
    }
    if (!input_buffer)
      input_buffer = input_queue_->GetFreeBuffer();

    absl::optional<V4L2WritableBufferRef> output_buffer;
    // If we are using DMABUF frames, try to always obtain the same V4L2 buffer.
    if (output_memory_type_ == V4L2_MEMORY_DMABUF) {
      const VideoFrame& output_frame =
          *(input_job_queue_.front()->output_frame.get());
      output_buffer = output_queue_->GetFreeBufferForFrame(output_frame);
    }
    if (!output_buffer)
      output_buffer = output_queue_->GetFreeBuffer();

    if (!input_buffer || !output_buffer)
      break;

    auto job_record = std::move(input_job_queue_.front());
    input_job_queue_.pop();
    EnqueueInput(job_record.get(), std::move(*input_buffer));
    EnqueueOutput(job_record.get(), std::move(*output_buffer));
    running_jobs_.emplace(std::move(job_record));
  }
}

void V4L2ImageProcessorBackend::Reset() {
  DVLOGF(3);
  DCHECK_CALLED_ON_VALID_SEQUENCE(backend_sequence_checker_);

  input_job_queue_ = {};
  running_jobs_ = {};
}

bool V4L2ImageProcessorBackend::ReconfigureV4L2Format(const gfx::Size& size,
                                                      enum v4l2_buf_type type) {
  struct v4l2_format format;
  memset(&format, 0, sizeof(format));
  format.type = type;
  if (device_->Ioctl(VIDIOC_G_FMT, &format) != 0) {
    VPLOGF(1) << "ioctl() failed: VIDIOC_G_FMT";
    return false;
  }

  if (static_cast<int>(format.fmt.pix_mp.width) == size.width() &&
      static_cast<int>(format.fmt.pix_mp.height) == size.height()) {
    return true;
  }
  format.fmt.pix_mp.width = size.width();
  format.fmt.pix_mp.height = size.height();
  if (device_->Ioctl(VIDIOC_S_FMT, &format) != 0) {
    VPLOGF(1) << "ioctl() failed: VIDIOC_S_FMT";
    return false;
  }

  auto queue = device_->GetQueue(type);
  const size_t num_buffers = queue->AllocatedBuffersCount();
  const v4l2_memory memory_type = queue->GetMemoryType();
  DCHECK_GT(num_buffers, 0u);
  return queue->DeallocateBuffers() &&
         AllocateV4L2Buffers(queue.get(), num_buffers, memory_type);
}

bool V4L2ImageProcessorBackend::CreateInputBuffers() {
  VLOGF(2);
  DCHECK_CALLED_ON_VALID_SEQUENCE(backend_sequence_checker_);
  DCHECK_EQ(input_queue_, nullptr);

  input_queue_ = device_->GetQueue(V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE);
  return input_queue_ && AllocateV4L2Buffers(input_queue_.get(), num_buffers_,
                                             input_memory_type_);
}

bool V4L2ImageProcessorBackend::CreateOutputBuffers() {
  VLOGF(2);
  DCHECK_CALLED_ON_VALID_SEQUENCE(backend_sequence_checker_);
  DCHECK_EQ(output_queue_, nullptr);

  output_queue_ = device_->GetQueue(V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE);
  return output_queue_ && AllocateV4L2Buffers(output_queue_.get(), num_buffers_,
                                              output_memory_type_);
}

void V4L2ImageProcessorBackend::DevicePollTask(bool poll_device) {
  DVLOGF(4);
  DCHECK_CALLED_ON_VALID_SEQUENCE(poll_sequence_checker_);

  bool event_pending;
  if (!device_->Poll(poll_device, &event_pending)) {
    NotifyError();
    return;
  }

  // All processing should happen on ServiceDeviceTask(), since we shouldn't
  // touch processor state from this thread.
  backend_task_runner_->PostTask(
      FROM_HERE, base::BindOnce(&V4L2ImageProcessorBackend::ServiceDeviceTask,
                                backend_weak_this_));
}

void V4L2ImageProcessorBackend::ServiceDeviceTask() {
  DVLOGF(4);
  DCHECK_CALLED_ON_VALID_SEQUENCE(backend_sequence_checker_);
  DCHECK(input_queue_);

  Dequeue();
  ProcessJobsTask();

  if (!device_->ClearDevicePollInterrupt()) {
    NotifyError();
    return;
  }

  bool poll_device = (input_queue_->QueuedBuffersCount() > 0 ||
                      output_queue_->QueuedBuffersCount() > 0);

  poll_task_runner_->PostTask(
      FROM_HERE, base::BindOnce(&V4L2ImageProcessorBackend::DevicePollTask,
                                poll_weak_this_, poll_device));

  DVLOGF(3) << __func__ << ": buffer counts: INPUT[" << input_job_queue_.size()
            << "] => DEVICE[" << input_queue_->FreeBuffersCount() << "+"
            << input_queue_->QueuedBuffersCount() << "/"
            << input_queue_->AllocatedBuffersCount() << "->"
            << output_queue_->AllocatedBuffersCount() -
                   output_queue_->QueuedBuffersCount()
            << "+" << output_queue_->QueuedBuffersCount() << "/"
            << output_queue_->AllocatedBuffersCount() << "]";
}

void V4L2ImageProcessorBackend::EnqueueInput(const JobRecord* job_record,
                                             V4L2WritableBufferRef buffer) {
  DVLOGF(4);
  DCHECK_CALLED_ON_VALID_SEQUENCE(backend_sequence_checker_);
  DCHECK(input_queue_);

  const size_t old_inputs_queued = input_queue_->QueuedBuffersCount();
  if (!EnqueueInputRecord(job_record, std::move(buffer))) {
    NotifyError();
    return;
  }

  if (old_inputs_queued == 0 && input_queue_->QueuedBuffersCount() != 0) {
    // We started up a previously empty queue.
    // Queue state changed; signal interrupt.
    if (!device_->SetDevicePollInterrupt()) {
      NotifyError();
      return;
    }
    // VIDIOC_STREAMON if we haven't yet.
    if (!input_queue_->Streamon())
      return;
  }
}

void V4L2ImageProcessorBackend::EnqueueOutput(JobRecord* job_record,
                                              V4L2WritableBufferRef buffer) {
  DVLOGF(4);
  DCHECK_CALLED_ON_VALID_SEQUENCE(backend_sequence_checker_);
  DCHECK(output_queue_);

  const int old_outputs_queued = output_queue_->QueuedBuffersCount();
  if (!EnqueueOutputRecord(job_record, std::move(buffer))) {
    NotifyError();
    return;
  }

  if (old_outputs_queued == 0 && output_queue_->QueuedBuffersCount() != 0) {
    // We just started up a previously empty queue.
    // Queue state changed; signal interrupt.
    if (!device_->SetDevicePollInterrupt()) {
      NotifyError();
      return;
    }
    // Start VIDIOC_STREAMON if we haven't yet.
    if (!output_queue_->Streamon())
      return;
  }
}

// static
void V4L2ImageProcessorBackend::V4L2VFRecycleThunk(
    scoped_refptr<base::SequencedTaskRunner> task_runner,
    absl::optional<base::WeakPtr<V4L2ImageProcessorBackend>> image_processor,
    V4L2ReadableBufferRef buf) {
  DVLOGF(4);
  DCHECK(image_processor);

  task_runner->PostTask(
      FROM_HERE, base::BindOnce(&V4L2ImageProcessorBackend::V4L2VFRecycleTask,
                                *image_processor, std::move(buf)));
}

void V4L2ImageProcessorBackend::V4L2VFRecycleTask(V4L2ReadableBufferRef buf) {
  DVLOGF(4);
  DCHECK_CALLED_ON_VALID_SEQUENCE(backend_sequence_checker_);

  // Release the buffer reference so we can directly call ProcessJobsTask()
  // knowing that we have an extra output buffer.
#if DCHECK_IS_ON()
  size_t original_free_buffers_count = output_queue_->FreeBuffersCount();
#endif
  buf = nullptr;
#if DCHECK_IS_ON()
  DCHECK_EQ(output_queue_->FreeBuffersCount(), original_free_buffers_count + 1);
#endif

  // A CAPTURE buffer has just been returned to the free list, let's see if
  // we can make progress on some jobs.
  ProcessJobsTask();
}

void V4L2ImageProcessorBackend::Dequeue() {
  DVLOGF(4);
  DCHECK_CALLED_ON_VALID_SEQUENCE(backend_sequence_checker_);
  DCHECK(input_queue_);
  DCHECK(output_queue_);
  DCHECK(input_queue_->IsStreaming());

  // Dequeue completed input (VIDEO_OUTPUT) buffers,
  // and recycle to the free list.
  while (input_queue_->QueuedBuffersCount() > 0) {
    auto [res, buffer] = input_queue_->DequeueBuffer();
    if (!res) {
      NotifyError();
      return;
    }
    if (!buffer) {
      // No error occurred, we are just out of buffers to dequeue.
      break;
    }
  }

  // Dequeue completed output (VIDEO_CAPTURE) buffers.
  // Return the finished buffer to the client via the job ready callback.
  while (output_queue_->QueuedBuffersCount() > 0) {
    DCHECK(output_queue_->IsStreaming());

    auto [res, buffer] = output_queue_->DequeueBuffer();
    if (!res) {
      NotifyError();
      return;
    } else if (!buffer) {
      break;
    }

    // Jobs are always processed in FIFO order.
    if (running_jobs_.empty() ||
        running_jobs_.front()->output_buffer_id != buffer->BufferId()) {
      DVLOGF(3) << "previous Reset() abondoned the job, ignore.";
      continue;
    }
    std::unique_ptr<JobRecord> job_record = std::move(running_jobs_.front());
    running_jobs_.pop();

    scoped_refptr<VideoFrame> output_frame;
    switch (output_memory_type_) {
      case V4L2_MEMORY_MMAP:
        // Wrap the V4L2 VideoFrame into another one with a destruction observer
        // so we can reuse the MMAP buffer once the client is done with it.
        {
          const auto& orig_frame = buffer->GetVideoFrame();
          output_frame = VideoFrame::WrapVideoFrame(
              orig_frame, orig_frame->format(), orig_frame->visible_rect(),
              orig_frame->natural_size());
          // Because VideoFrame destruction callback might be executed on any
          // sequence, we use a thunk to post the task to
          // |backend_task_runner_|.
          output_frame->AddDestructionObserver(
              base::BindOnce(&V4L2ImageProcessorBackend::V4L2VFRecycleThunk,
                             backend_task_runner_, backend_weak_this_, buffer));
          break;
        }
      case V4L2_MEMORY_DMABUF:
        output_frame = std::move(job_record->output_frame);
        break;

      default:
        NOTREACHED();
        return;
    }

    const auto timestamp = job_record->input_frame->timestamp();
    auto iter = buffer_tracers_.find(timestamp);
    if (iter != buffer_tracers_.end()) {
      iter->second->EndTrace(DecoderStatus::Codes::kOk);
      buffer_tracers_.erase(iter);
    }

    output_frame->set_timestamp(timestamp);
    output_frame->set_color_space(job_record->input_frame->ColorSpace());

    if (!job_record->legacy_ready_cb.is_null()) {
      std::move(job_record->legacy_ready_cb)
          .Run(buffer->BufferId(), std::move(output_frame));
    } else {
      std::move(job_record->ready_cb).Run(std::move(output_frame));
    }
  }
}

bool V4L2ImageProcessorBackend::EnqueueInputRecord(
    const JobRecord* job_record,
    V4L2WritableBufferRef buffer) {
  DVLOGF(4);
  DCHECK_CALLED_ON_VALID_SEQUENCE(backend_sequence_checker_);
  DCHECK(input_queue_);

  switch (input_memory_type_) {
    case V4L2_MEMORY_USERPTR: {
      VideoFrame& frame = *job_record->input_frame;
      const size_t num_planes = V4L2Device::GetNumPlanesOfV4L2PixFmt(
          input_config_.fourcc.ToV4L2PixFmt());
      std::vector<void*> user_ptrs(num_planes);
      if (frame.storage_type() == VideoFrame::STORAGE_SHMEM) {
        // TODO(b/243883312): This copies the video frame to a writable buffer
        // since the USERPTR API requires writable permission. Remove this
        // workaround once the unreasonable permission is fixed.
        const size_t buffer_size = frame.shm_region()->GetSize();
        std::vector<uint8_t> writable_buffer(buffer_size);
        std::memcpy(writable_buffer.data(), frame.data(0), buffer_size);
        for (size_t i = 0; i < num_planes; ++i) {
          const std::intptr_t plane_offset =
              reinterpret_cast<std::intptr_t>(frame.data(i)) -
              reinterpret_cast<std::intptr_t>(frame.data(0));
          user_ptrs[i] = writable_buffer.data() + plane_offset;
        }
        job_record->input_frame->AddDestructionObserver(base::BindOnce(
            [](std::vector<uint8_t>) {}, std::move(writable_buffer)));
      } else {
        for (size_t i = 0; i < num_planes; ++i)
          user_ptrs[i] = frame.writable_data(i);
      }

      for (size_t i = 0; i < num_planes; ++i) {
        int bytes_used =
            VideoFrame::PlaneSize(frame.format(), i, input_config_.size)
                .GetArea();
        buffer.SetPlaneBytesUsed(i, bytes_used);
      }
      if (!std::move(buffer).QueueUserPtr(user_ptrs)) {
        VPLOGF(1) << "Failed to queue a DMABUF buffer to input queue";
        NotifyError();
        return false;
      }
      break;
    }
    case V4L2_MEMORY_DMABUF: {
      auto input_handle = CreateHandle(job_record->input_frame.get());
      if (!input_handle) {
        VLOGF(1) << "Failed to create native GpuMemoryBufferHandle";
        NotifyError();
        return false;
      }

      FillV4L2BufferByGpuMemoryBufferHandle(
          input_config_.fourcc, input_config_.size, *input_handle, &buffer);
      if (!std::move(buffer).QueueDMABuf(
              input_handle->native_pixmap_handle.planes)) {
        VPLOGF(1) << "Failed to queue a DMABUF buffer to input queue";
        NotifyError();
        return false;
      }
      break;
    }
    default:
      NOTREACHED();
      return false;
  }
  DVLOGF(4) << "enqueued frame ts="
            << job_record->input_frame->timestamp().InMilliseconds()
            << " to device.";

  const auto timestamp = job_record->input_frame->timestamp();
  buffer_tracers_[timestamp] =
      std::make_unique<ScopedDecodeTrace>(kImageProcessorTraceName,
                                          /*is_key_frame=*/false, timestamp);
  return true;
}

bool V4L2ImageProcessorBackend::EnqueueOutputRecord(
    JobRecord* job_record,
    V4L2WritableBufferRef buffer) {
  DVLOGF(4);
  DCHECK_CALLED_ON_VALID_SEQUENCE(backend_sequence_checker_);

  job_record->output_buffer_id = buffer.BufferId();

  switch (buffer.Memory()) {
    case V4L2_MEMORY_MMAP:
      return std::move(buffer).QueueMMap();
    case V4L2_MEMORY_DMABUF: {
      auto output_handle = CreateHandle(job_record->output_frame.get());
      if (!output_handle) {
        VLOGF(1) << "Failed to create native GpuMemoryBufferHandle";
        NotifyError();
        return false;
      }

      FillV4L2BufferByGpuMemoryBufferHandle(
          output_config_.fourcc, output_config_.size, *output_handle, &buffer);
      return std::move(buffer).QueueDMABuf(
          output_handle->native_pixmap_handle.planes);
    }
    default:
      NOTREACHED();
      return false;
  }
}

}  // namespace media