Repository: opencv
Issue: [iOS] VideoWriter::write() with CAP_AVFOUNDATION backend results in BAD_ALLOC
Labels: platform: ios/osx

<!--
If you have a question rather than reporting a bug please go to https://forum.opencv.org where you get much faster responses.
If you need further assistance please read [How To Contribute](https://github.com/opencv/opencv/wiki/How_to_contribute).

This is a template helping you to create an issue which can be processed as quickly as possible. This is the bug reporting section for the OpenCV library.
-->

##### System information (version)
<!-- Example
- OpenCV => 4.2
- Operating System / Platform => Windows 64 Bit
- Compiler => Visual Studio 2017
-->

- OpenCV => 4.5.2-dev and 4.5.1 (tested on both)
- Operating System / Platform => XCode 14.4 (macOS Big Sur 11.1) testing on iOS Simulator (iOS 14.4)
- Compiler => Apple clang version 12.0.0 (clang-1200.0.32.29)

##### Detailed description

<!-- your description -->
My goal is to read a .mp4 file (H264) from the iOS bundle, process it, and save it back to .mp4 (H264). The application is written in Swift, and it communicates with OpenCV C++ code through a C interface.
Unfortunately, every time `VideoWriter::write()` with CAP_AVFOUNDATION backend is called, multiple threads that execute `vConvert_ARGB8888To420Yp8_CbCr8_sse4_1()` are spawned. One of these threads will always cause BAD_ALLOC. Of course, these threads work asynchronically, and BAD_ALLOC is thrown independently from where the main thread's execution is. To me, it seems like some data race, and I suspect there is a bug in the current OpenCV implementation of CAP_AVFOUNDATION backend API.

Using `cv::imwrite()` to write each frame as .jpg works fine. Alternatively I can use CAP_OPENCV_MJPEG with `fourcc = ['M', 'J', 'P', 'G']` and it can produce .avi (and only .avi).

I have tested the following approaches, and all of them causes BAD_ALLOC:
- writing the original frame captured by VideoCapture to VideoWriter without any processing
- writing monochromatic frame cv::Mat to VideoWriter without any processing
- adding `std::this_thread::sleep_for(std::chrono::milliseconds(1000));` after `VideoWriter::write()`, the main thread indeed goes asleep but the mentioned threads cause BAD_ALLOC in the background
- testing CAP_AVFOUNDATION with several different containers and codecs

Under no circumstances was I able to create a working video with CAP_AVFOUNDATION backend API. This is cumbersome as I cannot use FFMPEG on iOS, and I have to rely on AVFoundation instead.

##### Steps to reproduce

<!-- to add code example fence it with triple backticks and optional file extension
    ```.cpp
    // C++ code example
    ```

 or attach as .txt or .zip file
-->
//...
Simplified code that also causes BAD_ALLOC. Please notice that I am simply writing a static frame (no additional processing, no reading from VideoCapture).
```
//...
std::string outputVideoFilename = "pathToBundle/output.mp4"
auto fourcc = VideoWriter::fourcc('H', '2', '6', '4');
auto videoWriter = VideoWriter(outputVideoFilename, CAP_AVFOUNDATION, fourcc, fps, Size(width, height));

Mat testFrame(Size(width, height), CV_8UC3, Scalar(255,150,0));

for (int frameIdx = 0; frameIdx < nFrames; frameIdx++) {
    videoWriter.write(testFrame); 
}

videoWriter.release()
//...


/*
The configuration below works fine. Unfortunately, CAP_OPENCV_MJPEG is rather limited.

std::string outputVideoFilename = "pathToBundle/output.avi"
auto fourcc = VideoWriter::fourcc('M', 'J', 'P', 'G');
auto videoWriter = VideoWriter(outputVideoFilename, CAP_OPENCV_MJPEG, fourcc, fps, Size(width, height));
*/
```



##### Issue submission checklist

 - [x] I report the issue, it's not a question
   <!--
   OpenCV team works with forum.opencv.org, Stack Overflow and other communities
   to discuss problems. Tickets with question without real issue statement will be
   closed.
   -->
 - [x] I checked the problem with documentation, FAQ, open issues,
       forum.opencv.org, Stack Overflow, etc and have not found solution
   <!--
   Places to check:
   * OpenCV documentation: https://docs.opencv.org
   * FAQ page: https://github.com/opencv/opencv/wiki/FAQ
   * OpenCV forum: https://forum.opencv.org
   * OpenCV issue tracker: https://github.com/opencv/opencv/issues?q=is%3Aissue
   * Stack Overflow branch: https://stackoverflow.com/questions/tagged/opencv
   -->
 - [x] I updated to latest OpenCV version and the issue is still there
   <!--
   master branch for OpenCV 4.x and 3.4 branch for OpenCV 3.x releases.
   OpenCV team supports only latest release for each branch.
   The ticket is closed, if the problem is not reproduced with modern version.
   -->
 - [x] There is reproducer code and related data files: videos, images, onnx, etc
   <!--
   The best reproducer -- test case for OpenCV that we can add to the library.
   Recommendations for media files and binary files:
   * Try to reproduce the issue with images and videos in opencv_extra repository
     to reduce attachment size
   * Use PNG for images, if you report some CV related bug, but not image reader
     issue
   * Attach the image as archive to the ticket, if you report some reader issue.
     Image hosting services compress images and it breaks the repro code.
   * Provide ONNX file for some public model or ONNX file with with random weights,
     if you report ONNX parsing or handling issue. Architecture details diagram
     from netron tool can be very useful too. See https://lutzroeder.github.io/netron/
   -->