-
-
Notifications
You must be signed in to change notification settings - Fork 667
Expand file tree
/
Copy pathVideoAnimation.cpp
More file actions
1032 lines (895 loc) · 35 KB
/
Copy pathVideoAnimation.cpp
File metadata and controls
1032 lines (895 loc) · 35 KB
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
#include "pch.h"
#include "VideoAnimation.h"
#if __has_include("VideoAnimation.g.cpp")
#include "VideoAnimation.g.cpp"
#endif
#include <VideoAnimationStreamSource.h>
// divide by 255 and round to nearest
// apply a fast variant: (X+127)/255 = ((X+127)*257+257)>>16 = ((X+128)*257)>>16
#define FAST_DIV255(x) ((((x)+128) * 257) >> 16)
namespace winrt::Telegram::Native::implementation
{
static int open_codec_context(int* stream_idx, AVCodecContext** dec_ctx, AVFormatContext* fmt_ctx, enum AVMediaType type)
{
int ret, stream_index;
AVStream* st;
const AVCodec* dec = NULL;
AVDictionary* opts = NULL;
ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
if (ret < 0)
{
//OutputDebugStringFormat(L"can't find %s stream in input file", av_get_media_type_string(type));
return ret;
}
else
{
stream_index = ret;
st = fmt_ctx->streams[stream_index];
dec = avcodec_find_decoder(st->codecpar->codec_id);
if (!dec)
{
//OutputDebugStringFormat(L"failed to find %s codec", av_get_media_type_string(type));
return AVERROR(EINVAL);
}
*dec_ctx = avcodec_alloc_context3(dec);
if (!*dec_ctx)
{
//OutputDebugStringFormat(L"Failed to allocate the %s codec context", av_get_media_type_string(type));
return AVERROR(ENOMEM);
}
if ((ret = avcodec_parameters_to_context(*dec_ctx, st->codecpar)) < 0)
{
//OutputDebugStringFormat(L"Failed to copy %s codec parameters to decoder context", av_get_media_type_string(type));
return ret;
}
av_dict_set(&opts, "refcounted_frames", "1", 0);
if ((ret = avcodec_open2(*dec_ctx, dec, &opts)) < 0)
{
//OutputDebugStringFormat(L"Failed to open %s codec", av_get_media_type_string(type));
return ret;
}
*stream_idx = stream_index;
}
return 0;
}
static int find_best_stream(int* stream_idx, AVFormatContext* fmt_ctx, enum AVMediaType type)
{
int ret, stream_index;
AVStream* st;
const AVCodec* dec = NULL;
AVDictionary* opts = NULL;
ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
if (ret < 0)
{
return ret;
}
else
{
stream_index = ret;
st = fmt_ctx->streams[stream_index];
dec = avcodec_find_decoder(st->codecpar->codec_id);
if (!dec)
{
//OutputDebugStringFormat(L"failed to find %s codec", av_get_media_type_string(type));
return AVERROR(EINVAL);
}
*stream_idx = stream_index;
}
return 0;
}
int VideoAnimation::readCallback(void* opaque, uint8_t* buf, int buf_size)
{
VideoAnimation* info = reinterpret_cast<VideoAnimation*>(opaque);
if (!info->stopped)
{
if (auto stream = info->file.try_as<implementation::VideoAnimationStreamSource>())
{
ULONG bytesRead;
stream->m_stream->Read(buf, buf_size, &bytesRead);
return bytesRead == 0 ? AVERROR_EOF : bytesRead;
}
else
{
int64_t offset = info->file.Offset();
int64_t bytesRead;
info->file.ReadCallback(buf_size, 0, bytesRead);
if (info->fd == INVALID_HANDLE_VALUE)
{
info->fd = CreateFile2FromAppW(info->file.FilePath().data(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, OPEN_EXISTING, nullptr);
LARGE_INTEGER distancetoMove{};
distancetoMove.QuadPart = offset;
BOOL moved = SetFilePointerEx(info->fd, distancetoMove, NULL, FILE_BEGIN);
if (!moved)
{
return 0;
}
}
if (info->fd != INVALID_HANDLE_VALUE && bytesRead >= 0)
{
DWORD read;
if (ReadFile(info->fd, buf, buf_size > bytesRead ? bytesRead : buf_size, &read, NULL))
{
info->file.SeekCallback(offset + read);
return read > 0 ? read : AVERROR_EOF;
}
}
return AVERROR_EOF;
}
}
// Not 0: ffmpeg reads that as "no bytes this call" and can keep asking, which would spin
// instead of unwinding the demuxer that Stop() is trying to abort.
return AVERROR_EOF;
}
int64_t VideoAnimation::seekCallback(void* opaque, int64_t offset, int whence)
{
VideoAnimation* info = reinterpret_cast<VideoAnimation*>(opaque);
if (!info->stopped)
{
if (whence & FFMPEG_AVSEEK_SIZE)
{
return info->file.FileSize();
}
else if (auto stream = info->file.try_as<implementation::VideoAnimationStreamSource>())
{
LARGE_INTEGER li;
li.QuadPart = offset;
stream->m_stream->Seek(li, STREAM_SEEK_SET, NULL);
return offset;
}
else
{
info->file.SeekCallback(offset);
if (info->fd != INVALID_HANDLE_VALUE)
{
LARGE_INTEGER distancetoMove{};
distancetoMove.QuadPart = offset;
BOOL moved = SetFilePointerEx(info->fd, distancetoMove, NULL, FILE_BEGIN);
return moved ? offset : 0;
}
return offset;
}
}
// Same reason as readCallback: a seek that reports success at offset 0 would send the
// demuxer back to the start rather than letting it fail out.
return AVERROR_EOF;
}
void VideoAnimation::RedirectLoggingOutputs(void* ptr, int level, const char* fmt, va_list vargs)
{
CHAR buffer[1024];
vsprintf_s(buffer, 1024, fmt, vargs);
OutputDebugStringA(buffer);
}
static int get_stream_rotation(const AVStream* stream)
{
AVDictionaryEntry* e = av_dict_get(stream->metadata, "rotate", NULL, 0);
if (e && e->value)
{
if (!strcmp(e->value, "90") || !strcmp(e->value, "-270"))
{
return 90;
}
else if (!strcmp(e->value, "270") || !strcmp(e->value, "-90"))
{
return 270;
}
else if (!strcmp(e->value, "180") || !strcmp(e->value, "-180"))
{
return 180;
}
else if (!strcmp(e->value, "0"))
{
return 0;
}
}
const AVPacketSideData* displaymatrix = av_packet_side_data_get(
stream->codecpar->coded_side_data, stream->codecpar->nb_coded_side_data, AV_PKT_DATA_DISPLAYMATRIX);
if (displaymatrix)
{
return ((int)-av_display_rotation_get((int32_t*)displaymatrix->data) + 360) % 360;
}
return 0;
}
winrt::Telegram::Native::VideoAnimation VideoAnimation::LoadFromFile(IVideoAnimationSource file, bool preview, bool limitFps, bool probe)
{
auto info = winrt::make_self<VideoAnimation>();
file.SeekCallback(0);
int ret;
info->file = file;
//av_log_set_level(AV_LOG_DEBUG);
//av_log_set_callback(RedirectLoggingOutputs);
info->ioBuffer = (unsigned char*)av_malloc(64 * 1024);
info->ioContext = avio_alloc_context(info->ioBuffer, 64 * 1024, 0, (void*)info.get(), readCallback, nullptr, seekCallback);
if (info->ioContext == nullptr)
{
//delete info;
return nullptr;
}
info->fmt_ctx = avformat_alloc_context();
info->fmt_ctx->pb = info->ioContext;
AVDictionary* options = NULL;
av_dict_set(&options, "usetoc", "1", 0);
ret = avformat_open_input(&info->fmt_ctx, "http://localhost/file", NULL, &options);
av_dict_free(&options);
if (ret < 0)
{
//OutputDebugStringFormat(L"can't open source file %s, %s", info->src, av_err2str(ret));
//delete info;
return nullptr;
}
info->fmt_ctx->flags |= AVFMT_FLAG_FAST_SEEK;
if (preview)
{
info->fmt_ctx->flags |= AVFMT_FLAG_NOBUFFER;
}
if ((ret = avformat_find_stream_info(info->fmt_ctx, NULL)) < 0)
{
//OutputDebugStringFormat(L"can't find stream information %s, %s", info->src, av_err2str(ret));
//delete info;
return nullptr;
}
if (open_codec_context(&info->video_stream_idx, &info->video_dec_ctx, info->fmt_ctx, AVMEDIA_TYPE_VIDEO) >= 0)
{
info->video_stream = info->fmt_ctx->streams[info->video_stream_idx];
}
find_best_stream(&info->audio_stream_idx, info->fmt_ctx, AVMEDIA_TYPE_AUDIO);
if (!probe)
{
if (info->video_stream == nullptr)
{
//OutputDebugStringFormat(L"can't find video stream in the input, aborting %s", info->src);
//delete info;
return nullptr;
}
info->frame = av_frame_alloc();
if (info->frame == nullptr)
{
//OutputDebugStringFormat(L"can't allocate frame %s", info->src);
//delete info;
return nullptr;
}
info->pkt = av_packet_alloc();
if (info->pkt == nullptr)
{
//OutputDebugStringFormat(L"can't allocate packet %s", info->src);
//delete info;
return nullptr;
}
}
if (info->video_dec_ctx != nullptr)
{
info->pixelWidth = info->video_dec_ctx->width;
info->pixelHeight = info->video_dec_ctx->height;
info->rotation = get_stream_rotation(info->video_stream);
auto framerate = 30.0;
AVStream* video_stream = info->video_stream;
if (video_stream->avg_frame_rate.den && video_stream->avg_frame_rate.num)
{
framerate = av_q2d(video_stream->avg_frame_rate);
}
else if (video_stream->r_frame_rate.den && video_stream->r_frame_rate.num)
{
framerate = av_q2d(video_stream->r_frame_rate);
}
//auto guess = av_guess_frame_rate(info->fmt_ctx, info->video_stream, NULL);
//auto framerate = av_q2d(guess);
info->dropper = FrameDropper(framerate, limitFps ? 30.0 : 60.0);
info->framerate = info->dropper.frame_rate();
}
else
{
info->pixelWidth = 0;
info->pixelHeight = 0;
}
AVDictionaryEntry* title_tag = av_dict_get(info->fmt_ctx->metadata, "title", NULL, 0);
if (title_tag && title_tag->value)
{
info->title = winrt::to_hstring(title_tag->value);
}
AVDictionaryEntry* artist_tag = av_dict_get(info->fmt_ctx->metadata, "album_artist", NULL, 0);
if (artist_tag && artist_tag->value)
{
info->artist = winrt::to_hstring(artist_tag->value);
}
else
{
artist_tag = av_dict_get(info->fmt_ctx->metadata, "artist", NULL, 0);
if (artist_tag && artist_tag->value)
{
info->artist = winrt::to_hstring(artist_tag->value);
}
}
for (int32_t i = 0, l = info->fmt_ctx->nb_streams; i < l; ++i)
{
const auto stream = info->fmt_ctx->streams[i];
if (stream->disposition & AV_DISPOSITION_ATTACHED_PIC)
{
const auto& packet = stream->attached_pic;
if (packet.size)
{
info->album_stream_idx = i;
}
break;
}
}
//int requestedMaxSide = 420;
//double ratioX = (double)requestedMaxSide / info->video_dec_ctx->width;
//double ratioY = (double)requestedMaxSide / info->video_dec_ctx->height;
//double ratio = std::max(ratioX, ratioY);
info->maxWidth = info->pixelWidth; // (int)(info->video_dec_ctx->width * ratio);
info->maxHeight = info->pixelHeight; // (int)(info->video_dec_ctx->height * ratio);
//OutputDebugStringFormat(L"successfully opened file %s", info->src);
info->duration = (int32_t)(info->fmt_ctx->duration * 1000 / AV_TIME_BASE);
//(int32_t) (1000 * info->video_stream->duration * av_q2d(info->video_stream->time_base));
//env->ReleaseIntArrayElements(data, dataArr, 0);
return info.as<winrt::Telegram::Native::VideoAnimation>();
}
void VideoAnimation::Stop()
{
stopped = true;
}
void VideoAnimation::PrepareToSeek()
{
seeking = true;
}
void VideoAnimation::SeekToMilliseconds(int64_t ms, bool precise)
{
slim_lock_guard const guard(m_lock);
if (!fmt_ctx || !video_stream || video_stream_idx < 0)
{
return;
}
seeking = true;
// Convert milliseconds to timestamp in stream time base
int64_t target_ts = av_rescale_q(ms, { 1, 1000 }, video_stream->time_base);
// Seek to keyframe before or at target timestamp
int ret = avformat_seek_file(fmt_ctx, video_stream_idx, INT64_MIN, target_ts, target_ts, 0);
if (ret < 0)
{
// Fallback to av_seek_frame if avformat_seek_file fails
ret = av_seek_frame(fmt_ctx, video_stream_idx, target_ts, AVSEEK_FLAG_BACKWARD);
if (ret < 0)
{
seeking = false;
return;
}
}
// Flush decoder buffers after seek
avcodec_flush_buffers(video_dec_ctx);
seeking = false;
if (!precise)
{
return; // Fast seek - just go to nearest keyframe
}
// Precise seek - decode frames until we reach the target timestamp
AVPacket* pkt = av_packet_alloc();
if (!pkt)
{
return;
}
AVFrame* temp_frame = av_frame_alloc();
if (!temp_frame)
{
av_packet_free(&pkt);
return;
}
int max_tries = 1000;
bool found_target = false;
while (max_tries > 0 && !found_target)
{
ret = av_read_frame(fmt_ctx, pkt);
if (ret < 0)
{
if (ret == AVERROR_EOF)
{
break; // End of file
}
continue;
}
// Only process packets from our video stream
if (pkt->stream_index != video_stream_idx)
{
av_packet_unref(pkt);
continue;
}
// Send packet to decoder
ret = avcodec_send_packet(video_dec_ctx, pkt);
av_packet_unref(pkt);
if (ret < 0 && ret != AVERROR(EAGAIN))
{
break;
}
// Receive decoded frames
while (ret >= 0)
{
ret = avcodec_receive_frame(video_dec_ctx, temp_frame);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
{
break;
}
if (ret < 0)
{
break;
}
// Check if this frame is at or past our target timestamp
int64_t frame_ts = temp_frame->best_effort_timestamp;
if (frame_ts != AV_NOPTS_VALUE)
{
if (frame_ts >= target_ts)
{
// Copy this frame to your main frame buffer
av_frame_unref(frame); // Assuming 'frame' is your main frame
av_frame_ref(frame, temp_frame);
found_target = true;
break;
}
}
av_frame_unref(temp_frame);
}
max_tries--;
}
// Cleanup
av_frame_free(&temp_frame);
av_packet_free(&pkt);
// If we couldn't find the exact frame, seek back to the beginning
if (!found_target)
{
avformat_seek_file(fmt_ctx, video_stream_idx, 0, 0, 0, 0);
avcodec_flush_buffers(video_dec_ctx);
}
}
IRandomAccessStream VideoAnimation::GetAlbumCover()
{
if (album_stream_idx)
{
const auto album = fmt_ctx->streams[album_stream_idx];
const auto& packet = album->attached_pic;
HRESULT result;
IRandomAccessStream randomAccessStream = InMemoryRandomAccessStream();
winrt::com_ptr<IStream> stream;
CleanupIfFailed(result, CreateStreamOverRandomAccessStream(winrt::get_unknown(randomAccessStream), IID_PPV_ARGS(&stream)));
CleanupIfFailed(result, stream->Write(packet.data, packet.size, nullptr));
CleanupIfFailed(result, stream->Seek({ 0 }, STREAM_SEEK_SET, nullptr));
return randomAccessStream;
}
Cleanup:
return nullptr;
}
bool VideoAnimation::RenderSync(IBuffer bitmap, int32_t w, int32_t h, bool preview, double& seconds)
{
uint8_t* pixels = bitmap.data();
bool completed;
auto result = RenderSync(pixels, w, h, preview, seconds, completed);
return result;
}
inline double clamp(double value, double min, double max)
{
if (value > max)
{
return max;
}
else if (value < min)
{
return min;
}
return value;
}
bool VideoAnimation::RenderSync(uint8_t* pixels, int32_t width, int32_t height, bool preview, double& seconds, bool& completed)
{
slim_lock_guard const guard(m_lock);
completed = false;
int ret = 0;
int32_t triesCount = preview ? 50 : 6;
if (!fmt_ctx || !video_dec_ctx || !pkt || !frame)
{
return false;
}
while (!stopped && triesCount > 0)
{
if (waiting == Waiting::ReadFrame)
{
ret = av_read_frame(fmt_ctx, pkt);
if (ret >= 0)
{
if (pkt->stream_index == video_stream_idx)
{
waiting = Waiting::SendPacket;
}
else
{
av_packet_unref(pkt);
continue; // Skip non-video packets immediately
}
}
else if (ret == AVERROR_EOF)
{
// Handle EOF - send flush packet
if (has_decoded_frames && !preview)
{
completed = true;
// Seek back to beginning for loop playback
ret = avformat_seek_file(fmt_ctx, video_stream_idx, 0, 0, 0, 0);
if (ret < 0)
{
// Fallback to av_seek_frame
ret = av_seek_frame(fmt_ctx, video_stream_idx, 0, AVSEEK_FLAG_BACKWARD);
}
if (ret < 0)
{
goto Cleanup;
}
avcodec_flush_buffers(video_dec_ctx);
waiting = Waiting::ReadFrame;
// Cleared on the way round, as the drained branch below does.
// It is what holds off the budget at the end of the loop, so
// leaving it set means nothing is spent while the file is read
// from the start again, and a read that returns end of file
// straight after the seek arrives back here to seek once more.
has_decoded_frames = false;
continue;
}
else
{
// Send NULL packet to flush decoder
ret = avcodec_send_packet(video_dec_ctx, nullptr);
if (ret >= 0)
{
waiting = Waiting::ReceiveFrame;
}
else
{
goto Cleanup;
}
}
}
else
{
// Other errors
completed = true;
goto Cleanup;
}
}
if (waiting == Waiting::SendPacket)
{
ret = avcodec_send_packet(video_dec_ctx, pkt);
if (ret >= 0)
{
waiting = Waiting::ReceiveFrame;
av_packet_unref(pkt); // Unref after successful send
}
else if (ret == AVERROR(EAGAIN))
{
// Decoder needs more frames to be received first
waiting = Waiting::ReceiveFrame;
}
else
{
// Error sending packet
av_packet_unref(pkt);
waiting = Waiting::ReadFrame;
continue;
}
}
if (waiting == Waiting::ReceiveFrame)
{
ret = avcodec_receive_frame(video_dec_ctx, frame);
if (ret >= 0)
{
has_decoded_frames = true;
// Calculate frame timestamp
int64_t pts = frame->best_effort_timestamp;
if (pts == AV_NOPTS_VALUE)
{
pts = frame->pts;
}
if (pts != AV_NOPTS_VALUE)
{
if (dropper.should_display_frame())
{
double nextFrame = pts * av_q2d(video_stream->time_base);
seconds = clamp(nextFrame, 0.0, duration);
// Decode and render the frame
int decode_result = decode_frame(pixels, width, height);
if (decode_result >= 0)
{
return true; // Successfully rendered frame
}
// Conversion failure depends on the stream format, so it
// repeats for every remaining frame. has_decoded_frames is
// already set and freezes the budget below, which would
// otherwise leave this loop decoding the file end to end,
// seeking back to zero and repeating indefinitely. Spend a
// try to guarantee termination.
triesCount--;
}
}
av_frame_unref(frame);
waiting = Waiting::ReadFrame;
}
else if (ret == AVERROR(EAGAIN))
{
// Need to send more packets
waiting = Waiting::ReadFrame;
}
else if (ret == AVERROR_EOF)
{
// Decoder is fully drained
if (has_decoded_frames && !preview)
{
completed = true;
// Reset for loop playback
ret = avformat_seek_file(fmt_ctx, video_stream_idx, 0, 0, 0, 0);
if (ret < 0)
{
ret = av_seek_frame(fmt_ctx, video_stream_idx, 0, AVSEEK_FLAG_BACKWARD);
}
if (ret < 0)
{
goto Cleanup;
}
avcodec_flush_buffers(video_dec_ctx);
waiting = Waiting::ReadFrame;
has_decoded_frames = false;
continue;
}
else
{
completed = true;
goto Cleanup;
}
}
else
{
// Other receive errors
waiting = Waiting::ReadFrame;
continue;
}
}
// Decrement tries only if we haven't decoded any frames yet
if (!has_decoded_frames)
{
triesCount--;
}
}
Cleanup:
// Ensure packet is unreferenced
if (pkt)
{
av_packet_unref(pkt);
}
// If we stopped due to tries exhaustion without decoding, mark as completed
if (!has_decoded_frames && triesCount <= 0)
{
completed = true;
}
// Reached only on giving up; pixels is untouched.
return false;
}
inline bool is_aligned(const void* ptr, std::uintptr_t alignment) noexcept
{
auto iptr = reinterpret_cast<std::uintptr_t>(ptr);
return !(iptr % alignment);
}
inline int32_t ffalign(int32_t x, int32_t a)
{
return (((x)+(a)-1) & ~((a)-1));
}
int VideoAnimation::decode_frame(uint8_t* pixels, int32_t width, int32_t height)
{
if (!frame || !pixels || width <= 0 || height <= 0)
{
return -1;
}
// Check if frame has valid format
if (frame->format == AV_PIX_FMT_NONE || frame->width <= 0 || frame->height <= 0)
{
return -1;
}
// Formats libyuv converts without a scaler. Not the set of supported formats:
// anything else goes through swscale, including the high bit depth profiles
// such as the yuv420p10le produced by HEVC Main 10.
bool libyuv_format = (frame->format == AV_PIX_FMT_YUV420P ||
frame->format == AV_PIX_FMT_YUVA420P ||
frame->format == AV_PIX_FMT_BGRA ||
frame->format == AV_PIX_FMT_RGBA ||
frame->format == AV_PIX_FMT_YUVJ420P ||
frame->format == AV_PIX_FMT_YUV444P);
// Initialize SWS context if needed. The alignment test only chooses swscale in
// preference to libyuv, so it applies only when a libyuv path exists; otherwise
// the scaler is the only way to convert the frame. The scaling path below
// handles an unaligned destination through an intermediate buffer.
if (sws_ctx == nullptr && (!libyuv_format || ((intptr_t)pixels) % 16 == 0))
{
AVPixelFormat src_format = (AVPixelFormat)frame->format;
// Validate pixel format range
if (src_format > AV_PIX_FMT_NONE && src_format < AV_PIX_FMT_NB)
{
sws_ctx = sws_getContext(
frame->width, frame->height, src_format,
width, height, AV_PIX_FMT_BGRA,
SWS_BILINEAR, nullptr, nullptr, nullptr
);
}
// Fallback to decoder context format
else if (video_dec_ctx &&
video_dec_ctx->pix_fmt > AV_PIX_FMT_NONE &&
video_dec_ctx->pix_fmt < AV_PIX_FMT_NB)
{
sws_ctx = sws_getContext(
video_dec_ctx->width, video_dec_ctx->height, video_dec_ctx->pix_fmt,
width, height, AV_PIX_FMT_BGRA,
SWS_BILINEAR, nullptr, nullptr, nullptr
);
}
}
// No scaler and no direct path: the frame cannot be converted.
if (sws_ctx == nullptr && !libyuv_format)
{
return -1;
}
// Fast path: Use libyuv for direct conversion (no SWS context)
if (sws_ctx == nullptr)
{
switch (frame->format)
{
case AV_PIX_FMT_YUVA420P: {
// Check alpha plane exists
if (frame->data[3])
{
// Convert to ARGB first, then swap to BGRA
libyuv::I420AlphaToARGBMatrix(
frame->data[0], frame->linesize[0],
frame->data[1], frame->linesize[1],
frame->data[2], frame->linesize[2],
frame->data[3], frame->linesize[3],
pixels, width * 4,
&libyuv::kYvuI601Constants,
width, height, 1
);
// Convert ARGB to BGRA in-place
libyuv::ARGBToBGRA(pixels, width * 4, pixels, width * 4, width, height);
}
else
{
return -1; // Invalid YUVA format without alpha
}
break;
}
case AV_PIX_FMT_YUV444P: {
// Convert to ABGR first, then swap to BGRA
libyuv::H444ToARGB(
frame->data[0], frame->linesize[0],
frame->data[2], frame->linesize[2],
frame->data[1], frame->linesize[1],
pixels, width * 4, width, height
);
// Convert ABGR to BGRA (swap A and R channels)
libyuv::ARGBToBGRA(pixels, width * 4, pixels, width * 4, width, height);
break;
}
case AV_PIX_FMT_YUV420P:
case AV_PIX_FMT_YUVJ420P: {
// Convert to I420/H420 -> ABGR first, then to BGRA
if (frame->colorspace == AVCOL_SPC_BT709)
{
libyuv::H420ToARGB(
frame->data[0], frame->linesize[0],
frame->data[2], frame->linesize[2],
frame->data[1], frame->linesize[1],
pixels, width * 4, width, height
);
// Convert ABGR to BGRA (swap A and R channels)
libyuv::ARGBToBGRA(pixels, width * 4, pixels, width * 4, width, height);
}
else
{
libyuv::I420ToBGRA(
frame->data[0], frame->linesize[0],
frame->data[2], frame->linesize[2],
frame->data[1], frame->linesize[1],
pixels, width * 4, width, height
);
}
break;
}
case AV_PIX_FMT_RGBA:
// Convert RGBA to BGRA (swap R and B channels)
//libyuv::RGBAToBGRA(frame->data[0], frame->linesize[0], pixels, width * 4, width, height);
//break;
return -1;
case AV_PIX_FMT_BGRA:
// Direct copy - already in BGRA format
if (frame->width == width && frame->height == height &&
frame->linesize[0] == width * 4)
{
memcpy(pixels, frame->data[0], width * height * 4);
}
else
{
// Line-by-line copy for different strides
for (int y = 0; y < std::min(height, frame->height); y++)
{
memcpy(pixels + y * width * 4,
frame->data[0] + y * frame->linesize[0],
std::min(width, frame->width) * 4);
}
}
break;
default:
return -1; // Unsupported format
}
}
// SWS scaling path
else
{
// Calculate alignment and padding for better performance
auto dstWidth = FFALIGN(width, 16);
auto dstDiff = dstWidth - width;
auto srcWidth = frame->linesize[0] - width;
auto srcDiff = FFALIGN(srcWidth, 12) - srcWidth;
auto padding = (srcDiff > 0 && dstDiff > 0)
? std::min(srcDiff, dstDiff)
: std::max(srcDiff, dstDiff);
padding = std::min(padding, width % 16);
int32_t linesize = width * 4;
// Check if destination linesize is aligned to 64 bytes
bool dstAligned = (linesize % 64 == 0);
// Direct scaling if no padding issues
if (dstAligned && (padding == 0 || srcWidth % 30 == 0))
{
uint8_t* dst_planes[4] = { pixels, nullptr, nullptr, nullptr };
int dst_linesize[4] = { linesize, 0, 0, 0 };
int result = sws_scale(sws_ctx,
(const uint8_t* const*)frame->data,
frame->linesize,
0, frame->height,
dst_planes, dst_linesize);
if (result < 0)
{
return -1;
}
}
// Use intermediate buffer for alignment issues
else
{
if (dst_data == nullptr)
{
int32_t paddedsize = std::max(width + padding, 16) * height * 4;
dst_data = (uint8_t*)av_malloc(paddedsize);
if (!dst_data)
{
return -1;
}
}
uint8_t* dst_planes[4] = { dst_data, nullptr, nullptr, nullptr };
int dst_linesize[4] = { linesize, 0, 0, 0 };
int result = sws_scale(sws_ctx,
(const uint8_t* const*)frame->data,