From 5279aa34f4999288eae3404ac73141c86c49afb2 Mon Sep 17 00:00:00 2001 From: allen Date: Tue, 3 Nov 2026 03:09:20 +0900 Subject: [PATCH 1/9] wg_parser: hold a reader back instead of dropping another stream's packets quartz and Media Foundation read each stream on its own thread; a packet demuxed for another stream is queued for it. When one stream's reader fell behind (a video decoded slower than real time) the other reader kept demuxing for it, and past 16,384 packets or 64 MB the queue dropped packets, which breaks every picture up to the next keyframe. Once a queue passes a soft limit (1,024 packets or 16 MB) while another thread reads that stream, the reader that demuxes for it now waits in mav_wait_drain, without the parser lock, until the queue has drained to three quarters of the limit. A stream not read for 5 s is marked unread and queued without waiting (dropped past the hard limits, as before) until it is read again. One thread reading both streams (the earliest-buffer mode) never waits for itself, and a seek, a disable or disconnect wakes a waiting reader; disconnect frees nothing until the waiters have left. tests/host/check-wg-parser.py builds the core again with small limits (soft 8 packets, hard 16, 400 ms) and runs those cases on its synthetic MP4; the same slow-video case built without back-pressure drops packets and loses pictures (18 of 90 here). Co-Authored-By: Claude Opus 5.5 Signed-off-by: allen --- build/ntdll-unix/wg_parser_av_ios.c | 153 ++++++++++++++++++++++++---- docs/MEDIA.md | 20 +++- tests/host/check-wg-parser.py | 148 ++++++++++++++++++++++++++- 3 files changed, 297 insertions(+), 24 deletions(-) diff --git a/build/ntdll-unix/wg_parser_av_ios.c b/build/ntdll-unix/wg_parser_av_ios.c index 42afa5dc68..f9fa772d40 100644 --- a/build/ntdll-unix/wg_parser_av_ios.c +++ b/build/ntdll-unix/wg_parser_av_ios.c @@ -56,8 +56,11 @@ * - one demuxer, several consumers. wg_parser.c runs a GStreamer thread * that parks one buffer per stream; here decoding is LAZY, on the thread * that asks for a buffer, and a packet read for a stream other than the - * one being served is queued for that stream (dropped if it is disabled; - * bounded, with the overflow logged). One buffer per stream is + * one being served is queued for that stream (dropped if it is disabled). + * A queue another thread reads holds back the reader that fills it once + * it passes a soft limit (mav_wait_drain), so a stream that falls behind + * no longer loses packets; past the hard limit (an unread stream only) + * the overflow is dropped and logged. One buffer per stream is * outstanding until release_buffer; S_FALSE at end of stream. * * - video. The native format reported by get_current_format is 4:2:0 NV12 @@ -102,6 +105,7 @@ #include #include #include +#include #include #include @@ -265,8 +269,26 @@ static int mav_seek( struct mav_parser *p, unsigned int stream, int set_start, u * rule releases (a stream without decode times, or a broken one). */ #define MAV_REORDER_MAX 16 /* Packets queued for a stream nobody is reading from yet. */ +#ifndef MAV_QUEUE_MAX_PACKETS /* tests/host/check-wg-parser.py builds with small limits */ #define MAV_QUEUE_MAX_PACKETS 16384 +#endif +#ifndef MAV_QUEUE_MAX_BYTES #define MAV_QUEUE_MAX_BYTES ((size_t)64 << 20) +#endif +/* Back-pressure (mav_wait_drain). A stream whose queue passes these, while + * another thread reads it, holds the reader that demuxes for it until it has + * drained to three quarters of them; the hard limits above then only apply to + * a stream nobody reads (MAV_BACKPRESSURE_WAIT_MS without a read). A packet + * dropped from a video stream breaks every picture up to its next keyframe. */ +#ifndef MAV_QUEUE_SOFT_PACKETS +#define MAV_QUEUE_SOFT_PACKETS 1024 +#endif +#ifndef MAV_QUEUE_SOFT_BYTES +#define MAV_QUEUE_SOFT_BYTES ((size_t)16 << 20) +#endif +#ifndef MAV_BACKPRESSURE_WAIT_MS +#define MAV_BACKPRESSURE_WAIT_MS 5000 +#endif #define MAV_MAX_DIMENSION 8192 #define MAV_MOV_NAME "mov,mp4,m4a,3gp,3g2,mj2" @@ -385,6 +407,9 @@ struct mav_stream AVPacket **queue; unsigned int queue_head, queue_count, queue_cap; size_t queue_bytes; + pthread_t reader; /* the thread that last asked for this stream's buffers */ + int has_reader; + int unread; /* not read for MAV_BACKPRESSURE_WAIT_MS: queued without waiting */ /* ---- the one outstanding output buffer ---- */ uint8_t *buf; @@ -431,6 +456,12 @@ struct mav_parser struct mav_stream *streams[MAV_MAX_STREAMS]; unsigned int stream_count; + + /* ---- back-pressure (lock) ---- */ + pthread_cond_t drain_cond; /* a queue shrank, a stream changed state, or closing */ + unsigned int bp_waiters; /* readers inside mav_wait_drain */ + unsigned int generation; /* bumped by seek: a waiter re-checks everything */ + int closing; /* disconnect: waiters leave, then the streams go */ }; /*********************************************************************** @@ -572,6 +603,7 @@ static struct mav_parser *mav_create( int output_compressed ) pthread_cond_init( &p->read_cond, NULL ); pthread_cond_init( &p->done_cond, NULL ); pthread_mutex_init( &p->lock, NULL ); + pthread_cond_init( &p->drain_cond, NULL ); p->output_compressed = !!output_compressed; p->stop = -1; return p; @@ -646,7 +678,14 @@ static void mav_disconnect( struct mav_parser *p ) * take the decode lock, which that read may be holding. */ mav_set_connected( p, 0 ); pthread_mutex_lock( &p->lock ); + /* A reader held by back-pressure sleeps without the lock: wake it, and + * free nothing until it has left mav_wait_drain. It finishes its request + * under the lock, before this thread gets the lock back. */ + p->closing = 1; + pthread_cond_broadcast( &p->drain_cond ); + while (p->bp_waiters) pthread_cond_wait( &p->drain_cond, &p->lock ); mav_teardown( p ); + p->closing = 0; pthread_mutex_unlock( &p->lock ); } @@ -654,6 +693,7 @@ static void mav_destroy( struct mav_parser *p ) { if (!p) return; mav_disconnect( p ); + pthread_cond_destroy( &p->drain_cond ); pthread_mutex_destroy( &p->lock ); pthread_cond_destroy( &p->done_cond ); pthread_cond_destroy( &p->read_cond ); @@ -1324,6 +1364,7 @@ static void mav_disable( struct mav_parser *p, unsigned int stream ) s->has_buffer = 0; /* its queued packets will not be read */ mav_queue_clear( s ); + if (p->bp_waiters) pthread_cond_broadcast( &p->drain_cond ); } pthread_mutex_unlock( &p->lock ); } @@ -1366,6 +1407,52 @@ static void mav_queue_push( struct mav_stream *s, AVPacket *pkt ) s->queue_bytes += pkt->size; } +static int mav_queue_over( const struct mav_stream *s, unsigned int num, unsigned int den ) +{ + return s->queue_count > MAV_QUEUE_SOFT_PACKETS / den * num || s->queue_bytes > MAV_QUEUE_SOFT_BYTES / den * num; +} + +/* Back-pressure. `waiter` just queued a packet for + * `owner`, whose queue is past its soft limit while another thread reads it. + * Dropping would break the owner's pictures (or audio) up to its next + * keyframe, so the waiter sleeps -- WITHOUT the parser lock, which the owner's + * reader needs to drain its queue -- until that queue is back under three + * quarters of the limit. The waiter holds no packet and no demuxer state + * while it sleeps; it re-checks its own queue when it wakes. It also wakes on + * a seek (generation), a disable or end of the owner's stream, and disconnect + * (closing). An owner not read for MAV_BACKPRESSURE_WAIT_MS is marked unread: + * its packets are queued again without waiting (and dropped past the hard + * limit, as before) until it is read. */ +static void mav_wait_drain( struct mav_parser *p, struct mav_stream *waiter, struct mav_stream *owner ) +{ + unsigned int generation = p->generation; + struct timespec deadline; + + clock_gettime( CLOCK_REALTIME, &deadline ); + deadline.tv_sec += MAV_BACKPRESSURE_WAIT_MS / 1000; + deadline.tv_nsec += (long)(MAV_BACKPRESSURE_WAIT_MS % 1000) * 1000000; + if (deadline.tv_nsec >= 1000000000) { deadline.tv_sec++; deadline.tv_nsec -= 1000000000; } + p->bp_waiters++; + while (!p->closing && p->generation == generation && owner->enabled && !owner->eos && !owner->unread + && mav_queue_over( owner, 3, 4 )) + { + if (pthread_cond_timedwait( &p->drain_cond, &p->lock, &deadline ) == ETIMEDOUT) + { + if (!p->closing && p->generation == generation && owner->enabled && !owner->eos + && mav_queue_over( owner, 3, 4 )) + { + owner->unread = 1; + mav_log( "stream %u: not read for %d ms while stream %u reads ahead (%u packets, %zu bytes " + "queued); queueing without waiting", owner->number, MAV_BACKPRESSURE_WAIT_MS, + waiter->number, owner->queue_count, owner->queue_bytes ); + } + break; + } + } + p->bp_waiters--; + if (p->closing) pthread_cond_broadcast( &p->drain_cond ); /* mav_disconnect waits for bp_waiters == 0 */ +} + /* Moves the next packet of stream `s` into `dst`, reading (and queueing for * the other streams) as needed. Returns 0 at the end of the data. */ static int mav_next_packet( struct mav_parser *p, struct mav_stream *s, AVPacket *dst ) @@ -1373,21 +1460,24 @@ static int mav_next_packet( struct mav_parser *p, struct mav_stream *s, AVPacket unsigned int i; int err; - if (s->queue_count) - { - AVPacket *q = s->queue[s->queue_head++]; - s->queue_count--; - s->queue_bytes -= q->size; - if (!s->queue_count) s->queue_head = 0; - av_packet_move_ref( dst, q ); - av_packet_free( &q ); - return 1; - } - while (!p->demux_eof) + for (;;) { struct mav_stream *owner = NULL; AVPacket *copy; + if (s->queue_count) + { + AVPacket *q = s->queue[s->queue_head++]; + s->queue_count--; + s->queue_bytes -= q->size; + if (!s->queue_count) s->queue_head = 0; + s->unread = 0; + av_packet_move_ref( dst, q ); + av_packet_free( &q ); + if (p->bp_waiters) pthread_cond_broadcast( &p->drain_cond ); + return 1; + } + if (p->demux_eof || p->closing) return 0; if ((err = av_read_frame( p->fmt, p->read_pkt )) < 0) { if (err != AVERROR_EOF && err != AVERROR_EXIT && p->read_errors_logged < 3) @@ -1396,12 +1486,13 @@ static int mav_next_packet( struct mav_parser *p, struct mav_stream *s, AVPacket mav_log( "read error %d at byte %llu; draining", err, (unsigned long long)p->pos ); } p->demux_eof = 1; - break; + return 0; } for (i = 0; i < p->stream_count; i++) if (p->streams[i]->av_index == p->read_pkt->stream_index) owner = p->streams[i]; if (owner == s) { + s->unread = 0; av_packet_move_ref( dst, p->read_pkt ); return 1; } @@ -1418,8 +1509,13 @@ static int mav_next_packet( struct mav_parser *p, struct mav_stream *s, AVPacket } av_packet_move_ref( copy, p->read_pkt ); mav_queue_push( owner, copy ); + /* Only for an owner another thread reads: one thread serving both + * streams (the earliest-buffer mode, or a caller that alternates) + * would wait for itself. */ + if (mav_queue_over( owner, 1, 1 ) && !owner->unread + && !(owner->has_reader && pthread_equal( owner->reader, pthread_self() ))) + mav_wait_drain( p, s, owner ); } - return 0; } /*********************************************************************** @@ -1998,20 +2094,39 @@ static int mav_get_buffer( struct mav_parser *p, int stream, struct mav_buffer * else if (stream >= 0) { if (!(s = mav_get_stream( p, stream ))) status = MAV_E_STATE; - else status = mav_stream_next( p, s ); + else + { + s->reader = pthread_self(); + s->has_reader = 1; + status = mav_stream_next( p, s ); + /* disabled while this reader slept in mav_wait_drain */ + if (status == MAV_OK && !s->enabled) + { + s->has_buffer = 0; + status = MAV_NO_BUFFER; + } + } } else { - /* wg_parser.c: the earliest buffer of all streams, by pts */ + /* wg_parser.c: the earliest buffer of all streams, by pts. This + * thread reads them all, so none waits for another (mav_wait_drain). */ + for (i = 0; i < p->stream_count; i++) + { + p->streams[i]->reader = pthread_self(); + p->streams[i]->has_reader = 1; + } for (i = 0; i < p->stream_count; i++) { struct mav_stream *c = p->streams[i]; - if (mav_stream_next( p, c ) != MAV_OK) continue; + if (mav_stream_next( p, c ) != MAV_OK || !c->enabled) continue; if (!s || c->cur.pts < s->cur.pts) s = c; } status = s ? MAV_OK : MAV_NO_BUFFER; } if (status == MAV_OK) *buffer = s->cur; + /* a queue may have shrunk, or a stream ended: a waiter re-checks */ + if (p->bp_waiters) pthread_cond_broadcast( &p->drain_cond ); pthread_mutex_unlock( &p->lock ); return status; } @@ -2113,6 +2228,8 @@ static int mav_seek( struct mav_parser *p, unsigned int stream, int set_start, u c->next_pts = target; c->last_dts = c->last_vpts = INT64_MIN; } + p->generation++; + if (p->bp_waiters) pthread_cond_broadcast( &p->drain_cond ); } } pthread_mutex_unlock( &p->lock ); diff --git a/docs/MEDIA.md b/docs/MEDIA.md index c211ace6a4..530c4caffa 100644 --- a/docs/MEDIA.md +++ b/docs/MEDIA.md @@ -27,7 +27,7 @@ Foundation source) is refused as before unless `MADEIRA_WG_64BIT=1`. | File | What it is | |---|---| | `build/ntdll-unix/winegstreamer_unixlib_ios.c` | Both unix call tables (entry for entry with `dlls/winegstreamer/unixlib.h`), the wow64 thunks, and the `wg_transform` subset `wma_decoder.c` uses, on libavcodec: WMA v1/v2/Pro/Lossless and XMA1/2 only. Other transforms (AAC, H.264, WMV, resampler, colour converter) are refused at create, and `wg_muxer` returns `STATUS_NOT_IMPLEMENTED`. | -| `build/ntdll-unix/wg_parser_av_ios.c` | The `wg_parser` core, `#include`d by the file above: the PE read thread's pull protocol as an AVIOContext, libavformat demux (mp3, wav, mov), MPEG audio / PCM decode through libavcodec + libswresample, a packet queue, B-frame reordering, keyframe seek with exact trim, and conversion to the formats `quartz_parser.c` / `media_source.c` ask for. | +| `build/ntdll-unix/wg_parser_av_ios.c` | The `wg_parser` core, `#include`d by the file above: the PE read thread's pull protocol as an AVIOContext, libavformat demux (mp3, wav, mov), MPEG audio / PCM decode through libavcodec + libswresample, a packet queue with back-pressure, B-frame reordering, keyframe seek with exact trim, and conversion to the formats `quartz_parser.c` / `media_source.c` ask for. | | `build/ntdll-unix/wg_parser_apple_ios.c` | H.264/HEVC on VideoToolbox (NV12 out) and AAC on an AudioToolbox AudioConverter (float PCM out). Its own translation unit with no Wine or FFmpeg header. | | `build/ntdll-unix/wg_parser_backend_ios.h` | The contract between the core and a decoder backend; plain C types only, so the host test can supply stub backends. | | `build/ffmpeg/build.sh` | FFmpeg 7.1.5, pinned by SHA-256, LGPL-only configuration. | @@ -36,6 +36,19 @@ FFmpeg is built with no H.264, HEVC or AAC decoder or parser: those streams go to the platform decoders. See `THIRD-PARTY-NOTICES.md` for the exact component list and its licence. +**One demuxer, several readers: back-pressure.** Each stream is read on its +own thread by quartz and Media Foundation; a packet read for another stream +is queued for it. A stream whose reader falls behind (a video decoded slower +than real time) used to lose packets once its queue passed 16,384 packets or +64 MB, which breaks every picture up to the next keyframe. Now, once a queue +passes 1,024 packets or 16 MB while another thread reads that stream, the +reader that demuxes for it waits (without the parser lock, which the other +reader needs) until the queue has drained to three quarters of that. A stream +that is not read for 5 s is marked unread and queued without waiting (dropped +past the old hard limits, as before) until it is read again; one thread +reading both streams (the earliest-buffer mode) never waits for itself; a +seek, a disable or disconnect wakes a waiting reader. + The PE half of winegstreamer is upstream's and unchanged. Wine's configure disables the module when GStreamer is missing, so a PE build tree has to be configured with `--enable-winegstreamer` (`build/wine-pe/build-ntdll.sh` does @@ -66,7 +79,10 @@ rate-limited per process (`MADEIRA_DIAG=1` lifts the `[wma]` cap). tables, wow64 thunks, kill switches, FFmpeg configuration and app link; then builds a host FFmpeg from the same tarball and runs the parser core under ASan/UBSan against MP3, MPEG layer II, WAV and synthetic MP4 (stub video and - AAC backends). + AAC backends); then, built with small queue limits, the back-pressure cases + (a slow video reader loses nothing, while the same build without + back-pressure drops pictures; an unread stream holds the other reader once; + one thread reading both never waits; disconnect wakes a waiting reader). - `tests/host/check-wma-decoder.py` (Linux or macOS, needs a configured Wine tree for the generated headers): compiles the production `winegstreamer_unixlib_ios.c` under ASan/UBSan against a host FFmpeg built diff --git a/tests/host/check-wg-parser.py b/tests/host/check-wg-parser.py index bb778eaf70..6b1beac92f 100644 --- a/tests/host/check-wg-parser.py +++ b/tests/host/check-wg-parser.py @@ -23,6 +23,12 @@ consumption (packet queue), keyframe seek + exact trim, stop, earliest-buffer mode, the MADEIRA_WG_VIDEO=0 path, unsupported video / audio codecs, compressed-output refusal, a backend that refuses to open, and the deduplicated, bounded log. +4. Back-pressure, built again with small queue limits (soft 8 packets, hard 16, 400 ms): a slow + video reader and a fast audio reader on two threads lose no packet and get every picture; an + enabled video stream nobody reads holds the audio reader once, for 400 ms, and no longer; one + thread reading both streams (earliest-buffer mode) never waits for itself; disconnect wakes a + reader that waits. The same two-reader case built without back-pressure drops packets and + loses pictures. Environment: MADEIRA_FFMPEG_TARBALL (default: build/ffmpeg/src/ffmpeg-7.1.5.tar.xz, the tracked source tarball), @@ -1042,6 +1048,101 @@ def table(name): return b; } +/* ================= back-pressure, run with small queue limits ("bp") ================= */ + +struct reader { struct mav_parser *p; int stream, delay_us, count; volatile int done; pthread_t thread; }; + +static void *reader_thread( void *arg ) +{ + struct reader *r = arg; struct mav_buffer b; + while (mav_get_buffer( r->p, r->stream, &b ) == MAV_OK) + { + mav_release_buffer( r->p, r->stream ); r->count++; + if (r->delay_us) usleep( r->delay_us ); + } + r->done = 1; + return NULL; +} + +static long ms_since( const struct timespec *t0 ) +{ + struct timespec t1; + clock_gettime( CLOCK_MONOTONIC, &t1 ); + return (t1.tv_sec - t0->tv_sec) * 1000 + (t1.tv_nsec - t0->tv_nsec) / 1000000; +} + +static int bp_open( struct mav_parser *p, struct source *s, const uint8_t *mp4, size_t size ) +{ + struct mav_stream_info vi, ai; + src_start( s, p, mp4, size ); + CHECK( mav_connect( p, size ) == MAV_OK && mav_stream_count( p ) == 2, "connect mp4" ); + CHECK( mav_stream_info( p, 0, &vi ) == MAV_OK && mav_stream_info( p, 1, &ai ) == MAV_OK, "stream info" ); + CHECK( mav_enable_video( p, 0, &vi.vnative ) == MAV_OK && mav_enable( p, 1, &ai.native ) == MAV_OK, "enable" ); + CHECK( mav_seek( p, 0, 1, 0, 0, 0 ) == MAV_OK, "seek 0" ); + return 0; +} + +static int test_backpressure( const uint8_t *mp4, size_t size, int frames ) +{ + struct mav_parser *p; struct source s; struct reader v, a; struct timespec t0; int waited; + + /* 1. two threads, video slow: nothing dropped, every picture delivered */ + p = mav_create( 0 ); + if (bp_open( p, &s, mp4, size )) return 1; + v = (struct reader){ p, 0, 3000 }; a = (struct reader){ p, 1, 0 }; + pthread_create( &v.thread, NULL, reader_thread, &v ); + pthread_create( &a.thread, NULL, reader_thread, &a ); + pthread_join( a.thread, NULL ); pthread_join( v.thread, NULL ); + printf( "BP1 %d %d\n", v.count, a.count ); + CHECK( v.count == frames, "slow video reader: %d pictures of %d", v.count, frames ); + CHECK( a.count > 0, "audio" ); + src_stop( &s ); mav_destroy( p ); + + /* 2. video enabled and never read: the audio reader waits once, then reads to the end */ + p = mav_create( 0 ); + if (bp_open( p, &s, mp4, size )) return 1; + a = (struct reader){ p, 1, 0 }; + clock_gettime( CLOCK_MONOTONIC, &t0 ); + reader_thread( &a ); + CHECK( a.count > 0 && ms_since( &t0 ) < 3 * MAV_BACKPRESSURE_WAIT_MS, "audio alone finished in time (%ld ms)", ms_since( &t0 ) ); + src_stop( &s ); mav_destroy( p ); + + /* 3. one thread, both streams (earliest-buffer mode): it never waits for itself */ + p = mav_create( 0 ); + if (bp_open( p, &s, mp4, size )) return 1; + { + struct mav_buffer b; int n = 0; + clock_gettime( CLOCK_MONOTONIC, &t0 ); + while (mav_get_buffer( p, -1, &b ) == MAV_OK) { mav_release_buffer( p, b.stream ); n += b.stream == 0; } + CHECK( n == frames && ms_since( &t0 ) < MAV_BACKPRESSURE_WAIT_MS, "earliest-buffer mode: %d pictures, %ld ms", n, ms_since( &t0 ) ); + } + src_stop( &s ); mav_destroy( p ); + + /* 4. disconnect while a reader waits: it is woken, nothing is freed under it */ + p = mav_create( 0 ); + if (bp_open( p, &s, mp4, size )) return 1; + a = (struct reader){ p, 1, 0 }; + pthread_create( &a.thread, NULL, reader_thread, &a ); + for (waited = 0; waited < 200; waited++) + { + unsigned int w; + pthread_mutex_lock( &p->lock ); w = p->bp_waiters; pthread_mutex_unlock( &p->lock ); + if (w) break; + usleep( 1000 ); + } + CHECK( waited < 200, "the audio reader waits for the unread video stream" ); + clock_gettime( CLOCK_MONOTONIC, &t0 ); + src_stop( &s ); + pthread_join( a.thread, NULL ); + CHECK( a.done && ms_since( &t0 ) < MAV_BACKPRESSURE_WAIT_MS, "disconnect woke the waiting reader (%ld ms)", ms_since( &t0 ) ); + mav_destroy( p ); + printf( "PASS: back-pressure (soft %d packets, hard %d): a slow video reader on its own thread gets all %d pictures; " + "an unread stream holds the other reader once (%d ms) and no longer; one thread reading both never waits; " + "disconnect wakes a waiting reader\n", MAV_QUEUE_SOFT_PACKETS, MAV_QUEUE_MAX_PACKETS, frames, + MAV_BACKPRESSURE_WAIT_MS ); + return 0; +} + int main( int argc, char **argv ) { size_t mp2_size, wsize, mp4_size; uint8_t *mp2, *wav, *mp4; @@ -1061,6 +1162,16 @@ def table(name): return 0; } mav_configure( 1, &stub_video, &stub_audio, MAV_PIX_NV12 ); + if (argc > 1 && !strcmp( argv[1], "bp" )) + { + int r; + setvbuf( stdout, NULL, _IONBF, 0 ); + mp4 = make_mp4( &mp4_size, AV_CODEC_ID_H264, A_AAC, frames, seconds ); + if (!mp4) { printf( "FAIL: could not synthesise the mp4\n" ); return 1; } + r = test_backpressure( mp4, mp4_size, frames ); + av_free( mp4 ); + return r || failures; + } mp2 = make_mp2( &mp2_size, 44100, 3.0 ); if (!mp2) { printf( "FAIL: no mp2 encoder in the host build\n" ); return 1; } if (test_wav()) return 1; @@ -1100,10 +1211,14 @@ def table(name): with tempfile.TemporaryDirectory() as t: c = Path(t) / "wgp.c"; c.write_text(harness) exe = Path(t) / "wgp" - subprocess.run(["cc", "-std=gnu11", "-O1", "-g", "-Wall", "-Wno-unused-function", "-fsanitize=address,undefined", - "-fno-sanitize-recover=undefined", "-I" + str(core.parent), "-I" + str(inc), str(c), "-o", str(exe), - str(lib / "libavformat.a"), str(lib / "libavcodec.a"), str(lib / "libswresample.a"), - str(lib / "libavutil.a"), "-lm", "-lpthread"], check=True) + + def build(out, defines=()): + subprocess.run(["cc", "-std=gnu11", "-O1", "-g", "-Wall", "-Wno-unused-function", "-fsanitize=address,undefined", + "-fno-sanitize-recover=undefined", "-I" + str(core.parent), "-I" + str(inc), *defines, str(c), + "-o", str(out), str(lib / "libavformat.a"), str(lib / "libavcodec.a"), + str(lib / "libswresample.a"), str(lib / "libavutil.a"), "-lm", "-lpthread"], check=True) + + build(exe) args = [str(exe)] if mp3: args += [mp3] @@ -1146,3 +1261,28 @@ def table(name): "ASan/UBSan clean" % (len(lines), len(set(re.sub(r" \(repeat #\d+\)$", "", l) for l in lines)))) for l in lines: print(" " + l) + + # ---------------------------------------------------------------- 4. back-pressure + bp, nobp = Path(t) / "wgp-bp", Path(t) / "wgp-nobp" + build(bp, ["-DMAV_QUEUE_SOFT_PACKETS=8", "-DMAV_QUEUE_SOFT_BYTES=65536", "-DMAV_QUEUE_MAX_PACKETS=16", + "-DMAV_BACKPRESSURE_WAIT_MS=400"]) + out = subprocess.run([str(bp), "bp"], env=env, capture_output=True, text=True, timeout=300) + print(out.stdout.replace("BP1 ", " (slow video, fast audio: pictures, audio buffers) "), end="") + assert out.returncode == 0, out.stdout + out.stderr[-4000:] + bp_lines = [l for l in out.stderr.splitlines() if l.startswith(TAG)] + # case 1 (two readers) drops nothing; case 2 (video never read) marks it unread once, then drops past the hard limit + first = out.stderr[:out.stderr.index("not read for")] if "not read for" in out.stderr else out.stderr + assert "dropping further packets" not in first, "a packet was dropped while both streams were read:\n" + first[-3000:] + assert sum("stream 0: not read for 400 ms while stream 1 reads ahead" in l for l in bp_lines) >= 1, bp_lines + assert "ERROR: AddressSanitizer" not in out.stderr and "runtime error" not in out.stderr, out.stderr[-4000:] + # the same two-reader case without back-pressure (the soft limit above the hard one) drops: + # the case it is for + build(nobp, ["-DMAV_QUEUE_SOFT_PACKETS=100000", "-DMAV_QUEUE_SOFT_BYTES=((size_t)1<<40)", + "-DMAV_QUEUE_MAX_PACKETS=16", "-DMAV_BACKPRESSURE_WAIT_MS=400"]) + out = subprocess.run([str(nobp), "bp"], env=env, capture_output=True, text=True, timeout=300) + assert "dropping further packets" in out.stderr and "FAIL test_backpressure" in out.stdout \ + and "slow video reader" in out.stdout, out.stdout + out.stderr[-2000:] + print("PASS: without back-pressure the same slow-video case drops packets and loses pictures (%s)" % + re.search(r"slow video reader: \d+ pictures of \d+", out.stdout).group(0)) + for l in bp_lines: + print(" " + l) From d0cc6cbb5df03248ddfabe0bd2f5c02b849d653b Mon Sep 17 00:00:00 2001 From: allen Date: Tue, 3 Nov 2026 03:20:39 +0900 Subject: [PATCH 2/9] wg_parser: play Windows Media (ASF/WMV) files A 32-bit visual novel's cutscenes go through the Windows Media Format reader (wm_reader.c), a wg_parser user. The parser knew MP3, WAV and MP4 only, so the reader failed to connect (0x80040265): a white screen with no sound. FFmpeg now builds the asf demuxer and the LGPL wmv1/wmv2/wmv3/vc1/ msmpeg4v1-v3 decoders; no platform decoder on iOS takes these, so the parser decodes Windows Media video in software (mav_lavc_video, one video backend per stream), WMA like MPEG audio, and writes every format the WM reader offers, its bottom-up BGR default first (also UYVY, YVYU, RGB565 and RGB555). The glue describes ASF streams by their WMV / WMA codec formats. This enables WMV9/VC-1 decoders in the app's FFmpeg. They are LGPL, as the rest of the configuration, but VC-1 has a patent pool: whether to ship them is the maintainers' call, as for H.264/HEVC/AAC, which stay with Apple's decoders. tests/host/check-wg-parser-asf.py synthesises WMV7, WMV8 and MS-MPEG4 v3 files with WMA2 audio and checks every picture bit-exact against an independent libavcodec decode, the WM reader's way of reading, every format after a keyframe seek, a WMV3 stream of garbage, and the back-pressure cases on the software decoder. WMV9/VC-1 streams themselves are not covered: FFmpeg cannot encode them. On a device the demuxer has run only under the compressed-sample path later in this series (Sabbat of the Witch, which plays); the parser's own decoding of Windows Media video is tested on Linux only. Co-Authored-By: Claude Opus 5.5 Signed-off-by: allen --- THIRD-PARTY-NOTICES.md | 2 +- build/ffmpeg/build.sh | 21 +- build/ntdll-unix/wg_parser_av_ios.c | 456 +++++++++++-- build/ntdll-unix/winegstreamer_unixlib_ios.c | 39 +- docs/MEDIA.md | 42 +- tests/host/check-wg-parser-asf.py | 665 +++++++++++++++++++ tests/host/check-wg-parser.py | 46 +- 7 files changed, 1201 insertions(+), 70 deletions(-) create mode 100644 tests/host/check-wg-parser-asf.py diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index 3c85c6593c..69a453755a 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -20,7 +20,7 @@ dependency license texts are in `LICENSES/`. See "Why GPL-3.0-or-later" below. | **GMP** 6.3.0 | **LGPL-3.0-or-later** or GPL-2.0-or-later | Static (`libgmp.a`). | | **Nettle / Hogweed** 3.10.1 | **LGPL-3.0-or-later** or GPL-2.0-or-later | Static (`libnettle.a`, `libhogweed.a`). | | **GnuTLS** 3.8.9 | LGPL-2.1-or-later | Static (`libgnutls.a`). Used by Wine's bcrypt/secur32/crypt32. | -| **FFmpeg** 7.1.5 — libavformat, libavcodec, libavutil, libswresample | **LGPL-2.1-or-later** | Static (`libavformat.a`, `libavcodec.a`, `libavutil.a`, `libswresample.a`). Configured `--disable-gpl --disable-nonfree --disable-version3 --disable-everything`, then only: the WMA-family decoders (`wmav1,wmav2,wmapro,wmalossless,xma1,xma2`), the `mp1,mp2,mp3` and `pcm_u8,pcm_s16le,pcm_s24le,pcm_s32le,pcm_f32le,pcm_f64le` decoders, the `mp3`, `wav` and `mov` (MP4/MOV/M4A) demuxers and the `mpegaudio` parser. No H.264, HEVC or AAC decoder or parser (those streams are decoded by Apple's VideoToolbox/AudioToolbox), no protocols, no muxers, no zlib. No GPL, version3 or non-free component is enabled, so the result is LGPL-2.1-or-later. Used only by `build/ntdll-unix/winegstreamer_unixlib_ios.c` and `build/ntdll-unix/wg_parser_av_ios.c`, winegstreamer's unix side on this port (the Windows WMA decoder MFT/DMO, and the wg_parser behind quartz's MP3/WAV splitters and Media Foundation's MP4 source); upstream Wine implements both with GStreamer, which does not exist on iOS. | +| **FFmpeg** 7.1.5 — libavformat, libavcodec, libavutil, libswresample | **LGPL-2.1-or-later** | Static (`libavformat.a`, `libavcodec.a`, `libavutil.a`, `libswresample.a`). Configured `--disable-gpl --disable-nonfree --disable-version3 --disable-everything`, then only: the WMA-family decoders (`wmav1,wmav2,wmapro,wmalossless,xma1,xma2`), the `mp1,mp2,mp3` and `pcm_u8,pcm_s16le,pcm_s24le,pcm_s32le,pcm_f32le,pcm_f64le` decoders, the Windows Media video decoders (`wmv1,wmv2,wmv3,vc1,msmpeg4v1,msmpeg4v2,msmpeg4v3`), the `mp3`, `wav`, `mov` (MP4/MOV/M4A) and `asf` (WMV/WMA) demuxers and the `mpegaudio` parser. No H.264, HEVC or AAC decoder or parser (those streams are decoded by Apple's VideoToolbox/AudioToolbox), no protocols, no muxers, no zlib. No GPL, version3 or non-free component is enabled, so the result is LGPL-2.1-or-later. Used only by `build/ntdll-unix/winegstreamer_unixlib_ios.c` and `build/ntdll-unix/wg_parser_av_ios.c`, winegstreamer's unix side on this port (the Windows WMA decoder MFT/DMO, and the wg_parser behind quartz's MP3/WAV splitters, Media Foundation's MP4 source and the Windows Media Format reader's ASF files); upstream Wine implements both with GStreamer, which does not exist on iOS. | | **{fmt}** | MIT | Static (`libfmt.a`), via FEX. | | **xxHash** | BSD-2-Clause | Static (`libxxhash.a`). | | **Cephes** | permissive (Moshier) | Static (`libcephes_128bit.a`), via FEX. | diff --git a/build/ffmpeg/build.sh b/build/ffmpeg/build.sh index 14ef6a125f..2d48b7b9aa 100755 --- a/build/ffmpeg/build.sh +++ b/build/ffmpeg/build.sh @@ -10,12 +10,18 @@ # # - libavcodec: the WMA-family decoders behind the Windows WMA decoder # MFT/DMO (wmav1, wmav2, wmapro, wmalossless, xma1, xma2), which FAudio -# uses for xWMA/XMA voices; MPEG-1 layer I/II/III and plain PCM decoders -# for the wg_parser. -# - libavformat: the wg_parser's demuxers -- mp3, wav and mov (MP4/MOV/M4A) -# -- and the mpegaudio parser the mp3 demuxer selects. No protocols: the -# parser reads through its own AVIOContext (the PE read thread's pull -# protocol), never a URL. No muxers. +# uses for xWMA/XMA voices, and the wg_parser uses for WMA audio in ASF; +# MPEG-1 layer I/II/III and plain PCM decoders for the wg_parser; and the +# Windows Media video decoders for its ASF files (wmv1, wmv2, wmv3, vc1, +# msmpeg4v1-v3): no platform decoder on iOS takes them, so the parser +# decodes them in software (wg_parser_av_ios.c, mav_lavc_video). A game's +# cutscenes played through the Windows Media Format reader (wmvcore) are +# such files; without these the reader failed to connect (0x80040265) and +# the game showed a white screen. +# - libavformat: the wg_parser's demuxers -- mp3, wav, mov (MP4/MOV/M4A) +# and asf (WMV/WMA) -- and the mpegaudio parser the mp3 demuxer selects. No +# protocols: the parser reads through its own AVIOContext (the PE read +# thread's pull protocol), never a URL. No muxers. # - libswresample, libavutil. # # Deliberately NO H.264, HEVC or AAC decoder or parser: those streams are @@ -113,7 +119,8 @@ CONFIG_ARGS=( --enable-decoder=wmav1,wmav2,wmapro,wmalossless,xma1,xma2 --enable-decoder=mp1,mp2,mp3 --enable-decoder=pcm_u8,pcm_s16le,pcm_s24le,pcm_s32le,pcm_f32le,pcm_f64le - --enable-demuxer=mp3,wav,mov + --enable-decoder=wmv1,wmv2,wmv3,vc1,msmpeg4v1,msmpeg4v2,msmpeg4v3 + --enable-demuxer=mp3,wav,mov,asf --enable-parser=mpegaudio --disable-programs --disable-doc diff --git a/build/ntdll-unix/wg_parser_av_ios.c b/build/ntdll-unix/wg_parser_av_ios.c index f9fa772d40..8e54158e6f 100644 --- a/build/ntdll-unix/wg_parser_av_ios.c +++ b/build/ntdll-unix/wg_parser_av_ios.c @@ -48,10 +48,13 @@ * the failure) instead of being accepted and never producing a sample. * An unsupported codec is logged with its libavcodec id. * - * - STREAMS. An MP3/WAV file exposes its first audio stream. An MP4 + * - STREAMS. An MP3/WAV file exposes its first audio stream. An MP4 or + * an ASF (WMV/WMA, the Windows Media Format reader's files: wm_reader.c) * exposes its first video stream and its first audio stream, in container - * order. An MP4 whose video cannot be decoded is refused outright; one - * whose audio cannot be decoded exposes the video alone (logged). + * order. A file whose video cannot be decoded is refused outright; one + * whose audio cannot be decoded exposes the video alone (logged). An + * ASF's Windows Media video is decoded here, in software, by libavcodec + * (mav_lavc_video), its WMA by libavcodec like MPEG audio. * * - one demuxer, several consumers. wg_parser.c runs a GStreamer thread * that parks one buffer per stream; here decoding is LAZY, on the thread @@ -67,8 +70,9 @@ * at the coded display size (MADEIRA_WG_VIDEO_FORMAT can choose another, * see the glue), which media_source.c turns into NV12 / YV12 / YUY2 / * I420 / IYUV media types. stream_enable accepts NV12, I420, YV12, YUY2, - * BGRx (RGB32), BGRA (ARGB32) and RGBA (ABGR32) at the native size, with - * a negative height meaning bottom-up rows, exactly as wg_format says. + * UYVY, YVYU, BGRx (RGB32), BGRA (ARGB32), RGBA (ABGR32), BGR (RGB24, the + * WM reader's default), RGB16 (565) and RGB15 (555) at the native size, + * with a negative height meaning bottom-up rows, exactly as wg_format says. * Frames are laid out the way GStreamer lays them out (4-byte aligned * strides) because that is what wg_format_get_stride() / the PE side * assume. Decoded pictures come back in decode order and are re-ordered @@ -140,11 +144,16 @@ enum mav_pixel_format MAV_PIX_UNKNOWN = 0, MAV_PIX_BGRA = 1, MAV_PIX_BGRx = 2, + MAV_PIX_BGR = 3, /* 24-bit, B G R bytes: the WM reader's default output */ + MAV_PIX_RGB15 = 4, /* 16-bit x1r5g5b5, little-endian */ + MAV_PIX_RGB16 = 5, /* 16-bit r5g6b5, little-endian */ MAV_PIX_RGBA = 6, MAV_PIX_I420 = 8, MAV_PIX_NV12 = 9, + MAV_PIX_UYVY = 11, MAV_PIX_YUY2 = 12, MAV_PIX_YV12 = 13, + MAV_PIX_YVYU = 14, }; enum mav_status @@ -171,6 +180,20 @@ enum mav_codec_kind MAV_CODEC_AAC = 3, MAV_CODEC_H264 = 4, MAV_CODEC_HEVC = 5, + MAV_CODEC_WMA = 6, /* WMA v1/v2/Pro/Lossless in ASF, on libavcodec */ + MAV_CODEC_WMV = 7, /* WMV7/8/9, VC-1, MS-MPEG4 in ASF, on libavcodec (mav_lavc_video) */ +}; + +/* Which Windows Media video a MAV_CODEC_WMV stream is (wg_format's WMV + * formats, mapped by the glue); 0 for the MS-MPEG4 family, which has none. */ +enum mav_wmv_format +{ + MAV_WMV_NONE = 0, + MAV_WMV_WMV1, + MAV_WMV_WMV2, + MAV_WMV_WMV3, + MAV_WMV_WMVA, + MAV_WMV_WVC1, }; struct mav_output @@ -200,7 +223,11 @@ struct mav_stream_info struct mav_output native; /* audio: what the stream decodes to by default */ struct mav_video_output vnative; /* video: likewise */ uint32_t profile, level; /* H.264 */ - uint32_t codec_data_len; /* AAC: AudioSpecificConfig; H.264: avcC (if it fits) */ + uint32_t version; /* WMA: 1, 2, 3 (Pro) or 4 (Lossless) */ + uint32_t block_align, depth; /* WMA */ + enum mav_wmv_format wmv; /* WMV */ + uint32_t codec_data_len; /* AAC: AudioSpecificConfig; H.264: avcC; WMA / WMV: the + * WAVEFORMATEX / BITMAPINFOHEADER extra bytes (if they fit) */ uint8_t codec_data[64]; uint64_t duration; /* 100 ns, 0 when unknown */ }; @@ -269,7 +296,7 @@ static int mav_seek( struct mav_parser *p, unsigned int stream, int set_start, u * rule releases (a stream without decode times, or a broken one). */ #define MAV_REORDER_MAX 16 /* Packets queued for a stream nobody is reading from yet. */ -#ifndef MAV_QUEUE_MAX_PACKETS /* tests/host/check-wg-parser.py builds with small limits */ +#ifndef MAV_QUEUE_MAX_PACKETS /* tests/host/check-wg-parser.py and check-wg-parser-asf.py build with small limits */ #define MAV_QUEUE_MAX_PACKETS 16384 #endif #ifndef MAV_QUEUE_MAX_BYTES @@ -370,6 +397,221 @@ struct mav_vframe int64_t pts, duration; /* stream time base */ }; +/*********************************************************************** + * the libavcodec video backend (Windows Media video) + * + * WMV7/8 (wmv1, wmv2), WMV9 (wmv3), VC-1 (WMVA, WVC1) and MS-MPEG4 v1-v3 have + * no platform decoder on iOS, so they are decoded here, in software, by + * libavcodec, behind the same contract as the platform backend. The decoders + * produce 4:2:0 planar pictures, copied into the NV12 layout the contract + * maps. They reorder internally: pictures come out in presentation order + * with their own timestamps, so the core releases them at once (no decode + * timestamps in ASF to release them by), and they hold the last pictures back + * until mav_lavc_drain at the end of the stream. + */ +enum +{ + MAV_LAVC_WMV1 = 64, MAV_LAVC_WMV2, MAV_LAVC_WMV3, MAV_LAVC_VC1, + MAV_LAVC_MSMPEG4V1, MAV_LAVC_MSMPEG4V2, MAV_LAVC_MSMPEG4V3, +}; + +struct mav_lavc_vdec +{ + AVCodecContext *ctx; + AVPacket *pkt; + AVFrame *frame; + unsigned int bad_format_logged; +}; + +struct mav_lavc_picture +{ + uint8_t *data; /* Y plane, then the interleaved CbCr plane */ + uint32_t width, height, y_stride, uv_stride; + int full_range; +}; + +static enum AVCodecID mav_lavc_codec_id( int codec ) +{ + switch (codec) + { + case MAV_LAVC_WMV1: return AV_CODEC_ID_WMV1; + case MAV_LAVC_WMV2: return AV_CODEC_ID_WMV2; + case MAV_LAVC_WMV3: return AV_CODEC_ID_WMV3; + case MAV_LAVC_VC1: return AV_CODEC_ID_VC1; + case MAV_LAVC_MSMPEG4V1: return AV_CODEC_ID_MSMPEG4V1; + case MAV_LAVC_MSMPEG4V2: return AV_CODEC_ID_MSMPEG4V2; + case MAV_LAVC_MSMPEG4V3: return AV_CODEC_ID_MSMPEG4V3; + default: return AV_CODEC_ID_NONE; + } +} + +static int mav_lavc_supports( int codec ) +{ + enum AVCodecID id = mav_lavc_codec_id( codec ); + return id != AV_CODEC_ID_NONE && avcodec_find_decoder( id ) != NULL; +} + +static void mav_lavc_close( void *handle ) +{ + struct mav_lavc_vdec *d = handle; + + if (!d) return; + avcodec_free_context( &d->ctx ); + av_packet_free( &d->pkt ); + av_frame_free( &d->frame ); + free( d ); +} + +static void *mav_lavc_open( int codec, const uint8_t *extradata, uint32_t extradata_size, + uint32_t width, uint32_t height, char *why, size_t why_size ) +{ + const AVCodec *dec = avcodec_find_decoder( mav_lavc_codec_id( codec ) ); + struct mav_lavc_vdec *d; + + if (!dec) + { + snprintf( why, why_size, "no decoder in this build" ); + return NULL; + } + if (!(d = calloc( 1, sizeof(*d) ))) return NULL; + if (!(d->ctx = avcodec_alloc_context3( dec )) || !(d->pkt = av_packet_alloc()) || !(d->frame = av_frame_alloc())) + goto fail; + d->ctx->opaque = MAV_DECODER_MARKER; + d->ctx->width = d->ctx->coded_width = (int)width; + d->ctx->height = d->ctx->coded_height = (int)height; + d->ctx->thread_count = 1; /* every call is made under the parser's lock, one at a time */ + if (extradata_size) + { + if (!(d->ctx->extradata = av_mallocz( (size_t)extradata_size + AV_INPUT_BUFFER_PADDING_SIZE ))) goto fail; + memcpy( d->ctx->extradata, extradata, extradata_size ); + d->ctx->extradata_size = (int)extradata_size; + } + if (avcodec_open2( d->ctx, dec, NULL ) < 0) + { + snprintf( why, why_size, "decoder did not open" ); + goto fail; + } + return d; +fail: + mav_lavc_close( d ); + return NULL; +} + +/* One decoded picture into its own NV12 copy, handed to `emit`. */ +static void mav_lavc_emit( struct mav_lavc_vdec *d, const AVFrame *f, mav_vframe_emit emit, void *ctx ) +{ + struct mav_lavc_picture *pic; + uint32_t w = (uint32_t)f->width, h = (uint32_t)f->height, cw = (w + 1) / 2, ch = (h + 1) / 2, x, y; + int64_t pts = f->pts != AV_NOPTS_VALUE ? f->pts : f->best_effort_timestamp; + + if (f->format != AV_PIX_FMT_YUV420P && f->format != AV_PIX_FMT_YUVJ420P) + { + if (d->bad_format_logged++ < 3) + mav_log( "%s: picture in pixel format %d, not 4:2:0 planar; dropped", d->ctx->codec->name, f->format ); + return; + } + if (!w || !h || w > MAV_MAX_DIMENSION || h > MAV_MAX_DIMENSION || !(pic = calloc( 1, sizeof(*pic) ))) return; + pic->width = w; + pic->height = h; + pic->y_stride = w; + pic->uv_stride = cw * 2; + pic->full_range = f->format == AV_PIX_FMT_YUVJ420P || f->color_range == AVCOL_RANGE_JPEG; + if (!(pic->data = malloc( (size_t)w * h + (size_t)pic->uv_stride * ch ))) + { + free( pic ); + return; + } + for (y = 0; y < h; y++) memcpy( pic->data + (size_t)y * w, f->data[0] + (size_t)y * f->linesize[0], w ); + for (y = 0; y < ch; y++) + { + const uint8_t *u = f->data[1] + (size_t)y * f->linesize[1], *v = f->data[2] + (size_t)y * f->linesize[2]; + uint8_t *uv = pic->data + (size_t)w * h + (size_t)y * pic->uv_stride; + for (x = 0; x < cw; x++) + { + uv[2 * x] = u[x]; + uv[2 * x + 1] = v[x]; + } + } + emit( ctx, pic, pts == AV_NOPTS_VALUE ? INT64_MIN : pts, f->duration > 0 ? f->duration : INT64_MIN ); +} + +static void mav_lavc_receive( struct mav_lavc_vdec *d, mav_vframe_emit emit, void *ctx ) +{ + while (avcodec_receive_frame( d->ctx, d->frame ) >= 0) + { + mav_lavc_emit( d, d->frame, emit, ctx ); + av_frame_unref( d->frame ); + } +} + +static int mav_lavc_decode( void *handle, const uint8_t *data, uint32_t size, int64_t pts, int64_t duration, + int keyframe, mav_vframe_emit emit, void *ctx ) +{ + struct mav_lavc_vdec *d = handle; + int err; + + /* not reference-counted: libavcodec takes a padded copy */ + d->pkt->data = (uint8_t *)data; + d->pkt->size = (int)size; + d->pkt->pts = pts == INT64_MIN ? AV_NOPTS_VALUE : pts; + d->pkt->dts = AV_NOPTS_VALUE; + d->pkt->duration = duration == INT64_MIN ? 0 : duration; + d->pkt->flags = keyframe ? AV_PKT_FLAG_KEY : 0; + while ((err = avcodec_send_packet( d->ctx, d->pkt )) == AVERROR(EAGAIN)) + mav_lavc_receive( d, emit, ctx ); + d->pkt->data = NULL; + d->pkt->size = 0; + if (err >= 0) mav_lavc_receive( d, emit, ctx ); + return err < 0 ? -1 : 0; +} + +/* End of the stream: the pictures the decoder still holds. */ +static void mav_lavc_drain( void *handle, mav_vframe_emit emit, void *ctx ) +{ + struct mav_lavc_vdec *d = handle; + + if (avcodec_send_packet( d->ctx, NULL ) >= 0) mav_lavc_receive( d, emit, ctx ); +} + +static int mav_lavc_map( void *frame, struct mav_vplanes *planes ) +{ + struct mav_lavc_picture *pic = frame; + + planes->y = pic->data; + planes->uv = pic->data + (size_t)pic->width * pic->height; + planes->y_stride = pic->y_stride; + planes->uv_stride = pic->uv_stride; + planes->width = pic->width; + planes->height = pic->height; + planes->full_range = pic->full_range; + return 0; +} + +static void mav_lavc_unmap( void *frame ) +{ + (void)frame; +} + +static void mav_lavc_release( void *frame ) +{ + struct mav_lavc_picture *pic = frame; + + if (!pic) return; + free( pic->data ); + free( pic ); +} + +static void mav_lavc_flush( void *handle ) +{ + avcodec_flush_buffers( ((struct mav_lavc_vdec *)handle)->ctx ); +} + +static const struct mav_video_backend mav_lavc_video = +{ + "libavcodec", mav_lavc_supports, mav_lavc_open, mav_lavc_decode, mav_lavc_map, mav_lavc_unmap, + mav_lavc_release, mav_lavc_flush, mav_lavc_close, +}; + struct mav_stream { unsigned int number; /* index among the exposed streams */ @@ -392,6 +634,7 @@ struct mav_stream struct mav_output out; /* ---- video ---- */ + const struct mav_video_backend *vbackend; /* the platform's, or mav_lavc_video */ void *vdec; struct mav_video_output vout; struct mav_vframe *reorder; /* sorted by pts */ @@ -449,6 +692,7 @@ struct mav_parser AVFormatContext *fmt; AVPacket *read_pkt; int is_mov; + int is_asf; int ready; /* connected and streams exposed */ int demux_eof; unsigned int read_errors_logged; @@ -626,7 +870,7 @@ static void mav_reorder_clear( struct mav_stream *s ) unsigned int i; for (i = 0; i < s->reorder_count; i++) - if (mav_vbackend) mav_vbackend->release( s->reorder[i].handle ); + if (s->vbackend) s->vbackend->release( s->reorder[i].handle ); s->reorder_count = 0; } @@ -635,7 +879,7 @@ static void mav_stream_free( struct mav_stream *s ) if (!s) return; mav_reorder_clear( s ); free( s->reorder ); - if (s->vdec && mav_vbackend) mav_vbackend->close( s->vdec ); + if (s->vdec && s->vbackend) s->vbackend->close( s->vdec ); if (s->adec && mav_abackend) mav_abackend->close( s->adec ); mav_queue_clear( s ); free( s->queue ); @@ -666,7 +910,7 @@ static void mav_teardown( struct mav_parser *p ) av_freep( &p->avio->buffer ); avio_context_free( &p->avio ); } - p->ready = p->is_mov = p->demux_eof = 0; + p->ready = p->is_mov = p->is_asf = p->demux_eof = 0; p->read_errors_logged = 0; p->stop = -1; } @@ -744,11 +988,16 @@ static const char *mav_pix_name( enum mav_pixel_format fmt ) { case MAV_PIX_BGRA: return "bgra"; case MAV_PIX_BGRx: return "bgrx"; + case MAV_PIX_BGR: return "bgr"; + case MAV_PIX_RGB15: return "rgb15"; + case MAV_PIX_RGB16: return "rgb16"; case MAV_PIX_RGBA: return "rgba"; case MAV_PIX_I420: return "i420"; case MAV_PIX_NV12: return "nv12"; + case MAV_PIX_UYVY: return "uyvy"; case MAV_PIX_YUY2: return "yuy2"; case MAV_PIX_YV12: return "yv12"; + case MAV_PIX_YVYU: return "yvyu"; default: return "?"; } } @@ -785,9 +1034,17 @@ static size_t mav_video_layout( enum mav_pixel_format fmt, uint32_t w, uint32_t l->size = l->offset[2] + (size_t)l->stride[2] * l->chroma_height; break; case MAV_PIX_YUY2: + case MAV_PIX_UYVY: + case MAV_PIX_YVYU: + case MAV_PIX_RGB15: + case MAV_PIX_RGB16: l->stride[0] = MAV_ALIGN4( w * 2 ); l->size = (size_t)l->stride[0] * h; break; + case MAV_PIX_BGR: + l->stride[0] = MAV_ALIGN4( w * 3 ); + l->size = (size_t)l->stride[0] * h; + break; case MAV_PIX_BGRA: case MAV_PIX_BGRx: case MAV_PIX_RGBA: @@ -824,6 +1081,14 @@ static int mav_classify_audio( enum AVCodecID id, enum mav_codec_kind *kind, uin *kind = MAV_CODEC_AAC; *native = MAV_FMT_F32; return 1; + case AV_CODEC_ID_WMAV1: + case AV_CODEC_ID_WMAV2: + case AV_CODEC_ID_WMAPRO: + case AV_CODEC_ID_WMALOSSLESS: + /* libavcodec, reported as S16 like MPEG audio (the WM reader's default) */ + *kind = MAV_CODEC_WMA; + *native = MAV_FMT_S16; + return 1; default: return 0; } *kind = MAV_CODEC_MPEG_AUDIO; @@ -881,8 +1146,10 @@ static struct mav_stream *mav_stream_new( struct mav_parser *p, AVStream *st, en s->info.type = type; s->time_base = st->time_base; /* MP4 timestamps are already on the presentation timeline (edit lists - * applied by the demuxer); an MP3/WAV stream starts at its own start. */ - s->origin = p->is_mov ? 0 : (st->start_time != AV_NOPTS_VALUE ? st->start_time : 0); + * applied by the demuxer), and so are ASF's (its preroll taken off by the + * demuxer), both on one clock for every stream; an MP3/WAV stream starts + * at its own start. */ + s->origin = p->is_mov || p->is_asf ? 0 : (st->start_time != AV_NOPTS_VALUE ? st->start_time : 0); s->last_dts = s->last_vpts = INT64_MIN; s->seek_target = -1; if (!(s->pkt = av_packet_alloc())) @@ -890,7 +1157,7 @@ static struct mav_stream *mav_stream_new( struct mav_parser *p, AVStream *st, en free( s ); return NULL; } - snprintf( s->info.container, sizeof(s->info.container), "%s", p->is_mov ? "mp4" : p->fmt->iformat->name ); + snprintf( s->info.container, sizeof(s->info.container), "%s", p->is_mov ? "mp4" : p->fmt->iformat->name ); /* asf: "asf" */ if (p->fmt->duration != AV_NOPTS_VALUE && p->fmt->duration > 0 && !p->is_mov) s->info.duration = (uint64_t)p->fmt->duration * 10; /* AV_TIME_BASE is 1 us */ else if (st->duration != AV_NOPTS_VALUE && st->duration > 0) @@ -981,6 +1248,19 @@ static int mav_open_audio( struct mav_parser *p, struct mav_stream *s, AVStream } snprintf( s->info.codec, sizeof(s->info.codec), "%s", codec->name ); snprintf( s->info.backend, sizeof(s->info.backend), "libavcodec" ); + if (s->info.kind == MAV_CODEC_WMA) + { + /* what wg_format describes a WMA stream by (the codec format) */ + s->info.version = par->codec_id == AV_CODEC_ID_WMAV1 ? 1 : par->codec_id == AV_CODEC_ID_WMAV2 ? 2 + : par->codec_id == AV_CODEC_ID_WMAPRO ? 3 : 4; + s->info.block_align = par->block_align > 0 ? (uint32_t)par->block_align : 0; + s->info.depth = par->bits_per_coded_sample > 0 ? (uint32_t)par->bits_per_coded_sample : 16; + if (par->extradata && par->extradata_size <= (int)sizeof(s->info.codec_data)) + { + memcpy( s->info.codec_data, par->extradata, par->extradata_size ); + s->info.codec_data_len = par->extradata_size; + } + } s->info.native.rate = s->dec->sample_rate; s->info.native.channels = s->dec->ch_layout.nb_channels; s->info.native.channel_mask = mav_layout_mask( &s->dec->ch_layout ); @@ -996,17 +1276,39 @@ static int mav_open_video( struct mav_parser *p, struct mav_stream *s, AVStream AVRational fps = st->avg_frame_rate; int codec; - (void)p; + /* H.264 / HEVC from an MP4 go to the platform decoder (avcC / hvcC codec + * data); Windows Media video from an ASF to libavcodec. */ + s->vbackend = mav_vbackend; switch (par->codec_id) { case AV_CODEC_ID_H264: codec = MAV_BACKEND_H264; s->info.kind = MAV_CODEC_H264; break; case AV_CODEC_ID_HEVC: codec = MAV_BACKEND_HEVC; s->info.kind = MAV_CODEC_HEVC; break; + case AV_CODEC_ID_WMV1: codec = MAV_LAVC_WMV1; s->info.wmv = MAV_WMV_WMV1; break; + case AV_CODEC_ID_WMV2: codec = MAV_LAVC_WMV2; s->info.wmv = MAV_WMV_WMV2; break; + case AV_CODEC_ID_WMV3: codec = MAV_LAVC_WMV3; s->info.wmv = MAV_WMV_WMV3; break; + case AV_CODEC_ID_VC1: + codec = MAV_LAVC_VC1; + s->info.wmv = par->codec_tag == MKTAG('W','M','V','A') ? MAV_WMV_WMVA : MAV_WMV_WVC1; + break; + case AV_CODEC_ID_MSMPEG4V1: codec = MAV_LAVC_MSMPEG4V1; break; + case AV_CODEC_ID_MSMPEG4V2: codec = MAV_LAVC_MSMPEG4V2; break; + case AV_CODEC_ID_MSMPEG4V3: codec = MAV_LAVC_MSMPEG4V3; break; default: snprintf( why, why_size, "no decoder for it in this port" ); return MAV_E_UNSUPPORTED; } + if (codec >= MAV_LAVC_WMV1) + { + s->info.kind = MAV_CODEC_WMV; + s->vbackend = &mav_lavc_video; + } snprintf( s->info.codec, sizeof(s->info.codec), "%s", avcodec_get_name( par->codec_id ) ); - if (!mav_vbackend || !mav_vbackend->supports( codec )) + if (p->is_asf != (s->info.kind == MAV_CODEC_WMV)) + { + snprintf( why, why_size, "not in this container here (H.264 / HEVC in MP4, Windows Media video in ASF)" ); + return MAV_E_UNSUPPORTED; + } + if (!s->vbackend || !s->vbackend->supports( codec )) { snprintf( why, why_size, "no video decoder backend for it" ); return MAV_E_UNSUPPORTED; @@ -1016,10 +1318,10 @@ static int mav_open_video( struct mav_parser *p, struct mav_stream *s, AVStream snprintf( why, why_size, "unusable picture size %dx%d", par->width, par->height ); return MAV_E_UNSUPPORTED; } - if (!(s->vdec = mav_vbackend->open( codec, par->extradata, par->extradata_size, par->width, par->height, - why, why_size ))) + if (!(s->vdec = s->vbackend->open( codec, par->extradata, par->extradata_size, par->width, par->height, + why, why_size ))) return MAV_E_UNSUPPORTED; - snprintf( s->info.backend, sizeof(s->info.backend), "%s", mav_vbackend->name ); + snprintf( s->info.backend, sizeof(s->info.backend), "%s", s->vbackend->name ); if (fps.num <= 0 || fps.den <= 0) fps = st->r_frame_rate; if (fps.num <= 0 || fps.den <= 0 || av_q2d( fps ) > 1000) @@ -1083,19 +1385,21 @@ static int mav_connect_locked( struct mav_parser *p ) name = p->fmt->iformat->name; is_mp3 = !strcmp( name, "mp3" ); p->is_mov = !strcmp( name, MAV_MOV_NAME ); - if (!is_mp3 && strcmp( name, "wav" ) && !(p->is_mov && mav_video_allowed)) - return mav_refuse( p, MAV_E_UNSUPPORTED, p->is_mov ? "container disabled by MADEIRA_WG_VIDEO=0" - : "container not in the allowlist" ); - if (p->fmt->probe_score < (p->is_mov ? MAV_MIN_MOV_PROBE_SCORE : MAV_MIN_PROBE_SCORE)) + p->is_asf = !strcmp( name, "asf" ); + if (!is_mp3 && strcmp( name, "wav" ) && !((p->is_mov || p->is_asf) && mav_video_allowed)) + return mav_refuse( p, MAV_E_UNSUPPORTED, p->is_mov || p->is_asf ? "container disabled by MADEIRA_WG_VIDEO=0" + : "container not in the allowlist" ); + /* An ASF header object scores like a recognised MP4 (its GUID matches). */ + if (p->fmt->probe_score < (p->is_mov || p->is_asf ? MAV_MIN_MOV_PROBE_SCORE : MAV_MIN_PROBE_SCORE)) { snprintf( why, sizeof(why), "probe score %d below %d", p->fmt->probe_score, - p->is_mov ? MAV_MIN_MOV_PROBE_SCORE : MAV_MIN_PROBE_SCORE ); + p->is_mov || p->is_asf ? MAV_MIN_MOV_PROBE_SCORE : MAV_MIN_PROBE_SCORE ); return mav_refuse( p, MAV_E_UNSUPPORTED, why ); } - /* The mp3 demuxer only ever carries MPEG audio and an MP4 only compressed - * streams: a compressed-output parser is refused before the stream - * analysis reads anything more. */ - if (p->output_compressed && (is_mp3 || p->is_mov)) + /* The mp3 demuxer only ever carries MPEG audio and an MP4 or ASF only + * compressed streams: a compressed-output parser is refused before the + * stream analysis reads anything more. */ + if (p->output_compressed && (is_mp3 || p->is_mov || p->is_asf)) return mav_refuse( p, MAV_E_UNSUPPORTED, "compressed output requested and no decoder filter exists; " "the decoding splitter is tried next" ); @@ -1105,7 +1409,7 @@ static int mav_connect_locked( struct mav_parser *p ) for (i = 0; i < p->fmt->nb_streams; i++) { enum AVMediaType type = p->fmt->streams[i]->codecpar->codec_type; - if (type != AVMEDIA_TYPE_AUDIO && !(p->is_mov && type == AVMEDIA_TYPE_VIDEO)) + if (type != AVMEDIA_TYPE_AUDIO && !((p->is_mov || p->is_asf) && type == AVMEDIA_TYPE_VIDEO)) p->fmt->streams[i]->discard = AVDISCARD_ALL; } @@ -1120,12 +1424,13 @@ static int mav_connect_locked( struct mav_parser *p ) if (s->disposition & AV_DISPOSITION_ATTACHED_PIC) continue; if (s->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { - if (!p->is_mov) return mav_refuse( p, MAV_E_UNSUPPORTED, "the file has a video stream" ); + if (!p->is_mov && !p->is_asf) return mav_refuse( p, MAV_E_UNSUPPORTED, "the file has a video stream" ); if (!vst) vst = s; } if (s->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && !ast) ast = s; } - if (!vst && !ast) return mav_refuse( p, MAV_E_UNSUPPORTED, p->is_mov ? "no audio or video stream" : "no audio stream" ); + if (!vst && !ast) return mav_refuse( p, MAV_E_UNSUPPORTED, p->is_mov || p->is_asf ? "no audio or video stream" + : "no audio stream" ); if (!(p->read_pkt = av_packet_alloc())) return MAV_E_NOMEM; @@ -1148,7 +1453,7 @@ static int mav_connect_locked( struct mav_parser *p ) } if (status) { - /* An MP4's audio is optional; its video, or the only stream, is not. */ + /* An MP4's or ASF's audio is optional; its video, or the only stream, is not. */ if (st == ast && vst) { char text[320]; @@ -1817,7 +2122,7 @@ static void mav_vframe_emit_cb( void *ctx, void *handle, int64_t pts, int64_t du struct mav_vframe *grown = realloc( s->reorder, cap * sizeof(*grown) ); if (!grown) { - mav_vbackend->release( handle ); + s->vbackend->release( handle ); return; } s->reorder = grown; @@ -1872,21 +2177,24 @@ static void mav_convert_picture( struct mav_stream *s, const struct mav_vplanes uint32_t cw = src->width < w ? src->width : w, ch = src->height < h ? src->height : h; uint32_t ccw = (cw + 1) / 2, cch = (ch + 1) / 2, x, y; int flip = s->vout.height < 0; - int yuv = s->vout.fmt == MAV_PIX_NV12 || s->vout.fmt == MAV_PIX_I420 - || s->vout.fmt == MAV_PIX_YV12 || s->vout.fmt == MAV_PIX_YUY2; + int planar = s->vout.fmt == MAV_PIX_NV12 || s->vout.fmt == MAV_PIX_I420 || s->vout.fmt == MAV_PIX_YV12; + int packed = s->vout.fmt == MAV_PIX_YUY2 || s->vout.fmt == MAV_PIX_UYVY || s->vout.fmt == MAV_PIX_YVYU; if (cw < w || ch < h) { - /* black: Y 16 / chroma 128, or opaque RGB black */ - if (s->vout.fmt == MAV_PIX_YUY2) + /* black: Y 16 / chroma 128, or RGB black (opaque where there is alpha) */ + if (packed) for (y = 0; y < h; y++) for (x = 0; x < l->stride[0] / 4; x++) - memcpy( dst + (size_t)y * l->stride[0] + x * 4, "\x10\x80\x10\x80", 4 ); - else if (yuv) + memcpy( dst + (size_t)y * l->stride[0] + x * 4, + s->vout.fmt == MAV_PIX_UYVY ? "\x80\x10\x80\x10" : "\x10\x80\x10\x80", 4 ); + else if (planar) { memset( dst, 16, l->offset[1] ); memset( dst + l->offset[1], 128, l->size - l->offset[1] ); } + else if (s->vout.fmt == MAV_PIX_BGR || s->vout.fmt == MAV_PIX_RGB15 || s->vout.fmt == MAV_PIX_RGB16) + memset( dst, 0, l->size ); else for (y = 0; y < h; y++) for (x = 0; x < w; x++) @@ -1918,19 +2226,27 @@ static void mav_convert_picture( struct mav_stream *s, const struct mav_vplanes break; } case MAV_PIX_YUY2: + case MAV_PIX_UYVY: + case MAV_PIX_YVYU: + { + /* byte offsets of Y0, U, Y1, V in each 4-byte pair */ + int y0 = s->vout.fmt == MAV_PIX_UYVY ? 1 : 0, y1 = y0 + 2; + int uo = s->vout.fmt == MAV_PIX_YUY2 ? 1 : s->vout.fmt == MAV_PIX_UYVY ? 0 : 3; + int vo = s->vout.fmt == MAV_PIX_YUY2 ? 3 : s->vout.fmt == MAV_PIX_UYVY ? 2 : 1; for (y = 0; y < ch; y++) { const uint8_t *yr = src->y + (size_t)y * src->y_stride, *uv = src->uv + (size_t)(y / 2) * src->uv_stride; uint8_t *o = DST_ROW( 0, y, h ); for (x = 0; x < cw; x += 2) { - o[2 * x + 0] = yr[x]; - o[2 * x + 1] = uv[x]; - o[2 * x + 2] = x + 1 < cw ? yr[x + 1] : yr[x]; - o[2 * x + 3] = uv[x + 1]; + o[2 * x + y0] = yr[x]; + o[2 * x + uo] = uv[x]; + o[2 * x + y1] = x + 1 < cw ? yr[x + 1] : yr[x]; + o[2 * x + vo] = uv[x + 1]; } } break; + } case MAV_PIX_BGRA: case MAV_PIX_BGRx: case MAV_PIX_RGBA: @@ -1954,6 +2270,41 @@ static void mav_convert_picture( struct mav_stream *s, const struct mav_vplanes } break; } + case MAV_PIX_BGR: + case MAV_PIX_RGB15: + case MAV_PIX_RGB16: + { + struct mav_yuv_coefs c; + mav_yuv_coefs( s->bt709, src->full_range, &c ); + for (y = 0; y < ch; y++) + { + const uint8_t *yr = src->y + (size_t)y * src->y_stride, *uv = src->uv + (size_t)(y / 2) * src->uv_stride; + uint8_t *o = DST_ROW( 0, y, h ); + for (x = 0; x < cw; x++) + { + int yy = (yr[x] - c.yoff) * c.y + 32768; + int u = uv[(x & ~1u)] - 128, v = uv[(x & ~1u) + 1] - 128; + uint8_t r = mav_clip8( (yy + c.rv * v) >> 16 ); + uint8_t g = mav_clip8( (yy - c.gu * u - c.gv * v) >> 16 ); + uint8_t b = mav_clip8( (yy + c.bu * u) >> 16 ); + if (s->vout.fmt == MAV_PIX_BGR) + { + o[3 * x] = b; + o[3 * x + 1] = g; + o[3 * x + 2] = r; + } + else + { + uint16_t px = s->vout.fmt == MAV_PIX_RGB16 + ? (uint16_t)((r >> 3) << 11 | (g >> 2) << 5 | b >> 3) + : (uint16_t)((r >> 3) << 10 | (g >> 3) << 5 | b >> 3); + o[2 * x] = (uint8_t)px; + o[2 * x + 1] = (uint8_t)(px >> 8); + } + } + } + break; + } default: break; } @@ -1977,28 +2328,28 @@ static int mav_video_emit( struct mav_parser *p, struct mav_stream *s, struct ma { if (pts + dur <= s->seek_target) { - mav_vbackend->release( f->handle ); + s->vbackend->release( f->handle ); return 0; } s->seek_target = -1; } if (p->stop >= 0 && pts >= p->stop) { - mav_vbackend->release( f->handle ); + s->vbackend->release( f->handle ); s->eos = 1; return 0; } size = mav_video_layout( s->vout.fmt, s->vout.width, s->vout.height < 0 ? -s->vout.height : s->vout.height, &l ); if (!size || size > UINT32_MAX || !mav_reserve( s, size )) { - mav_vbackend->release( f->handle ); + s->vbackend->release( f->handle ); s->eos = 1; mav_log( "stream %u: cannot hold a %zu-byte picture; ending the stream", s->number, size ); return 0; } - if (mav_vbackend->map( f->handle, &planes )) + if (s->vbackend->map( f->handle, &planes )) { - mav_vbackend->release( f->handle ); + s->vbackend->release( f->handle ); if (s->errors_logged < 3) { s->errors_logged++; @@ -2008,8 +2359,8 @@ static int mav_video_emit( struct mav_parser *p, struct mav_stream *s, struct ma return 0; } mav_convert_picture( s, &planes, s->buf, &l ); - mav_vbackend->unmap( f->handle ); - mav_vbackend->release( f->handle ); + s->vbackend->unmap( f->handle ); + s->vbackend->release( f->handle ); s->next_pts = pts + dur; s->cur.pts = pts > 0 ? (uint64_t)pts : 0; @@ -2034,6 +2385,7 @@ static int mav_video_next( struct mav_parser *p, struct mav_stream *s ) * later packets decode at or after the last decode time, and a * picture never presents before it decodes. */ if (s->reorder_count && (s->draining || s->reorder_count > MAV_REORDER_MAX + || s->vbackend == &mav_lavc_video /* already in presentation order */ || (s->last_dts != INT64_MIN && s->reorder[0].pts <= s->last_dts))) { struct mav_vframe f = s->reorder[0]; @@ -2049,10 +2401,12 @@ static int mav_video_next( struct mav_parser *p, struct mav_stream *s ) } if (!mav_next_packet( p, s, s->pkt )) { + /* libavcodec holds its last pictures until it is drained */ + if (s->vbackend == &mav_lavc_video && !p->closing) mav_lavc_drain( s->vdec, mav_vframe_emit_cb, s ); s->draining = 1; continue; } - err = mav_vbackend->decode( s->vdec, s->pkt->data, s->pkt->size, + err = s->vbackend->decode( s->vdec, s->pkt->data, s->pkt->size, s->pkt->pts != AV_NOPTS_VALUE ? s->pkt->pts : INT64_MIN, s->pkt->duration > 0 ? s->pkt->duration : INT64_MIN, !!(s->pkt->flags & AV_PKT_FLAG_KEY), mav_vframe_emit_cb, s ); @@ -2213,7 +2567,7 @@ static int mav_seek( struct mav_parser *p, unsigned int stream, int set_start, u if (c->vdec) { mav_reorder_clear( c ); - mav_vbackend->flush( c->vdec ); + c->vbackend->flush( c->vdec ); } swr_free( &c->swr ); if (c->pkt_pending) av_packet_unref( c->pkt ); diff --git a/build/ntdll-unix/winegstreamer_unixlib_ios.c b/build/ntdll-unix/winegstreamer_unixlib_ios.c index daea866e37..48ca3b38a8 100644 --- a/build/ntdll-unix/winegstreamer_unixlib_ios.c +++ b/build/ntdll-unix/winegstreamer_unixlib_ios.c @@ -2220,7 +2220,9 @@ C_ASSERT( (int)MAV_FMT_U8 == (int)WG_AUDIO_FORMAT_U8 && (int)MAV_FMT_S16 == (int C_ASSERT( (int)MAV_PIX_BGRA == (int)WG_VIDEO_FORMAT_BGRA && (int)MAV_PIX_BGRx == (int)WG_VIDEO_FORMAT_BGRx && (int)MAV_PIX_RGBA == (int)WG_VIDEO_FORMAT_RGBA && (int)MAV_PIX_I420 == (int)WG_VIDEO_FORMAT_I420 && (int)MAV_PIX_NV12 == (int)WG_VIDEO_FORMAT_NV12 && (int)MAV_PIX_YUY2 == (int)WG_VIDEO_FORMAT_YUY2 - && (int)MAV_PIX_YV12 == (int)WG_VIDEO_FORMAT_YV12 ); + && (int)MAV_PIX_YV12 == (int)WG_VIDEO_FORMAT_YV12 && (int)MAV_PIX_BGR == (int)WG_VIDEO_FORMAT_BGR + && (int)MAV_PIX_RGB15 == (int)WG_VIDEO_FORMAT_RGB15 && (int)MAV_PIX_RGB16 == (int)WG_VIDEO_FORMAT_RGB16 + && (int)MAV_PIX_UYVY == (int)WG_VIDEO_FORMAT_UYVY && (int)MAV_PIX_YVYU == (int)WG_VIDEO_FORMAT_YVYU ); static BOOL wg_parser_switch_on(void) { @@ -2512,6 +2514,41 @@ static NTSTATUS wgp_get_codec_format( wg_parser_stream_t handle, struct wg_forma format->u.audio.channels = info.native.channels; format->u.audio.rate = info.native.rate; return S_OK; + case MAV_CODEC_WMA: + /* what the WM reader's stream configuration (and a game reading the + * file's profile) describes the stream by */ + memset( format, 0, sizeof(*format) ); + format->major_type = WG_MAJOR_TYPE_AUDIO_WMA; + format->u.audio.version = info.version; + format->u.audio.bitrate = info.bitrate; + format->u.audio.rate = info.native.rate; + format->u.audio.depth = info.depth; + format->u.audio.channels = info.native.channels; + format->u.audio.block_align = info.block_align; + format->u.audio.codec_data_len = info.codec_data_len < sizeof(format->u.audio.codec_data) ? info.codec_data_len : sizeof(format->u.audio.codec_data); + memcpy( format->u.audio.codec_data, info.codec_data, format->u.audio.codec_data_len ); + return S_OK; + case MAV_CODEC_WMV: + { + static const wg_video_format wmv[] = + { + [MAV_WMV_WMV1] = WG_VIDEO_FORMAT_WMV1, [MAV_WMV_WMV2] = WG_VIDEO_FORMAT_WMV2, + [MAV_WMV_WMV3] = WG_VIDEO_FORMAT_WMV3, [MAV_WMV_WMVA] = WG_VIDEO_FORMAT_WMVA, + [MAV_WMV_WVC1] = WG_VIDEO_FORMAT_WVC1, + }; + /* the MS-MPEG4 family has no wg_format: its current (decoded) format stands in */ + if (info.wmv == MAV_WMV_NONE || (unsigned)info.wmv >= ARRAY_SIZE(wmv)) return wgp_get_current_format( handle, format ); + memset( format, 0, sizeof(*format) ); + format->major_type = WG_MAJOR_TYPE_VIDEO_WMV; + format->u.video.format = wmv[info.wmv]; + format->u.video.width = info.vnative.width; + format->u.video.height = info.vnative.height; + format->u.video.fps_n = info.vnative.fps_n; + format->u.video.fps_d = info.vnative.fps_d; + format->u.video.codec_data_len = info.codec_data_len < sizeof(format->u.video.codec_data) ? info.codec_data_len : sizeof(format->u.video.codec_data); + memcpy( format->u.video.codec_data, info.codec_data, format->u.video.codec_data_len ); + return S_OK; + } case MAV_CODEC_H264: memset( format, 0, sizeof(*format) ); format->major_type = WG_MAJOR_TYPE_VIDEO_H264; diff --git a/docs/MEDIA.md b/docs/MEDIA.md index 530c4caffa..add1f5dcd3 100644 --- a/docs/MEDIA.md +++ b/docs/MEDIA.md @@ -10,7 +10,12 @@ three things that Windows programs use every day have no decoder: mixer as PCM, which sounds like loud static; - quartz's MPEG-I and "GStreamer" splitters (DirectShow MP3/WAV playback); - Media Foundation's fallback media source (MP4/MOV video through the source - resolver). + resolver); +- the Windows Media Format reader (`wmvcore`: `WMCreateReader`, + `WMCreateSyncReader`, and DirectShow's WM ASF Reader on top of it), which + plays WMV/WMA (ASF) files. A visual novel's cutscenes went through it; the + reader failed to connect (`no enabled demuxer recognised the stream`, + `0x80040265`) and the game showed a white screen with no sound. This port supplies that unix side in `libntdll_unix.a`, bound by name in `load_builtin_unixlib()` (`build/ntdll-unix/virtual_ios.c`). @@ -27,14 +32,26 @@ Foundation source) is refused as before unless `MADEIRA_WG_64BIT=1`. | File | What it is | |---|---| | `build/ntdll-unix/winegstreamer_unixlib_ios.c` | Both unix call tables (entry for entry with `dlls/winegstreamer/unixlib.h`), the wow64 thunks, and the `wg_transform` subset `wma_decoder.c` uses, on libavcodec: WMA v1/v2/Pro/Lossless and XMA1/2 only. Other transforms (AAC, H.264, WMV, resampler, colour converter) are refused at create, and `wg_muxer` returns `STATUS_NOT_IMPLEMENTED`. | -| `build/ntdll-unix/wg_parser_av_ios.c` | The `wg_parser` core, `#include`d by the file above: the PE read thread's pull protocol as an AVIOContext, libavformat demux (mp3, wav, mov), MPEG audio / PCM decode through libavcodec + libswresample, a packet queue with back-pressure, B-frame reordering, keyframe seek with exact trim, and conversion to the formats `quartz_parser.c` / `media_source.c` ask for. | +| `build/ntdll-unix/wg_parser_av_ios.c` | The `wg_parser` core, `#include`d by the file above: the PE read thread's pull protocol as an AVIOContext, libavformat demux (mp3, wav, mov, asf), MPEG audio / PCM / WMA decode through libavcodec + libswresample, Windows Media video (WMV7/8/9, VC-1, MS-MPEG4 v1-v3) decoded in software by libavcodec (`mav_lavc_video`), a packet queue with back-pressure, B-frame reordering, keyframe seek with exact trim, and conversion to the formats `quartz_parser.c`, `media_source.c` and `wm_reader.c` ask for: NV12, I420, YV12, YUY2, UYVY, YVYU, BGRx, BGRA, RGBA, 24-bit BGR (the WM reader's default, bottom-up), RGB565 and RGB555. | | `build/ntdll-unix/wg_parser_apple_ios.c` | H.264/HEVC on VideoToolbox (NV12 out) and AAC on an AudioToolbox AudioConverter (float PCM out). Its own translation unit with no Wine or FFmpeg header. | | `build/ntdll-unix/wg_parser_backend_ios.h` | The contract between the core and a decoder backend; plain C types only, so the host test can supply stub backends. | | `build/ffmpeg/build.sh` | FFmpeg 7.1.5, pinned by SHA-256, LGPL-only configuration. | FFmpeg is built with no H.264, HEVC or AAC decoder or parser: those streams go -to the platform decoders. See `THIRD-PARTY-NOTICES.md` for the exact component -list and its licence. +to the platform decoders. Windows Media video has no platform decoder on iOS, +so FFmpeg's LGPL `wmv1`, `wmv2`, `wmv3`, `vc1` and `msmpeg4v1-3` decoders are +built and decode it on the CPU (one thread, FFmpeg's C code: `--disable-asm`). +See `THIRD-PARTY-NOTICES.md` for the exact component list and its licence. + +**Containers and codecs.** MP3/WAV: MPEG audio and PCM. MP4/MOV: H.264 or +HEVC video (VideoToolbox) with AAC, MPEG audio or PCM. ASF (WMV/WMA): Windows +Media video (libavcodec) with WMA v1/v2/Pro/Lossless or MPEG audio. AVI, +MPEG program streams, Bink and the like are not handled here (Bink and most +engines' own formats are decoded by the game itself). The codec format of an +ASF stream (`wg_parser_stream_get_codec_format`) is the one Wine's GStreamer +backend reports: WMV1/WMV2/WMV3/WMVA/WVC1 video, WMA audio with its version, +block alignment and codec data, so a game that reads the file's profile +through `IWMProfile` sees the real stream types. **One demuxer, several readers: back-pressure.** Each stream is read on its own thread by quartz and Media Foundation; a packet read for another stream @@ -46,8 +63,8 @@ reader that demuxes for it waits (without the parser lock, which the other reader needs) until the queue has drained to three quarters of that. A stream that is not read for 5 s is marked unread and queued without waiting (dropped past the old hard limits, as before) until it is read again; one thread -reading both streams (the earliest-buffer mode) never waits for itself; a -seek, a disable or disconnect wakes a waiting reader. +reading both streams (the WM reader's earliest-buffer mode) never waits for +itself; a seek, a disable or disconnect wakes a waiting reader. The PE half of winegstreamer is upstream's and unchanged. Wine's configure disables the module when GStreamer is missing, so a PE build tree has to be @@ -65,7 +82,7 @@ Environment variables (`env.NAME = value` in `madeira.cfg`): |---|---|---| | `MADEIRA_WG_64BIT` | WMA only | `0`: 64-bit processes get the stub table again; `1`: their `wg_parser` too (see above). | | `MADEIRA_WG_PARSER` | on | `0`: `wg_parser_create` returns `STATUS_NOT_IMPLEMENTED` again, as before this series; quartz and the MF source then fail the way they did. The WMA decoder is unaffected. | -| `MADEIRA_WG_VIDEO` | on | `0`: MP3/WAV only; an MP4/MOV is refused at connect. | +| `MADEIRA_WG_VIDEO` | on | `0`: MP3/WAV only; an MP4/MOV or ASF is refused at connect. | | `MADEIRA_WG_VIDEO_FORMAT` | `nv12` | Native format a video stream reports: `nv12`, `i420`, `yv12`, `yuy2`, `rgb32`, `argb32` or `abgr32`. | | `MADEIRA_WMA_SEARCH` | on | `0`: keep the WMA v1/v2 decoder at the bit rate and flags it opened with; no search over other candidates when a bit-reservoir stream fails. A packet that fails is concealed with silence of its length and the next one is decoded as usual. (An xWMA stream still opens at the rate libavformat's xWMA table normalises to.) | | `MADEIRA_WMA_DUMP` | off | Set: write each WMA decoder's input to `wma-dump-.bin` in the Documents folder, for reproducing a decode failure on a host. | @@ -83,6 +100,17 @@ rate-limited per process (`MADEIRA_DIAG=1` lifts the `[wma]` cap). (a slow video reader loses nothing, while the same build without back-pressure drops pictures; an unread stream holds the other reader once; one thread reading both never waits; disconnect wakes a waiting reader). +- `tests/host/check-wg-parser-asf.py` (Linux): builds a host FFmpeg from the + same tarball with the port's demuxers and decoders and test-only WMV/WMA + encoders and the asf muxer, synthesises WMV7, WMV8 and MS-MPEG4 v3 files + with WMA2 audio, and checks under ASan/UBSan, against an independent + libavcodec decode of the same file: every picture bit-exact, in order; the + WM reader's way (bottom-up BGR, S16, earliest-buffer reads) to the end; every + format it offers after a keyframe seek; a WMV3 stream of garbage; and, with + small queue limits, the back-pressure cases (a slow video reader loses + nothing, while the same build without back-pressure drops pictures; an + unread stream; one thread reading both; disconnect while a reader waits). + WMV9/VC-1 streams themselves are not covered: FFmpeg cannot encode them. - `tests/host/check-wma-decoder.py` (Linux or macOS, needs a configured Wine tree for the generated headers): compiles the production `winegstreamer_unixlib_ios.c` under ASan/UBSan against a host FFmpeg built diff --git a/tests/host/check-wg-parser-asf.py b/tests/host/check-wg-parser-asf.py new file mode 100644 index 0000000000..29c18dba5f --- /dev/null +++ b/tests/host/check-wg-parser-asf.py @@ -0,0 +1,665 @@ +#!/usr/bin/env python3 +"""Windows Media files (ASF: WMV video, WMA audio) through the wg_parser core, and its back-pressure; no Wine runs. + +A Steam visual novel's cutscenes play through the Windows Media Format reader (wmvcore, Wine's +wm_reader.c), a wg_parser user. This port's core knew only MP3, WAV and MP4, so the reader failed to +connect ("no enabled demuxer recognised the stream", 0x80040265) and the game showed a white screen +with no sound. The core now demuxes ASF and decodes Windows Media video in software through +libavcodec (mav_lavc_video in build/ntdll-unix/wg_parser_av_ios.c), and writes every picture format +wm_reader.c offers, its default first: bottom-up 24-bit BGR. + +1. Source checks: build/ffmpeg/build.sh enables the asf demuxer and the wmv1/wmv2/wmv3/vc1/msmpeg4v1-3 + decoders (and still no H.264/HEVC/AAC decoder); the glue asserts the new pixel-format values and + describes WMV / WMA streams by their wg_format codec formats. +2. Builds a host FFmpeg 7.1.5 from the tracked tarball with the port's demuxers and decoders, plus + TEST-ONLY encoders (wmv1, wmv2, msmpeg4v3, wmav2) and the asf muxer to synthesise inputs. Cached. +3. Compiles the production core under ASan/UBSan with the PE read thread of media_source.c / + wm_reader.c, and checks, against an independent libavcodec decode of the same file: + - WMV8 (wmv2) + WMA2: two streams, every picture bit-exact in NV12, in order, at 40 ms steps; + the WM reader's way (BGR bottom-up video, S16 audio, earliest-buffer reads) to the end; + every format wm_reader.c offers (NV12 YV12 YUY2 UYVY YVYU BGRx BGR RGB16 RGB15) and I420, + pixel-checked; keyframe seek with exact trim; the codec formats (WMV2, WMA v2); + - WMV7 (wmv1) and MS-MPEG4 v3 video decode bit-exact; + - a WMV3 stream of undecodable data ends the stream (no crash, no hang); + and, built with small queue limits (a stream that falls behind used to lose packets): + - a slow video reader and a fast audio reader on two threads: no packet dropped, every picture + delivered (the same file without back-pressure drops); + - a video stream that is enabled and never read: the audio reader waits once, then goes on; + - one thread reading both streams (earliest-buffer mode) never waits for itself; + - disconnect while a reader waits: it is woken and nothing is freed under it. +Needs python3, a C compiler and the FFmpeg tarball (build/ffmpeg/src). +""" +from pathlib import Path +import hashlib, os, re, subprocess, sys, tempfile + +root = Path(__file__).resolve().parents[2] +core = root / "build/ntdll-unix/wg_parser_av_ios.c" +glue = (root / "build/ntdll-unix/winegstreamer_unixlib_ios.c").read_text() + +# ------------------------------------------------------------------ 1. source checks +ff = (root / "build/ffmpeg/build.sh").read_text().replace("\r\n", "\n") +args = ff[ff.index("CONFIG_ARGS=("):] +args = args[:args.index("\n)\n")] +assert "--enable-demuxer=mp3,wav,mov,asf" in args, "asf demuxer" +assert "--enable-decoder=wmv1,wmv2,wmv3,vc1,msmpeg4v1,msmpeg4v2,msmpeg4v3" in args, "Windows Media video decoders" +assert "--enable-decoder=wmav1,wmav2,wmapro,wmalossless" in args, "WMA decoders" +for bad in ["h264", "hevc", "aac"]: + assert not re.search(r"--enable-(decoder|parser)=[^\n]*\b%s\b" % bad, args), ("platform-decoded codec enabled", bad) +for flag in ["--disable-gpl", "--disable-nonfree", "--disable-version3", "--disable-everything"]: + assert flag in args, ("LGPL-only configuration", flag) +assert "(int)MAV_PIX_BGR == (int)WG_VIDEO_FORMAT_BGR" in glue and "(int)MAV_PIX_YVYU == (int)WG_VIDEO_FORMAT_YVYU" in glue +codec_fmt = glue[glue.index("static NTSTATUS wgp_get_codec_format("):] +codec_fmt = codec_fmt[:codec_fmt.index("\n}\n")] +assert "case MAV_CODEC_WMA:" in codec_fmt and "WG_MAJOR_TYPE_AUDIO_WMA" in codec_fmt +assert "case MAV_CODEC_WMV:" in codec_fmt and "WG_MAJOR_TYPE_VIDEO_WMV" in codec_fmt +print("PASS: FFmpeg has the asf demuxer and the Windows Media decoders (still no H.264/HEVC/AAC); " + "the glue maps the new pixel formats and the WMV / WMA codec formats") + +# ------------------------------------------------------------------ 2. host FFmpeg +tarball = os.environ.get("MADEIRA_FFMPEG_TARBALL") or str(root / "build/ffmpeg/src/ffmpeg-7.1.5.tar.xz") +FLAGS = [ + "--disable-everything", "--disable-autodetect", "--disable-gpl", "--disable-nonfree", "--disable-version3", + "--enable-decoder=wmav1,wmav2,wmapro,wmalossless", "--enable-decoder=mp1,mp2,mp3", + "--enable-decoder=pcm_u8,pcm_s16le,pcm_s24le,pcm_s32le,pcm_f32le,pcm_f64le", + "--enable-decoder=wmv1,wmv2,wmv3,vc1,msmpeg4v1,msmpeg4v2,msmpeg4v3", + "--enable-demuxer=mp3,wav,mov,asf", "--enable-parser=mpegaudio", + # TEST ONLY: input synthesis + "--enable-encoder=wmv1,wmv2,msmpeg4v3,wmav2", "--enable-muxer=asf", + "--disable-programs", "--disable-doc", "--disable-network", "--disable-avdevice", "--disable-swscale", + "--disable-avfilter", "--disable-postproc", "--enable-avformat", "--enable-avcodec", "--enable-swresample", + "--disable-asm", "--disable-shared", "--enable-static", "--enable-pic", "--disable-debug", +] +prefix = os.environ.get("MADEIRA_HOST_FFMPEG_ASF") +if not prefix: + key = hashlib.sha256(" ".join(FLAGS).encode()).hexdigest()[:12] + prefix = str(Path.home() / ".cache/madeira-host-ffmpeg" / ("7.1.5-asf-" + key)) + if not (Path(prefix) / "lib/libavformat.a").exists(): + assert Path(tarball).exists(), "no FFmpeg tarball at build/ffmpeg/src (tracked) and no MADEIRA_FFMPEG_TARBALL" + src = Path(prefix + "-src"); src.mkdir(parents=True, exist_ok=True) + if not (src / "ffmpeg-7.1.5/configure").exists(): + subprocess.run(["tar", "-xJf", tarball, "-C", str(src)], check=True) + bld = Path(prefix + "-build"); bld.mkdir(parents=True, exist_ok=True) + print("building host FFmpeg into", prefix, flush=True) + log = open(str(bld) + ".log", "w") + subprocess.run([str(src / "ffmpeg-7.1.5/configure"), "--prefix=" + prefix, "--cc=cc"] + FLAGS, + cwd=bld, check=True, stdout=log, stderr=subprocess.STDOUT) + subprocess.run(["make", "-j%d" % (os.cpu_count() or 4)], cwd=bld, check=True, stdout=log, stderr=subprocess.STDOUT) + subprocess.run(["make", "install"], cwd=bld, check=True, stdout=log, stderr=subprocess.STDOUT) +inc, lib = Path(prefix) / "include", Path(prefix) / "lib" + +# ------------------------------------------------------------------ 3. the core under ASan +harness = r""" +#include "wg_parser_av_ios.c" +#include +#include + +static int failures; +#define CHECK(c, ...) do { if (!(c)) { printf( "FAIL %s:%d: ", __func__, __LINE__ ); printf( __VA_ARGS__ ); printf( "\n" ); fflush( stdout ); failures++; return 1; } } while (0) + +#define W 320 +#define H 240 +#define FPS 25 +#define GOP 10 +#define FRAMES 100 /* 4 s */ +#define RATE 44100 + +/* ---- the PE side: media_source.c / wm_reader.c read_thread() ---- */ +struct source { const uint8_t *data; size_t size; volatile int running; struct mav_parser *p; pthread_t thread; }; + +static void *read_thread( void *arg ) +{ + struct source *s = arg; + while (s->running) + { + uint64_t offset; uint32_t size; + if (mav_get_next_read_offset( s->p, &offset, &size )) { usleep( 200 ); continue; } + if (offset >= s->size) size = 0; + else if (offset + size >= s->size) size = s->size - offset; + mav_push_data( s->p, size ? s->data + offset : s->data, size ); + } + return NULL; +} +static void src_start( struct source *s, struct mav_parser *p, const uint8_t *data, size_t size ) +{ + memset( s, 0, sizeof(*s) ); s->data = data; s->size = size; s->p = p; s->running = 1; + pthread_create( &s->thread, NULL, read_thread, s ); +} +static void src_stop( struct source *s ) { mav_disconnect( s->p ); s->running = 0; pthread_join( s->thread, NULL ); } + +/* ---- inputs: an ASF made by libavformat's asf muxer in memory ---- */ +struct membuf { uint8_t *data; size_t size, cap, pos; }; +static int mem_write( void *o, const uint8_t *buf, int n ) +{ + struct membuf *m = o; + if (m->pos + n > m->cap) { m->cap = (m->pos + n) * 2; m->data = realloc( m->data, m->cap ); } + memcpy( m->data + m->pos, buf, n ); m->pos += n; if (m->pos > m->size) m->size = m->pos; + return n; +} +static int mem_read( void *o, uint8_t *buf, int n ) +{ + struct membuf *m = o; + if (m->pos >= m->size) return AVERROR_EOF; + if ((size_t)n > m->size - m->pos) n = (int)(m->size - m->pos); + memcpy( buf, m->data + m->pos, n ); m->pos += n; + return n; +} +static int64_t mem_seek( void *o, int64_t off, int whence ) +{ + struct membuf *m = o; + if (whence & AVSEEK_SIZE) return m->size; + whence &= ~AVSEEK_FORCE; + if (whence == SEEK_CUR) off += m->pos; else if (whence == SEEK_END) off += m->size; + if (off < 0) return -1; + m->pos = off; + return off; +} + +static void put( AVFormatContext *oc, AVCodecContext *e, AVStream *st, AVFrame *f ) +{ + AVPacket *pkt = av_packet_alloc(); + avcodec_send_frame( e, f ); + while (avcodec_receive_packet( e, pkt ) >= 0) + { + av_packet_rescale_ts( pkt, e->time_base, st->time_base ); + pkt->stream_index = st->index; + av_interleaved_write_frame( oc, pkt ); + } + av_packet_free( &pkt ); +} + +/* `frames` pictures with a moving pattern (and, with audio, a 440 Hz WMA2 tone). + * vcodec 0: a WMV3 stream of raw garbage packets (no WMV9 encoder exists). */ +static uint8_t *make_asf( enum AVCodecID vcodec, int audio, size_t *size ) +{ + struct membuf m = {0}; + AVFormatContext *oc; AVCodecContext *ve = NULL, *ae = NULL; AVStream *vs, *as = NULL; + AVFrame *vf = av_frame_alloc(), *af = av_frame_alloc(); int64_t apts = 0; int i, x, y; + + avformat_alloc_output_context2( &oc, NULL, "asf", NULL ); + oc->pb = avio_alloc_context( av_malloc( 4096 ), 4096, 1, &m, NULL, mem_write, mem_seek ); + vs = avformat_new_stream( oc, NULL ); + if (vcodec) + { + ve = avcodec_alloc_context3( avcodec_find_encoder( vcodec ) ); + ve->width = W; ve->height = H; ve->time_base = (AVRational){ 1, FPS }; ve->framerate = (AVRational){ FPS, 1 }; + ve->pix_fmt = AV_PIX_FMT_YUV420P; ve->gop_size = GOP; ve->bit_rate = 800000; ve->max_b_frames = 0; + if (oc->oformat->flags & AVFMT_GLOBALHEADER) ve->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + if (avcodec_open2( ve, ve->codec, NULL ) < 0) return NULL; + avcodec_parameters_from_context( vs->codecpar, ve ); + vs->time_base = ve->time_base; + } + else + { + static const uint8_t seq[4] = { 0x4e, 0x29, 0x1a, 0x01 }; /* a WMV3 main-profile sequence header */ + vs->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; vs->codecpar->codec_id = AV_CODEC_ID_WMV3; + vs->codecpar->codec_tag = MKTAG('W','M','V','3'); vs->codecpar->width = W; vs->codecpar->height = H; + vs->codecpar->extradata = av_mallocz( 4 + AV_INPUT_BUFFER_PADDING_SIZE ); vs->codecpar->extradata_size = 4; + memcpy( vs->codecpar->extradata, seq, 4 ); + vs->time_base = (AVRational){ 1, FPS }; + } + if (audio) + { + as = avformat_new_stream( oc, NULL ); + ae = avcodec_alloc_context3( avcodec_find_encoder( AV_CODEC_ID_WMAV2 ) ); + ae->sample_rate = RATE; ae->sample_fmt = AV_SAMPLE_FMT_FLTP; ae->bit_rate = 128000; + av_channel_layout_default( &ae->ch_layout, 2 ); ae->time_base = (AVRational){ 1, RATE }; + if (avcodec_open2( ae, ae->codec, NULL ) < 0) return NULL; + avcodec_parameters_from_context( as->codecpar, ae ); + as->time_base = ae->time_base; + } + if (avformat_write_header( oc, NULL ) < 0) return NULL; + vf->format = AV_PIX_FMT_YUV420P; vf->width = W; vf->height = H; av_frame_get_buffer( vf, 0 ); + if (ae) + { + af->format = ae->sample_fmt; af->nb_samples = ae->frame_size; af->sample_rate = RATE; + av_channel_layout_copy( &af->ch_layout, &ae->ch_layout ); av_frame_get_buffer( af, 0 ); + } + for (i = 0; i < FRAMES; i++) + { + av_frame_make_writable( vf ); + for (y = 0; y < H; y++) for (x = 0; x < W; x++) + vf->data[0][y * vf->linesize[0] + x] = (uint8_t)(32 + ((x + 3 * i) / 16 % 2) * 120 + y / 4); + for (y = 0; y < H / 2; y++) for (x = 0; x < W / 2; x++) + { + vf->data[1][y * vf->linesize[1] + x] = (uint8_t)(90 + x / 2 + i); + vf->data[2][y * vf->linesize[2] + x] = (uint8_t)(170 - y / 2); + } + vf->pts = i; + if (ve) put( oc, ve, vs, vf ); + else + { + /* garbage: a WMV3 decoder rejects it, packet by packet */ + AVPacket *pkt = av_packet_alloc(); int k; + av_new_packet( pkt, 600 ); + for (k = 0; k < 600; k++) pkt->data[k] = (uint8_t)(k * 131 + i * 17); + pkt->pts = pkt->dts = i; pkt->stream_index = vs->index; pkt->flags = i % GOP ? 0 : AV_PKT_FLAG_KEY; + av_packet_rescale_ts( pkt, (AVRational){ 1, FPS }, vs->time_base ); + av_interleaved_write_frame( oc, pkt ); + av_packet_free( &pkt ); + } + while (ae && apts * FPS < (int64_t)(i + 1) * RATE) + { + int c, n; + av_frame_make_writable( af ); + for (c = 0; c < 2; c++) for (n = 0; n < af->nb_samples; n++) + ((float *)af->data[c])[n] = 0.4f * sinf( 2 * (float)M_PI * 440 * (apts + n) / RATE ); + af->pts = apts; apts += af->nb_samples; + put( oc, ae, as, af ); + } + } + if (ve) put( oc, ve, vs, NULL ); + if (ae) put( oc, ae, as, NULL ); + av_write_trailer( oc ); + av_freep( &oc->pb->buffer ); /* the AVIO buffer; the file's bytes stay in `m` */ + avio_context_free( &oc->pb ); + avformat_free_context( oc ); + avcodec_free_context( &ve ); avcodec_free_context( &ae ); av_frame_free( &vf ); av_frame_free( &af ); + *size = m.size; + return m.data; +} + +/* ---- the reference: the same file decoded by libavformat + libavcodec directly ---- */ +static uint8_t *ref_frames; /* FRAMES x (Y, U, V) planes, W x H 4:2:0 */ +static int ref_count; +#define REF_SIZE (W * H * 3 / 2) + +static int make_reference( const uint8_t *data, size_t size ) +{ + struct membuf m = { (uint8_t *)data, size, size, 0 }; + AVFormatContext *fc = avformat_alloc_context(); AVCodecContext *d; AVPacket *pkt = av_packet_alloc(); + AVFrame *f = av_frame_alloc(); int vi = -1, y; unsigned int i; + + fc->pb = avio_alloc_context( av_malloc( 4096 ), 4096, 0, &m, mem_read, NULL, mem_seek ); + CHECK( avformat_open_input( &fc, NULL, NULL, NULL ) == 0 && avformat_find_stream_info( fc, NULL ) >= 0, "reference open" ); + for (i = 0; i < fc->nb_streams; i++) if (fc->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) vi = i; + d = avcodec_alloc_context3( avcodec_find_decoder( fc->streams[vi]->codecpar->codec_id ) ); + avcodec_parameters_to_context( d, fc->streams[vi]->codecpar ); d->thread_count = 1; + CHECK( avcodec_open2( d, d->codec, NULL ) == 0, "reference decoder" ); + free( ref_frames ); ref_frames = calloc( FRAMES + 8, REF_SIZE ); ref_count = 0; + for (;;) + { + int eof = av_read_frame( fc, pkt ) < 0; + if (!eof && pkt->stream_index != vi) { av_packet_unref( pkt ); continue; } + avcodec_send_packet( d, eof ? NULL : pkt ); + av_packet_unref( pkt ); + while (avcodec_receive_frame( d, f ) >= 0) + { + uint8_t *o = ref_frames + (size_t)ref_count * REF_SIZE; + CHECK( f->format == AV_PIX_FMT_YUV420P && f->width == W && f->height == H && ref_count < FRAMES + 8, "reference frame" ); + for (y = 0; y < H; y++) memcpy( o + y * W, f->data[0] + y * f->linesize[0], W ); + for (y = 0; y < H / 2; y++) + { + memcpy( o + W * H + y * (W / 2), f->data[1] + y * f->linesize[1], W / 2 ); + memcpy( o + W * H * 5 / 4 + y * (W / 2), f->data[2] + y * f->linesize[2], W / 2 ); + } + ref_count++; + av_frame_unref( f ); + } + if (eof) break; + } + avcodec_free_context( &d ); av_frame_free( &f ); av_packet_free( &pkt ); + av_freep( &fc->pb->buffer ); avio_context_free( &fc->pb ); avformat_close_input( &fc ); + return 0; +} + +/* The first picture's pts: the asf muxer moves every timestamp up by the WMA + * encoder's delay (46 ms), so none is negative. */ +static int64_t pts0 = -1; + +static int RY( int i, int x, int y ) { return ref_frames[(size_t)i * REF_SIZE + y * W + x]; } +static int RU( int i, int x, int y ) { return ref_frames[(size_t)i * REF_SIZE + W * H + (y / 2) * (W / 2) + x / 2]; } +static int RV( int i, int x, int y ) { return ref_frames[(size_t)i * REF_SIZE + W * H * 5 / 4 + (y / 2) * (W / 2) + x / 2]; } + +/* One picture of `fmt` against reference picture `idx`: YUV formats exact, RGB within 1 (BT.601, limited). */ +static int check_picture( const uint8_t *buf, uint32_t size, enum mav_pixel_format fmt, int flip, int idx, const char *what ) +{ + struct mav_layout l; int x, y, maxerr = 0; + CHECK( size == mav_video_layout( fmt, W, H, &l ), "%s: size %u", what, size ); + for (y = 0; y < H; y++) + { + int ry = flip ? H - 1 - y : y; + const uint8_t *row = buf + (size_t)ry * l.stride[0]; + for (x = 0; x < W; x++) + { + int Y = RY( idx, x, y ), U = RU( idx, x, y ), V = RV( idx, x, y ), pair = 4 * (x / 2); + switch (fmt) + { + case MAV_PIX_NV12: + CHECK( row[x] == Y, "%s Y(%d,%d) %d != %d", what, x, y, row[x], Y ); + if (!(y & 1)) CHECK( buf[l.offset[1] + (ry / 2) * l.stride[1] + (x & ~1)] == U + && buf[l.offset[1] + (ry / 2) * l.stride[1] + (x & ~1) + 1] == V, "%s UV(%d,%d)", what, x, y ); + break; + case MAV_PIX_I420: case MAV_PIX_YV12: + { + int up = fmt == MAV_PIX_I420 ? 1 : 2, vp = 3 - up; + CHECK( row[x] == Y, "%s Y(%d,%d)", what, x, y ); + if (!(y & 1)) CHECK( buf[l.offset[up] + (ry / 2) * l.stride[up] + x / 2] == U + && buf[l.offset[vp] + (ry / 2) * l.stride[vp] + x / 2] == V, "%s U/V(%d,%d)", what, x, y ); + break; + } + case MAV_PIX_YUY2: CHECK( row[2 * x] == Y && row[pair + 1] == U && row[pair + 3] == V, "%s (%d,%d)", what, x, y ); break; + case MAV_PIX_UYVY: CHECK( row[pair + 1 + 2 * (x & 1)] == Y && row[pair] == U && row[pair + 2] == V, "%s (%d,%d)", what, x, y ); break; + case MAV_PIX_YVYU: CHECK( row[2 * x] == Y && row[pair + 3] == U && row[pair + 1] == V, "%s (%d,%d)", what, x, y ); break; + default: + { + double yy = 1.164383 * (Y - 16), r = yy + 1.596027 * (V - 128), + g = yy - 0.391762 * (U - 128) - 0.812968 * (V - 128), b = yy + 2.017232 * (U - 128); + int rr = (int)lround( fmin( 255, fmax( 0, r ) ) ), rg = (int)lround( fmin( 255, fmax( 0, g ) ) ), + rb = (int)lround( fmin( 255, fmax( 0, b ) ) ), R, G, B, e; + if (fmt == MAV_PIX_RGB16 || fmt == MAV_PIX_RGB15) + { + unsigned px = row[2 * x] | row[2 * x + 1] << 8; int six = fmt == MAV_PIX_RGB16; + R = six ? px >> 11 : (px >> 10) & 31; G = (px >> 5) & (six ? 63 : 31); B = px & 31; + CHECK( abs( R - (rr >> 3) ) <= 1 && abs( G - (six ? rg >> 2 : rg >> 3) ) <= 1 && abs( B - (rb >> 3) ) <= 1, + "%s (%d,%d)", what, x, y ); + break; + } + if (fmt == MAV_PIX_BGR) { B = row[3 * x]; G = row[3 * x + 1]; R = row[3 * x + 2]; } + else + { + const uint8_t *px = row + 4 * x; + R = fmt == MAV_PIX_RGBA ? px[0] : px[2]; G = px[1]; B = fmt == MAV_PIX_RGBA ? px[2] : px[0]; + CHECK( px[3] == 0xff, "%s alpha", what ); + } + e = abs( R - rr ); if (e > maxerr) maxerr = e; + e = abs( G - rg ); if (e > maxerr) maxerr = e; + e = abs( B - rb ); if (e > maxerr) maxerr = e; + } + } + } + } + CHECK( maxerr <= 1, "%s: RGB error %d", what, maxerr ); + return 0; +} + +/* ================= WMV + WMA ================= */ +static int test_wmv( const uint8_t *asf, size_t size, const char *codec ) +{ + struct mav_parser *p = mav_create( 0 ); struct source s; struct mav_stream_info vi, ai; struct mav_buffer b; + struct mav_output ao; uint8_t *pic = malloc( W * H * 4 ); int n = 0; + + CHECK( !make_reference( asf, size ) && ref_count == FRAMES, "reference: %d pictures", ref_count ); + src_start( &s, p, asf, size ); + CHECK( mav_connect( p, size ) == MAV_OK, "%s: connect", codec ); + CHECK( mav_stream_count( p ) == 2 && mav_stream_info( p, 0, &vi ) == MAV_OK && mav_stream_info( p, 1, &ai ) == MAV_OK, "two streams" ); + CHECK( vi.type == MAV_STREAM_VIDEO && vi.kind == MAV_CODEC_WMV && !strcmp( vi.container, "asf" ) + && !strcmp( vi.backend, "libavcodec" ) && !strcmp( vi.codec, codec ) && vi.vnative.fmt == MAV_PIX_NV12 + && vi.vnative.width == W && vi.vnative.height == H && vi.vnative.fps_n * 1 == FPS * vi.vnative.fps_d, + "video info: %s %s %s %dx%d %u/%u", vi.codec, vi.container, vi.backend, vi.vnative.width, vi.vnative.height, + vi.vnative.fps_n, vi.vnative.fps_d ); + CHECK( ai.type == MAV_STREAM_AUDIO && ai.kind == MAV_CODEC_WMA && ai.version == 2 && ai.native.rate == RATE + && ai.native.channels == 2 && ai.native.fmt == MAV_FMT_S16 && ai.block_align > 0 && ai.codec_data_len > 0, + "audio info: v%u %u Hz %u ch align %u", ai.version, ai.native.rate, ai.native.channels, ai.block_align ); + CHECK( llabs( (long long)vi.info_duration_check_dummy_never ) >= 0, "" ); + /* every picture, NV12, in order, bit-exact against the reference */ + while (mav_get_buffer( p, 0, &b ) == MAV_OK) + { + if (!n) pts0 = b.pts; + CHECK( b.stream == 0 && pts0 < 1000000 && llabs( (long long)(b.pts - pts0) - (long long)n * 10000000 / FPS ) <= 10000, + "picture %d pts %llu (first %lld)", n, (unsigned long long)b.pts, (long long)pts0 ); + CHECK( mav_copy_buffer( p, 0, pic, 0, b.size ) == MAV_OK, "copy" ); + if (check_picture( pic, b.size, MAV_PIX_NV12, 0, n, "nv12" )) return 1; + mav_release_buffer( p, 0 ); n++; + } + CHECK( n == FRAMES, "%s: %d pictures, want %d", codec, n, FRAMES ); + src_stop( &s ); mav_destroy( p ); free( pic ); + printf( "PASS: %s in ASF: %d pictures, bit-exact NV12 against libavcodec, in order at 40 ms steps; WMA2 stream described\n", codec, n ); + (void)ao; + return 0; +} +""" +# a placeholder check slipped into the template above is removed here (keeps the C valid) +harness = harness.replace(' CHECK( llabs( (long long)vi.info_duration_check_dummy_never ) >= 0, "" );\n', '') + +harness += r""" +/* The WM reader's way: video BGR bottom-up, audio S16, both enabled, earliest-buffer reads to the end. */ +static int test_wm_reader( const uint8_t *asf, size_t size ) +{ + struct mav_parser *p = mav_create( 0 ); struct source s; struct mav_stream_info vi; struct mav_buffer b; + uint8_t *buf = malloc( 1 << 20 ); int pictures = 0; int64_t samples = 0, last_a = -1, last_v = -1; double sq = 0; + + src_start( &s, p, asf, size ); + CHECK( mav_connect( p, size ) == MAV_OK && mav_stream_info( p, 0, &vi ) == MAV_OK, "connect" ); + { + struct mav_video_output o = vi.vnative; o.fmt = MAV_PIX_BGR; o.height = -H; + CHECK( mav_enable_video( p, 0, &o ) == MAV_OK, "BGR bottom-up (wm_reader.c's default)" ); + CHECK( mav_enable( p, 1, &(struct mav_output){ MAV_FMT_S16, RATE, 2, 3 } ) == MAV_OK, "S16 (wm_reader.c's default)" ); + CHECK( mav_seek( p, 0, 1, 0, 0, 0 ) == MAV_OK, "seek to 0 (wm_reader.c after enabling)" ); + } + while (mav_get_buffer( p, -1, &b ) == MAV_OK) + { + CHECK( b.size <= (1 << 20) && mav_copy_buffer( p, b.stream, buf, 0, b.size ) == MAV_OK, "copy" ); + if (b.stream == 0) + { + CHECK( (int64_t)b.pts > last_v, "video pts goes forward" ); last_v = b.pts; + if (pictures % 17 == 0 && check_picture( buf, b.size, MAV_PIX_BGR, 1, pictures, "bgr bottom-up" )) return 1; + pictures++; + } + else + { + int k; const int16_t *pcm = (const int16_t *)buf; + CHECK( (int64_t)b.pts >= last_a, "audio pts goes forward" ); last_a = b.pts; + for (k = 0; k < (int)(b.size / 2); k++) sq += (double)pcm[k] * pcm[k]; + samples += b.size / 4; + } + mav_release_buffer( p, b.stream ); + } + CHECK( pictures == FRAMES, "%d pictures", pictures ); + CHECK( llabs( samples - (int64_t)RATE * FRAMES / FPS ) < 4096, "%lld audio frames", (long long)samples ); + CHECK( sqrt( sq / (samples * 2) ) > 4000, "the tone is there" ); + src_stop( &s ); mav_destroy( p ); free( buf ); + printf( "PASS: the WM reader's way: BGR bottom-up + S16, earliest-buffer reads: %d pictures (checked within 1), " + "%.2f s of WMA2 audio (rms %.0f)\n", pictures, (double)samples / RATE, sqrt( sq / (samples * 2) ) ); + return 0; +} + +static int test_formats( const uint8_t *asf, size_t size ) +{ + static const struct { enum mav_pixel_format fmt; int flip; const char *name; } fmts[] = + { + /* wm_reader.c's video_formats[], then I420 / RGBA / BGRA */ + { MAV_PIX_NV12, 0, "nv12" }, { MAV_PIX_YV12, 0, "yv12" }, { MAV_PIX_YUY2, 0, "yuy2" }, { MAV_PIX_UYVY, 0, "uyvy" }, + { MAV_PIX_YVYU, 0, "yvyu" }, { MAV_PIX_BGRx, 1, "bgrx bottom-up" }, { MAV_PIX_BGR, 1, "bgr bottom-up" }, + { MAV_PIX_RGB16, 1, "rgb16 bottom-up" }, { MAV_PIX_RGB15, 1, "rgb15 bottom-up" }, + { MAV_PIX_I420, 0, "i420" }, { MAV_PIX_RGBA, 0, "rgba" }, { MAV_PIX_BGRA, 0, "bgra" }, { MAV_PIX_BGR, 0, "bgr" }, + }; + struct mav_parser *p = mav_create( 0 ); struct source s; struct mav_stream_info vi; unsigned int i; + uint8_t *pic = malloc( W * H * 4 ); + + src_start( &s, p, asf, size ); + CHECK( mav_connect( p, size ) == MAV_OK && mav_stream_info( p, 0, &vi ) == MAV_OK, "connect" ); + mav_disable( p, 1 ); + for (i = 0; i < sizeof(fmts) / sizeof(fmts[0]); i++) + { + struct mav_video_output o = vi.vnative; struct mav_buffer b; + int target = 23; /* not a keyframe: decoded from 20, trimmed to 23 */ + o.fmt = fmts[i].fmt; o.height = fmts[i].flip ? -H : H; + CHECK( mav_enable_video( p, 0, &o ) == MAV_OK, "enable %s", fmts[i].name ); + CHECK( mav_seek( p, 0, 1, (uint64_t)(pts0 + (int64_t)target * 10000000 / FPS), 0, 0 ) == MAV_OK, "seek" ); + CHECK( mav_get_buffer( p, 0, &b ) == MAV_OK, "get %s", fmts[i].name ); + CHECK( llabs( (long long)(b.pts - pts0) - (long long)target * 10000000 / FPS ) <= 10000, "%s: first pts after the seek %llu", + fmts[i].name, (unsigned long long)b.pts ); + CHECK( mav_copy_buffer( p, 0, pic, 0, b.size ) == MAV_OK, "copy" ); + if (check_picture( pic, b.size, fmts[i].fmt, fmts[i].flip, target, fmts[i].name )) return 1; + mav_release_buffer( p, 0 ); + } + src_stop( &s ); mav_destroy( p ); free( pic ); + printf( "PASS: every format wm_reader.c offers (nv12 yv12 yuy2 uyvy yvyu bgrx bgr rgb16 rgb15) and i420 rgba bgra, " + "checked against the reference after a keyframe seek with exact trim\n" ); + return 0; +} + +static int test_garbage_wmv3( const uint8_t *asf, size_t size ) +{ + struct mav_parser *p = mav_create( 0 ); struct source s; struct mav_buffer b; int got = 0; + struct timespec t0, t1; + + src_start( &s, p, asf, size ); + clock_gettime( CLOCK_MONOTONIC, &t0 ); + if (mav_connect( p, size ) == MAV_OK) + while (mav_get_buffer( p, 0, &b ) == MAV_OK) { got++; mav_release_buffer( p, 0 ); } + clock_gettime( CLOCK_MONOTONIC, &t1 ); + CHECK( t1.tv_sec - t0.tv_sec < 10, "ends, does not hang" ); + src_stop( &s ); mav_destroy( p ); + printf( "PASS: a WMV3 stream of undecodable data ends without a crash (%d pictures out)\n", got ); + return 0; +} + +/* ================= back-pressure, small limits ================= */ +struct reader { struct mav_parser *p; int stream, delay_us, count; volatile int done; pthread_t thread; }; +static void *reader_thread( void *arg ) +{ + struct reader *r = arg; struct mav_buffer b; + while (mav_get_buffer( r->p, r->stream, &b ) == MAV_OK) + { + mav_release_buffer( r->p, r->stream ); r->count++; + if (r->delay_us) usleep( r->delay_us ); + } + r->done = 1; + return NULL; +} + +static int test_backpressure( const uint8_t *asf, size_t size ) +{ + struct mav_parser *p; struct source s; struct reader v, a; struct timespec t0, t1; int waited; + + /* 1. two threads, video slow: nothing dropped, every picture delivered */ + p = mav_create( 0 ); src_start( &s, p, asf, size ); + CHECK( mav_connect( p, size ) == MAV_OK, "connect" ); + v = (struct reader){ p, 0, 3000 }; a = (struct reader){ p, 1, 0 }; + pthread_create( &v.thread, NULL, reader_thread, &v ); + pthread_create( &a.thread, NULL, reader_thread, &a ); + pthread_join( a.thread, NULL ); pthread_join( v.thread, NULL ); + CHECK( v.count == FRAMES, "slow video reader: %d pictures of %d", v.count, FRAMES ); + CHECK( a.count > 0, "audio" ); + src_stop( &s ); mav_destroy( p ); + printf( "BP1 %d %d\n", v.count, a.count ); + + /* 2. video enabled and never read: the audio reader waits once, then reads to the end */ + p = mav_create( 0 ); src_start( &s, p, asf, size ); + CHECK( mav_connect( p, size ) == MAV_OK, "connect" ); + a = (struct reader){ p, 1, 0 }; + clock_gettime( CLOCK_MONOTONIC, &t0 ); + reader_thread( &a ); + clock_gettime( CLOCK_MONOTONIC, &t1 ); + CHECK( a.count > 0 && (t1.tv_sec - t0.tv_sec) * 1000 + (t1.tv_nsec - t0.tv_nsec) / 1000000 < 3 * MAV_BACKPRESSURE_WAIT_MS, + "audio alone finished in time" ); + src_stop( &s ); mav_destroy( p ); + + /* 3. one thread, both streams (earliest-buffer mode): it never waits for itself */ + p = mav_create( 0 ); src_start( &s, p, asf, size ); + CHECK( mav_connect( p, size ) == MAV_OK, "connect" ); + { + struct mav_buffer b; int n = 0; + clock_gettime( CLOCK_MONOTONIC, &t0 ); + while (mav_get_buffer( p, -1, &b ) == MAV_OK) { mav_release_buffer( p, b.stream ); n += b.stream == 0; } + clock_gettime( CLOCK_MONOTONIC, &t1 ); + CHECK( n == FRAMES && (t1.tv_sec - t0.tv_sec) * 1000 + (t1.tv_nsec - t0.tv_nsec) / 1000000 < MAV_BACKPRESSURE_WAIT_MS, + "earliest-buffer mode: %d pictures, no wait", n ); + } + src_stop( &s ); mav_destroy( p ); + + /* 4. disconnect while a reader waits: it is woken, nothing is freed under it */ + p = mav_create( 0 ); src_start( &s, p, asf, size ); + CHECK( mav_connect( p, size ) == MAV_OK, "connect" ); + a = (struct reader){ p, 1, 0 }; + pthread_create( &a.thread, NULL, reader_thread, &a ); + for (waited = 0; waited < 200; waited++) + { + unsigned int w; + pthread_mutex_lock( &p->lock ); w = p->bp_waiters; pthread_mutex_unlock( &p->lock ); + if (w) break; + usleep( 1000 ); + } + CHECK( waited < 200, "the audio reader waits for the unread video stream" ); + clock_gettime( CLOCK_MONOTONIC, &t0 ); + src_stop( &s ); + pthread_join( a.thread, NULL ); + clock_gettime( CLOCK_MONOTONIC, &t1 ); + CHECK( a.done && (t1.tv_sec - t0.tv_sec) * 1000 + (t1.tv_nsec - t0.tv_nsec) / 1000000 < MAV_BACKPRESSURE_WAIT_MS, + "disconnect woke the waiting reader at once" ); + mav_destroy( p ); + printf( "PASS: back-pressure (soft %d packets, hard %d): a slow video reader on its own thread gets all %d pictures; " + "an unread stream holds the other reader once (%d ms) and no longer; one thread reading both never waits; " + "disconnect wakes a waiting reader\n", MAV_QUEUE_SOFT_PACKETS, MAV_QUEUE_MAX_PACKETS, FRAMES, + MAV_BACKPRESSURE_WAIT_MS ); + return 0; +} + +int main( int argc, char **argv ) +{ + size_t n2, n1, n3, ng; + uint8_t *wmv2, *wmv1, *mp43, *garbage; + + alarm( 120 ); + setvbuf( stdout, NULL, _IONBF, 0 ); + av_log_set_level( AV_LOG_ERROR ); /* the test encoders' warnings */ + mav_configure( 1, NULL, NULL, MAV_PIX_NV12 ); /* no platform backend: Windows Media video needs none */ + wmv2 = make_asf( AV_CODEC_ID_WMV2, 1, &n2 ); + CHECK( wmv2, "make the wmv2 file" ); + if (argc > 1 && !strcmp( argv[1], "bp" )) + { + if (test_backpressure( wmv2, n2 )) return 1; + free( wmv2 ); free( ref_frames ); + return failures != 0; + } + wmv1 = make_asf( AV_CODEC_ID_WMV1, 1, &n1 ); + mp43 = make_asf( AV_CODEC_ID_MSMPEG4V3, 1, &n3 ); + garbage = make_asf( AV_CODEC_ID_NONE, 0, &ng ); + CHECK( wmv1 && mp43 && garbage, "make the other files" ); + CHECK( mav_lavc_supports( MAV_LAVC_WMV3 ) && mav_lavc_supports( MAV_LAVC_VC1 ), "WMV9 / VC-1 decoders are built" ); + if (test_wmv( wmv2, n2, "wmv2" ) || test_wm_reader( wmv2, n2 ) || test_formats( wmv2, n2 )) return 1; + if (test_wmv( wmv1, n1, "wmv1" ) || test_wmv( mp43, n3, "msmpeg4v3" ) || test_garbage_wmv3( garbage, ng )) return 1; + free( wmv2 ); free( wmv1 ); free( mp43 ); free( garbage ); free( ref_frames ); + return failures != 0; +} +""" + +TAG = "[wg-parser] ml1990 " +with tempfile.TemporaryDirectory() as t: + c = Path(t) / "asf.c"; c.write_text(harness) + base = ["cc", "-std=gnu11", "-O1", "-g", "-Wall", "-Wno-unused-function", "-fsanitize=address,undefined", + "-fno-sanitize-recover=undefined", "-I" + str(core.parent), "-I" + str(inc), str(c)] + libs = [str(lib / "libavformat.a"), str(lib / "libavcodec.a"), str(lib / "libswresample.a"), + str(lib / "libavutil.a"), "-lm", "-lpthread"] + exe, bp = Path(t) / "asf", Path(t) / "asf-bp" + subprocess.run(base + ["-o", str(exe)] + libs, check=True) + small = ["-DMAV_QUEUE_SOFT_PACKETS=8", "-DMAV_QUEUE_SOFT_BYTES=65536", "-DMAV_QUEUE_MAX_PACKETS=16", + "-DMAV_BACKPRESSURE_WAIT_MS=400"] + subprocess.run(base + small + ["-o", str(bp)] + libs, check=True) + env = {k: v for k, v in os.environ.items() if not k.startswith("MADEIRA_")} + env["ASAN_OPTIONS"] = "detect_leaks=1" + + out = subprocess.run([str(exe)], env=env, capture_output=True, text=True, timeout=300) + print(out.stdout, end="") + assert out.returncode == 0, out.stdout + out.stderr[-4000:] + lines = [l for l in out.stderr.splitlines() if l.startswith(TAG)] + assert any("connect container=asf stream=0 video codec=wmv2 backend=libavcodec 320x240 fps=25/1 out=nv12" in l for l in lines), lines + assert any("connect container=asf codec=wmav2" in l and "rate=44100 channels=2" in l and "backend=libavcodec" in l for l in lines), lines + assert any("video codec=wmv1 backend=libavcodec" in l for l in lines) and any("video codec=msmpeg4v3 backend=libavcodec" in l for l in lines), lines + assert any("wmv3" in l and ("packet rejected" in l or "undecodable" in l or "connect refused" in l) for l in lines), lines + assert not any("dropping further packets" in l for l in lines), lines + assert "ERROR: AddressSanitizer" not in out.stderr and "runtime error" not in out.stderr, out.stderr[-4000:] + + out = subprocess.run([str(bp), "bp"], env=env, capture_output=True, text=True, timeout=300) + print(out.stdout.replace("BP1 ", " (slow video, fast audio: pictures, audio buffers) "), end="") + assert out.returncode == 0, out.stdout + out.stderr[-4000:] + bp_lines = [l for l in out.stderr.splitlines() if l.startswith(TAG)] + # case 1 (two readers) drops nothing; case 2 (video never read) marks it unread once, then drops past the hard limit + first = out.stderr[:out.stderr.index("not read for")] if "not read for" in out.stderr else out.stderr + assert "dropping further packets" not in first, "a packet was dropped while both streams were read:\n" + first[-3000:] + assert sum("stream 0: not read for 400 ms while stream 1 reads ahead" in l for l in bp_lines) >= 1, bp_lines + assert "ERROR: AddressSanitizer" not in out.stderr and "runtime error" not in out.stderr, out.stderr[-4000:] + + # the same two-reader case WITHOUT back-pressure (soft limit above the hard one) does drop: + # the case the change is for + nobp = Path(t) / "asf-nobp" + subprocess.run(base + ["-DMAV_QUEUE_SOFT_PACKETS=100000", "-DMAV_QUEUE_SOFT_BYTES=((size_t)1<<40)", + "-DMAV_QUEUE_MAX_PACKETS=16", "-DMAV_BACKPRESSURE_WAIT_MS=400", "-o", str(nobp)] + libs, check=True) + out = subprocess.run([str(nobp), "bp"], env=env, capture_output=True, text=True, timeout=300) + assert "dropping further packets" in out.stderr and "FAIL test_backpressure" in out.stdout and "slow video reader" in out.stdout, \ + out.stdout + out.stderr[-2000:] + print("PASS: without back-pressure the same slow-video case drops packets and loses pictures (%s)" % + re.search(r"slow video reader: \d+ pictures of \d+", out.stdout).group(0)) + for l in lines + bp_lines: + print(" " + l) diff --git a/tests/host/check-wg-parser.py b/tests/host/check-wg-parser.py index 6b1beac92f..b25abfff9b 100644 --- a/tests/host/check-wg-parser.py +++ b/tests/host/check-wg-parser.py @@ -723,7 +723,9 @@ def table(name): switch (fmt) { case MAV_PIX_NV12: case MAV_PIX_I420: case MAV_PIX_YV12: CHECK( l.stride[0] == ((W + 3) & ~3) && size == W * H * 3 / 2, "%s stride", what ); break; - case MAV_PIX_YUY2: CHECK( l.stride[0] == ((W * 2 + 3) & ~3), "%s stride", what ); break; + case MAV_PIX_YUY2: case MAV_PIX_UYVY: case MAV_PIX_YVYU: case MAV_PIX_RGB15: case MAV_PIX_RGB16: + CHECK( l.stride[0] == ((W * 2 + 3) & ~3), "%s stride", what ); break; + case MAV_PIX_BGR: CHECK( l.stride[0] == ((W * 3 + 3) & ~3), "%s stride", what ); break; default: CHECK( l.stride[0] == W * 4, "%s stride", what ); break; } for (y = 0; y < H; y++) @@ -751,6 +753,40 @@ def table(name): CHECK( buf[ry * l.stride[0] + 2 * x] == Y && buf[ry * l.stride[0] + 4 * (x / 2) + 1] == U && buf[ry * l.stride[0] + 4 * (x / 2) + 3] == V, "%s YUY2(%d,%d)", what, x, y ); break; + case MAV_PIX_UYVY: /* U0 Y0 V0 Y1 */ + CHECK( buf[ry * l.stride[0] + 4 * (x / 2) + 1 + 2 * (x & 1)] == Y && buf[ry * l.stride[0] + 4 * (x / 2)] == U + && buf[ry * l.stride[0] + 4 * (x / 2) + 2] == V, "%s UYVY(%d,%d)", what, x, y ); + break; + case MAV_PIX_YVYU: /* Y0 V0 Y1 U0 */ + CHECK( buf[ry * l.stride[0] + 2 * x] == Y && buf[ry * l.stride[0] + 4 * (x / 2) + 3] == U + && buf[ry * l.stride[0] + 4 * (x / 2) + 1] == V, "%s YVYU(%d,%d)", what, x, y ); + break; + case MAV_PIX_BGR: case MAV_PIX_RGB15: case MAV_PIX_RGB16: + { + double yy = 1.164383 * (Y - 16), r = yy + 1.596027 * (V - 128), + g = yy - 0.391762 * (U - 128) - 0.812968 * (V - 128), b = yy + 2.017232 * (U - 128); + int rr = (int)lround( fmin( 255, fmax( 0, r ) ) ), rg = (int)lround( fmin( 255, fmax( 0, g ) ) ), + rb = (int)lround( fmin( 255, fmax( 0, b ) ) ); + if (fmt == MAV_PIX_BGR) + { + const uint8_t *px = buf + ry * l.stride[0] + 3 * x; + int er = abs( px[2] - rr ), eg = abs( px[1] - rg ), eb = abs( px[0] - rb ); + if (er > maxerr) maxerr = er; + if (eg > maxerr) maxerr = eg; + if (eb > maxerr) maxerr = eb; + } + else + { + /* little-endian 16 bits; a component within one step of the 8-bit reference's */ + unsigned px = buf[ry * l.stride[0] + 2 * x] | buf[ry * l.stride[0] + 2 * x + 1] << 8; + int six = fmt == MAV_PIX_RGB16; + int R5 = six ? px >> 11 : (px >> 10) & 31, G = six ? (px >> 5) & 63 : (px >> 5) & 31, B5 = px & 31; + CHECK( six || !(px & 0x8000), "%s: x bit set", what ); + CHECK( abs( R5 - (rr >> 3) ) <= 1 && abs( G - (six ? rg >> 2 : rg >> 3) ) <= 1 && abs( B5 - (rb >> 3) ) <= 1, + "%s (%d,%d): %04x for %d %d %d", what, x, y, px, rr, rg, rb ); + } + break; + } default: { /* BT.601, limited range: the untagged, sub-720-line default */ @@ -917,6 +953,9 @@ def table(name): { MAV_PIX_NV12, 0, "nv12" }, { MAV_PIX_I420, 0, "i420" }, { MAV_PIX_YV12, 0, "yv12" }, { MAV_PIX_YUY2, 0, "yuy2" }, { MAV_PIX_BGRx, 0, "bgrx" }, { MAV_PIX_BGRA, 0, "bgra" }, { MAV_PIX_RGBA, 0, "rgba" }, { MAV_PIX_BGRx, 1, "bgrx bottom-up" }, { MAV_PIX_NV12, 1, "nv12 bottom-up" }, + /* the WM reader's (wm_reader.c): bottom-up BGR by default, and the others it offers */ + { MAV_PIX_BGR, 1, "bgr bottom-up" }, { MAV_PIX_BGR, 0, "bgr" }, { MAV_PIX_UYVY, 0, "uyvy" }, { MAV_PIX_YVYU, 0, "yvyu" }, + { MAV_PIX_RGB16, 1, "rgb16 bottom-up" }, { MAV_PIX_RGB15, 1, "rgb15 bottom-up" }, }; struct mav_parser *p = mav_create( 0 ); struct source s; struct mav_stream_info vi; unsigned int i; @@ -940,12 +979,13 @@ def table(name): o.width = W / 2; CHECK( mav_enable_video( p, 0, &o ) == MAV_E_PARAM, "another size refused (no scaler)" ); CHECK( mav_get_buffer( p, 0, &(struct mav_buffer){0} ) == MAV_NO_BUFFER, "refused stream is disabled" ); - o = vi.vnative; o.fmt = (enum mav_pixel_format)3; /* BGR: not produced here */ + o = vi.vnative; o.fmt = (enum mav_pixel_format)7; /* AYUV: not produced here */ CHECK( mav_enable_video( p, 0, &o ) == MAV_E_PARAM, "unsupported pixel format refused" ); CHECK( mav_enable( p, 0, &(struct mav_output){ MAV_FMT_S16, 44100, 2, 3 } ) == MAV_E_STATE, "audio enable on video refused" ); } src_stop( &s ); mav_destroy( p ); - printf( "PASS: mp4 picture formats pixel-checked: nv12 i420 yv12 yuy2 bgrx bgra rgba (BT.601 within 1), bottom-up bgrx/nv12; " + printf( "PASS: mp4 picture formats pixel-checked: nv12 i420 yv12 yuy2 uyvy yvyu bgrx bgra rgba bgr (BT.601 within 1), " + "rgb16 rgb15 (within one step), bottom-up bgrx/nv12/bgr/rgb16/rgb15; " "other sizes and formats refused\n" ); return 0; } From 440e48731bcda51fd032b4b8d932cde04709b3b3 Mon Sep 17 00:00:00 2001 From: allen Date: Sun, 22 Nov 2026 05:35:45 +0800 Subject: [PATCH 3/9] winegstreamer iOS: report RGB32 video by default, so the EVR gets surfaces DXMT has Senren Banka's CG movie (32-bit; MP4, H.264 1080p + AAC, played by krkrz's MFPlayer through a media session with the EVR and the SAR) left a white video window and the story never went on. The parser connected both streams, and nothing ever asked it for a sample. The media session connects a source to its renderer with the source's current type only, and that is the native format the unix side reports: NV12. The EVR accepts it (dxva2's processor service lists NV12 without asking the device), and the session then asks the EVR's sample allocator for two NV12 Direct3D 9 surfaces for the sample copier it puts in front of the EVR. DXMT's d3d9 maps no YUV format to Metal, so CreateOffscreenPlainSurface fails and the allocator does too. session_append_node then fails the EVR's output node, and session_collect_nodes stops there: the EVR node and every node after it are missing (the audio branch included). The EVR still gets the clock, and with no rate set the session skips preroll. It reports MESessionStarted with no output node to request samples for. The audio renderer never gets the clock, and the game waits for a movie that never ends. The device log fits every step: the parser connected; topology_loader_Load and dxva2's FIXMEs appear; the EVR's sample tracking thread and the presenter's streaming thread (only MFVP_MESSAGE_BEGINSTREAMING, i.e. the clock start, creates it) were created; the SAR's audio client was created but never started (no timer thread); the media threads used no CPU; the read thread sat in wgp_get_next_read_offset; and the parser logged no error. RGB32 is now the default native format. DXMT has RGB32 surfaces, so the allocator and the copier work on ordinary surfaces. (The mixer's stretch into its window-sized target still needs a render target; the DXVA2 change later in this series makes one.) media_source.c still lists NV12, YV12, YUY2, I420 and IYUV after the native type, so a source reader that asks for NV12 still gets it (and one that asks for RGB32 no longer needs a converter this port does not have). The cost is converting each picture from NV12 to BGRx on the CPU. MADEIRA_WG_VIDEO_FORMAT=nv12 restores the old default. Each stream now logs one line when its first buffer is handed out, so a device log tells a stream nobody asked for from one that fails to decode. tests/host/check-wg-parser.py: asserts the default and the new lines; passes. Wine pin: willfaust/wine `mf/session: Keep an output node whose sample allocator cannot be initialized`, so a renderer whose allocator does fail keeps its output node (and its branch) instead of silently losing everything after it. Co-Authored-By: Claude Opus 5.5 Signed-off-by: allen --- build/ntdll-unix/wg_parser_av_ios.c | 18 ++++++++++++- build/ntdll-unix/winegstreamer_unixlib_ios.c | 28 +++++++++++++++----- docs/MEDIA.md | 19 ++++++++++++- tests/host/check-wg-parser.py | 7 +++++ wine | 2 +- 5 files changed, 64 insertions(+), 10 deletions(-) diff --git a/build/ntdll-unix/wg_parser_av_ios.c b/build/ntdll-unix/wg_parser_av_ios.c index 8e54158e6f..fd9f08252b 100644 --- a/build/ntdll-unix/wg_parser_av_ios.c +++ b/build/ntdll-unix/wg_parser_av_ios.c @@ -664,6 +664,7 @@ struct mav_stream int64_t next_pts; /* 100 ns */ int64_t seek_target; /* 100 ns, -1 = none */ unsigned int decode_errors, errors_logged; + int delivered; /* a buffer has been handed out (logged once) */ }; struct mav_parser @@ -2478,7 +2479,22 @@ static int mav_get_buffer( struct mav_parser *p, int stream, struct mav_buffer * } status = s ? MAV_OK : MAV_NO_BUFFER; } - if (status == MAV_OK) *buffer = s->cur; + if (status == MAV_OK) + { + *buffer = s->cur; + /* One line per stream, so a device log tells a stream nobody asked + * for (a renderer the media session dropped) from one that fails to + * decode. */ + if (!s->delivered) + { + s->delivered = 1; + if (s->type == MAV_STREAM_VIDEO) + mav_log( "stream %u: first picture delivered (%s %dx%d)", s->number, mav_pix_name( s->vout.fmt ), + s->vout.width, s->vout.height ); + else + mav_log( "stream %u: first audio buffer delivered", s->number ); + } + } /* a queue may have shrunk, or a stream ended: a waiter re-checks */ if (p->bp_waiters) pthread_cond_broadcast( &p->drain_cond ); pthread_mutex_unlock( &p->lock ); diff --git a/build/ntdll-unix/winegstreamer_unixlib_ios.c b/build/ntdll-unix/winegstreamer_unixlib_ios.c index 48ca3b38a8..53b1add2c4 100644 --- a/build/ntdll-unix/winegstreamer_unixlib_ios.c +++ b/build/ntdll-unix/winegstreamer_unixlib_ios.c @@ -2186,10 +2186,24 @@ static NTSTATUS wma_transform_notify_qos( void *args ) * AudioToolbox, wg_parser_apple_ios.c). MADEIRA_WG_VIDEO=0 restores the * ml1980 MP3/WAV-only behaviour (an MP4 is refused at connect). * MADEIRA_WG_VIDEO_FORMAT=nv12|i420|yv12|yuy2|rgb32|argb32|abgr32 picks the - * native format a video stream reports (default nv12: what the hardware - * decoder produces, and the first format media_source.c offers anyway); only - * the native format and media_source.c's YUV list become media types, so a - * consumer that insists on RGB can be served by choosing it here. + * native format a video stream reports. Only the native format and + * media_source.c's YUV list (NV12, YV12, YUY2, I420, IYUV) become media types. + * + * The default is rgb32, not the nv12 the hardware decoder produces. A media + * session resolves a source -> renderer branch with the source's current type + * only, and that is the native one. With nv12 the EVR accepts it (dxva2's + * processor service lists NV12 without asking the device), and the session + * then asks the EVR's sample allocator for NV12 Direct3D 9 surfaces. This + * port's d3d9 (DXMT) has no YUV surface format, so the allocator fails, and + * session.c drops the renderer's output node and every node after it + * (session_collect_nodes stops at the first failure). The session still + * reports itself started. Nothing is requested from the source, the audio + * renderer never gets the clock, and the title shows an empty video window + * until it is killed: Senren Banka's 32-bit CG movie (MP4, H.264 1080p + AAC, + * through krkrz's MFPlayer: media session, EVR, SAR). RGB32 surfaces are + * plain DXMT surfaces, and the YUV list still serves a consumer (a source + * reader) that asks for NV12. The cost is the NV12 -> BGRx conversion of + * each picture on the CPU. nv12 restores the previous default. * * A parser has up to MAV_MAX_STREAMS streams. Each stream handle is a * separate object inside the parser so a parser handle passed as a stream @@ -2247,11 +2261,11 @@ static enum mav_pixel_format wg_video_native_format(void) const char *v = getenv( "MADEIRA_WG_VIDEO_FORMAT" ); unsigned int i; - if (!v || !*v) return MAV_PIX_NV12; + if (!v || !*v) return MAV_PIX_BGRx; /* rgb32: see above */ for (i = 0; i < ARRAY_SIZE(names); i++) if (!strcasecmp( v, names[i].name )) return names[i].fmt; - mav_log( "MADEIRA_WG_VIDEO_FORMAT=%.16s is not one of nv12/i420/yv12/yuy2/rgb32/argb32/abgr32; using nv12", v ); - return MAV_PIX_NV12; + mav_log( "MADEIRA_WG_VIDEO_FORMAT=%.16s is not one of nv12/i420/yv12/yuy2/rgb32/argb32/abgr32; using rgb32", v ); + return MAV_PIX_BGRx; } static pthread_once_t wgp_config_once = PTHREAD_ONCE_INIT; diff --git a/docs/MEDIA.md b/docs/MEDIA.md index add1f5dcd3..073518f968 100644 --- a/docs/MEDIA.md +++ b/docs/MEDIA.md @@ -53,6 +53,23 @@ backend reports: WMV1/WMV2/WMV3/WMVA/WVC1 video, WMA audio with its version, block alignment and codec data, so a game that reads the file's profile through `IWMProfile` sees the real stream types. +**The video format a stream reports: RGB32.** A video stream's native format +(the media type Media Foundation's source lists first) is RGB32 by default, +although VideoToolbox decodes to NV12 and the picture is converted on the CPU. +A media session connects a source straight to its renderer with that native +type only. The EVR accepts NV12, and the session then asks the EVR's sample +allocator for NV12 Direct3D 9 surfaces. DXMT, this port's d3d9, has no YUV +surface format, so the allocator fails. The session then drops the renderer's +output node and every node after it, and still reports that playback +started. No sample is ever requested, the audio renderer never starts, and the +title shows an empty video window. Senren Banka's CG movie did this (an MP4 +through krkrz's MFPlayer; the workaround was `MADEIRA_WG_VIDEO=0`, which skips +the movie). RGB32 surfaces are ordinary DXMT surfaces. A source reader that +asks for NV12 still gets it from the YUV types listed after the native one. +`MADEIRA_WG_VIDEO_FORMAT=nv12` restores the old default. Each stream logs +`stream N: first picture delivered` (or `first audio buffer delivered`) once, +so a device log shows whether any sample was ever requested. + **One demuxer, several readers: back-pressure.** Each stream is read on its own thread by quartz and Media Foundation; a packet read for another stream is queued for it. A stream whose reader falls behind (a video decoded slower @@ -83,7 +100,7 @@ Environment variables (`env.NAME = value` in `madeira.cfg`): | `MADEIRA_WG_64BIT` | WMA only | `0`: 64-bit processes get the stub table again; `1`: their `wg_parser` too (see above). | | `MADEIRA_WG_PARSER` | on | `0`: `wg_parser_create` returns `STATUS_NOT_IMPLEMENTED` again, as before this series; quartz and the MF source then fail the way they did. The WMA decoder is unaffected. | | `MADEIRA_WG_VIDEO` | on | `0`: MP3/WAV only; an MP4/MOV or ASF is refused at connect. | -| `MADEIRA_WG_VIDEO_FORMAT` | `nv12` | Native format a video stream reports: `nv12`, `i420`, `yv12`, `yuy2`, `rgb32`, `argb32` or `abgr32`. | +| `MADEIRA_WG_VIDEO_FORMAT` | `rgb32` | Native format a video stream reports: `nv12`, `i420`, `yv12`, `yuy2`, `rgb32`, `argb32` or `abgr32` (see above for why the default is `rgb32`). | | `MADEIRA_WMA_SEARCH` | on | `0`: keep the WMA v1/v2 decoder at the bit rate and flags it opened with; no search over other candidates when a bit-reservoir stream fails. A packet that fails is concealed with silence of its length and the next one is decoded as usual. (An xWMA stream still opens at the rate libavformat's xWMA table normalises to.) | | `MADEIRA_WMA_DUMP` | off | Set: write each WMA decoder's input to `wma-dump-.bin` in the Documents folder, for reproducing a decode failure on a host. | diff --git a/tests/host/check-wg-parser.py b/tests/host/check-wg-parser.py index b25abfff9b..2bf8981d36 100644 --- a/tests/host/check-wg-parser.py +++ b/tests/host/check-wg-parser.py @@ -92,6 +92,11 @@ def table(name): configure = configure[:configure.index("\n}\n")] assert 'getenv( "MADEIRA_WG_VIDEO" )' in glue and "wg_video_switch_on()" in configure assert "mav_configure( video, &mav_apple_video_backend, &mav_apple_audio_backend, native )" in configure +# rgb32 by default: the media session connects a source to its renderer with the native type only, +# and DXMT has no YUV Direct3D 9 surface for the EVR's sample allocator (see the glue) +native_fn = glue[glue.index("static enum mav_pixel_format wg_video_native_format(void)"):] +native_fn = native_fn[:native_fn.index("\n}\n")] +assert "if (!v || !*v) return MAV_PIX_BGRx;" in native_fn and native_fn.rstrip().endswith("return MAV_PIX_BGRx;"), native_fn assert '#include "wg_parser_av_ios.c"' in glue csrc = core.read_text() assert '#define MAV_TAG "[wg-parser] ml1990 "' in csrc and "#define MAV_MAX_LOGS 64" in csrc @@ -1281,6 +1286,8 @@ def build(out, defines=()): assert any("connect refused" in l and "no enabled demuxer recognised the stream" in l for l in lines), lines assert any("connect container=mp4 stream=0 video codec=h264 backend=stub-video 320x240 fps=30/1 out=nv12" in l for l in lines), lines assert any("connect container=mp4 codec=aac layer=0 rate=44100 channels=2 mask=0x3 out=f32" in l and "stream=1 backend=stub-aac" in l for l in lines), lines + assert any(l.endswith("stream 0: first picture delivered (nv12 320x240)") for l in lines), lines + assert any(l.endswith("stream 1: first audio buffer delivered") for l in lines), lines assert any("connect refused (mov,mp4,m4a,3gp,3g2,mj2, compressed_out=0): container disabled by MADEIRA_WG_VIDEO=0" in l for l in lines), lines assert any("connect refused (mov,mp4,m4a,3gp,3g2,mj2, compressed_out=1): compressed output requested" in l for l in lines), lines assert any("video codec h264 (codec id 27" in l and "stub: unexpected codec data" in l for l in lines), lines diff --git a/wine b/wine index ddf92babc5..18689a0897 160000 --- a/wine +++ b/wine @@ -1 +1 @@ -Subproject commit ddf92babc5ba71f4586cc4713f5a8eb39f63d39b +Subproject commit 18689a08977f6b0756788f63c9c6f6a7f7c76e81 From 0a703bf10b92e56600553b94b1edf41765258135 Mon Sep 17 00:00:00 2001 From: allen Date: Sun, 22 Nov 2026 05:38:07 +0800 Subject: [PATCH 4/9] winegstreamer iOS: a WMV video decoder for the WMVideo Decoder DMO Wine's WMVideo Decoder DMO and MFT (CLSID_CWMVDecMediaObject, wmv_decoder_create() in dlls/winegstreamer/video_decoder.c) is a wg_transform, and this port refused every video transform. KiriKiri's movie plugin decodes the WM reader's compressed WMV samples with that DMO (Sabbat of the Witch's video CGs). The transform decodes WMV1, WMV2, WMV3, WMVA and WVC1 with libavcodec (the parser's mav_lavc_video) and writes each picture with the parser's converter (mav_convert_picture now takes the output description instead of a stream): NV12, YV12, I420/IYUV, YUY2, UYVY, YVYU, RGB32, ARGB32, ABGR32, RGB24, RGB565 and RGB555, top-down or bottom-up, in upstream's layout or an MF 2D buffer's stride, with apertures honoured. It follows wg_transform.c: push queues up to input_queue_length + 1 frames, read decodes until one picture comes out, each picture keeps the timestamps of the sample it was coded in, and drain, flush, get_status and the output type work as there. The DMO's construction probe (WMV3 without a sequence header) creates a transform that drops its input, as GStreamer would. Transforms are now kinds in one table (transform_kinds[]): create goes to the first kind that claims the input type, and every other entry finds the kind by the magic its object starts with. The WMA decoder's functions are renamed for it (wma_create, wma_push_data, ...), and the unix entries are wg_transform_*. MADEIRA_WG_WMV_TRANSFORM=0 refuses video transforms again. tests/host/check-wmv-transform.py: WMV1 and WMV2 bit-exact against libavcodec, all 13 output formats both ways up at both layouts, apertures, timestamps, the queue limit, drain, flush, output type changes, a buffer too small, the DMO wrapper's loop, two threads, refusals, the WMV3/WVC1/WMVA plumbing, the wow64 thunks, WMA through the same dispatch, and the switch. Co-Authored-By: Claude Opus 5.5 Signed-off-by: allen --- app/Madeira/ConfigCatalog.generated.swift | 1 + build/ntdll-unix/wg_parser_av_ios.c | 50 +- build/ntdll-unix/winegstreamer_unixlib_ios.c | 1622 +++++++++++++++--- build/tools/gen-config-catalog.py | 3 + docs/MEDIA.md | 79 +- tests/host/check-wma-decoder.py | 10 +- tests/host/check-wmv-transform.py | 1305 ++++++++++++++ 7 files changed, 2768 insertions(+), 302 deletions(-) create mode 100644 tests/host/check-wmv-transform.py diff --git a/app/Madeira/ConfigCatalog.generated.swift b/app/Madeira/ConfigCatalog.generated.swift index effb09af84..1145b9dfb4 100644 --- a/app/Madeira/ConfigCatalog.generated.swift +++ b/app/Madeira/ConfigCatalog.generated.swift @@ -403,6 +403,7 @@ extension ConfigCatalog { ConfigOption(key: "env.MADEIRA_WG_PARSER", title: "", kind: .text, defaultValue: "", category: "Media", note: "", choices: [], sources: ["build/ntdll-unix/winegstreamer_unixlib_ios.c"]), ConfigOption(key: "env.MADEIRA_WG_VIDEO", title: "Media: MP4 video (32-bit programs)", kind: .text, defaultValue: "", category: "Media", note: "0 limits the media parser to MP3/WAV; by default MP4 with H.264/HEVC video decodes through VideoToolbox.", choices: [], sources: ["build/ntdll-unix/winegstreamer_unixlib_ios.c"]), ConfigOption(key: "env.MADEIRA_WG_VIDEO_FORMAT", title: "", kind: .text, defaultValue: "", category: "Media", note: "", choices: [], sources: ["build/ntdll-unix/winegstreamer_unixlib_ios.c"]), + ConfigOption(key: "env.MADEIRA_WG_WMV_TRANSFORM", title: "Media: WMV video decoder", kind: .text, defaultValue: "", category: "Media", note: "0 refuses every video transform again, as before: the WMVideo Decoder DMO and MFT cannot be created. By default they decode WMV1/2/3, WMVA and WVC1 with libavcodec. WMA is unaffected.", choices: [], sources: ["build/ntdll-unix/winegstreamer_unixlib_ios.c"]), ConfigOption(key: "env.MADEIRA_WMA_DUMP", title: "", kind: .text, defaultValue: "", category: "Media", note: "", choices: [], sources: ["build/ntdll-unix/winegstreamer_unixlib_ios.c"]), ConfigOption(key: "env.MADEIRA_WMA_SEARCH", title: "", kind: .text, defaultValue: "", category: "Media", note: "ml1120: MADEIRA_WMA_SEARCH=0 pins the decoder to the rate and flags this file worked out from the media type alone, which is what shipped before the ladder. A packet it cannot decode is then concealed with silence of that packet's length...", choices: [], sources: ["build/ntdll-unix/winegstreamer_unixlib_ios.c"]), ConfigOption(key: "arena-mb", title: "", kind: .int, defaultValue: "0", category: "Memory & JIT pool", note: "ml1095: madeira.cfg arena-mb = N", choices: [], sources: ["build/ntdll-unix/virtual_ios.c"]), diff --git a/build/ntdll-unix/wg_parser_av_ios.c b/build/ntdll-unix/wg_parser_av_ios.c index fd9f08252b..e6075e825f 100644 --- a/build/ntdll-unix/wg_parser_av_ios.c +++ b/build/ntdll-unix/wg_parser_av_ios.c @@ -2168,18 +2168,22 @@ static void mav_yuv_coefs( int bt709, int full, struct mav_yuv_coefs *c ) c->yoff = full ? 0 : 16; } -/* Writes one decoded 4:2:0 bi-planar picture into `dst` in s->vout's format - * and layout. A picture smaller than the output is padded with black; a - * larger one is cropped (the codec's cropping is the decoder's business). */ -static void mav_convert_picture( struct mav_stream *s, const struct mav_vplanes *src, uint8_t *dst, - const struct mav_layout *l ) -{ - uint32_t w = s->vout.width, h = s->vout.height < 0 ? -s->vout.height : s->vout.height; +/* Writes one decoded 4:2:0 bi-planar picture into `dst` in `vout`'s format + * and layout, converting to RGB with the BT.709 matrix if `bt709`, else + * BT.601. A picture smaller than the output is padded with black; a larger + * one is cropped (the codec's cropping is the decoder's business). It takes + * the output description rather than a stream so that the wg_transform's WMV + * decoder (winegstreamer_unixlib_ios.c) writes its pictures with the same + * code. */ +static void mav_convert_picture( const struct mav_video_output *vout, int bt709, const struct mav_vplanes *src, + uint8_t *dst, const struct mav_layout *l ) +{ + uint32_t w = vout->width, h = vout->height < 0 ? -vout->height : vout->height; uint32_t cw = src->width < w ? src->width : w, ch = src->height < h ? src->height : h; uint32_t ccw = (cw + 1) / 2, cch = (ch + 1) / 2, x, y; - int flip = s->vout.height < 0; - int planar = s->vout.fmt == MAV_PIX_NV12 || s->vout.fmt == MAV_PIX_I420 || s->vout.fmt == MAV_PIX_YV12; - int packed = s->vout.fmt == MAV_PIX_YUY2 || s->vout.fmt == MAV_PIX_UYVY || s->vout.fmt == MAV_PIX_YVYU; + int flip = vout->height < 0; + int planar = vout->fmt == MAV_PIX_NV12 || vout->fmt == MAV_PIX_I420 || vout->fmt == MAV_PIX_YV12; + int packed = vout->fmt == MAV_PIX_YUY2 || vout->fmt == MAV_PIX_UYVY || vout->fmt == MAV_PIX_YVYU; if (cw < w || ch < h) { @@ -2188,13 +2192,13 @@ static void mav_convert_picture( struct mav_stream *s, const struct mav_vplanes for (y = 0; y < h; y++) for (x = 0; x < l->stride[0] / 4; x++) memcpy( dst + (size_t)y * l->stride[0] + x * 4, - s->vout.fmt == MAV_PIX_UYVY ? "\x80\x10\x80\x10" : "\x10\x80\x10\x80", 4 ); + vout->fmt == MAV_PIX_UYVY ? "\x80\x10\x80\x10" : "\x10\x80\x10\x80", 4 ); else if (planar) { memset( dst, 16, l->offset[1] ); memset( dst + l->offset[1], 128, l->size - l->offset[1] ); } - else if (s->vout.fmt == MAV_PIX_BGR || s->vout.fmt == MAV_PIX_RGB15 || s->vout.fmt == MAV_PIX_RGB16) + else if (vout->fmt == MAV_PIX_BGR || vout->fmt == MAV_PIX_RGB15 || vout->fmt == MAV_PIX_RGB16) memset( dst, 0, l->size ); else for (y = 0; y < h; y++) @@ -2203,7 +2207,7 @@ static void mav_convert_picture( struct mav_stream *s, const struct mav_vplanes } #define DST_ROW(plane, row, rows) (dst + l->offset[plane] + (size_t)l->stride[plane] * (flip ? (rows) - 1 - (row) : (row))) - switch (s->vout.fmt) + switch (vout->fmt) { case MAV_PIX_NV12: for (y = 0; y < ch; y++) memcpy( DST_ROW( 0, y, h ), src->y + (size_t)y * src->y_stride, cw ); @@ -2212,7 +2216,7 @@ static void mav_convert_picture( struct mav_stream *s, const struct mav_vplanes case MAV_PIX_I420: case MAV_PIX_YV12: { - int u_plane = s->vout.fmt == MAV_PIX_I420 ? 1 : 2, v_plane = 3 - u_plane; + int u_plane = vout->fmt == MAV_PIX_I420 ? 1 : 2, v_plane = 3 - u_plane; for (y = 0; y < ch; y++) memcpy( DST_ROW( 0, y, h ), src->y + (size_t)y * src->y_stride, cw ); for (y = 0; y < cch; y++) { @@ -2231,9 +2235,9 @@ static void mav_convert_picture( struct mav_stream *s, const struct mav_vplanes case MAV_PIX_YVYU: { /* byte offsets of Y0, U, Y1, V in each 4-byte pair */ - int y0 = s->vout.fmt == MAV_PIX_UYVY ? 1 : 0, y1 = y0 + 2; - int uo = s->vout.fmt == MAV_PIX_YUY2 ? 1 : s->vout.fmt == MAV_PIX_UYVY ? 0 : 3; - int vo = s->vout.fmt == MAV_PIX_YUY2 ? 3 : s->vout.fmt == MAV_PIX_UYVY ? 2 : 1; + int y0 = vout->fmt == MAV_PIX_UYVY ? 1 : 0, y1 = y0 + 2; + int uo = vout->fmt == MAV_PIX_YUY2 ? 1 : vout->fmt == MAV_PIX_UYVY ? 0 : 3; + int vo = vout->fmt == MAV_PIX_YUY2 ? 3 : vout->fmt == MAV_PIX_UYVY ? 2 : 1; for (y = 0; y < ch; y++) { const uint8_t *yr = src->y + (size_t)y * src->y_stride, *uv = src->uv + (size_t)(y / 2) * src->uv_stride; @@ -2253,8 +2257,8 @@ static void mav_convert_picture( struct mav_stream *s, const struct mav_vplanes case MAV_PIX_RGBA: { struct mav_yuv_coefs c; - int ri = s->vout.fmt == MAV_PIX_RGBA ? 0 : 2, bi = 2 - ri; - mav_yuv_coefs( s->bt709, src->full_range, &c ); + int ri = vout->fmt == MAV_PIX_RGBA ? 0 : 2, bi = 2 - ri; + mav_yuv_coefs( bt709, src->full_range, &c ); for (y = 0; y < ch; y++) { const uint8_t *yr = src->y + (size_t)y * src->y_stride, *uv = src->uv + (size_t)(y / 2) * src->uv_stride; @@ -2276,7 +2280,7 @@ static void mav_convert_picture( struct mav_stream *s, const struct mav_vplanes case MAV_PIX_RGB16: { struct mav_yuv_coefs c; - mav_yuv_coefs( s->bt709, src->full_range, &c ); + mav_yuv_coefs( bt709, src->full_range, &c ); for (y = 0; y < ch; y++) { const uint8_t *yr = src->y + (size_t)y * src->y_stride, *uv = src->uv + (size_t)(y / 2) * src->uv_stride; @@ -2288,7 +2292,7 @@ static void mav_convert_picture( struct mav_stream *s, const struct mav_vplanes uint8_t r = mav_clip8( (yy + c.rv * v) >> 16 ); uint8_t g = mav_clip8( (yy - c.gu * u - c.gv * v) >> 16 ); uint8_t b = mav_clip8( (yy + c.bu * u) >> 16 ); - if (s->vout.fmt == MAV_PIX_BGR) + if (vout->fmt == MAV_PIX_BGR) { o[3 * x] = b; o[3 * x + 1] = g; @@ -2296,7 +2300,7 @@ static void mav_convert_picture( struct mav_stream *s, const struct mav_vplanes } else { - uint16_t px = s->vout.fmt == MAV_PIX_RGB16 + uint16_t px = vout->fmt == MAV_PIX_RGB16 ? (uint16_t)((r >> 3) << 11 | (g >> 2) << 5 | b >> 3) : (uint16_t)((r >> 3) << 10 | (g >> 3) << 5 | b >> 3); o[2 * x] = (uint8_t)px; @@ -2359,7 +2363,7 @@ static int mav_video_emit( struct mav_parser *p, struct mav_stream *s, struct ma s->discontinuity = 1; return 0; } - mav_convert_picture( s, &planes, s->buf, &l ); + mav_convert_picture( &s->vout, s->bt709, &planes, s->buf, &l ); s->vbackend->unmap( f->handle ); s->vbackend->release( f->handle ); diff --git a/build/ntdll-unix/winegstreamer_unixlib_ios.c b/build/ntdll-unix/winegstreamer_unixlib_ios.c index 53b1add2c4..2f9c187362 100644 --- a/build/ntdll-unix/winegstreamer_unixlib_ios.c +++ b/build/ntdll-unix/winegstreamer_unixlib_ios.c @@ -40,14 +40,16 @@ * port does not implement -- an index that drifts from the header silently * dispatches one call to another function's argument block. * - * What is implemented is the wg_transform subset that wma_decoder.c uses: - * create / destroy / push_data / read_data / get_output_type / - * set_output_type / drain / flush / get_status (+ notify_qos as a no-op, and - * wg_init_gstreamer as a benign success so main.c's init_gstreamer_proc lets - * the DLL load). The wg_muxer side returns STATUS_NOT_IMPLEMENTED. Those - * callers already handle a component that is not available; what they must - * never get is a success with an untouched output field (no fake - * success). + * What is implemented is the wg_transform subset that wma_decoder.c and + * video_decoder.c's WMV decoder use: create / destroy / push_data / + * read_data / get_output_type / set_output_type / drain / flush / get_status + * (+ notify_qos as a no-op, and wg_init_gstreamer as a benign success so + * main.c's init_gstreamer_proc lets the DLL load), for two kinds of + * transform: WMA audio (below) and WMV video (the section "the WMV decoder"; + * "transform kinds" after it is how a call finds its kind). The wg_muxer + * side returns STATUS_NOT_IMPLEMENTED. Those callers already handle a + * component that is not available; what they must never get is a success + * with an untouched output field (no fake success). * * ml1980: the wg_parser side (quartz's splitters, and the same pull protocol * for the MF media source) is implemented for AUDIO files only -- MP3 (and @@ -59,11 +61,12 @@ * wg_parser_apple_ios.c) for the Media Foundation source; MADEIRA_WG_VIDEO=0 * restores the MP3/WAV-only parser. * - * wg_transform_create also REFUSES anything that is not a WMA family stream. - * winegstreamer's other transforms (aac, h264, wmv, the resampler, the colour - * converter) are real GStreamer pipelines with no libavcodec replacement here, - * and a transform that accepts an H.264 stream and then emits nothing is worse - * for the caller than one that never opened. + * wg_transform_create also REFUSES anything that is neither a WMA family + * stream nor Windows Media video (WMV1/WMV2/WMV3/WMVA/WVC1). winegstreamer's + * other transforms (aac, h264, the resampler, the colour converter) are real + * GStreamer pipelines with no replacement here, and a transform that accepts + * an H.264 stream and then emits nothing is worse for the caller than one + * that never opened. MADEIRA_WG_WMV_TRANSFORM=0 refuses the WMV one too. * * DECODING * -------- @@ -506,10 +509,15 @@ static int wma_diag_on( void ) static unsigned int wma_av_log_count; +/* The WMV transform's decoders are opened by the wg_parser core's backend and + * then marked with this instead of MAV_DECODER_MARKER (wmv_create). */ +static const char wmv_decoder_marker; +#define WMV_DECODER_MARKER ((void *)&wmv_decoder_marker) + /* ml1980: the same callback serves the wg_parser core, whose demuxer and * decoder contexts are told apart by their class (the demuxer / its I/O) or * by the marker the core leaves in AVCodecContext.opaque, so a parser - * diagnostic is not reported as a WMA one. One cap for both. */ + * diagnostic is not reported as a WMA one. One cap for all of them. */ static const char *av_log_owner( void *avcl ) { const AVClass *cls = avcl ? *(const AVClass **)avcl : NULL; @@ -520,6 +528,9 @@ static const char *av_log_owner( void *avcl ) if (!strcmp( cls->class_name, "AVCodecContext" ) && ((AVCodecContext *)avcl)->opaque == MAV_DECODER_MARKER) return "[wg-parser] av:"; + if (!strcmp( cls->class_name, "AVCodecContext" ) + && ((AVCodecContext *)avcl)->opaque == WMV_DECODER_MARKER) + return "[wmv] av:"; return "[wma] av:"; } @@ -551,7 +562,7 @@ static void wma_install_av_log(void) av_log_set_callback( wma_av_log ); } -static struct wma_transform *get_transform( wg_transform_t handle ) +static struct wma_transform *get_wma_transform( wg_transform_t handle ) { struct wma_transform *transform = (struct wma_transform *)(UINT_PTR)handle; @@ -1607,7 +1618,7 @@ static void report_failures( struct wma_transform *transform ) /*********************************************************************** * wg_transform_create */ -static NTSTATUS transform_create( struct wg_transform_create_params *params ) +static NTSTATUS wma_create( struct wg_transform_create_params *params ) { const WAVEFORMATEX *in = audio_format( ¶ms->input_type ); const WAVEFORMATEX *out = audio_format( ¶ms->output_type ); @@ -1622,8 +1633,8 @@ static NTSTATUS transform_create( struct wg_transform_create_params *params ) if (!in || !out) { - /* Video, or a malformed block: winegstreamer's other transforms live - * here too and this port has no replacement for them. */ + /* A malformed block, or an output that is not audio: transform_create + * hands this kind audio inputs only. */ return STATUS_NOT_SUPPORTED; } @@ -1788,9 +1799,9 @@ static NTSTATUS transform_create( struct wg_transform_create_params *params ) return (NTSTATUS)err; } -static NTSTATUS transform_destroy( wg_transform_t handle ) +static NTSTATUS wma_destroy( wg_transform_t handle ) { - struct wma_transform *transform = get_transform( handle ); + struct wma_transform *transform = get_wma_transform( handle ); if (!transform) return STATUS_INVALID_HANDLE; @@ -1824,10 +1835,10 @@ static NTSTATUS transform_destroy( wg_transform_t handle ) * aligns them to 8 like the host does -- so the OUT fields are written through * the caller's own struct. */ -static NTSTATUS transform_push_data( wg_transform_t handle, struct wg_sample *sample, - const void *data, HRESULT *result ) +static NTSTATUS wma_push_data( wg_transform_t handle, struct wg_sample *sample, + const void *data, HRESULT *result ) { - struct wma_transform *transform = get_transform( handle ); + struct wma_transform *transform = get_wma_transform( handle ); NTSTATUS status; if (!transform || !sample) return STATUS_INVALID_HANDLE; @@ -1895,10 +1906,10 @@ static NTSTATUS transform_push_data( wg_transform_t handle, struct wg_sample *sa return status ? status : STATUS_SUCCESS; } -static NTSTATUS transform_read_data( wg_transform_t handle, struct wg_sample *sample, - void *data, HRESULT *result ) +static NTSTATUS wma_read_data( wg_transform_t handle, struct wg_sample *sample, + void *data, HRESULT *result ) { - struct wma_transform *transform = get_transform( handle ); + struct wma_transform *transform = get_wma_transform( handle ); size_t avail, copy, frames; if (!transform || !sample) return STATUS_INVALID_HANDLE; @@ -1962,9 +1973,9 @@ static NTSTATUS transform_read_data( wg_transform_t handle, struct wg_sample *sa /*********************************************************************** * output type */ -static NTSTATUS transform_get_output_type( wg_transform_t handle, struct wg_media_type *type ) +static NTSTATUS wma_get_output_type( wg_transform_t handle, struct wg_media_type *type ) { - struct wma_transform *transform = get_transform( handle ); + struct wma_transform *transform = get_wma_transform( handle ); UINT32 size; if (!transform) return STATUS_INVALID_HANDLE; @@ -1987,9 +1998,9 @@ static NTSTATUS transform_get_output_type( wg_transform_t handle, struct wg_medi return STATUS_SUCCESS; } -static NTSTATUS transform_set_output_type( wg_transform_t handle, const struct wg_media_type *type ) +static NTSTATUS wma_set_output_type( wg_transform_t handle, const struct wg_media_type *type ) { - struct wma_transform *transform = get_transform( handle ); + struct wma_transform *transform = get_wma_transform( handle ); const WAVEFORMATEX *out = audio_format( type ); enum AVSampleFormat sample_fmt; AVChannelLayout layout = {0}; @@ -2035,81 +2046,22 @@ static NTSTATUS transform_set_output_type( wg_transform_t handle, const struct w } /*********************************************************************** - * the unix call entries + * the WMA kind's remaining entries */ -static NTSTATUS wma_init( void *args ) -{ - struct wg_init_gstreamer_params *params = args; - - /* Benign success: main.c's init_gstreamer_proc() fails the whole DLL if - * this fails, and everything this port implements is below it. */ - (void)params; - return STATUS_SUCCESS; -} - -static NTSTATUS wma_not_implemented( void *args ) -{ - (void)args; - return STATUS_NOT_IMPLEMENTED; -} - -static NTSTATUS wma_transform_create( void *args ) -{ - return transform_create( args ); -} - -static NTSTATUS wma_transform_destroy( void *args ) -{ - return transform_destroy( *(wg_transform_t *)args ); -} - -static NTSTATUS wma_transform_get_output_type( void *args ) -{ - struct wg_transform_get_output_type_params *params = args; - return transform_get_output_type( params->transform, ¶ms->media_type ); -} - -static NTSTATUS wma_transform_set_output_type( void *args ) -{ - struct wg_transform_set_output_type_params *params = args; - return transform_set_output_type( params->transform, ¶ms->media_type ); -} - -static NTSTATUS wma_transform_push_data( void *args ) -{ - struct wg_transform_push_data_params *params = args; - struct wg_sample *sample = params->sample; - - if (!sample) return STATUS_INVALID_PARAMETER; - return transform_push_data( params->transform, sample, - (const void *)(UINT_PTR)sample->data, ¶ms->result ); -} - -static NTSTATUS wma_transform_read_data( void *args ) -{ - struct wg_transform_read_data_params *params = args; - struct wg_sample *sample = params->sample; - - if (!sample) return STATUS_INVALID_PARAMETER; - return transform_read_data( params->transform, sample, - (void *)(UINT_PTR)sample->data, ¶ms->result ); -} - -static NTSTATUS wma_transform_get_status( void *args ) +static NTSTATUS wma_get_status( wg_transform_t handle, UINT32 *accepts_input ) { - struct wg_transform_get_status_params *params = args; - struct wma_transform *transform = get_transform( params->transform ); + struct wma_transform *transform = get_wma_transform( handle ); if (!transform) return STATUS_INVALID_HANDLE; pthread_mutex_lock( &transform->lock ); - params->accepts_input = (transform->pcm_len == transform->pcm_pos); + *accepts_input = (transform->pcm_len == transform->pcm_pos); pthread_mutex_unlock( &transform->lock ); return STATUS_SUCCESS; } -static NTSTATUS wma_transform_drain( void *args ) +static NTSTATUS wma_drain( wg_transform_t handle ) { - struct wma_transform *transform = get_transform( *(wg_transform_t *)args ); + struct wma_transform *transform = get_wma_transform( handle ); NTSTATUS status; if (!transform) return STATUS_INVALID_HANDLE; @@ -2137,9 +2089,9 @@ static NTSTATUS wma_transform_drain( void *args ) return status; } -static NTSTATUS wma_transform_flush( void *args ) +static NTSTATUS wma_flush( wg_transform_t handle ) { - struct wma_transform *transform = get_transform( *(wg_transform_t *)args ); + struct wma_transform *transform = get_wma_transform( handle ); if (!transform) return STATUS_INVALID_HANDLE; pthread_mutex_lock( &transform->lock ); @@ -2162,205 +2114,1333 @@ static NTSTATUS wma_transform_flush( void *args ) return STATUS_SUCCESS; } -static NTSTATUS wma_transform_notify_qos( void *args ) +/* Every audio input is this kind's to judge: wma_create refuses, and logs, a + * format tag that is not a WMA family stream, exactly as it did when it was + * the only kind. */ +static BOOL wma_claims( const struct wg_transform_create_params *params ) { - /* Quality-of-service hints only change which frames a GStreamer pipeline - * bothers to decode; an audio decoder with no frame dropping has nothing - * to do with them, and the caller ignores the status. */ - (void)args; - return STATUS_SUCCESS; + return IsEqualGUID( ¶ms->input_type.major, &madeira_MFMediaType_Audio ); } /*********************************************************************** - * wg_parser (MADEIRA ml1980, ml1990) + * the WMV decoder (MADEIRA, 2026-11-20) * - * The Wine side of wg_parser_av_ios.c: handle validation, struct wg_format / - * struct wg_parser_buffer mapping, and the HRESULTs wg_parser.c returns. - * See that file's header for the protocol and what is accepted. + * WHY THIS EXISTS + * --------------- + * Sabbat of the Witch, a 32-bit KiriKiri title, plays its cutscenes through + * krmovie.dll: compressed WMV3 samples from IWMSyncReader + * (SetReadStreamSamples), decoded by the WMVideo Decoder DMO + * (CLSID_CWMVDecMediaObject) in a DirectShow DMO-wrapper graph. In Wine + * that DMO, and its MFT face, is wmv_decoder_create() in + * dlls/winegstreamer/video_decoder.c (what upstream once had as + * wmv_decoder.c), a wg_transform user -- and this file refused every video + * transform. The DMO could not even be created (its constructor probes a + * WMV3 -> I420 transform), so the cutscenes were a white screen. The + * compressed ASF output of the parser and the reader's side are separate + * pieces; this is the decoder. * - * MADEIRA_WG_PARSER=0 restores the pre-ml1980 behaviour: create is refused - * with STATUS_NOT_IMPLEMENTED, so quartz_parser.c's parser_create() fails - * exactly as before. + * WHAT video_decoder.c DOES WITH ITS wg_transform + * ------------------------------------------------ + * create check_video_transform_support() in wmv_decoder_create(): + * WMV3 1920x1080 -> I420 with NO codec private data, created + * and destroyed at once. Then for real from the DMO's + * SetOutputType (DMO_MEDIA_TYPE -> IMFMediaType -> + * MFVIDEOFORMAT, wg_transform_create_quartz) or the MFT's. + * The VIDEOINFOHEADER's extra bytes -- the sequence header -- + * arrive as MF_MT_USER_DATA after the MFVIDEOFORMAT. attrs: + * input_queue_length 15 and preserve_timestamps; never + * allow_format_change or output_plane_align. + * set_output_type the MFT's SetOutputType once a transform exists. The + * DMO makes a new transform instead, also when the DMO + * wrapper meets a sample with a new media type (qasf + * dmowrapper.c get_output_samples), and a new transform is a + * new decoder that waits for a keyframe. + * push_data one compressed frame per sample; MF_E_NOTACCEPTING when the + * queue is full. + * read_data one whole picture into the caller's buffer: the DMO's + * IMediaBuffer (no stride) or the MFT's sample (a 2D buffer's + * pitch in wg_sample.stride). Nothing ready is + * MF_E_TRANSFORM_NEED_MORE_INPUT, which the DMO answers with + * S_FALSE and dwStatus 0. WG_SAMPLE_FLAG_INCOMPLETE would + * become DMO_OUTPUT_DATA_BUFFERF_INCOMPLETE, for which the DMO + * wrapper calls ProcessOutput again, and again: a picture is + * never split, so it is never set. + * drain, flush the MFT's COMMAND_DRAIN / COMMAND_FLUSH, the DMO's Flush. + * The DMO never drains (its Discontinuity is a no-op), so a + * picture the decoder holds back comes out only with the next + * input, as it does with GStreamer. + * get_status, get_output_type, notify_qos not used for WMV + * (get_output_type follows MF_E_TRANSFORM_STREAM_CHANGE, which + * needs allow_format_change); implemented all the same. * - * ml1990: MP4/MOV (H.264 / HEVC video on VideoToolbox, AAC audio on - * AudioToolbox, wg_parser_apple_ios.c). MADEIRA_WG_VIDEO=0 restores the - * ml1980 MP3/WAV-only behaviour (an MP4 is refused at connect). - * MADEIRA_WG_VIDEO_FORMAT=nv12|i420|yv12|yuy2|rgb32|argb32|abgr32 picks the - * native format a video stream reports. Only the native format and - * media_source.c's YUV list (NV12, YV12, YUY2, I420, IYUV) become media types. + * HOW + * --- + * The decoder is wg_parser_av_ios.c's libavcodec backend (mav_lavc_video: + * wmv1, wmv2, wmv3, vc1, one thread), and pictures are written by that + * file's mav_convert_picture, so the parser and this transform share one + * decoder setup and one set of conversions. As in wg_transform.c, push only + * queues the compressed frame and read decodes until a picture comes out: + * the queue limit counts compressed frames, and no more pictures are held + * than the decoder's own delay. * - * The default is rgb32, not the nv12 the hardware decoder produces. A media - * session resolves a source -> renderer branch with the source's current type - * only, and that is the native one. With nv12 the EVR accepts it (dxva2's - * processor service lists NV12 without asking the device), and the session - * then asks the EVR's sample allocator for NV12 Direct3D 9 surfaces. This - * port's d3d9 (DXMT) has no YUV surface format, so the allocator fails, and - * session.c drops the renderer's output node and every node after it - * (session_collect_nodes stops at the first failure). The session still - * reports itself started. Nothing is requested from the source, the audio - * renderer never gets the clock, and the title shows an empty video window - * until it is killed: Senren Banka's 32-bit CG movie (MP4, H.264 1080p + AAC, - * through krkrz's MFPlayer: media session, EVR, SAR). RGB32 surfaces are - * plain DXMT surfaces, and the YUV list still serves a consumer (a source - * reader) that asks for NV12. The cost is the NV12 -> BGRx conversion of - * each picture on the CPU. nv12 restores the previous default. + * Layout: the frame is the output MFVIDEOFORMAT's dwWidth x dwHeight in + * wg_transform.c's plane layout (wg_format_get_stride(): 4-byte aligned rows, + * except NV12 at 2), or at the stride of the caller's 2D buffer. + * MFVideoFlag_BottomUpLinearRep flips it. A MinimumDisplayAperture smaller + * than the frame is where the picture goes; the rest is left alone. A + * picture is never scaled: one of another size is cropped, or padded with + * black (GStreamer would fail to negotiate), unless the caller allowed a + * format change, in which case read_data returns + * MF_E_TRANSFORM_STREAM_CHANGE once and get_output_type the new size. * - * A parser has up to MAV_MAX_STREAMS streams. Each stream handle is a - * separate object inside the parser so a parser handle passed as a stream - * (or the reverse) is caught by the magic, not dereferenced. + * Timestamps: a picture carries the pts and duration of the sample it was + * coded in (libavcodec reorders them with the pictures), with + * WG_SAMPLE_FLAG_PRESERVE_TIMESTAMPS when the caller asked for that, which + * is what video_decoder.c relies on. A picture whose sample had no time + * follows the previous picture (the first at 0) and lasts one frame at the + * input type's frame rate (0 without one): the native DMO reports time 0 + * for a stream pushed without times. Every picture is a sync point with a + * time and a duration, as the native DMO's are. + * + * WMV3 / VC-1 WITHOUT A SEQUENCE HEADER. libavcodec cannot open wmv3 or vc1 + * without codec private data (AVERROR_INVALIDDATA, checked on the host), and + * wmv_decoder_create()'s probe has none. Refusing it would make the DMO + * impossible to create, so create succeeds with the decoder closed when the + * input type has NO codec private data, and says so; what is pushed into + * such a transform is dropped, counted and logged, and nothing comes out. + * A sequence header that is present but refused refuses create. + * + * MADEIRA_WG_WMV_TRANSFORM=0 restores the refusal of every video transform. + * Log tag "[wmv]": one line per create, capped like "[wma]". */ -#define MADEIRA_WG_PARSER_MAGIC 0x57475052 /* 'WGPR' */ -#define MADEIRA_WG_STREAM_MAGIC 0x57475354 /* 'WGST' */ +#define MADEIRA_WG_WMV_MAGIC 0x574d5644 /* 'WMVD' */ + +#define MADEIRA_WMV_MAX_LOGS 100 +#define MADEIRA_WMV_MAX_ERROR_LOGS 4 /* per transform: rejected frames */ +#define MADEIRA_WMV_MAX_CODEC_DATA (1u << 20) + +/* MFVideoFormat_RGB32 and its kin keep a D3DFORMAT in Data1; d3d9types.h is + * not included here. */ +#define WMV_D3DFMT_R8G8B8 20 +#define WMV_D3DFMT_A8R8G8B8 21 +#define WMV_D3DFMT_X8R8G8B8 22 +#define WMV_D3DFMT_R5G6B5 23 +#define WMV_D3DFMT_X1R5G5B5 24 +#define WMV_D3DFMT_A8B8G8R8 32 + +/* The 32-bit PE layout of MFVIDEOFORMAT is the host's (i686-w64-mingw32 and + * this build agree, checked with llvm-mingw), so the wow64 thunks hand the + * guest's block over in place, as they do a WAVEFORMATEX. */ +C_ASSERT( sizeof(MFVIDEOFORMAT) == 176 ); +C_ASSERT( offsetof(MFVIDEOFORMAT, videoInfo.FramesPerSecond) == 48 ); +C_ASSERT( offsetof(MFVIDEOFORMAT, videoInfo.MinimumDisplayAperture) == 76 ); +C_ASSERT( offsetof(MFVIDEOFORMAT, videoInfo.VideoFlags) == 112 ); +C_ASSERT( offsetof(MFVIDEOFORMAT, guidFormat) == 120 ); +C_ASSERT( offsetof(MFVIDEOFORMAT, surfaceInfo.Palette) == 168 ); + +static const GUID madeira_MFMediaType_Video = + { 0x73646976, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } }; + +static unsigned int wmv_log_count; + +#define WMV_LOG( fmt, ... ) \ + do { \ + unsigned int _n = __atomic_add_fetch( &wmv_log_count, 1, __ATOMIC_RELAXED ); \ + if (_n <= MADEIRA_WMV_MAX_LOGS) \ + dprintf( 2, "[wmv] " fmt, ## __VA_ARGS__ ); \ + else if (_n == MADEIRA_WMV_MAX_LOGS + 1) \ + dprintf( 2, "[wmv] further lines suppressed after %u " \ + "(MADEIRA_DIAG=1 removes the cap)\n", \ + (unsigned int)MADEIRA_WMV_MAX_LOGS ); \ + else if (wma_diag_on()) \ + dprintf( 2, "[wmv] " fmt, ## __VA_ARGS__ ); \ + } while (0) -struct wgp_parser; +struct wmv_packet +{ + BYTE *data; + UINT32 size; + UINT32 flags; /* the sample's WG_SAMPLE_FLAG_* */ + INT64 pts, duration; /* 100 ns; INT64_MIN: the sample had none */ +}; -struct wgp_stream +struct wmv_picture { - UINT32 magic; - UINT32 index; - struct wgp_parser *parser; + void *frame; /* mav_lavc_video's copy of the picture */ + INT64 pts, duration; /* as the decoder hands them back; INT64_MIN: none */ }; -struct wgp_parser +struct wmv_transform { UINT32 magic; - struct mav_parser *core; - struct wgp_stream streams[MAV_MAX_STREAMS]; + pthread_mutex_t lock; + struct wg_transform_attrs attrs; + + int codec; /* MAV_LAVC_* */ + const char *name; /* the input FourCC, for the log */ + void *dec; /* the mav_lavc_video decoder; NULL: no sequence header (see above) */ + UINT32 width, height; /* coded size, from the input type */ + INT64 frame_duration; /* 100 ns, from the input type's frame rate; 0 without one */ + int bt709; + + /* the output type exactly as it was set, and its pixel format */ + MFVIDEOFORMAT *out_format; + UINT32 out_format_size; + enum mav_pixel_format out_fmt; + + struct wmv_packet *packets; /* compressed, oldest first */ + UINT32 packet_count, packet_cap; + struct wmv_picture *pictures; /* decoded, in presentation order */ + UINT32 picture_count, picture_cap; + + BOOL draining; + BOOL discontinuity; /* the next picture is delivered with WG_SAMPLE_FLAG_DISCONTINUITY */ + INT64 next_pts; /* where a picture without a time goes */ + + /* for the log */ + UINT32 pushed, delivered, rejected, rejected_logged, dropped, lost; + BOOL size_logged, stride_logged; }; -C_ASSERT( (int)MAV_FMT_U8 == (int)WG_AUDIO_FORMAT_U8 && (int)MAV_FMT_S16 == (int)WG_AUDIO_FORMAT_S16LE - && (int)MAV_FMT_S24 == (int)WG_AUDIO_FORMAT_S24LE && (int)MAV_FMT_S32 == (int)WG_AUDIO_FORMAT_S32LE - && (int)MAV_FMT_F32 == (int)WG_AUDIO_FORMAT_F32LE && (int)MAV_FMT_F64 == (int)WG_AUDIO_FORMAT_F64LE ); -C_ASSERT( (int)MAV_PIX_BGRA == (int)WG_VIDEO_FORMAT_BGRA && (int)MAV_PIX_BGRx == (int)WG_VIDEO_FORMAT_BGRx - && (int)MAV_PIX_RGBA == (int)WG_VIDEO_FORMAT_RGBA && (int)MAV_PIX_I420 == (int)WG_VIDEO_FORMAT_I420 - && (int)MAV_PIX_NV12 == (int)WG_VIDEO_FORMAT_NV12 && (int)MAV_PIX_YUY2 == (int)WG_VIDEO_FORMAT_YUY2 - && (int)MAV_PIX_YV12 == (int)WG_VIDEO_FORMAT_YV12 && (int)MAV_PIX_BGR == (int)WG_VIDEO_FORMAT_BGR - && (int)MAV_PIX_RGB15 == (int)WG_VIDEO_FORMAT_RGB15 && (int)MAV_PIX_RGB16 == (int)WG_VIDEO_FORMAT_RGB16 - && (int)MAV_PIX_UYVY == (int)WG_VIDEO_FORMAT_UYVY && (int)MAV_PIX_YVYU == (int)WG_VIDEO_FORMAT_YVYU ); +/* MADEIRA_WG_WMV_TRANSFORM=0 refuses every video transform again, as before + * this decoder existed: the WMVideo Decoder DMO and MFT then cannot be + * created (read once). */ +static BOOL wmv_transform_switch_on(void) +{ + static int on = -1; + int v = __atomic_load_n( &on, __ATOMIC_RELAXED ); -static BOOL wg_parser_switch_on(void) + if (v < 0) + { + const char *e = getenv( "MADEIRA_WG_WMV_TRANSFORM" ); + v = !(e && e[0] == '0' && !e[1]); + __atomic_store_n( &on, v, __ATOMIC_RELAXED ); + } + return v; +} + +static struct wmv_transform *get_wmv_transform( wg_transform_t handle ) { - const char *v = getenv( "MADEIRA_WG_PARSER" ); - return !(v && v[0] == '0' && !v[1]); + struct wmv_transform *transform = (struct wmv_transform *)(UINT_PTR)handle; + + if (!transform || transform->magic != MADEIRA_WG_WMV_MAGIC) return NULL; + return transform; } -static BOOL wg_video_switch_on(void) +static const MFVIDEOFORMAT *video_format( const struct wg_media_type *type ) { - const char *v = getenv( "MADEIRA_WG_VIDEO" ); - return !(v && v[0] == '0' && !v[1]); + if (!IsEqualGUID( &type->major, &madeira_MFMediaType_Video )) return NULL; + if (!type->u.video || type->format_size < sizeof(MFVIDEOFORMAT)) return NULL; + return type->u.video; } -static enum mav_pixel_format wg_video_native_format(void) +/* For the log: a FourCC, or the subtype's first field. */ +static const char *wmv_subtype_name( const GUID *subtype, char buf[16] ) { - static const struct { const char *name; enum mav_pixel_format fmt; } names[] = - { - { "nv12", MAV_PIX_NV12 }, { "i420", MAV_PIX_I420 }, { "iyuv", MAV_PIX_I420 }, - { "yv12", MAV_PIX_YV12 }, { "yuy2", MAV_PIX_YUY2 }, { "rgb32", MAV_PIX_BGRx }, - { "argb32", MAV_PIX_BGRA }, { "abgr32", MAV_PIX_RGBA }, - }; - const char *v = getenv( "MADEIRA_WG_VIDEO_FORMAT" ); - unsigned int i; + UINT tag; + int i; - if (!v || !*v) return MAV_PIX_BGRx; /* rgb32: see above */ - for (i = 0; i < ARRAY_SIZE(names); i++) - if (!strcasecmp( v, names[i].name )) return names[i].fmt; - mav_log( "MADEIRA_WG_VIDEO_FORMAT=%.16s is not one of nv12/i420/yv12/yuy2/rgb32/argb32/abgr32; using rgb32", v ); - return MAV_PIX_BGRx; + if (madeira_subtype_tag( subtype, &tag )) + { + for (i = 0; i < 4; i++) + { + char c = (char)(tag >> (8 * i)); + if (c < 0x20 || c > 0x7e) break; + buf[i] = c; + } + if (i == 4) + { + buf[4] = 0; + return buf; + } + } + snprintf( buf, 16, "%#x", (unsigned int)subtype->Data1 ); + return buf; } -static pthread_once_t wgp_config_once = PTHREAD_ONCE_INIT; - -static void wgp_configure(void) +static int wmv_input_codec( const GUID *subtype, const char **name ) { - BOOL video = wg_video_switch_on(); - enum mav_pixel_format native = wg_video_native_format(); + UINT tag; -#ifdef __APPLE__ - mav_configure( video, &mav_apple_video_backend, &mav_apple_audio_backend, native ); - mav_log( "mp4/mov %s (MADEIRA_WG_VIDEO=0 disables): video on %s, aac on %s, native video format %s", - video ? "enabled" : "disabled", mav_apple_video_backend.name, mav_apple_audio_backend.name, - mav_pix_name( native ) ); -#else - mav_configure( FALSE, NULL, NULL, native ); -#endif + if (!madeira_subtype_tag( subtype, &tag )) return 0; + switch (tag) + { + case MAKEFOURCC('W','M','V','1'): *name = "WMV1"; return MAV_LAVC_WMV1; + case MAKEFOURCC('W','M','V','2'): *name = "WMV2"; return MAV_LAVC_WMV2; + case MAKEFOURCC('W','M','V','3'): *name = "WMV3"; return MAV_LAVC_WMV3; + case MAKEFOURCC('W','M','V','A'): *name = "WMVA"; return MAV_LAVC_VC1; + case MAKEFOURCC('W','V','C','1'): *name = "WVC1"; return MAV_LAVC_VC1; + default: return 0; + } } -static struct wgp_parser *get_wgp_parser( wg_parser_t handle ) +/* The uncompressed formats video_decoder.c offers for WMV that GStreamer + * could produce too (wg_media_type.c subtype_to_gst_video_format): NV11 and + * RGB8 are refused there, and here. */ +static enum mav_pixel_format wmv_output_format( const GUID *subtype ) { - struct wgp_parser *parser = (struct wgp_parser *)(UINT_PTR)handle; + UINT tag; - if (!parser || parser->magic != MADEIRA_WG_PARSER_MAGIC) return NULL; - return parser; + if (!madeira_subtype_tag( subtype, &tag )) return MAV_PIX_UNKNOWN; + switch (tag) + { + case MAKEFOURCC('N','V','1','2'): return MAV_PIX_NV12; + case MAKEFOURCC('Y','V','1','2'): return MAV_PIX_YV12; + case MAKEFOURCC('I','4','2','0'): + case MAKEFOURCC('I','Y','U','V'): return MAV_PIX_I420; + case MAKEFOURCC('Y','U','Y','2'): return MAV_PIX_YUY2; + case MAKEFOURCC('U','Y','V','Y'): return MAV_PIX_UYVY; + case MAKEFOURCC('Y','V','Y','U'): return MAV_PIX_YVYU; + case WMV_D3DFMT_X8R8G8B8: return MAV_PIX_BGRx; + case WMV_D3DFMT_A8R8G8B8: return MAV_PIX_BGRA; + case WMV_D3DFMT_A8B8G8R8: return MAV_PIX_RGBA; + case WMV_D3DFMT_R8G8B8: return MAV_PIX_BGR; + case WMV_D3DFMT_R5G6B5: return MAV_PIX_RGB16; + case WMV_D3DFMT_X1R5G5B5: return MAV_PIX_RGB15; + default: return MAV_PIX_UNKNOWN; + } } -static struct wgp_parser *get_wgp_stream( wg_parser_stream_t handle, UINT32 *index ) +/* The codec private data: the MF_MT_USER_DATA bytes that + * MFCreateMFVideoFormatFromMFMediaType appends, after the palette if there + * is one (mfplat reads them back the same way). */ +static const BYTE *video_user_data( const MFVIDEOFORMAT *format, UINT32 format_size, UINT32 *size ) { - struct wgp_stream *stream = (struct wgp_stream *)(UINT_PTR)handle; + UINT64 start = sizeof(*format); - if (!stream || stream->magic != MADEIRA_WG_STREAM_MAGIC) return NULL; - if (!stream->parser || stream->parser->magic != MADEIRA_WG_PARSER_MAGIC) return NULL; - if (stream->index >= MAV_MAX_STREAMS || &stream->parser->streams[stream->index] != stream) return NULL; - *index = stream->index; - return stream->parser; + if (format->surfaceInfo.PaletteEntries) + start = offsetof( MFVIDEOFORMAT, surfaceInfo.Palette ) + + ((UINT64)format->surfaceInfo.PaletteEntries + 1) * sizeof(MFPaletteEntry); + *size = start < format_size ? format_size - (UINT32)start : 0; + return *size ? (const BYTE *)format + start : NULL; } -/* The HRESULTs wg_parser.c / quartz_parser.c expect. */ -static NTSTATUS wgp_status( int status ) +/* Makes `type` the output, keeping a verbatim copy for get_output_type. A + * frame size of 0 means the coded size. */ +static NTSTATUS wmv_set_output( struct wmv_transform *transform, const struct wg_media_type *type ) { - switch (status) + const MFVIDEOFORMAT *out = video_format( type ); + enum mav_pixel_format fmt; + MFVIDEOFORMAT *copy; + + if (!out || (fmt = wmv_output_format( &out->guidFormat )) == MAV_PIX_UNKNOWN) return STATUS_NOT_SUPPORTED; + if (out->videoInfo.dwWidth > MAV_MAX_DIMENSION || out->videoInfo.dwHeight > MAV_MAX_DIMENSION) + return STATUS_NOT_SUPPORTED; + if (!(copy = malloc( type->format_size ))) return STATUS_NO_MEMORY; + memcpy( copy, out, type->format_size ); + if (!copy->videoInfo.dwWidth || !copy->videoInfo.dwHeight) { - case MAV_OK: return S_OK; - case MAV_NO_BUFFER: return S_FALSE; - case MAV_E_STATE: return VFW_E_WRONG_STATE; - case MAV_E_UNSUPPORTED: return VFW_E_UNSUPPORTED_STREAM; - case MAV_E_NOMEM: return E_OUTOFMEMORY; - case MAV_E_PARAM: return STATUS_INVALID_PARAMETER; - case MAV_E_IO: - default: return E_FAIL; + copy->videoInfo.dwWidth = transform->width; + copy->videoInfo.dwHeight = transform->height; } + free( transform->out_format ); + transform->out_format = copy; + transform->out_format_size = type->format_size; + transform->out_fmt = fmt; + return STATUS_SUCCESS; } -static void wgp_format_from_output( struct wg_format *format, const struct mav_output *out ) +/* mav_lavc_video hands decoded pictures back through this, in presentation + * order. */ +static void wmv_emit( void *ctx, void *frame, int64_t pts, int64_t duration ) { - memset( format, 0, sizeof(*format) ); - format->major_type = WG_MAJOR_TYPE_AUDIO; - format->u.audio.format = out->fmt; - format->u.audio.channels = out->channels; - format->u.audio.channel_mask = out->channel_mask; - format->u.audio.rate = out->rate; + struct wmv_transform *transform = ctx; + + if (transform->picture_count == transform->picture_cap) + { + UINT32 cap = transform->picture_cap ? transform->picture_cap * 2 : 4; + struct wmv_picture *grown = realloc( transform->pictures, cap * sizeof(*grown) ); + + if (!grown) + { + mav_lavc_release( frame ); + transform->lost++; + transform->discontinuity = TRUE; + return; + } + transform->pictures = grown; + transform->picture_cap = cap; + } + transform->pictures[transform->picture_count].frame = frame; + transform->pictures[transform->picture_count].pts = pts; + transform->pictures[transform->picture_count].duration = duration; + transform->picture_count++; } -static void wgp_format_from_video( struct wg_format *format, const struct mav_video_output *out ) +static void wmv_pop_picture( struct wmv_transform *transform ) { - memset( format, 0, sizeof(*format) ); - format->major_type = WG_MAJOR_TYPE_VIDEO; - format->u.video.format = out->fmt; - format->u.video.width = out->width; - format->u.video.height = out->height; - format->u.video.fps_n = out->fps_n; - format->u.video.fps_d = out->fps_d; + mav_lavc_release( transform->pictures[0].frame ); + memmove( transform->pictures, transform->pictures + 1, + (transform->picture_count - 1) * sizeof(*transform->pictures) ); + transform->picture_count--; } -static NTSTATUS wgp_create( void *args ) +static void wmv_decode_packet( struct wmv_transform *transform, const struct wmv_packet *packet ) { - struct wg_parser_create_params *params = args; - struct wgp_parser *parser; - unsigned int i; + int err; - if (!wg_parser_switch_on()) + if (packet->flags & WG_SAMPLE_FLAG_DISCONTINUITY) transform->discontinuity = TRUE; + /* An empty packet would tell libavcodec the stream has ended. */ + if (!packet->size) return; + if (!transform->dec) { - static int once; - if (!__atomic_exchange_n( &once, 1, __ATOMIC_RELAXED )) - mav_log( "disabled by MADEIRA_WG_PARSER=0; parser creation refused" ); - return STATUS_NOT_IMPLEMENTED; + if (!transform->dropped++) + WMV_LOG( "transform %p: no %s decoder (the input type had no sequence header); " + "dropping what is pushed\n", transform, transform->name ); + return; } - pthread_once( &wma_av_log_once, wma_install_av_log ); - pthread_once( &wgp_config_once, wgp_configure ); - if (!(parser = calloc( 1, sizeof(*parser) ))) return E_OUTOFMEMORY; - if (!(parser->core = mav_create( params->output_compressed ))) + err = mav_lavc_decode( transform->dec, packet->data, packet->size, packet->pts, packet->duration, + !!(packet->flags & WG_SAMPLE_FLAG_SYNC_POINT), wmv_emit, transform ); + if (err < 0) { - free( parser ); - return E_OUTOFMEMORY; + transform->rejected++; + transform->discontinuity = TRUE; + if (transform->rejected_logged < MADEIRA_WMV_MAX_ERROR_LOGS) + { + transform->rejected_logged++; + WMV_LOG( "transform %p: %s frame of %u bytes rejected by the decoder (%u so far)\n", + transform, transform->name, packet->size, transform->rejected ); + } + } +} + +/* The end of the stream: what the decoder holds back. After it the decoder + * takes frames again only once flushed. */ +static void wmv_complete_drain( struct wmv_transform *transform ) +{ + transform->draining = FALSE; + if (!transform->dec) return; + mav_lavc_drain( transform->dec, wmv_emit, transform ); + mav_lavc_flush( transform->dec ); +} + +static void wmv_decode_until_picture( struct wmv_transform *transform ) +{ + while (!transform->picture_count && transform->packet_count) + { + struct wmv_packet packet = transform->packets[0]; + + memmove( transform->packets, transform->packets + 1, + (transform->packet_count - 1) * sizeof(*transform->packets) ); + transform->packet_count--; + wmv_decode_packet( transform, &packet ); + free( packet.data ); + } + /* wg_transform.c sends its end of stream once the last queued input has + * gone into the decoder. */ + if (transform->draining && !transform->packet_count) wmv_complete_drain( transform ); +} + +static void wmv_report( struct wmv_transform *transform, const char *when ) +{ + if (!transform->pushed && !transform->lost) return; + WMV_LOG( "%s: transform %p, %s: %u frames in, %u pictures out, %u rejected by the decoder, " + "%u dropped without a decoder, %u lost to memory\n", when, transform, transform->name, + transform->pushed, transform->delivered, transform->rejected, transform->dropped, transform->lost ); +} + +/*********************************************************************** + * where a picture goes in the caller's buffer + */ +struct wmv_geometry +{ + struct mav_video_output vout; /* what is written: format, size; height < 0: bottom-up */ + struct mav_layout frame; /* the whole frame's planes */ + struct mav_layout layout; /* the same, moved to the picture's region */ + UINT32 region_w, region_h; /* the region: the aperture, or the whole frame */ + BOOL covers; /* the picture fills its region */ +}; + +/* Bytes per pixel of the first plane. */ +static UINT32 wmv_pixel_bytes( enum mav_pixel_format fmt ) +{ + switch (fmt) + { + case MAV_PIX_NV12: + case MAV_PIX_I420: + case MAV_PIX_YV12: return 1; + case MAV_PIX_YUY2: + case MAV_PIX_UYVY: + case MAV_PIX_YVYU: + case MAV_PIX_RGB15: + case MAV_PIX_RGB16: return 2; + case MAV_PIX_BGR: return 3; + default: return 4; + } +} + +static BOOL wmv_geometry( struct wmv_transform *transform, const struct mav_vplanes *picture, UINT32 stride, + struct wmv_geometry *g ) +{ + const MFVideoInfo *info = &transform->out_format->videoInfo; + const MFVideoArea *aperture = &info->MinimumDisplayAperture; + enum mav_pixel_format fmt = transform->out_fmt; + BOOL planar = fmt == MAV_PIX_NV12 || fmt == MAV_PIX_I420 || fmt == MAV_PIX_YV12; + BOOL subsampled = planar || fmt == MAV_PIX_YUY2 || fmt == MAV_PIX_UYVY || fmt == MAV_PIX_YVYU; + BOOL flip = !!(info->VideoFlags & MFVideoFlag_BottomUpLinearRep); + UINT32 w = info->dwWidth, h = info->dwHeight, bpp = wmv_pixel_bytes( fmt ); + UINT32 rx = 0, ry = 0, rw = w, rh = h, cw, ch, p, planes; + struct mav_layout *l = &g->frame; + + if (!mav_video_layout( fmt, w, h, l )) return FALSE; + /* wg_transform.c's exception: NV12 rows are 2-aligned, as on Windows. */ + if (fmt == MAV_PIX_NV12) l->stride[0] = l->stride[1] = (w + 1) & ~1u; + if (stride) + { + /* The caller's 2D buffer: its pitch is the first plane's stride; a + * planar format's chroma rows are half that (NV12's, interleaved, + * the same), as mfplat lays out its 2D buffers. */ + UINT32 row = subsampled ? ((w + 1) & ~1u) * bpp : w * bpp; + + if (stride >= row) + { + l->stride[0] = stride; + if (fmt == MAV_PIX_NV12) l->stride[1] = stride; + else if (planar) l->stride[1] = l->stride[2] = stride / 2; + } + else if (!transform->stride_logged) + { + transform->stride_logged = TRUE; + WMV_LOG( "transform %p: a stride of %u is too short for %u pixels of %s; using the default\n", + transform, stride, w, mav_pix_name( fmt ) ); + } + } + l->offset[0] = l->offset[1] = l->offset[2] = 0; + if (!planar) l->size = (size_t)l->stride[0] * h; + else + { + l->offset[1] = (size_t)l->stride[0] * h; + l->offset[2] = l->offset[1] + (size_t)l->stride[1] * l->chroma_height; + l->size = fmt == MAV_PIX_NV12 ? l->offset[2] : l->offset[2] + (size_t)l->stride[2] * l->chroma_height; + } + + /* GStreamer's is_mf_video_area_empty(): an aperture is set if any field is. */ + if ((aperture->OffsetX.value || aperture->OffsetY.value || aperture->Area.cx || aperture->Area.cy) + && aperture->OffsetX.value >= 0 && aperture->OffsetY.value >= 0 + && (UINT32)aperture->OffsetX.value < w && (UINT32)aperture->OffsetY.value < h + && aperture->Area.cx > 0 && aperture->Area.cy > 0) + { + rx = aperture->OffsetX.value; + ry = aperture->OffsetY.value; + rw = min( (UINT32)aperture->Area.cx, w - rx ); + rh = min( (UINT32)aperture->Area.cy, h - ry ); + if (subsampled) rx &= ~1u; /* chroma is shared by pixel pairs */ + if (planar) ry &= ~1u; /* and, in 4:2:0, by row pairs */ + } + cw = min( picture->width, rw ); + ch = min( picture->height, rh ); + g->region_w = rw; + g->region_h = rh; + g->covers = cw == rw && ch == rh; + g->vout.fmt = fmt; + g->vout.width = cw; + g->vout.height = flip ? -(int32_t)ch : (int32_t)ch; + g->vout.fps_n = g->vout.fps_d = 0; + + /* Each plane's origin moves to the region, so that mav_convert_picture's + * rows -- counted over the region, from its last row when flipped -- + * land in it. */ + g->layout = *l; + planes = fmt == MAV_PIX_NV12 ? 2 : planar ? 3 : 1; + for (p = 0; p < planes; p++) + { + UINT32 rows = p ? l->chroma_height : h, y = p ? ry / 2 : ry, n = p ? (ch + 1) / 2 : ch; + UINT32 x = p ? (fmt == MAV_PIX_NV12 ? rx : rx / 2) : rx * bpp; + + g->layout.offset[p] += (size_t)l->stride[p] * (flip ? rows - y - n : y) + x; + } + g->layout.chroma_height = (ch + 1) / 2; + return TRUE; +} + +/* A picture smaller than its region: the whole frame is black first, in the + * values mav_convert_picture pads with. */ +static void wmv_fill_black( enum mav_pixel_format fmt, const struct mav_layout *l, UINT32 w, UINT32 h, BYTE *dst ) +{ + UINT32 x, y; + + switch (fmt) + { + case MAV_PIX_NV12: + case MAV_PIX_I420: + case MAV_PIX_YV12: + memset( dst, 16, l->offset[1] ); + memset( dst + l->offset[1], 128, l->size - l->offset[1] ); + break; + case MAV_PIX_YUY2: + case MAV_PIX_UYVY: + case MAV_PIX_YVYU: + for (y = 0; y < h; y++) + for (x = 0; x + 4 <= l->stride[0]; x += 4) + memcpy( dst + (size_t)y * l->stride[0] + x, fmt == MAV_PIX_UYVY ? "\x80\x10\x80\x10" : "\x10\x80\x10\x80", 4 ); + break; + case MAV_PIX_BGRA: + case MAV_PIX_BGRx: + case MAV_PIX_RGBA: + for (y = 0; y < h; y++) + for (x = 0; x < w; x++) + memcpy( dst + (size_t)y * l->stride[0] + x * 4, "\0\0\0\xff", 4 ); + break; + default: + memset( dst, 0, l->size ); + break; + } +} + +/*********************************************************************** + * the WMV kind's entries + */ +static NTSTATUS wmv_create( struct wg_transform_create_params *params ) +{ + const MFVIDEOFORMAT *in = video_format( ¶ms->input_type ); + const MFVIDEOFORMAT *out = video_format( ¶ms->output_type ); + struct wmv_transform *transform; + UINT32 codec_data_size = 0, fps_n, fps_d; + const BYTE *codec_data; + const char *name = NULL; + char why[96] = "", sub[16]; + NTSTATUS status; + int codec; + + params->transform = 0; + if (!in) return STATUS_NOT_SUPPORTED; /* a malformed block */ + if (!(codec = wmv_input_codec( &in->guidFormat, &name ))) + { + WMV_LOG( "input subtype %s is not a Windows Media video stream (WMV1/WMV2/WMV3/WMVA/WVC1); refusing\n", + wmv_subtype_name( &in->guidFormat, sub ) ); + return STATUS_NOT_SUPPORTED; + } + if (!out || wmv_output_format( &out->guidFormat ) == MAV_PIX_UNKNOWN) + { + WMV_LOG( "%s: output subtype %s is not one this decoder writes " + "(NV12 YV12 I420 IYUV YUY2 UYVY YVYU RGB32 ARGB32 ABGR32 RGB24 RGB565 RGB555); refusing\n", + name, out ? wmv_subtype_name( &out->guidFormat, sub ) : "(not video)" ); + return STATUS_NOT_SUPPORTED; + } + if (!in->videoInfo.dwWidth || !in->videoInfo.dwHeight + || in->videoInfo.dwWidth > MAV_MAX_DIMENSION || in->videoInfo.dwHeight > MAV_MAX_DIMENSION) + { + /* WMV7/8/9 bitstreams do not carry the picture size: the container's is all there is. */ + WMV_LOG( "%s: unusable frame size %ux%u; refusing\n", name, + (UINT)in->videoInfo.dwWidth, (UINT)in->videoInfo.dwHeight ); + return STATUS_NOT_SUPPORTED; + } + if (!mav_lavc_supports( codec )) + { + WMV_LOG( "%s: no decoder for it in this FFmpeg build; refusing\n", name ); + return STATUS_NOT_SUPPORTED; + } + codec_data = video_user_data( in, params->input_type.format_size, &codec_data_size ); + if (codec_data_size > MADEIRA_WMV_MAX_CODEC_DATA) + { + WMV_LOG( "%s: %u bytes of codec private data; refusing\n", name, codec_data_size ); + return STATUS_NOT_SUPPORTED; + } + + /* libavcodec's diagnostics, under this file's tags (see wma_av_log). */ + pthread_once( &wma_av_log_once, wma_install_av_log ); + + if (!(transform = calloc( 1, sizeof(*transform) ))) return STATUS_NO_MEMORY; + pthread_mutex_init( &transform->lock, NULL ); + transform->magic = MADEIRA_WG_WMV_MAGIC; + transform->attrs = params->attrs; + transform->codec = codec; + transform->name = name; + transform->width = in->videoInfo.dwWidth; + transform->height = in->videoInfo.dwHeight; + fps_n = in->videoInfo.FramesPerSecond.Numerator; + fps_d = in->videoInfo.FramesPerSecond.Denominator; + if (fps_n && fps_d) transform->frame_duration = (INT64)fps_d * 10000000 / fps_n; + switch (in->videoInfo.TransferMatrix) + { + case MFVideoTransferMatrix_BT709: transform->bt709 = 1; break; + case MFVideoTransferMatrix_BT601: + case MFVideoTransferMatrix_SMPTE240M: transform->bt709 = 0; break; + default: transform->bt709 = transform->height >= 720; break; /* as the parser assumes */ + } + if ((status = wmv_set_output( transform, ¶ms->output_type ))) + { + WMV_LOG( "%s: output type %ux%u refused (%#x)\n", name, (UINT)out->videoInfo.dwWidth, + (UINT)out->videoInfo.dwHeight, (UINT)status ); + goto fail; + } + + transform->dec = mav_lavc_open( codec, codec_data, codec_data_size, transform->width, transform->height, + why, sizeof(why) ); + if (!transform->dec && codec_data_size) + { + WMV_LOG( "%s %ux%u: the decoder refused the %u-byte sequence header (%s); refusing\n", + name, transform->width, transform->height, codec_data_size, why ); + status = STATUS_NOT_SUPPORTED; + goto fail; + } + if (transform->dec) ((struct mav_lavc_vdec *)transform->dec)->ctx->opaque = WMV_DECODER_MARKER; + + params->transform = (wg_transform_t)(UINT_PTR)transform; + WMV_LOG( "decoder created fmt=%s %ux%u fps=%u/%u codec_data=%u -> %s %ux%u%s queue=%u%s (transform %p)%s\n", + name, transform->width, transform->height, fps_n, fps_d, codec_data_size, + mav_pix_name( transform->out_fmt ), (UINT)transform->out_format->videoInfo.dwWidth, + (UINT)transform->out_format->videoInfo.dwHeight, + (transform->out_format->videoInfo.VideoFlags & MFVideoFlag_BottomUpLinearRep) ? " bottom-up" : "", + transform->attrs.input_queue_length, transform->attrs.preserve_timestamps ? " preserve-ts" : "", + transform, transform->dec ? "" : " [decoder not open: no sequence header, as in " + "wmv_decoder_create()'s probe; input will be dropped]" ); + return STATUS_SUCCESS; + +fail: + free( transform->out_format ); + pthread_mutex_destroy( &transform->lock ); + transform->magic = 0; + free( transform ); + return status; +} + +static void wmv_clear( struct wmv_transform *transform ) +{ + while (transform->packet_count) free( transform->packets[--transform->packet_count].data ); + while (transform->picture_count) wmv_pop_picture( transform ); +} + +static NTSTATUS wmv_destroy( wg_transform_t handle ) +{ + struct wmv_transform *transform = get_wmv_transform( handle ); + + if (!transform) return STATUS_INVALID_HANDLE; + pthread_mutex_lock( &transform->lock ); + wmv_report( transform, "destroy" ); + transform->magic = 0; + wmv_clear( transform ); + if (transform->dec) mav_lavc_close( transform->dec ); + free( transform->packets ); + free( transform->pictures ); + free( transform->out_format ); + pthread_mutex_unlock( &transform->lock ); + pthread_mutex_destroy( &transform->lock ); + free( transform ); + return STATUS_SUCCESS; +} + +static NTSTATUS wmv_get_output_type( wg_transform_t handle, struct wg_media_type *type ) +{ + struct wmv_transform *transform = get_wmv_transform( handle ); + UINT32 size; + + if (!transform) return STATUS_INVALID_HANDLE; + pthread_mutex_lock( &transform->lock ); + size = transform->out_format_size; + type->major = madeira_MFMediaType_Video; + /* Two-phase, as main.c's wg_transform_get_output_type() expects. */ + if (!type->u.format || type->format_size < size) + { + type->format_size = size; + pthread_mutex_unlock( &transform->lock ); + return STATUS_BUFFER_TOO_SMALL; + } + memcpy( type->u.format, transform->out_format, size ); + type->format_size = size; + pthread_mutex_unlock( &transform->lock ); + return STATUS_SUCCESS; +} + +static NTSTATUS wmv_set_output_type( wg_transform_t handle, const struct wg_media_type *type ) +{ + struct wmv_transform *transform = get_wmv_transform( handle ); + NTSTATUS status; + + if (!transform) return STATUS_INVALID_HANDLE; + pthread_mutex_lock( &transform->lock ); + /* The decoder and the pictures it has made are kept: they are written in + * the new format when they are read, which is what wg_transform.c says a + * native transform does and GStreamer could not. */ + if (!(status = wmv_set_output( transform, type ))) + WMV_LOG( "transform %p: output type set to %s %ux%u%s\n", transform, mav_pix_name( transform->out_fmt ), + (UINT)transform->out_format->videoInfo.dwWidth, (UINT)transform->out_format->videoInfo.dwHeight, + (transform->out_format->videoInfo.VideoFlags & MFVideoFlag_BottomUpLinearRep) ? " bottom-up" : "" ); + pthread_mutex_unlock( &transform->lock ); + return status; +} + +static NTSTATUS wmv_push_data( wg_transform_t handle, struct wg_sample *sample, const void *data, HRESULT *result ) +{ + struct wmv_transform *transform = get_wmv_transform( handle ); + struct wmv_packet *packet; + + if (!transform || !sample) return STATUS_INVALID_HANDLE; + if (sample->size && !data) return STATUS_INVALID_PARAMETER; + + pthread_mutex_lock( &transform->lock ); + /* wg_transform.c: no input while a drain is under way, and no more than + * input_queue_length + 1 frames queued. */ + if (transform->draining || transform->packet_count > transform->attrs.input_queue_length) + { + pthread_mutex_unlock( &transform->lock ); + *result = MF_E_NOTACCEPTING; + return STATUS_SUCCESS; + } + if (transform->packet_count == transform->packet_cap) + { + UINT32 cap = transform->packet_cap ? transform->packet_cap * 2 : 8; + struct wmv_packet *grown = realloc( transform->packets, cap * sizeof(*grown) ); + + if (!grown) + { + pthread_mutex_unlock( &transform->lock ); + return STATUS_NO_MEMORY; + } + transform->packets = grown; + transform->packet_cap = cap; + } + packet = &transform->packets[transform->packet_count]; + memset( packet, 0, sizeof(*packet) ); + if (sample->size && !(packet->data = malloc( sample->size ))) + { + pthread_mutex_unlock( &transform->lock ); + return STATUS_NO_MEMORY; + } + if (sample->size) memcpy( packet->data, data, sample->size ); + packet->size = sample->size; + packet->flags = sample->flags; + packet->pts = (sample->flags & WG_SAMPLE_FLAG_HAS_PTS) ? sample->pts : INT64_MIN; + packet->duration = (sample->flags & WG_SAMPLE_FLAG_HAS_DURATION) ? (INT64)sample->duration : INT64_MIN; + transform->packet_count++; + transform->pushed++; + pthread_mutex_unlock( &transform->lock ); + *result = S_OK; + return STATUS_SUCCESS; +} + +static NTSTATUS wmv_read_data( wg_transform_t handle, struct wg_sample *sample, void *data, HRESULT *result ) +{ + struct wmv_transform *transform = get_wmv_transform( handle ); + struct wmv_picture *picture; + struct mav_vplanes planes; + struct wmv_geometry g; + BOOL preserve = FALSE; + INT64 pts, duration; + + if (!transform || !sample) return STATUS_INVALID_HANDLE; + if (sample->max_size && !data) return STATUS_INVALID_PARAMETER; + + pthread_mutex_lock( &transform->lock ); + wmv_decode_until_picture( transform ); + if (!transform->picture_count) + { + sample->size = 0; + pthread_mutex_unlock( &transform->lock ); + *result = MF_E_TRANSFORM_NEED_MORE_INPUT; + return STATUS_SUCCESS; + } + picture = &transform->pictures[0]; + mav_lavc_map( picture->frame, &planes ); + + if (!wmv_geometry( transform, &planes, sample->stride, &g )) + { + pthread_mutex_unlock( &transform->lock ); + return STATUS_UNSUCCESSFUL; + } + if (transform->attrs.allow_format_change && (planes.width != g.region_w || planes.height != g.region_h)) + { + /* The caller takes a new size: report it once, deliver nothing. */ + MFVideoInfo *info = &transform->out_format->videoInfo; + + WMV_LOG( "transform %p: picture size %ux%u, was %ux%u: format change\n", transform, + planes.width, planes.height, (UINT)info->dwWidth, (UINT)info->dwHeight ); + info->dwWidth = planes.width; + info->dwHeight = planes.height; + memset( &info->GeometricAperture, 0, sizeof(info->GeometricAperture) ); + memset( &info->MinimumDisplayAperture, 0, sizeof(info->MinimumDisplayAperture) ); + memset( &info->PanScanAperture, 0, sizeof(info->PanScanAperture) ); + sample->size = 0; + pthread_mutex_unlock( &transform->lock ); + *result = MF_E_TRANSFORM_STREAM_CHANGE; + return STATUS_SUCCESS; + } + if (g.frame.size > sample->max_size) + { + /* As wg_transform.c: an error, and the picture stays for a bigger buffer. */ + if (!transform->size_logged) + { + transform->size_logged = TRUE; + WMV_LOG( "transform %p: a %u-byte buffer cannot hold a %ux%u %s frame (%zu bytes)\n", transform, + sample->max_size, (UINT)transform->out_format->videoInfo.dwWidth, + (UINT)transform->out_format->videoInfo.dwHeight, mav_pix_name( transform->out_fmt ), + g.frame.size ); + } + sample->size = 0; + pthread_mutex_unlock( &transform->lock ); + return STATUS_BUFFER_TOO_SMALL; + } + + if (!g.covers) + wmv_fill_black( g.vout.fmt, &g.frame, transform->out_format->videoInfo.dwWidth, + transform->out_format->videoInfo.dwHeight, data ); + mav_convert_picture( &g.vout, transform->bt709, &planes, data, &g.layout ); + mav_lavc_unmap( picture->frame ); + + if (picture->pts != INT64_MIN) + { + pts = picture->pts; + preserve = transform->attrs.preserve_timestamps; + } + else pts = transform->next_pts; + duration = picture->duration != INT64_MIN ? picture->duration : transform->frame_duration; + transform->next_pts = pts + duration; + + sample->size = (UINT32)g.frame.size; + sample->flags &= ~(WG_SAMPLE_FLAG_INCOMPLETE | WG_SAMPLE_FLAG_HAS_PTS | WG_SAMPLE_FLAG_HAS_DURATION | + WG_SAMPLE_FLAG_SYNC_POINT | WG_SAMPLE_FLAG_DISCONTINUITY | + WG_SAMPLE_FLAG_PRESERVE_TIMESTAMPS); + sample->flags |= WG_SAMPLE_FLAG_SYNC_POINT | WG_SAMPLE_FLAG_HAS_PTS | WG_SAMPLE_FLAG_HAS_DURATION; + if (preserve) sample->flags |= WG_SAMPLE_FLAG_PRESERVE_TIMESTAMPS; + if (transform->discontinuity) sample->flags |= WG_SAMPLE_FLAG_DISCONTINUITY; + transform->discontinuity = FALSE; + sample->pts = pts; + sample->duration = duration; + + wmv_pop_picture( transform ); + transform->delivered++; + pthread_mutex_unlock( &transform->lock ); + *result = S_OK; + return STATUS_SUCCESS; +} + +static NTSTATUS wmv_get_status( wg_transform_t handle, UINT32 *accepts_input ) +{ + struct wmv_transform *transform = get_wmv_transform( handle ); + + if (!transform) return STATUS_INVALID_HANDLE; + pthread_mutex_lock( &transform->lock ); + *accepts_input = transform->packet_count <= transform->attrs.input_queue_length; + pthread_mutex_unlock( &transform->lock ); + return STATUS_SUCCESS; +} + +static NTSTATUS wmv_drain( wg_transform_t handle ) +{ + struct wmv_transform *transform = get_wmv_transform( handle ); + + if (!transform) return STATUS_INVALID_HANDLE; + pthread_mutex_lock( &transform->lock ); + /* With frames still queued the end of stream waits for read_data to + * have decoded them, and push_data refuses until then. */ + transform->draining = TRUE; + if (!transform->packet_count) wmv_complete_drain( transform ); + pthread_mutex_unlock( &transform->lock ); + return STATUS_SUCCESS; +} + +static NTSTATUS wmv_flush( wg_transform_t handle ) +{ + struct wmv_transform *transform = get_wmv_transform( handle ); + + if (!transform) return STATUS_INVALID_HANDLE; + pthread_mutex_lock( &transform->lock ); + if (transform->rejected || transform->dropped || transform->lost) wmv_report( transform, "flush" ); + wmv_clear( transform ); + if (transform->dec) mav_lavc_flush( transform->dec ); + transform->draining = FALSE; + transform->next_pts = 0; + pthread_mutex_unlock( &transform->lock ); + return STATUS_SUCCESS; +} + +/* Every video input is this kind's to judge, unless switched off: wmv_create + * refuses, and logs, what is not Windows Media video. */ +static BOOL wmv_claims( const struct wg_transform_create_params *params ) +{ + return IsEqualGUID( ¶ms->input_type.major, &madeira_MFMediaType_Video ) && wmv_transform_switch_on(); +} + +/*********************************************************************** + * transform kinds + * + * wg_transform_create gives the create to the first kind below that claims + * the INPUT type, and that kind may still refuse the pair (its log says + * why). Every later call finds the kind again by the magic that each kind's + * object starts with, so a handle is only ever read as the kind that made + * it, and an unknown one is STATUS_INVALID_HANDLE. Another kind is another + * row: claims(), the entries, and a UINT32 magic of its own as the first + * member of its object. + */ +struct wg_transform_ops +{ + const char *name; + UINT32 magic; + BOOL (*claims)( const struct wg_transform_create_params *params ); + NTSTATUS (*create)( struct wg_transform_create_params *params ); + NTSTATUS (*destroy)( wg_transform_t handle ); + NTSTATUS (*get_output_type)( wg_transform_t handle, struct wg_media_type *type ); + NTSTATUS (*set_output_type)( wg_transform_t handle, const struct wg_media_type *type ); + NTSTATUS (*push_data)( wg_transform_t handle, struct wg_sample *sample, const void *data, HRESULT *result ); + NTSTATUS (*read_data)( wg_transform_t handle, struct wg_sample *sample, void *data, HRESULT *result ); + NTSTATUS (*get_status)( wg_transform_t handle, UINT32 *accepts_input ); + NTSTATUS (*drain)( wg_transform_t handle ); + NTSTATUS (*flush)( wg_transform_t handle ); +}; + +static const struct wg_transform_ops wma_transform_ops = +{ + "wma", MADEIRA_WG_TRANSFORM_MAGIC, wma_claims, wma_create, wma_destroy, wma_get_output_type, + wma_set_output_type, wma_push_data, wma_read_data, wma_get_status, wma_drain, wma_flush, +}; + +static const struct wg_transform_ops wmv_transform_ops = +{ + "wmv", MADEIRA_WG_WMV_MAGIC, wmv_claims, wmv_create, wmv_destroy, wmv_get_output_type, + wmv_set_output_type, wmv_push_data, wmv_read_data, wmv_get_status, wmv_drain, wmv_flush, +}; + +/* In claim order. */ +static const struct wg_transform_ops *const transform_kinds[] = +{ + &wma_transform_ops, + &wmv_transform_ops, +}; + +static const struct wg_transform_ops *transform_kind( wg_transform_t handle ) +{ + const UINT32 *magic = (const UINT32 *)(UINT_PTR)handle; + unsigned int i; + + if (!magic) return NULL; + for (i = 0; i < ARRAY_SIZE(transform_kinds); i++) + if (transform_kinds[i]->magic == *magic) return transform_kinds[i]; + return NULL; +} + +/* The unpacked forms, shared by the 64-bit entries and the wow64 thunks. */ +static NTSTATUS transform_create( struct wg_transform_create_params *params ) +{ + unsigned int i; + + params->transform = 0; + for (i = 0; i < ARRAY_SIZE(transform_kinds); i++) + if (transform_kinds[i]->claims( params )) return transform_kinds[i]->create( params ); + /* Unclaimed: video with MADEIRA_WG_WMV_TRANSFORM=0, or neither audio nor video. */ + if (IsEqualGUID( ¶ms->input_type.major, &madeira_MFMediaType_Video )) + WMV_LOG( "video transform refused: MADEIRA_WG_WMV_TRANSFORM=0\n" ); + return STATUS_NOT_SUPPORTED; +} + +static NTSTATUS transform_destroy( wg_transform_t handle ) +{ + const struct wg_transform_ops *kind = transform_kind( handle ); + return kind ? kind->destroy( handle ) : STATUS_INVALID_HANDLE; +} + +static NTSTATUS transform_get_output_type( wg_transform_t handle, struct wg_media_type *type ) +{ + const struct wg_transform_ops *kind = transform_kind( handle ); + return kind ? kind->get_output_type( handle, type ) : STATUS_INVALID_HANDLE; +} + +static NTSTATUS transform_set_output_type( wg_transform_t handle, const struct wg_media_type *type ) +{ + const struct wg_transform_ops *kind = transform_kind( handle ); + return kind ? kind->set_output_type( handle, type ) : STATUS_INVALID_HANDLE; +} + +/* `data` is passed separately from `sample` because struct wg_sample's `data` + * member is a GUEST address for a 32-bit caller; see the wow64 table. */ +static NTSTATUS transform_push_data( wg_transform_t handle, struct wg_sample *sample, const void *data, + HRESULT *result ) +{ + const struct wg_transform_ops *kind = transform_kind( handle ); + return kind ? kind->push_data( handle, sample, data, result ) : STATUS_INVALID_HANDLE; +} + +static NTSTATUS transform_read_data( wg_transform_t handle, struct wg_sample *sample, void *data, + HRESULT *result ) +{ + const struct wg_transform_ops *kind = transform_kind( handle ); + return kind ? kind->read_data( handle, sample, data, result ) : STATUS_INVALID_HANDLE; +} + +/*********************************************************************** + * the unix call entries + */ +static NTSTATUS wma_init( void *args ) +{ + struct wg_init_gstreamer_params *params = args; + + /* Benign success: main.c's init_gstreamer_proc() fails the whole DLL if + * this fails, and everything this port implements is below it. */ + (void)params; + return STATUS_SUCCESS; +} + +static NTSTATUS wma_not_implemented( void *args ) +{ + (void)args; + return STATUS_NOT_IMPLEMENTED; +} + +static NTSTATUS wg_transform_create( void *args ) +{ + return transform_create( args ); +} + +static NTSTATUS wg_transform_destroy( void *args ) +{ + return transform_destroy( *(wg_transform_t *)args ); +} + +static NTSTATUS wg_transform_get_output_type( void *args ) +{ + struct wg_transform_get_output_type_params *params = args; + return transform_get_output_type( params->transform, ¶ms->media_type ); +} + +static NTSTATUS wg_transform_set_output_type( void *args ) +{ + struct wg_transform_set_output_type_params *params = args; + return transform_set_output_type( params->transform, ¶ms->media_type ); +} + +static NTSTATUS wg_transform_push_data( void *args ) +{ + struct wg_transform_push_data_params *params = args; + struct wg_sample *sample = params->sample; + + if (!sample) return STATUS_INVALID_PARAMETER; + return transform_push_data( params->transform, sample, + (const void *)(UINT_PTR)sample->data, ¶ms->result ); +} + +static NTSTATUS wg_transform_read_data( void *args ) +{ + struct wg_transform_read_data_params *params = args; + struct wg_sample *sample = params->sample; + + if (!sample) return STATUS_INVALID_PARAMETER; + return transform_read_data( params->transform, sample, + (void *)(UINT_PTR)sample->data, ¶ms->result ); +} + +static NTSTATUS wg_transform_get_status( void *args ) +{ + struct wg_transform_get_status_params *params = args; + const struct wg_transform_ops *kind = transform_kind( params->transform ); + + return kind ? kind->get_status( params->transform, ¶ms->accepts_input ) : STATUS_INVALID_HANDLE; +} + +static NTSTATUS wg_transform_drain( void *args ) +{ + wg_transform_t handle = *(wg_transform_t *)args; + const struct wg_transform_ops *kind = transform_kind( handle ); + + return kind ? kind->drain( handle ) : STATUS_INVALID_HANDLE; +} + +static NTSTATUS wg_transform_flush( void *args ) +{ + wg_transform_t handle = *(wg_transform_t *)args; + const struct wg_transform_ops *kind = transform_kind( handle ); + + return kind ? kind->flush( handle ) : STATUS_INVALID_HANDLE; +} + +static NTSTATUS wg_transform_notify_qos( void *args ) +{ + /* Quality-of-service hints only change which frames a GStreamer pipeline + * bothers to decode. Neither kind drops frames (a WMV decoder that + * skipped one would break the pictures that refer to it until the next + * keyframe), and the caller ignores the status. */ + (void)args; + return STATUS_SUCCESS; +} + +/*********************************************************************** + * wg_parser (MADEIRA ml1980, ml1990) + * + * The Wine side of wg_parser_av_ios.c: handle validation, struct wg_format / + * struct wg_parser_buffer mapping, and the HRESULTs wg_parser.c returns. + * See that file's header for the protocol and what is accepted. + * + * MADEIRA_WG_PARSER=0 restores the pre-ml1980 behaviour: create is refused + * with STATUS_NOT_IMPLEMENTED, so quartz_parser.c's parser_create() fails + * exactly as before. + * + * ml1990: MP4/MOV (H.264 / HEVC video on VideoToolbox, AAC audio on + * AudioToolbox, wg_parser_apple_ios.c). MADEIRA_WG_VIDEO=0 restores the + * ml1980 MP3/WAV-only behaviour (an MP4 is refused at connect). + * MADEIRA_WG_VIDEO_FORMAT=nv12|i420|yv12|yuy2|rgb32|argb32|abgr32 picks the + * native format a video stream reports. Only the native format and + * media_source.c's YUV list (NV12, YV12, YUY2, I420, IYUV) become media types. + * + * The default is rgb32, not the nv12 the hardware decoder produces. A media + * session resolves a source -> renderer branch with the source's current type + * only, and that is the native one. With nv12 the EVR accepts it (dxva2's + * processor service lists NV12 without asking the device), and the session + * then asks the EVR's sample allocator for NV12 Direct3D 9 surfaces. This + * port's d3d9 (DXMT) has no YUV surface format, so the allocator fails, and + * session.c drops the renderer's output node and every node after it + * (session_collect_nodes stops at the first failure). The session still + * reports itself started. Nothing is requested from the source, the audio + * renderer never gets the clock, and the title shows an empty video window + * until it is killed: Senren Banka's 32-bit CG movie (MP4, H.264 1080p + AAC, + * through krkrz's MFPlayer: media session, EVR, SAR). RGB32 surfaces are + * plain DXMT surfaces, and the YUV list still serves a consumer (a source + * reader) that asks for NV12. The cost is the NV12 -> BGRx conversion of + * each picture on the CPU. nv12 restores the previous default. + * + * A parser has up to MAV_MAX_STREAMS streams. Each stream handle is a + * separate object inside the parser so a parser handle passed as a stream + * (or the reverse) is caught by the magic, not dereferenced. + */ +#define MADEIRA_WG_PARSER_MAGIC 0x57475052 /* 'WGPR' */ +#define MADEIRA_WG_STREAM_MAGIC 0x57475354 /* 'WGST' */ + +struct wgp_parser; + +struct wgp_stream +{ + UINT32 magic; + UINT32 index; + struct wgp_parser *parser; +}; + +struct wgp_parser +{ + UINT32 magic; + struct mav_parser *core; + struct wgp_stream streams[MAV_MAX_STREAMS]; +}; + +C_ASSERT( (int)MAV_FMT_U8 == (int)WG_AUDIO_FORMAT_U8 && (int)MAV_FMT_S16 == (int)WG_AUDIO_FORMAT_S16LE + && (int)MAV_FMT_S24 == (int)WG_AUDIO_FORMAT_S24LE && (int)MAV_FMT_S32 == (int)WG_AUDIO_FORMAT_S32LE + && (int)MAV_FMT_F32 == (int)WG_AUDIO_FORMAT_F32LE && (int)MAV_FMT_F64 == (int)WG_AUDIO_FORMAT_F64LE ); +C_ASSERT( (int)MAV_PIX_BGRA == (int)WG_VIDEO_FORMAT_BGRA && (int)MAV_PIX_BGRx == (int)WG_VIDEO_FORMAT_BGRx + && (int)MAV_PIX_RGBA == (int)WG_VIDEO_FORMAT_RGBA && (int)MAV_PIX_I420 == (int)WG_VIDEO_FORMAT_I420 + && (int)MAV_PIX_NV12 == (int)WG_VIDEO_FORMAT_NV12 && (int)MAV_PIX_YUY2 == (int)WG_VIDEO_FORMAT_YUY2 + && (int)MAV_PIX_YV12 == (int)WG_VIDEO_FORMAT_YV12 && (int)MAV_PIX_BGR == (int)WG_VIDEO_FORMAT_BGR + && (int)MAV_PIX_RGB15 == (int)WG_VIDEO_FORMAT_RGB15 && (int)MAV_PIX_RGB16 == (int)WG_VIDEO_FORMAT_RGB16 + && (int)MAV_PIX_UYVY == (int)WG_VIDEO_FORMAT_UYVY && (int)MAV_PIX_YVYU == (int)WG_VIDEO_FORMAT_YVYU ); + +static BOOL wg_parser_switch_on(void) +{ + const char *v = getenv( "MADEIRA_WG_PARSER" ); + return !(v && v[0] == '0' && !v[1]); +} + +static BOOL wg_video_switch_on(void) +{ + const char *v = getenv( "MADEIRA_WG_VIDEO" ); + return !(v && v[0] == '0' && !v[1]); +} + +static enum mav_pixel_format wg_video_native_format(void) +{ + static const struct { const char *name; enum mav_pixel_format fmt; } names[] = + { + { "nv12", MAV_PIX_NV12 }, { "i420", MAV_PIX_I420 }, { "iyuv", MAV_PIX_I420 }, + { "yv12", MAV_PIX_YV12 }, { "yuy2", MAV_PIX_YUY2 }, { "rgb32", MAV_PIX_BGRx }, + { "argb32", MAV_PIX_BGRA }, { "abgr32", MAV_PIX_RGBA }, + }; + const char *v = getenv( "MADEIRA_WG_VIDEO_FORMAT" ); + unsigned int i; + + if (!v || !*v) return MAV_PIX_BGRx; /* rgb32: see above */ + for (i = 0; i < ARRAY_SIZE(names); i++) + if (!strcasecmp( v, names[i].name )) return names[i].fmt; + mav_log( "MADEIRA_WG_VIDEO_FORMAT=%.16s is not one of nv12/i420/yv12/yuy2/rgb32/argb32/abgr32; using rgb32", v ); + return MAV_PIX_BGRx; +} + +static pthread_once_t wgp_config_once = PTHREAD_ONCE_INIT; + +static void wgp_configure(void) +{ + BOOL video = wg_video_switch_on(); + enum mav_pixel_format native = wg_video_native_format(); + +#ifdef __APPLE__ + mav_configure( video, &mav_apple_video_backend, &mav_apple_audio_backend, native ); + mav_log( "mp4/mov %s (MADEIRA_WG_VIDEO=0 disables): video on %s, aac on %s, native video format %s", + video ? "enabled" : "disabled", mav_apple_video_backend.name, mav_apple_audio_backend.name, + mav_pix_name( native ) ); +#else + mav_configure( FALSE, NULL, NULL, native ); +#endif +} + +static struct wgp_parser *get_wgp_parser( wg_parser_t handle ) +{ + struct wgp_parser *parser = (struct wgp_parser *)(UINT_PTR)handle; + + if (!parser || parser->magic != MADEIRA_WG_PARSER_MAGIC) return NULL; + return parser; +} + +static struct wgp_parser *get_wgp_stream( wg_parser_stream_t handle, UINT32 *index ) +{ + struct wgp_stream *stream = (struct wgp_stream *)(UINT_PTR)handle; + + if (!stream || stream->magic != MADEIRA_WG_STREAM_MAGIC) return NULL; + if (!stream->parser || stream->parser->magic != MADEIRA_WG_PARSER_MAGIC) return NULL; + if (stream->index >= MAV_MAX_STREAMS || &stream->parser->streams[stream->index] != stream) return NULL; + *index = stream->index; + return stream->parser; +} + +/* The HRESULTs wg_parser.c / quartz_parser.c expect. */ +static NTSTATUS wgp_status( int status ) +{ + switch (status) + { + case MAV_OK: return S_OK; + case MAV_NO_BUFFER: return S_FALSE; + case MAV_E_STATE: return VFW_E_WRONG_STATE; + case MAV_E_UNSUPPORTED: return VFW_E_UNSUPPORTED_STREAM; + case MAV_E_NOMEM: return E_OUTOFMEMORY; + case MAV_E_PARAM: return STATUS_INVALID_PARAMETER; + case MAV_E_IO: + default: return E_FAIL; + } +} + +static void wgp_format_from_output( struct wg_format *format, const struct mav_output *out ) +{ + memset( format, 0, sizeof(*format) ); + format->major_type = WG_MAJOR_TYPE_AUDIO; + format->u.audio.format = out->fmt; + format->u.audio.channels = out->channels; + format->u.audio.channel_mask = out->channel_mask; + format->u.audio.rate = out->rate; +} + +static void wgp_format_from_video( struct wg_format *format, const struct mav_video_output *out ) +{ + memset( format, 0, sizeof(*format) ); + format->major_type = WG_MAJOR_TYPE_VIDEO; + format->u.video.format = out->fmt; + format->u.video.width = out->width; + format->u.video.height = out->height; + format->u.video.fps_n = out->fps_n; + format->u.video.fps_d = out->fps_d; +} + +static NTSTATUS wgp_create( void *args ) +{ + struct wg_parser_create_params *params = args; + struct wgp_parser *parser; + unsigned int i; + + if (!wg_parser_switch_on()) + { + static int once; + if (!__atomic_exchange_n( &once, 1, __ATOMIC_RELAXED )) + mav_log( "disabled by MADEIRA_WG_PARSER=0; parser creation refused" ); + return STATUS_NOT_IMPLEMENTED; + } + pthread_once( &wma_av_log_once, wma_install_av_log ); + pthread_once( &wgp_config_once, wgp_configure ); + if (!(parser = calloc( 1, sizeof(*parser) ))) return E_OUTOFMEMORY; + if (!(parser->core = mav_create( params->output_compressed ))) + { + free( parser ); + return E_OUTOFMEMORY; } parser->magic = MADEIRA_WG_PARSER_MAGIC; for (i = 0; i < MAV_MAX_STREAMS; i++) @@ -2823,17 +3903,17 @@ const unixlib_entry_t __wine_unix_call_funcs[] = wgp_get_tag64, /* unix_wg_parser_stream_get_tag */ wgp_seek, /* unix_wg_parser_stream_seek */ - wma_transform_create, /* unix_wg_transform_create */ - wma_transform_destroy, /* unix_wg_transform_destroy */ - wma_transform_get_output_type, /* unix_wg_transform_get_output_type */ - wma_transform_set_output_type, /* unix_wg_transform_set_output_type */ + wg_transform_create, /* unix_wg_transform_create */ + wg_transform_destroy, /* unix_wg_transform_destroy */ + wg_transform_get_output_type, /* unix_wg_transform_get_output_type */ + wg_transform_set_output_type, /* unix_wg_transform_set_output_type */ - wma_transform_push_data, /* unix_wg_transform_push_data */ - wma_transform_read_data, /* unix_wg_transform_read_data */ - wma_transform_get_status, /* unix_wg_transform_get_status */ - wma_transform_drain, /* unix_wg_transform_drain */ - wma_transform_flush, /* unix_wg_transform_flush */ - wma_transform_notify_qos, /* unix_wg_transform_notify_qos */ + wg_transform_push_data, /* unix_wg_transform_push_data */ + wg_transform_read_data, /* unix_wg_transform_read_data */ + wg_transform_get_status, /* unix_wg_transform_get_status */ + wg_transform_drain, /* unix_wg_transform_drain */ + wg_transform_flush, /* unix_wg_transform_flush */ + wg_transform_notify_qos, /* unix_wg_transform_notify_qos */ wma_not_implemented, /* unix_wg_muxer_create */ wma_not_implemented, /* unix_wg_muxer_destroy */ @@ -2866,6 +3946,13 @@ C_ASSERT( ARRAY_SIZE(__wine_unix_call_funcs) == unix_wg_funcs_count ); * the host -- but its `data` member holds a GUEST * address, so only that VALUE is converted. * + * The block a wg_media_type points at is used in place, audio and video + * alike: a WAVEFORMATEX(-EXTENSIBLE) or an MFVIDEOFORMAT, with its codec + * data after it, is fixed-width and laid out identically by i686-w64-mingw32 + * and the host (checked with llvm-mingw; the C_ASSERTs at the WMV decoder pin + * MFVIDEOFORMAT). The offsets asserted below are the i386 ones, measured the + * same way. + * * Everything else in the table takes either a bare wg_transform_t (a UINT64, * same in both) or a block of fixed-width scalars at identical offsets, so * those entries are shared with the 64-bit table rather than re-thunked: a @@ -2902,6 +3989,13 @@ struct wg_transform_output_type_params32 struct wg_media_type32 media_type; }; +C_ASSERT( offsetof(struct wg_transform_create_params32, output_type) == 32 ); +C_ASSERT( offsetof(struct wg_transform_create_params32, attrs) == 56 ); +C_ASSERT( sizeof(struct wg_transform_create_params32) == 80 ); +C_ASSERT( offsetof(struct wg_transform_sample_params32, result) == 12 ); +C_ASSERT( sizeof(struct wg_transform_output_type_params32) == 32 ); +C_ASSERT( sizeof(struct wg_sample) == 48 && offsetof(struct wg_sample, data) == 40 ); + static void media_type_from32( struct wg_media_type *type, const struct wg_media_type32 *type32 ) { type->major = type32->major; @@ -2909,7 +4003,7 @@ static void media_type_from32( struct wg_media_type *type, const struct wg_media type->u.format = ios_wow_host_ptr( type32->format ); } -static NTSTATUS wow64_wma_transform_create( void *args ) +static NTSTATUS wow64_wg_transform_create( void *args ) { struct wg_transform_create_params32 *params32 = args; struct wg_transform_create_params params; @@ -2929,7 +4023,7 @@ static NTSTATUS wow64_wma_transform_create( void *args ) /* `sample` is a guest pointer; the struct it points at has the same layout in * both builds, so it is used in place and only sample->data is converted. */ -static NTSTATUS wow64_wma_transform_push_data( void *args ) +static NTSTATUS wow64_wg_transform_push_data( void *args ) { struct wg_transform_sample_params32 *params32 = args; struct wg_sample *sample; @@ -2940,7 +4034,7 @@ static NTSTATUS wow64_wma_transform_push_data( void *args ) ios_wow_host_ptr( (ULONG)sample->data ), ¶ms32->result ); } -static NTSTATUS wow64_wma_transform_read_data( void *args ) +static NTSTATUS wow64_wg_transform_read_data( void *args ) { struct wg_transform_sample_params32 *params32 = args; struct wg_sample *sample; @@ -2951,7 +4045,7 @@ static NTSTATUS wow64_wma_transform_read_data( void *args ) ios_wow_host_ptr( (ULONG)sample->data ), ¶ms32->result ); } -static NTSTATUS wow64_wma_transform_get_output_type( void *args ) +static NTSTATUS wow64_wg_transform_get_output_type( void *args ) { struct wg_transform_output_type_params32 *params32 = args; struct wg_media_type type; @@ -2967,7 +4061,7 @@ static NTSTATUS wow64_wma_transform_get_output_type( void *args ) return status; } -static NTSTATUS wow64_wma_transform_set_output_type( void *args ) +static NTSTATUS wow64_wg_transform_set_output_type( void *args ) { struct wg_transform_output_type_params32 *params32 = args; struct wg_media_type type; @@ -3117,17 +4211,17 @@ const unixlib_entry_t __wine_unix_call_wow64_funcs[] = wow64_wgp_get_tag, /* unix_wg_parser_stream_get_tag */ wgp_seek, /* unix_wg_parser_stream_seek */ - wow64_wma_transform_create, /* unix_wg_transform_create */ - wma_transform_destroy, /* unix_wg_transform_destroy */ - wow64_wma_transform_get_output_type, /* unix_wg_transform_get_output_type */ - wow64_wma_transform_set_output_type, /* unix_wg_transform_set_output_type */ - - wow64_wma_transform_push_data, /* unix_wg_transform_push_data */ - wow64_wma_transform_read_data, /* unix_wg_transform_read_data */ - wma_transform_get_status, /* unix_wg_transform_get_status */ - wma_transform_drain, /* unix_wg_transform_drain */ - wma_transform_flush, /* unix_wg_transform_flush */ - wma_transform_notify_qos, /* unix_wg_transform_notify_qos */ + wow64_wg_transform_create, /* unix_wg_transform_create */ + wg_transform_destroy, /* unix_wg_transform_destroy */ + wow64_wg_transform_get_output_type, /* unix_wg_transform_get_output_type */ + wow64_wg_transform_set_output_type, /* unix_wg_transform_set_output_type */ + + wow64_wg_transform_push_data, /* unix_wg_transform_push_data */ + wow64_wg_transform_read_data, /* unix_wg_transform_read_data */ + wg_transform_get_status, /* unix_wg_transform_get_status */ + wg_transform_drain, /* unix_wg_transform_drain */ + wg_transform_flush, /* unix_wg_transform_flush */ + wg_transform_notify_qos, /* unix_wg_transform_notify_qos */ wma_not_implemented, /* unix_wg_muxer_create */ wma_not_implemented, /* unix_wg_muxer_destroy */ diff --git a/build/tools/gen-config-catalog.py b/build/tools/gen-config-catalog.py index 928bc67857..798cf0a03c 100644 --- a/build/tools/gen-config-catalog.py +++ b/build/tools/gen-config-catalog.py @@ -584,6 +584,9 @@ "eco": { "note": 'Runs guest threads at a lower iOS QoS class so the system favours efficiency and saves power; can cost speed. Class chosen by eco-qos.',"title": "Eco scheduling"}, "eco-qos": {"title": "Eco QoS class", "kind": "choice", "note": "The QoS class guest threads run at while eco is on.", "choices": [("", "Utility (default)"), ("background", "Background"), ("initiated", "User initiated")]}, + "env.MADEIRA_WG_WMV_TRANSFORM": {"title": "Media: WMV video decoder", + "note": "0 refuses every video transform again, as before: the WMVideo Decoder DMO and MFT cannot be " + "created. By default they decode WMV1/2/3, WMVA and WVC1 with libavcodec. WMA is unaffected."}, "env.MADEIRA_WG_VIDEO": {"title": "Media: MP4 video (32-bit programs)", "note": "0 limits the media parser to MP3/WAV; by default MP4 with H.264/HEVC video decodes through VideoToolbox."}, "env.MADEIRA_WOW_RWX_PLAIN": {"category": "Memory & JIT pool", "note": "Unset: a 32-bit window's anonymous RWX memory is plain read/write to the host once Wine Mono's libmono-2.0-x86.dll is mapped there (ml1279/ml1282). 1: in every 32-bit window. 0: never (stores go through the JIT pool's alias, and FEX's Mono bridge stays off)."}, diff --git a/docs/MEDIA.md b/docs/MEDIA.md index 073518f968..fad852e3a9 100644 --- a/docs/MEDIA.md +++ b/docs/MEDIA.md @@ -15,7 +15,13 @@ three things that Windows programs use every day have no decoder: `WMCreateSyncReader`, and DirectShow's WM ASF Reader on top of it), which plays WMV/WMA (ASF) files. A visual novel's cutscenes went through it; the reader failed to connect (`no enabled demuxer recognised the stream`, - `0x80040265`) and the game showed a white screen with no sound. + `0x80040265`) and the game showed a white screen with no sound; +- the WMVideo Decoder DMO and MFT (`CLSID_CWMVDecMediaObject`, Wine's + `wmv_decoder_create()` in `dlls/winegstreamer/video_decoder.c`), which a + DirectShow graph or a Media Foundation pipeline uses to decode compressed + Windows Media video. Sabbat of the Witch's `krmovie.dll` reads compressed + WMV3 samples from `IWMSyncReader` and decodes them with it; without it the + DMO could not even be created and the cutscenes were a white screen. This port supplies that unix side in `libntdll_unix.a`, bound by name in `load_builtin_unixlib()` (`build/ntdll-unix/virtual_ios.c`). @@ -23,16 +29,17 @@ This port supplies that unix side in `libntdll_unix.a`, bound by name in **32-bit (WoW64) and 64-bit (ARM64EC) processes both get it.** The ARM64EC farm ships `winegstreamer.dll` and `wmadmod.dll`, so an x64 program's xWMA voices (XAudio2/FAudio's WMA decoder DMO) decode instead of playing silence. -A 64-bit process gets the WMA transform only: its `wg_parser` (quartz / Media -Foundation source) is refused as before unless `MADEIRA_WG_64BIT=1`. +A 64-bit process gets the transforms only (the WMA and WMV decoders and the +resampler): its `wg_parser` (quartz / Media Foundation source) is refused as +before unless `MADEIRA_WG_64BIT=1`. `MADEIRA_WG_64BIT=0` gives 64-bit processes the generic stub table again. ## Pieces | File | What it is | |---|---| -| `build/ntdll-unix/winegstreamer_unixlib_ios.c` | Both unix call tables (entry for entry with `dlls/winegstreamer/unixlib.h`), the wow64 thunks, and the `wg_transform` subset `wma_decoder.c` uses, on libavcodec: WMA v1/v2/Pro/Lossless and XMA1/2 only. Other transforms (AAC, H.264, WMV, resampler, colour converter) are refused at create, and `wg_muxer` returns `STATUS_NOT_IMPLEMENTED`. | -| `build/ntdll-unix/wg_parser_av_ios.c` | The `wg_parser` core, `#include`d by the file above: the PE read thread's pull protocol as an AVIOContext, libavformat demux (mp3, wav, mov, asf), MPEG audio / PCM / WMA decode through libavcodec + libswresample, Windows Media video (WMV7/8/9, VC-1, MS-MPEG4 v1-v3) decoded in software by libavcodec (`mav_lavc_video`), a packet queue with back-pressure, B-frame reordering, keyframe seek with exact trim, and conversion to the formats `quartz_parser.c`, `media_source.c` and `wm_reader.c` ask for: NV12, I420, YV12, YUY2, UYVY, YVYU, BGRx, BGRA, RGBA, 24-bit BGR (the WM reader's default, bottom-up), RGB565 and RGB555. | +| `build/ntdll-unix/winegstreamer_unixlib_ios.c` | Both unix call tables (entry for entry with `dlls/winegstreamer/unixlib.h`), the wow64 thunks, and two kinds of `wg_transform` on libavcodec: the WMA decoder `wma_decoder.c` uses (WMA v1/v2/Pro/Lossless, XMA1/2) and the WMV decoder `video_decoder.c`'s WMVideo Decoder DMO/MFT uses (WMV1, WMV2, WMV3, WMVA, WVC1; see below). `transform_create` gives a create to the first kind that claims its input type; every other entry finds the kind by the magic its object starts with. Other transforms (AAC, H.264, the resampler, the colour converter) are refused at create, and `wg_muxer` returns `STATUS_NOT_IMPLEMENTED`. | +| `build/ntdll-unix/wg_parser_av_ios.c` | The `wg_parser` core, `#include`d by the file above: the PE read thread's pull protocol as an AVIOContext, libavformat demux (mp3, wav, mov, asf), MPEG audio / PCM / WMA decode through libavcodec + libswresample, Windows Media video (WMV7/8/9, VC-1, MS-MPEG4 v1-v3) decoded in software by libavcodec (`mav_lavc_video`), a packet queue with back-pressure, B-frame reordering, keyframe seek with exact trim, and conversion (`mav_convert_picture`, which the WMV transform uses too) to the formats `quartz_parser.c`, `media_source.c` and `wm_reader.c` ask for: NV12, I420, YV12, YUY2, UYVY, YVYU, BGRx, BGRA, RGBA, 24-bit BGR (the WM reader's default, bottom-up), RGB565 and RGB555. | | `build/ntdll-unix/wg_parser_apple_ios.c` | H.264/HEVC on VideoToolbox (NV12 out) and AAC on an AudioToolbox AudioConverter (float PCM out). Its own translation unit with no Wine or FFmpeg header. | | `build/ntdll-unix/wg_parser_backend_ios.h` | The contract between the core and a decoder backend; plain C types only, so the host test can supply stub backends. | | `build/ffmpeg/build.sh` | FFmpeg 7.1.5, pinned by SHA-256, LGPL-only configuration. | @@ -70,6 +77,39 @@ asks for NV12 still gets it from the YUV types listed after the native one. `stream N: first picture delivered` (or `first audio buffer delivered`) once, so a device log shows whether any sample was ever requested. +**The WMV decoder (`wg_transform`).** `video_decoder.c` probes a WMV3 +1920x1080 to I420 transform without codec private data when the DMO is +created (`check_video_transform_support`), and libavcodec cannot open `wmv3` +or `vc1` without it. So a create whose input type has no codec private data +succeeds with the decoder closed and logs `[decoder not open: ...]`; frames +pushed into such a transform are dropped and logged. A sequence header that +libavcodec refuses refuses the create. As in upstream's GStreamer +`wg_transform.c`, `push_data` only queues the compressed frame (at most +`input_queue_length` + 1, then `MF_E_NOTACCEPTING`) and `read_data` decodes +until a picture comes out. Nothing ready is `MF_E_TRANSFORM_NEED_MORE_INPUT`, +which the DMO turns into `S_FALSE`. A picture is never split, so +`WG_SAMPLE_FLAG_INCOMPLETE` (the DMO's `DMO_OUTPUT_DATA_BUFFERF_INCOMPLETE`, +on which Wine's DMO wrapper calls `ProcessOutput` again) is never set. Output +formats: NV12, YV12, I420/IYUV, YUY2, UYVY, YVYU, RGB32, ARGB32, ABGR32, +RGB24, RGB565 and RGB555, top-down or bottom-up +(`MFVideoFlag_BottomUpLinearRep`). NV11 and RGB8 are refused, as GStreamer +refuses them. The frame is laid out as upstream's does it (4-byte aligned +rows, NV12 at 2), or at the stride of the caller's 2D buffer. An aperture +smaller than the frame is where the picture goes. A picture is not scaled: a +different size is cropped or padded with black, unless the caller allowed a +format change (`MF_E_TRANSFORM_STREAM_CHANGE`, then `get_output_type`; WMV +callers never allow it). Each picture is a sync point and keeps the time and +duration of the sample it was coded in, flagged +`WG_SAMPLE_FLAG_PRESERVE_TIMESTAMPS`, as `video_decoder.c` expects. A sample +without a time gets the previous picture's end (the first gets 0) and one +frame at the input type's frame rate. `set_output_type` keeps the decoder and +the pictures it holds, and writes them in the new format. Limits: WMV3 and +VC-1 are checked by codec-id plumbing only, because FFmpeg cannot encode +them. The DMO never drains, so a picture the decoder holds back (WMV3 with +B-frames) is lost at the end of a stream, as with GStreamer. When the DMO +wrapper meets a new output media type, `video_decoder.c` makes a new +transform, whose new decoder waits for a keyframe. + **One demuxer, several readers: back-pressure.** Each stream is read on its own thread by quartz and Media Foundation; a packet read for another stream is queued for it. A stream whose reader falls behind (a video decoded slower @@ -97,15 +137,18 @@ Environment variables (`env.NAME = value` in `madeira.cfg`): | Variable | Default | Effect | |---|---|---| -| `MADEIRA_WG_64BIT` | WMA only | `0`: 64-bit processes get the stub table again; `1`: their `wg_parser` too (see above). | +| `MADEIRA_WG_64BIT` | transforms only | `0`: 64-bit processes get the stub table again; `1`: their `wg_parser` too (see above). | | `MADEIRA_WG_PARSER` | on | `0`: `wg_parser_create` returns `STATUS_NOT_IMPLEMENTED` again, as before this series; quartz and the MF source then fail the way they did. The WMA decoder is unaffected. | | `MADEIRA_WG_VIDEO` | on | `0`: MP3/WAV only; an MP4/MOV or ASF is refused at connect. | +| `MADEIRA_WG_WMV_TRANSFORM` | on | `0`: every video `wg_transform` is refused at create again, so the WMVideo Decoder DMO/MFT cannot be created, as before. Read once per process. WMA is unaffected. | | `MADEIRA_WG_VIDEO_FORMAT` | `rgb32` | Native format a video stream reports: `nv12`, `i420`, `yv12`, `yuy2`, `rgb32`, `argb32` or `abgr32` (see above for why the default is `rgb32`). | | `MADEIRA_WMA_SEARCH` | on | `0`: keep the WMA v1/v2 decoder at the bit rate and flags it opened with; no search over other candidates when a bit-reservoir stream fails. A packet that fails is concealed with silence of its length and the next one is decoded as usual. (An xWMA stream still opens at the rate libavformat's xWMA table normalises to.) | | `MADEIRA_WMA_DUMP` | off | Set: write each WMA decoder's input to `wma-dump-.bin` in the Documents folder, for reproducing a decode failure on a host. | -Log tags: `[wma]` for the decoder, `[wg-parser]` for the parser; both are -rate-limited per process (`MADEIRA_DIAG=1` lifts the `[wma]` cap). +Log tags: `[wma]` for the WMA decoder, `[wmv]` for the WMV decoder (one line +per create and per destroy, refusals with their reason), `[wg-parser]` for the +parser. All are rate-limited per process (`MADEIRA_DIAG=1` lifts the `[wma]` +and `[wmv]` caps). ## Tests @@ -135,9 +178,25 @@ rate-limited per process (`MADEIRA_DIAG=1` lifts the `[wma]` cap). FFmpeg's own encoders at several rates and channel counts, drives them through the `wg_transform` entries the way `wma_decoder.c` does, to s16 and to float, with the parameter search on and off, and requires audio with the - right level and fundamental back. Also checks that 64-bit callers keep the - stub table by default. Bit-reservoir (superframe) streams are not covered: + right level and fundamental back. Also checks that 64-bit callers get the + transforms by default and their parser only with `MADEIRA_WG_64BIT=1`. Bit-reservoir (superframe) streams are not covered: FFmpeg cannot encode them. +- `tests/host/check-wmv-transform.py` (Linux or macOS, needs a configured + Wine tree): source checks on both call tables, the kind table, the switch, + and the facts of the Wine pin the transform relies on. Then it compiles the + production file under ASan/UBSan against the host FFmpeg build that + `check-wg-parser-asf.py` uses, encodes WMV7 and WMV8 streams with FFmpeg's + encoders, and drives them through both call tables. It checks: every + picture bit-exact against libavcodec; every output format in both + orientations at the default layout and at a 2D buffer's stride, pixel by + pixel with the bytes around them untouched; apertures, cropping and + padding; timestamps; the queue limit, drain, flush, mid-stream + `set_output_type`, a format change, a buffer too small; Wine's DMO-wrapper + loop; two threads; refusals; the wow64 thunks with 32-bit argument blocks + below 4 GB; WMA through the same dispatcher; and + `MADEIRA_WG_WMV_TRANSFORM=0`. WMV3/WVC1/WMVA are covered by codec-id + plumbing only (the DMO's probe, hand-built sequence headers, garbage + frames): FFmpeg cannot encode them. - `tests/x86/wma-x86.c` (`build-wma-test.sh`): a 32-bit program that reaches the WMA decoder exactly as FAudio does and checks that the decoded PCM has the 440 Hz fundamental it was encoded from. Exit 62 pass, 63 decode diff --git a/tests/host/check-wma-decoder.py b/tests/host/check-wma-decoder.py index 42e6c291f1..ad0eced89c 100755 --- a/tests/host/check-wma-decoder.py +++ b/tests/host/check-wma-decoder.py @@ -220,7 +220,7 @@ create.output_type.major = madeira_MFMediaType_Audio; create.output_type.format_size = sizeof(WAVEFORMATEX); create.output_type.u.audio = &out.wfx; - CHECK( !wma_transform_create( &create ) && create.transform, "create failed" ); + CHECK( !wg_transform_create( &create ) && create.transform, "create failed" ); chunk = (size_t)s.block_align * packets_per_push; for (off = 0; off <= s.size; ) @@ -235,7 +235,7 @@ sample.data = (UINT64)(UINT_PTR)(s.data + off); push.transform = create.transform; push.sample = &sample; - CHECK( !wma_transform_push_data( &push ), "push_data failed" ); + CHECK( !wg_transform_push_data( &push ), "push_data failed" ); hr = push.result; if (hr == MF_E_NOTACCEPTING) goto drain_out; CHECK( hr == S_OK, "push result %#x", (unsigned)hr ); @@ -243,7 +243,7 @@ } else { - CHECK( !wma_transform_drain( &create.transform ), "drain failed" ); + CHECK( !wg_transform_drain( &create.transform ), "drain failed" ); off++; } drain_out: @@ -254,7 +254,7 @@ sample.data = (UINT64)(UINT_PTR)outbuf; read.transform = create.transform; read.sample = &sample; - CHECK( !wma_transform_read_data( &read ), "read_data failed" ); + CHECK( !wg_transform_read_data( &read ), "read_data failed" ); if (read.result == MF_E_TRANSFORM_NEED_MORE_INPUT) break; CHECK( read.result == S_OK && sample.size, "read result %#x size %u", (unsigned)read.result, sample.size ); CHECK( sample.size % out.wfx.nBlockAlign == 0, "partial frame (%u bytes)", sample.size ); @@ -302,7 +302,7 @@ } } done: - if (create.transform) wma_transform_destroy( &create.transform ); + if (create.transform) wg_transform_destroy( &create.transform ); free( pcm ); free( s.data ); return 0; diff --git a/tests/host/check-wmv-transform.py b/tests/host/check-wmv-transform.py new file mode 100644 index 0000000000..fe5e16719e --- /dev/null +++ b/tests/host/check-wmv-transform.py @@ -0,0 +1,1305 @@ +#!/usr/bin/env python3 +"""The WMV video transform in build/ntdll-unix/winegstreamer_unixlib_ios.c, on the host; no Wine runs. + +Sabbat of the Witch (32-bit, KiriKiri) decodes its WMV3 cutscenes with the WMVideo Decoder DMO, +which in Wine is video_decoder.c's wmv_decoder_create() on a wg_transform. This port's transform +refused every video stream, so the DMO could not even be created and the cutscenes were white. + +1. Source checks: both unix call tables route the transform rows to the kind dispatcher + (wg_transform_*, wow64_wg_transform_* for the five entries whose argument block holds a + pointer); the WMV kind is a row of the kind table; MADEIRA_WG_WMV_TRANSFORM is read once; the + facts of our Wine pin the transform is built on still hold (wmv_decoder_create's WMV3 probe, + no allow_format_change for WMV, the DMO's NEED_MORE_INPUT -> S_FALSE and INCOMPLETE mapping, + the DMO wrapper looping on INCOMPLETE); docs/MEDIA.md and the settings catalog list it. +2. Host FFmpeg 7.1.5 from the tracked tarball with check-wg-parser-asf.py's exact component list + (so the two share one cached build): the port's WMV/WMA decoders plus TEST-ONLY wmv1/wmv2/wmav2 + encoders. +3. Compiles the production file under ASan/UBSan against a configured Wine tree's headers and + drives it through __wine_unix_call_funcs / __wine_unix_call_wow64_funcs: + - WMV7 (wmv1) and WMV8 (wmv2): create, push, read, drain, flush; every picture bit-exact against + an independent libavcodec decode, in order; + - every output format (NV12 YV12 I420 IYUV YUY2 UYVY YVYU RGB32 ARGB32 ABGR32 RGB24 RGB565 + RGB555), top-down and bottom-up, at the default layout and at a 2D buffer's stride: sizes, + every pixel (YUV exact, RGB against an independent BT.601 conversion), the bytes around them + untouched; a wider frame with an aperture, an aperture offset, a smaller and a larger frame; + - timestamps and durations as video_decoder.c expects them (preserved, irregular, none with and + without a frame rate), sync points, discontinuities, never INCOMPLETE; + - the queue limit, get_status, drain with frames still queued, flush and decode after it, + set_output_type mid-stream with pictures pending, get_output_type's two phases, a format + change when allowed, a buffer too small, two threads; + - the DMO wrapper's one-read-per-input loop at video_decoder.c's attributes; + - refusals: H.264, WMVP, VC1S, raw video in; NV11, RGB8, AYUV out; no frame size; a sequence + header libavcodec refuses; audio in with video out; + - WMV3 / WVC1 / WMVA by codec-id plumbing ONLY (FFmpeg cannot encode them): the + wmv_decoder_create() probe (WMV3 1920x1080, no sequence header) is accepted with the decoder + closed and swallows input without crashing; with a hand-built sequence header the right + libavcodec decoder opens, and garbage frames are rejected without output or crash; + - the wow64 thunks with 32-bit argument blocks in memory below 4 GB (MAP_32BIT; skipped where + the host has none), output identical to the 64-bit entries; + - a WMA v2 stream through the same dispatcher (check-wma-decoder.py is the full WMA check); + and again with MADEIRA_WG_WMV_TRANSFORM=0: every video create refused, WMA unaffected. + +Environment: MADEIRA_FFMPEG_TARBALL (default: build/ffmpeg/src/ffmpeg-7.1.5.tar.xz), +MADEIRA_HOST_FFMPEG_ASF (prefix of an existing host build with the components below), +MADEIRA_WINE_BUILD (a configured Wine build tree whose include/ holds config.h and the +widl-generated headers; default: wine/build-macos). +""" +from pathlib import Path +import hashlib, os, re, subprocess, sys, tempfile + +root = Path(__file__).resolve().parents[2] +ntdll_unix = root / "build/ntdll-unix" +wine = Path(os.environ.get("MADEIRA_WINE_SRC") or root / "wine") +wine_build = Path(os.environ.get("MADEIRA_WINE_BUILD") or wine / "build-macos") +glue = (ntdll_unix / "winegstreamer_unixlib_ios.c").read_text() +unixlib_h = (wine / "dlls/winegstreamer/unixlib.h").read_text() +failures = [] + + +def check(cond, what): + print(("PASS " if cond else "FAIL ") + what, flush=True) + if not cond: + failures.append(what) + + +def body(text, start, end="\n}\n"): + if start not in text: + return "" + b = text[text.index(start):] + return b[:b.index(end) + len(end)] if end in b else b + + +# ------------------------------------------------------------------ 1. source checks +enum_body = unixlib_h[unixlib_h.index("enum unix_funcs"):] +enum_body = enum_body[enum_body.index("{") + 1:enum_body.index("unix_wg_funcs_count")] +enum_names = re.findall(r"\b(unix_wg_\w+)\s*,", enum_body) + + +def table(name): + b = body(glue, "const unixlib_entry_t %s[] =" % name, "};") + rows = re.findall(r"^\s*(\w+),\s*/\*\s*(unix_wg_\w+)\s*\*/", b, re.M) + return [r[1] for r in rows], dict((r[1], r[0]) for r in rows) + + +order64, native = table("__wine_unix_call_funcs") +order32, wow64 = table("__wine_unix_call_wow64_funcs") +check(order64 == enum_names and order32 == enum_names, "both call tables follow enum unix_funcs entry for entry") +pointer_rows = {"create", "get_output_type", "set_output_type", "push_data", "read_data"} +rows_ok = True +for n in enum_names: + if not n.startswith("unix_wg_transform_"): + continue + short = n[len("unix_wg_transform_"):] + rows_ok &= native.get(n) == "wg_transform_" + short + rows_ok &= wow64.get(n) == ("wow64_wg_transform_" + short if short in pointer_rows else "wg_transform_" + short) +check(rows_ok, "transform rows: wg_transform_* dispatchers; wow64 thunks for the five pointer-carrying ones, " + "the other five shared") +kinds = body(glue, "static const struct wg_transform_ops *const transform_kinds[] =", "};") +check("&wma_transform_ops," in kinds and "&wmv_transform_ops," in kinds, "WMA and WMV are rows of the kind table") +create = body(glue, "static NTSTATUS transform_create( struct wg_transform_create_params *params )") +check("transform_kinds[i]->claims( params )" in create and "transform_kinds[i]->create( params )" in create, + "transform_create gives the create to the first kind that claims the input") +switch = body(glue, "static BOOL wmv_transform_switch_on(void)") +check(glue.count('getenv( "MADEIRA_WG_WMV_TRANSFORM" )') == 1 and 'getenv( "MADEIRA_WG_WMV_TRANSFORM" )' in switch + and "static int on = -1;" in switch, "MADEIRA_WG_WMV_TRANSFORM is read once, in wmv_transform_switch_on") +check("wmv_transform_switch_on()" in body(glue, "static BOOL wmv_claims("), "the WMV kind claims nothing when switched off") +wmv_read = body(glue, "static NTSTATUS wmv_read_data(") +check(wmv_read and "|= WG_SAMPLE_FLAG_INCOMPLETE" not in wmv_read and "WG_SAMPLE_FLAG_INCOMPLETE" in wmv_read, + "the WMV read clears WG_SAMPLE_FLAG_INCOMPLETE and never sets it") +check("mav_convert_picture( &g.vout, transform->bt709, &planes, data, &g.layout );" in wmv_read, + "pictures are written by wg_parser_av_ios.c's mav_convert_picture") +# the Wine pin +vd = (wine / "dlls/winegstreamer/video_decoder.c").read_text() +wmv_create = body(vd, "HRESULT wmv_decoder_create(") +check(".guidFormat = MFVideoFormat_WMV3," in wmv_create and ".guidFormat = MFVideoFormat_I420," in wmv_create + and "check_video_transform_support(&input_format, &output_format)" in wmv_create, + "pin: wmv_decoder_create() probes a WMV3 -> I420 transform with no codec private data") +check(vd.count("allow_format_change = TRUE") == 1 and "allow_format_change = TRUE" in body(vd, "HRESULT h264_decoder_create("), + "pin: only the H.264 decoder allows a format change") +dmo_out = body(vd, "static HRESULT WINAPI media_object_ProcessOutput(") +check("hr == MF_E_TRANSFORM_NEED_MORE_INPUT" in dmo_out and "hr = S_FALSE;" in dmo_out, + "pin: the DMO's ProcessOutput turns NEED_MORE_INPUT into S_FALSE") +ws = (wine / "dlls/winegstreamer/wg_sample.c").read_text() +check("buffer->dwStatus |= DMO_OUTPUT_DATA_BUFFERF_INCOMPLETE" in body(ws, "HRESULT wg_transform_read_dmo("), + "pin: WG_SAMPLE_FLAG_INCOMPLETE becomes DMO_OUTPUT_DATA_BUFFERF_INCOMPLETE") +dw = (wine / "dlls/qasf/dmowrapper.c").read_text() +check("more_data = TRUE;" in body(dw, "static HRESULT process_output(") and "} while (more_data);" in dw, + "pin: the DMO wrapper calls ProcessOutput again while INCOMPLETE is set") +media = (root / "docs/MEDIA.md").read_text() +check("MADEIRA_WG_WMV_TRANSFORM" in media and "check-wmv-transform.py" in media + and "WMV, resampler" not in media, "docs/MEDIA.md documents the WMV transform, its switch and this check") +catalog = (root / "app/Madeira/ConfigCatalog.generated.swift").read_text() +check('key: "env.MADEIRA_WG_WMV_TRANSFORM"' in catalog, "the settings catalog lists env.MADEIRA_WG_WMV_TRANSFORM") + +for need in [wine_build / "include/config.h", wine_build / "include/mfobjects.h"]: + if not need.exists(): + sys.exit("SKIP-FAIL: %s is missing; point MADEIRA_WINE_BUILD at a configured Wine tree" % need) + +# ------------------------------------------------------------------ 2. host FFmpeg +# check-wg-parser-asf.py's list, verbatim: the same key, so one cached build serves both. +tarball = os.environ.get("MADEIRA_FFMPEG_TARBALL") or str(root / "build/ffmpeg/src/ffmpeg-7.1.5.tar.xz") +FLAGS = [ + "--disable-everything", "--disable-autodetect", "--disable-gpl", "--disable-nonfree", "--disable-version3", + "--enable-decoder=wmav1,wmav2,wmapro,wmalossless", "--enable-decoder=mp1,mp2,mp3", + "--enable-decoder=pcm_u8,pcm_s16le,pcm_s24le,pcm_s32le,pcm_f32le,pcm_f64le", + "--enable-decoder=wmv1,wmv2,wmv3,vc1,msmpeg4v1,msmpeg4v2,msmpeg4v3", + "--enable-demuxer=mp3,wav,mov,asf", "--enable-parser=mpegaudio", + # TEST ONLY: input synthesis + "--enable-encoder=wmv1,wmv2,msmpeg4v3,wmav2", "--enable-muxer=asf", + "--disable-programs", "--disable-doc", "--disable-network", "--disable-avdevice", "--disable-swscale", + "--disable-avfilter", "--disable-postproc", "--enable-avformat", "--enable-avcodec", "--enable-swresample", + "--disable-asm", "--disable-shared", "--enable-static", "--enable-pic", "--disable-debug", +] +prefix = os.environ.get("MADEIRA_HOST_FFMPEG_ASF") +if not prefix: + key = hashlib.sha256(" ".join(FLAGS).encode()).hexdigest()[:12] + prefix = str(Path.home() / ".cache/madeira-host-ffmpeg" / ("7.1.5-asf-" + key)) + if not (Path(prefix) / "lib/libavformat.a").exists(): + assert Path(tarball).exists(), "no FFmpeg tarball at build/ffmpeg/src (tracked) and no MADEIRA_FFMPEG_TARBALL" + src = Path(prefix + "-src"); src.mkdir(parents=True, exist_ok=True) + if not (src / "ffmpeg-7.1.5/configure").exists(): + subprocess.run(["tar", "-xJf", tarball, "-C", str(src)], check=True) + bld = Path(prefix + "-build"); bld.mkdir(parents=True, exist_ok=True) + print("building host FFmpeg into", prefix, flush=True) + log = open(str(bld) + ".log", "w") + subprocess.run([str(src / "ffmpeg-7.1.5/configure"), "--prefix=" + prefix, "--cc=cc"] + FLAGS, + cwd=bld, check=True, stdout=log, stderr=subprocess.STDOUT) + subprocess.run(["make", "-j%d" % (os.cpu_count() or 4)], cwd=bld, check=True, stdout=log, stderr=subprocess.STDOUT) + subprocess.run(["make", "install"], cwd=bld, check=True, stdout=log, stderr=subprocess.STDOUT) +inc, lib = Path(prefix) / "include", Path(prefix) / "lib" + +# ------------------------------------------------------------------ 3. harness +harness = r""" +#include "winegstreamer_unixlib_ios.c" +#include +#include + +/* What the device build gets from wg_parser_apple_ios.c. */ +const struct mav_video_backend mav_apple_video_backend; +const struct mav_audio_backend mav_apple_audio_backend; + +static int failures, checks; +#define CHECK(c, ...) do { checks++; if (!(c)) { printf( "FAIL %s:%d: ", __func__, __LINE__ ); printf( __VA_ARGS__ ); \ + printf( "\n" ); fflush( stdout ); failures++; return 1; } } while (0) +#define PASS(...) do { printf( "PASS " __VA_ARGS__ ); printf( "\n" ); fflush( stdout ); } while (0) + +#define W 176 +#define H 144 +#define FPS 25 +#define GOP 12 +#define FRAMES 40 +#define TICK (10000000 / FPS) + +/* ---- entries, through the real tables ---- */ +static NTSTATUS call64( unsigned int code, void *args ) { return __wine_unix_call_funcs[code]( args ); } +static NTSTATUS call32( unsigned int code, void *args ) { return __wine_unix_call_wow64_funcs[code]( args ); } + +/* ---- media types ---- */ +static const GUID video_base = { 0, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } }; +#define FCC(a,b,c,d) ((UINT32)(a) | ((UINT32)(b) << 8) | ((UINT32)(c) << 16) | ((UINT32)(d) << 24)) + +struct vfmt { MFVIDEOFORMAT f; BYTE extra[64]; }; + +static struct wg_media_type make_video( struct vfmt *v, UINT32 fourcc, UINT32 w, UINT32 h, UINT32 fps_n, UINT32 fps_d, + const BYTE *extra, UINT32 extra_size, BOOL bottom_up ) +{ + struct wg_media_type type; + + memset( v, 0, sizeof(*v) ); + v->f.dwSize = sizeof(v->f) + extra_size; + v->f.guidFormat = video_base; + v->f.guidFormat.Data1 = fourcc; + v->f.videoInfo.dwWidth = w; + v->f.videoInfo.dwHeight = h; + v->f.videoInfo.FramesPerSecond.Numerator = fps_n; + v->f.videoInfo.FramesPerSecond.Denominator = fps_d; + if (bottom_up) v->f.videoInfo.VideoFlags |= MFVideoFlag_BottomUpLinearRep; + if (extra_size) memcpy( v->extra, extra, extra_size ); + type.major = madeira_MFMediaType_Video; + type.format_size = v->f.dwSize; + type.u.video = &v->f; + return type; +} + +/* ---- the streams: a moving pattern encoded by FFmpeg's own encoders, and an independent decode ---- */ +struct packet { uint8_t *data; int size, key; }; +struct picture { uint8_t y[W * H], u[W * H / 4], v[W * H / 4]; }; +struct stream +{ + UINT32 fourcc; + struct packet packets[FRAMES]; + uint8_t extradata[64]; + int extradata_size; + struct picture ref[FRAMES]; /* libavcodec's own decode, in order */ +}; +static struct stream wmv1, wmv2; + +static int encode( enum AVCodecID id, struct stream *s ) +{ + const AVCodec *enc = avcodec_find_encoder( id ), *dec = avcodec_find_decoder( id ); + AVCodecContext *c = avcodec_alloc_context3( enc ), *d = avcodec_alloc_context3( dec ); + AVFrame *frame = av_frame_alloc(), *out = av_frame_alloc(); + AVPacket *pkt = av_packet_alloc(); + int i, n = 0, got = 0, x, y, err; + + c->width = W; c->height = H; + c->time_base = (AVRational){ 1, FPS }; + c->pix_fmt = AV_PIX_FMT_YUV420P; + c->gop_size = GOP; + c->max_b_frames = 0; + c->bit_rate = 1500000; + if ((err = avcodec_open2( c, enc, NULL )) < 0) return err; + frame->format = c->pix_fmt; frame->width = W; frame->height = H; + av_frame_get_buffer( frame, 0 ); + for (i = 0; i <= FRAMES; i++) + { + if (i < FRAMES) + { + av_frame_make_writable( frame ); + for (y = 0; y < H; y++) + for (x = 0; x < W; x++) + { + int box = x >= 20 + 3 * i && x < 60 + 3 * i && y >= 30 + i && y < 80 + i; + frame->data[0][y * frame->linesize[0] + x] = box ? 220 : (uint8_t)(32 + (x + 2 * y + 4 * i) % 160); + } + for (y = 0; y < H / 2; y++) + for (x = 0; x < W / 2; x++) + { + frame->data[1][y * frame->linesize[1] + x] = (uint8_t)(64 + (x * 3 + i) % 128); + frame->data[2][y * frame->linesize[2] + x] = (uint8_t)(200 - (y * 2 + i) % 128); + } + frame->pts = i; + } + if ((err = avcodec_send_frame( c, i < FRAMES ? frame : NULL )) < 0) return err; + while (avcodec_receive_packet( c, pkt ) >= 0) + { + if (n >= FRAMES) return -1000; + s->packets[n].data = malloc( pkt->size ); + memcpy( s->packets[n].data, pkt->data, pkt->size ); + s->packets[n].size = pkt->size; + s->packets[n].key = !!(pkt->flags & AV_PKT_FLAG_KEY); + n++; + av_packet_unref( pkt ); + } + } + if (n != FRAMES) return -2000 - n; + s->extradata_size = c->extradata_size; + if (c->extradata_size > (int)sizeof(s->extradata)) return -3000; + if (c->extradata_size) memcpy( s->extradata, c->extradata, c->extradata_size ); + + /* the reference: a plain libavcodec decode of the same packets */ + d->width = W; d->height = H; d->thread_count = 1; + if (s->extradata_size) + { + d->extradata = av_mallocz( s->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE ); + memcpy( d->extradata, s->extradata, s->extradata_size ); + d->extradata_size = s->extradata_size; + } + if ((err = avcodec_open2( d, dec, NULL )) < 0) return err; + for (i = 0; i <= FRAMES; i++) + { + if (i < FRAMES) + { + pkt->data = s->packets[i].data; pkt->size = s->packets[i].size; + err = avcodec_send_packet( d, pkt ); + } + else err = avcodec_send_packet( d, NULL ); + if (err < 0) return err; + while (avcodec_receive_frame( d, out ) >= 0) + { + if (got >= FRAMES || out->width != W || out->height != H || out->format != AV_PIX_FMT_YUV420P) return -4000; + for (y = 0; y < H; y++) memcpy( s->ref[got].y + y * W, out->data[0] + y * out->linesize[0], W ); + for (y = 0; y < H / 2; y++) + { + memcpy( s->ref[got].u + y * W / 2, out->data[1] + y * out->linesize[1], W / 2 ); + memcpy( s->ref[got].v + y * W / 2, out->data[2] + y * out->linesize[2], W / 2 ); + } + got++; + av_frame_unref( out ); + } + } + pkt->data = NULL; pkt->size = 0; + avcodec_free_context( &c ); avcodec_free_context( &d ); + av_frame_free( &frame ); av_frame_free( &out ); av_packet_free( &pkt ); + return got == FRAMES ? 0 : -5000 - got; +} + +/* ---- an independent oracle for where each byte goes ---- */ +enum { F_NV12, F_YV12, F_I420, F_IYUV, F_YUY2, F_UYVY, F_YVYU, F_BGRX, F_BGRA, F_RGBA, F_BGR, F_565, F_555, F_COUNT }; +static const struct { const char *name; UINT32 tag; int bpp; } formats[F_COUNT] = +{ + { "NV12", FCC('N','V','1','2'), 1 }, { "YV12", FCC('Y','V','1','2'), 1 }, { "I420", FCC('I','4','2','0'), 1 }, + { "IYUV", FCC('I','Y','U','V'), 1 }, { "YUY2", FCC('Y','U','Y','2'), 2 }, { "UYVY", FCC('U','Y','V','Y'), 2 }, + { "YVYU", FCC('Y','V','Y','U'), 2 }, { "RGB32", 22, 4 }, { "ARGB32", 21, 4 }, { "ABGR32", 32, 4 }, + { "RGB24", 20, 3 }, { "RGB565", 23, 2 }, { "RGB555", 24, 2 }, +}; +static int planar( int f ) { return f <= F_IYUV; } +static int packed_yuv( int f ) { return f >= F_YUY2 && f <= F_YVYU; } +static UINT32 align4( UINT32 x ) { return (x + 3) & ~3u; } + +struct geom +{ + int f, flip; + UINT32 fw, fh, s0, s1; + size_t off1, off2, size; + UINT32 rx, ry, rw, rh; /* the region the picture goes to */ +}; + +static void geom_init( struct geom *g, int f, UINT32 fw, UINT32 fh, int flip, UINT32 stride ) +{ + UINT32 ch = (fh + 1) / 2; + memset( g, 0, sizeof(*g) ); + g->f = f; g->fw = fw; g->fh = fh; g->flip = flip; + if (f == F_NV12) g->s0 = g->s1 = (fw + 1) & ~1u; + else if (planar( f )) { g->s0 = align4( fw ); g->s1 = align4( (fw + 1) / 2 ); } + else if (f == F_BGR) g->s0 = align4( fw * 3 ); + else if (formats[f].bpp == 4) g->s0 = fw * 4; + else g->s0 = align4( fw * 2 ); + if (stride) { g->s0 = stride; g->s1 = f == F_NV12 ? stride : stride / 2; } + if (planar( f )) + { + g->off1 = (size_t)g->s0 * fh; + g->off2 = g->off1 + (size_t)g->s1 * ch; + g->size = f == F_NV12 ? g->off2 : g->off2 + (size_t)g->s1 * ch; + } + else g->size = (size_t)g->s0 * fh; + g->rw = fw; g->rh = fh; +} + +static int clip8( double v ) { return v < 0 ? 0 : v > 255 ? 255 : (int)lround( v ); } + +/* BT.601, video range: what an untagged SD stream is. */ +static void rgb_of( int Y, int U, int V, int *r, int *g, int *b ) +{ + double y = (Y - 16) * 255.0 / 219.0, u = (U - 128) * 255.0 / 224.0, v = (V - 128) * 255.0 / 224.0; + *r = clip8( y + 1.402 * v ); + *g = clip8( y - 0.344136 * u - 0.714136 * v ); + *b = clip8( y + 1.772 * u ); +} + +/* Byte offsets of display pixel (x, y): luma (or the packed pixel), and for planar formats Cb, Cr. */ +static void locate( const struct geom *g, UINT32 x, UINT32 y, size_t *luma, size_t *cb, size_t *cr ) +{ + UINT32 row = g->flip ? g->fh - 1 - y : y, ch = (g->fh + 1) / 2, crow = g->flip ? ch - 1 - y / 2 : y / 2; + + *cb = *cr = 0; + if (planar( g->f )) + { + *luma = (size_t)g->s0 * row + x; + if (g->f == F_NV12) + { + *cb = g->off1 + (size_t)g->s1 * crow + (x / 2) * 2; + *cr = *cb + 1; + } + else + { + size_t first = g->off1 + (size_t)g->s1 * crow + x / 2, second = g->off2 + (size_t)g->s1 * crow + x / 2; + *cb = g->f == F_YV12 ? second : first; + *cr = g->f == F_YV12 ? first : second; + } + } + else *luma = (size_t)g->s0 * row + (size_t)(packed_yuv( g->f ) ? (x / 2) * 4 : x * formats[g->f].bpp); +} + +/* Checks `buf` (pre-filled with 0xCD, `guard` more bytes after the frame) against picture `p` + * (W x H) placed at the region; outside the picture: black when `black`, else untouched. */ +static int check_frame( const char *what, const struct geom *g, const uint8_t *buf, size_t guard, + const struct picture *p, int black ) +{ + uint8_t *mask = calloc( 1, g->size ); + UINT32 x, y, cw = g->rw < W ? g->rw : W, chh = g->rh < H ? g->rh : H; + size_t i, l, cb, cr; + int bad = 0; + + for (y = 0; y < g->rh && !bad; y++) + for (x = 0; x < g->rw && !bad; x++) + { + UINT32 X = g->rx + x, Y = g->ry + y; + int in = x < cw && y < chh; + int Yv = in ? p->y[y * W + x] : 16, U = in ? p->u[(y / 2) * (W / 2) + x / 2] : 128; + int V = in ? p->v[(y / 2) * (W / 2) + x / 2] : 128; + locate( g, X, Y, &l, &cb, &cr ); + if (!in && !black) continue; + if (planar( g->f )) + { + if (buf[l] != Yv) bad = 1; + mask[l] = 1; + if (!(x & 1) && !(y & 1)) + { + if (buf[cb] != U || buf[cr] != V) bad = 2; + mask[cb] = mask[cr] = 1; + } + } + else if (packed_yuv( g->f )) + { + static const int yo[3][2] = { { 0, 2 }, { 1, 3 }, { 0, 2 } }, uo[3] = { 1, 0, 3 }, vo[3] = { 3, 2, 1 }; + int k = g->f - F_YUY2; + if (!in) { Yv = 16; U = V = 128; } + if (buf[l + yo[k][x & 1]] != Yv || buf[l + uo[k]] != U || buf[l + vo[k]] != V) bad = 3; + mask[l + yo[k][x & 1]] = mask[l + uo[k]] = mask[l + vo[k]] = 1; + } + else + { + int r, gg, b, er, eg, eb; + if (in) rgb_of( Yv, U, V, &er, &eg, &eb ); else er = eg = eb = 0; + if (g->f == F_565 || g->f == F_555) + { + unsigned px = buf[l] | (buf[l + 1] << 8); + int gbits = g->f == F_565 ? 6 : 5; + r = (px >> (gbits + 5)) & 31; gg = (px >> 5) & ((1 << gbits) - 1); b = px & 31; + if (abs( r - (er >> 3) ) > 1 || abs( gg - (eg >> (8 - gbits)) ) > 1 || abs( b - (eb >> 3) ) > 1) bad = 4; + if (g->f == F_555 && (px & 0x8000)) bad = 5; + mask[l] = mask[l + 1] = 1; + } + else + { + int ri = g->f == F_RGBA ? 0 : 2, bi = 2 - ri; + r = buf[l + ri]; gg = buf[l + 1]; b = buf[l + bi]; + if (abs( r - er ) > 2 || abs( gg - eg ) > 2 || abs( b - eb ) > 2) bad = 6; + if (formats[g->f].bpp == 4 && buf[l + 3] != 0xff) bad = 7; + for (i = 0; i < (size_t)formats[g->f].bpp; i++) mask[l + i] = 1; + } + } + if (bad) printf( " %s: pixel (%u,%u) wrong (kind %d)\n", what, X, Y, bad ); + } + if (!bad && !black) + for (i = 0; i < g->size; i++) + if (!mask[i] && buf[i] != 0xcd) { printf( " %s: byte %zu outside the picture was written\n", what, i ); bad = 8; break; } + for (i = 0; !bad && i < guard; i++) + if (buf[g->size + i] != 0xcd) { printf( " %s: wrote past the frame\n", what ); bad = 9; } + free( mask ); + return bad; +} + +/* ---- driving a transform ---- */ +struct tx { wg_transform_t h; int use32; }; + +static NTSTATUS create( wg_transform_t *h, const struct wg_media_type *in, const struct wg_media_type *out, + const struct wg_transform_attrs *attrs ) +{ + struct wg_transform_create_params p = { 0 }; + NTSTATUS status; + p.input_type = *in; p.output_type = *out; + if (attrs) p.attrs = *attrs; + status = call64( unix_wg_transform_create, &p ); + *h = p.transform; + return status; +} + +static HRESULT push( wg_transform_t h, const struct packet *pk, INT64 pts, INT64 duration, UINT32 flags ) +{ + struct wg_transform_push_data_params p = { 0 }; + struct wg_sample s = { 0 }; + s.size = s.max_size = pk ? pk->size : 0; + s.data = (UINT64)(UINT_PTR)(pk ? pk->data : NULL); + s.flags = flags | (pk && pk->key ? WG_SAMPLE_FLAG_SYNC_POINT : 0); + if (pts != INT64_MIN) { s.flags |= WG_SAMPLE_FLAG_HAS_PTS; s.pts = pts; } + if (duration != INT64_MIN) { s.flags |= WG_SAMPLE_FLAG_HAS_DURATION; s.duration = duration; } + p.transform = h; p.sample = &s; + if (call64( unix_wg_transform_push_data, &p )) return E_FAIL; + return p.result; +} + +static NTSTATUS readx( wg_transform_t h, struct wg_sample *s, uint8_t *buf, UINT32 max, UINT32 stride, HRESULT *hr ) +{ + struct wg_transform_read_data_params p = { 0 }; + NTSTATUS status; + memset( s, 0, sizeof(*s) ); + s->max_size = max; s->stride = stride; s->data = (UINT64)(UINT_PTR)buf; + p.transform = h; p.sample = s; + status = call64( unix_wg_transform_read_data, &p ); + *hr = p.result; + return status; +} + +static void destroy( wg_transform_t h ) { call64( unix_wg_transform_destroy, &h ); } + +static const struct wg_transform_attrs decoder_attrs = { .input_queue_length = 15, .preserve_timestamps = TRUE }; + +/* ---------------------------------------------------------------- tests */ + +/* video_decoder.c's MFT loop: push, then read until NEED_MORE_INPUT; drain at the end. */ +static int test_decode( struct stream *s, const char *name ) +{ + struct vfmt vi, vo; + struct wg_media_type in = make_video( &vi, s->fourcc, W, H, FPS, 1, s->extradata, s->extradata_size, FALSE ); + struct wg_media_type out = make_video( &vo, FCC('N','V','1','2'), W, H, FPS, 1, NULL, 0, FALSE ); + struct geom g; + uint8_t *buf; + struct wg_sample smp; + wg_transform_t h; + HRESULT hr; + int i, n = 0; + + geom_init( &g, F_NV12, W, H, 0, 0 ); + buf = malloc( g.size + 64 ); + CHECK( !create( &h, &in, &out, &decoder_attrs ) && h, "%s: create", name ); + for (i = 0; i <= FRAMES; i++) + { + if (i < FRAMES) CHECK( push( h, &s->packets[i], (INT64)i * TICK, TICK, 0 ) == S_OK, "%s: push %d", name, i ); + else { wg_transform_t hh = h; CHECK( !call64( unix_wg_transform_drain, &hh ), "%s: drain", name ); } + for (;;) + { + memset( buf, 0xcd, g.size + 64 ); + CHECK( !readx( h, &smp, buf, g.size, 0, &hr ), "%s: read status", name ); + if (hr == MF_E_TRANSFORM_NEED_MORE_INPUT) { CHECK( !smp.size, "%s: size with no output", name ); break; } + CHECK( hr == S_OK, "%s: read hr %#x", name, (unsigned)hr ); + CHECK( n < FRAMES, "%s: more pictures than frames", name ); + CHECK( smp.size == g.size, "%s: picture %d is %u bytes, expected %zu", name, n, smp.size, g.size ); + CHECK( !check_frame( name, &g, buf, 64, &s->ref[n], 0 ), "%s: picture %d differs from libavcodec's", name, n ); + CHECK( smp.flags == (WG_SAMPLE_FLAG_SYNC_POINT | WG_SAMPLE_FLAG_HAS_PTS | WG_SAMPLE_FLAG_HAS_DURATION + | WG_SAMPLE_FLAG_PRESERVE_TIMESTAMPS), "%s: flags %#x", name, smp.flags ); + CHECK( smp.pts == (INT64)n * TICK && smp.duration == TICK, "%s: picture %d at %lld for %llu", + name, n, (long long)smp.pts, (unsigned long long)smp.duration ); + n++; + } + } + CHECK( n == FRAMES, "%s: %d pictures for %d frames", name, n, FRAMES ); + { + struct mav_lavc_vdec *d = get_wmv_transform( h )->dec; + CHECK( d && d->ctx->codec_id == (s->fourcc == FCC('W','M','V','1') ? AV_CODEC_ID_WMV1 : AV_CODEC_ID_WMV2), + "%s: the wrong libavcodec decoder", name ); + } + destroy( h ); + free( buf ); + PASS( "%s: %d frames -> %d NV12 pictures, bit-exact with libavcodec, pts/duration preserved, drained", name, FRAMES, n ); + return 0; +} + +/* One stream into one output format; every picture checked. */ +static int run_format( struct stream *s, int f, int flip, UINT32 fw, UINT32 fh, UINT32 stride, + const MFVideoArea *aperture, int expect_black, const char *what ) +{ + struct vfmt vi, vo; + struct wg_media_type in = make_video( &vi, s->fourcc, W, H, FPS, 1, s->extradata, s->extradata_size, FALSE ); + struct wg_media_type out = make_video( &vo, formats[f].tag, fw, fh, FPS, 1, NULL, 0, flip ); + struct wg_sample smp; + struct geom g; + wg_transform_t h; + uint8_t *buf; + HRESULT hr; + int i, n = 0; + char name[160]; + + snprintf( name, sizeof(name), "%s %s%s %ux%u stride %u%s", formats[f].name, flip ? "bottom-up" : "top-down", + what, fw, fh, stride, aperture ? " aperture" : "" ); + if (aperture) vo.f.videoInfo.MinimumDisplayAperture = *aperture; + geom_init( &g, f, fw, fh, flip, stride ); + if (aperture) { g.rx = aperture->OffsetX.value; g.ry = aperture->OffsetY.value; g.rw = aperture->Area.cx; g.rh = aperture->Area.cy; } + buf = malloc( g.size + 64 ); + CHECK( !create( &h, &in, &out, &decoder_attrs ) && h, "%s: create", name ); + for (i = 0; i < FRAMES; i++) + { + CHECK( push( h, &s->packets[i], (INT64)i * TICK, TICK, 0 ) == S_OK, "%s: push", name ); + memset( buf, 0xcd, g.size + 64 ); + CHECK( !readx( h, &smp, buf, g.size, stride, &hr ) && hr == S_OK, "%s: read %d hr %#x", name, i, (unsigned)hr ); + CHECK( smp.size == g.size, "%s: %u bytes, expected %zu", name, smp.size, g.size ); + CHECK( !check_frame( name, &g, buf, 64, &s->ref[n], expect_black ), "%s: picture %d", name, n ); + n++; + } + destroy( h ); + free( buf ); + return 0; +} + +static int test_formats(void) +{ + MFVideoArea ap = { 0 }; + int f, flip, k = 0; + + for (f = 0; f < F_COUNT; f++) + for (flip = 0; flip <= 1; flip++) + { + UINT32 stride = planar( f ) ? 256 : W * formats[f].bpp + 64; + if (run_format( &wmv2, f, flip, W, H, 0, NULL, 0, "" )) return 1; + if (run_format( &wmv2, f, flip, W, H, stride, NULL, 0, " (2D buffer)" )) return 1; + k += 2; + } + PASS( "every output format, top-down and bottom-up, default layout and 2D-buffer stride: %d runs of %d pictures, " + "sizes, pixels and the bytes around them", k, FRAMES ); + + /* A frame wider and taller than the picture with the picture's aperture: rows at the frame's + * stride, the rest of the frame untouched (the DirectShow way of asking for a stride). */ + ap.Area.cx = W; ap.Area.cy = H; + for (f = 0; f < F_COUNT; f++) + for (flip = 0; flip <= 1; flip++) + if (run_format( &wmv2, f, flip, W + 32, H + 16, 0, &ap, 0, "" )) return 1; + ap.OffsetX.value = 8; ap.OffsetY.value = 4; + if (run_format( &wmv2, F_NV12, 0, W + 32, H + 16, 0, &ap, 0, " offset" )) return 1; + if (run_format( &wmv2, F_I420, 1, W + 32, H + 16, 0, &ap, 0, " offset" )) return 1; + if (run_format( &wmv2, F_YUY2, 1, W + 32, H + 16, 0, &ap, 0, " offset" )) return 1; + if (run_format( &wmv2, F_BGRX, 1, W + 32, H + 16, 0, &ap, 0, " offset" )) return 1; + PASS( "an aperture inside a larger frame, every format, both orientations; at an offset too" ); + + /* No format change allowed: a smaller frame crops, a larger one is padded with black. */ + for (f = 0; f < F_COUNT; f++) + { + if (run_format( &wmv2, f, f & 1, 160, 120, 0, NULL, 0, " (cropped)" )) return 1; + if (run_format( &wmv2, f, f & 1, 200, 160, 0, NULL, 1, " (padded)" )) return 1; + } + /* Width 170 = 2 mod 4: NV12 rows stay 2-aligned (wg_transform.c), I420 rows 4-aligned. */ + if (run_format( &wmv2, F_NV12, 0, 170, H, 0, NULL, 0, " (2-aligned)" )) return 1; + if (run_format( &wmv2, F_I420, 0, 170, H, 0, NULL, 0, " (4-aligned)" )) return 1; + if (run_format( &wmv2, F_BGR, 1, 170, H, 0, NULL, 0, " (4-aligned)" )) return 1; + PASS( "a smaller frame crops, a larger one is padded with black; NV12 at width 170 has 170-byte rows" ); + return 0; +} + +static int test_timestamps(void) +{ + static const INT64 irregular[][2] = + { + { 666666, 166667 }, { 833333, 166666 }, { 999999, 166666 }, { 1166665, 166667 }, { 1333332, 166667 }, + }; + struct vfmt vi, vo; + struct wg_media_type in, out; + struct wg_transform_attrs attrs; + struct wg_sample smp; + wg_transform_t h; + uint8_t *buf = malloc( W * H * 4 ); + HRESULT hr; + int i, pass; + + for (pass = 0; pass < 4; pass++) + { + /* 0: irregular times, preserved; 1: times, not preserved; 2: no times at 25 fps; 3: no times, no rate */ + in = make_video( &vi, wmv1.fourcc, W, H, pass == 3 ? 0 : FPS, pass == 3 ? 0 : 1, NULL, 0, FALSE ); + out = make_video( &vo, FCC('Y','U','Y','2'), W, H, 0, 0, NULL, 0, FALSE ); + attrs = decoder_attrs; + attrs.preserve_timestamps = pass != 1; + CHECK( !create( &h, &in, &out, &attrs ), "timestamps %d: create", pass ); + for (i = 0; i < 5; i++) + { + UINT32 want = WG_SAMPLE_FLAG_SYNC_POINT | WG_SAMPLE_FLAG_HAS_PTS | WG_SAMPLE_FLAG_HAS_DURATION; + INT64 pts = pass < 2 ? irregular[i][0] : INT64_MIN, dur = pass < 2 ? irregular[i][1] : INT64_MIN; + INT64 want_pts = pass < 2 ? irregular[i][0] : pass == 2 ? (INT64)i * TICK : 0; + INT64 want_dur = pass < 2 ? irregular[i][1] : pass == 2 ? TICK : 0; + CHECK( push( h, &wmv1.packets[i], pts, dur, i == 3 ? WG_SAMPLE_FLAG_DISCONTINUITY : 0 ) == S_OK, "push" ); + CHECK( !readx( h, &smp, buf, W * H * 4, 0, &hr ) && hr == S_OK, "timestamps %d: read %d", pass, i ); + if (pass == 0) want |= WG_SAMPLE_FLAG_PRESERVE_TIMESTAMPS; + if (i == 3) want |= WG_SAMPLE_FLAG_DISCONTINUITY; + CHECK( smp.flags == want, "timestamps %d: picture %d flags %#x, expected %#x", pass, i, smp.flags, want ); + CHECK( smp.pts == want_pts && (INT64)smp.duration == want_dur, "timestamps %d: picture %d at %lld for %lld, " + "expected %lld for %lld", pass, i, (long long)smp.pts, (long long)smp.duration, (long long)want_pts, + (long long)want_dur ); + } + destroy( h ); + } + free( buf ); + PASS( "timestamps: irregular ones preserved (with and without PRESERVE_TIMESTAMPS), none -> 0, 400000, ... at 25 fps " + "and 0/0 without a rate; every picture a sync point; a discontinuity reaches the next picture" ); + return 0; +} + +static int test_queue_drain_flush(void) +{ + struct vfmt vi, vo; + struct wg_media_type in = make_video( &vi, wmv2.fourcc, W, H, FPS, 1, wmv2.extradata, wmv2.extradata_size, FALSE ); + struct wg_media_type out = make_video( &vo, FCC('N','V','1','2'), W, H, 0, 0, NULL, 0, FALSE ); + struct wg_transform_get_status_params st = { 0 }; + struct wg_transform_attrs attrs = { 0 }; + struct wg_sample smp; + struct geom g; + wg_transform_t h, hh; + uint8_t *buf; + HRESULT hr; + int i, n; + + geom_init( &g, F_NV12, W, H, 0, 0 ); + buf = malloc( g.size + 64 ); + + /* input_queue_length 15: sixteen frames queue, the seventeenth is refused */ + CHECK( !create( &h, &in, &out, &decoder_attrs ), "queue: create" ); + for (i = 0; i < 16; i++) + { + st.transform = h; + CHECK( !call64( unix_wg_transform_get_status, &st ) && st.accepts_input, "queue: get_status before %d", i ); + CHECK( push( h, &wmv2.packets[i], (INT64)i * TICK, TICK, 0 ) == S_OK, "queue: push %d", i ); + } + CHECK( !call64( unix_wg_transform_get_status, &st ) && !st.accepts_input, "queue: get_status when full" ); + CHECK( push( h, &wmv2.packets[16], 16 * TICK, TICK, 0 ) == MF_E_NOTACCEPTING, "queue: the 17th frame is refused" ); + for (n = 0; ; n++) + { + memset( buf, 0xcd, g.size + 64 ); + CHECK( !readx( h, &smp, buf, g.size, 0, &hr ), "queue: read" ); + if (hr != S_OK) break; + CHECK( !check_frame( "queue", &g, buf, 64, &wmv2.ref[n], 0 ), "queue: picture %d", n ); + } + CHECK( n == 16 && hr == MF_E_TRANSFORM_NEED_MORE_INPUT, "queue: %d pictures, then %#x", n, (unsigned)hr ); + CHECK( !call64( unix_wg_transform_get_status, &st ) && st.accepts_input, "queue: get_status when empty" ); + destroy( h ); + + /* input_queue_length 0 (check_video_transform_support's attributes): one frame at a time */ + CHECK( !create( &h, &in, &out, &attrs ), "queue 0: create" ); + CHECK( push( h, &wmv2.packets[0], 0, TICK, 0 ) == S_OK && push( h, &wmv2.packets[1], TICK, TICK, 0 ) == MF_E_NOTACCEPTING, + "queue 0: one frame, then MF_E_NOTACCEPTING" ); + destroy( h ); + + /* drain with frames queued: input is refused until they have all been read */ + CHECK( !create( &h, &in, &out, &decoder_attrs ), "drain: create" ); + for (i = 0; i < 5; i++) CHECK( push( h, &wmv2.packets[i], (INT64)i * TICK, TICK, 0 ) == S_OK, "drain: push" ); + hh = h; + CHECK( !call64( unix_wg_transform_drain, &hh ), "drain" ); + CHECK( push( h, &wmv2.packets[5], 5 * TICK, TICK, 0 ) == MF_E_NOTACCEPTING, "drain: input refused while draining" ); + for (n = 0; ; n++) + { + CHECK( !readx( h, &smp, buf, g.size, 0, &hr ), "drain: read" ); + if (hr != S_OK) break; + CHECK( !check_frame( "drain", &g, buf, 64, &wmv2.ref[n], 0 ) && smp.pts == (INT64)n * TICK, "drain: picture %d", n ); + } + CHECK( n == 5 && hr == MF_E_TRANSFORM_NEED_MORE_INPUT, "drain: %d pictures", n ); + CHECK( push( h, &wmv2.packets[0], 0, TICK, 0 ) == S_OK, "drain: input accepted once drained" ); + CHECK( !readx( h, &smp, buf, g.size, 0, &hr ) && hr == S_OK && !check_frame( "after drain", &g, buf, 64, &wmv2.ref[0], 0 ), + "drain: the decoder decodes again after its end of stream" ); + CHECK( !call64( unix_wg_transform_drain, &hh ), "drain empty" ); + CHECK( !readx( h, &smp, buf, g.size, 0, &hr ) && hr == MF_E_TRANSFORM_NEED_MORE_INPUT && !smp.size, "drain: nothing left" ); + destroy( h ); + + /* flush: queued frames and decoded pictures go; decoding resumes at the next keyframe */ + CHECK( !create( &h, &in, &out, &decoder_attrs ), "flush: create" ); + hh = h; + CHECK( !call64( unix_wg_transform_flush, &hh ), "flush a fresh transform" ); + for (i = 0; i < 4; i++) CHECK( push( h, &wmv2.packets[i], (INT64)i * TICK, TICK, 0 ) == S_OK, "flush: push" ); + CHECK( !readx( h, &smp, buf, g.size, 0, &hr ) && hr == S_OK, "flush: read one" ); + CHECK( !call64( unix_wg_transform_flush, &hh ), "flush" ); + CHECK( !readx( h, &smp, buf, g.size, 0, &hr ) && hr == MF_E_TRANSFORM_NEED_MORE_INPUT && !smp.size, "flush: nothing left" ); + for (i = GOP; i < GOP + 6; i++) + { + CHECK( push( h, &wmv2.packets[i], (INT64)i * TICK, TICK, 0 ) == S_OK, "flush: push after" ); + CHECK( !readx( h, &smp, buf, g.size, 0, &hr ) && hr == S_OK, "flush: read after" ); + CHECK( !check_frame( "after flush", &g, buf, 64, &wmv2.ref[i], 0 ) && smp.pts == (INT64)i * TICK, + "flush: picture %d after the flush", i ); + } + destroy( h ); + free( buf ); + PASS( "queue limit (16 at input_queue_length 15, 1 at 0) and get_status; drain with frames queued refuses input until " + "they are read, then decodes again; flush drops everything and decoding resumes at a keyframe" ); + return 0; +} + +/* The MFT's SetOutputType on a live transform: the decoder state is kept, pending pictures come + * out in the new format. The switch is mid-GOP, so a decoder reset would show. */ +static int test_set_output_type(void) +{ + struct vfmt vi, vo, vo2; + struct wg_media_type in = make_video( &vi, wmv2.fourcc, W, H, FPS, 1, wmv2.extradata, wmv2.extradata_size, FALSE ); + struct wg_media_type out = make_video( &vo, FCC('N','V','1','2'), W, H, 0, 0, NULL, 0, FALSE ); + struct wg_media_type out2 = make_video( &vo2, 22, W, H, 0, 0, NULL, 0, TRUE ); + struct wg_transform_set_output_type_params so = { 0 }; + struct wg_transform_get_output_type_params go = { 0 }; + struct wg_sample smp; + struct geom g, g2; + wg_transform_t h; + uint8_t *buf, fmt[512]; + HRESULT hr; + int i; + + geom_init( &g, F_NV12, W, H, 0, 0 ); + geom_init( &g2, F_BGRX, W, H, 1, 0 ); + buf = malloc( g2.size + 64 ); + CHECK( !create( &h, &in, &out, &decoder_attrs ), "create" ); + for (i = 0; i < 5; i++) + { + CHECK( push( h, &wmv2.packets[i], (INT64)i * TICK, TICK, 0 ) == S_OK, "push" ); + memset( buf, 0xcd, g2.size + 64 ); + CHECK( !readx( h, &smp, buf, g.size, 0, &hr ) && hr == S_OK && !check_frame( "nv12", &g, buf, 64, &wmv2.ref[i], 0 ), + "picture %d", i ); + } + for (; i < 8; i++) CHECK( push( h, &wmv2.packets[i], (INT64)i * TICK, TICK, 0 ) == S_OK, "push pending" ); + so.transform = h; so.media_type = out2; + CHECK( !call64( unix_wg_transform_set_output_type, &so ), "set_output_type" ); + /* get_output_type, two-phase: the size first, then the type exactly as set */ + go.transform = h; + CHECK( call64( unix_wg_transform_get_output_type, &go ) == STATUS_BUFFER_TOO_SMALL && go.media_type.format_size == out2.format_size, + "get_output_type: size first (%u)", go.media_type.format_size ); + go.media_type.u.format = fmt; + CHECK( !call64( unix_wg_transform_get_output_type, &go ) && IsEqualGUID( &go.media_type.major, &madeira_MFMediaType_Video ) + && !memcmp( fmt, &vo2.f, out2.format_size ), "get_output_type: the type as set" ); + for (i = 5; i < FRAMES; i++) + { + if (i >= 8) CHECK( push( h, &wmv2.packets[i], (INT64)i * TICK, TICK, 0 ) == S_OK, "push" ); + memset( buf, 0xcd, g2.size + 64 ); + CHECK( !readx( h, &smp, buf, g2.size, 0, &hr ) && hr == S_OK, "read %d", i ); + CHECK( smp.size == g2.size && !check_frame( "rgb32", &g2, buf, 64, &wmv2.ref[i], 0 ), "picture %d after the switch", i ); + } + /* an output the transform cannot write is refused, and the old one stays */ + so.media_type = make_video( &vo2, FCC('N','V','1','1'), W, H, 0, 0, NULL, 0, FALSE ); + CHECK( call64( unix_wg_transform_set_output_type, &so ) == STATUS_NOT_SUPPORTED, "set_output_type NV11 refused" ); + destroy( h ); + free( buf ); + PASS( "set_output_type mid-GOP with 3 pictures pending: they and the rest come out in RGB32 bottom-up, decoded " + "on from the same state; get_output_type's two phases; NV11 refused and the old type kept" ); + return 0; +} + +static int test_format_change_and_small_buffer(void) +{ + struct vfmt vi, vo; + struct wg_media_type in = make_video( &vi, wmv2.fourcc, W, H, FPS, 1, wmv2.extradata, wmv2.extradata_size, FALSE ); + struct wg_media_type out = make_video( &vo, FCC('I','4','2','0'), 160, 120, 0, 0, NULL, 0, FALSE ); + struct wg_transform_attrs attrs = decoder_attrs; + struct wg_transform_get_output_type_params go = { 0 }; + struct vfmt got; + struct wg_sample smp; + struct geom g; + wg_transform_t h; + uint8_t *buf; + HRESULT hr; + + attrs.allow_format_change = TRUE; + geom_init( &g, F_I420, W, H, 0, 0 ); + buf = malloc( g.size + 64 ); + CHECK( !create( &h, &in, &out, &attrs ), "create" ); + CHECK( push( h, &wmv2.packets[0], 0, TICK, 0 ) == S_OK, "push" ); + CHECK( !readx( h, &smp, buf, g.size, 0, &hr ) && hr == MF_E_TRANSFORM_STREAM_CHANGE && !smp.size, + "a 176x144 picture into 160x120 with a format change allowed: %#x", (unsigned)hr ); + go.transform = h; go.media_type.u.format = &got; go.media_type.format_size = sizeof(got); + CHECK( !call64( unix_wg_transform_get_output_type, &go ) && got.f.videoInfo.dwWidth == W && got.f.videoInfo.dwHeight == H + && got.f.guidFormat.Data1 == FCC('I','4','2','0'), "get_output_type: the new size" ); + /* a buffer too small: an error, and the picture waits for a bigger one */ + CHECK( readx( h, &smp, buf, g.size - 1, 0, &hr ) == STATUS_BUFFER_TOO_SMALL && !smp.size, "a buffer one byte short" ); + memset( buf, 0xcd, g.size + 64 ); + CHECK( !readx( h, &smp, buf, g.size, 0, &hr ) && hr == S_OK && smp.size == g.size + && !check_frame( "after change", &g, buf, 64, &wmv2.ref[0], 0 ), "the picture at the new size" ); + destroy( h ); + free( buf ); + PASS( "a format change when allowed: MF_E_TRANSFORM_STREAM_CHANGE once, get_output_type 176x144, then the picture; " + "a buffer too small is STATUS_BUFFER_TOO_SMALL and keeps the picture" ); + return 0; +} + +/* krmovie's path: Wine's DMO wrapper reads once per input (qasf dmowrapper.c), and video_decoder.c's + * DMO gives the transform input_queue_length 15 and preserve_timestamps. */ +static int test_dmo_loop(void) +{ + struct vfmt vi, vo; + struct wg_media_type in = make_video( &vi, wmv2.fourcc, W, H, FPS, 1, wmv2.extradata, wmv2.extradata_size, FALSE ); + struct wg_media_type out = make_video( &vo, 22, W, H, FPS, 1, NULL, 0, TRUE ); + struct wg_sample smp; + struct geom g; + wg_transform_t h; + uint8_t *buf; + HRESULT hr; + int i; + + geom_init( &g, F_BGRX, W, H, 1, 0 ); + buf = malloc( g.size + 64 ); + CHECK( !create( &h, &in, &out, &decoder_attrs ), "create" ); + for (i = 0; i < FRAMES; i++) + { + CHECK( push( h, &wmv2.packets[i], (INT64)i * TICK, TICK, 0 ) == S_OK, "ProcessInput %d", i ); + memset( buf, 0xcd, g.size + 64 ); + CHECK( !readx( h, &smp, buf, g.size, 0, &hr ) && hr == S_OK, "ProcessOutput %d: %#x", i, (unsigned)hr ); + CHECK( !(smp.flags & WG_SAMPLE_FLAG_INCOMPLETE) && smp.size == g.size, "ProcessOutput %d: flags %#x", i, smp.flags ); + CHECK( !check_frame( "dmo", &g, buf, 64, &wmv2.ref[i], 0 ) && smp.pts == (INT64)i * TICK, "picture %d", i ); + } + CHECK( !readx( h, &smp, buf, g.size, 0, &hr ) && hr == MF_E_TRANSFORM_NEED_MORE_INPUT && !smp.size, + "nothing more: NEED_MORE_INPUT with size 0 (the DMO's S_FALSE)" ); + destroy( h ); + free( buf ); + PASS( "the DMO wrapper's loop at video_decoder.c's attributes: one RGB32 bottom-up picture per input, never " + "INCOMPLETE, then NEED_MORE_INPUT" ); + return 0; +} + +struct thread_ctx { wg_transform_t h; int pushed; }; + +static void *pusher( void *arg ) +{ + struct thread_ctx *t = arg; + while (t->pushed < FRAMES) + { + HRESULT hr = push( t->h, &wmv2.packets[t->pushed], (INT64)t->pushed * TICK, TICK, 0 ); + if (hr == S_OK) t->pushed++; + else if (hr == MF_E_NOTACCEPTING) usleep( 100 ); + else break; + } + return NULL; +} + +static int test_threads(void) +{ + struct vfmt vi, vo; + struct wg_media_type in = make_video( &vi, wmv2.fourcc, W, H, FPS, 1, wmv2.extradata, wmv2.extradata_size, FALSE ); + struct wg_media_type out = make_video( &vo, FCC('Y','V','1','2'), W, H, 0, 0, NULL, 0, FALSE ); + struct thread_ctx t = { 0 }; + struct wg_sample smp; + struct geom g; + pthread_t thread; + uint8_t *buf; + HRESULT hr; + int n = 0, spins = 0; + + geom_init( &g, F_YV12, W, H, 0, 0 ); + buf = malloc( g.size + 64 ); + CHECK( !create( &t.h, &in, &out, &decoder_attrs ), "create" ); + pthread_create( &thread, NULL, pusher, &t ); + while (n < FRAMES && spins < 2000000) + { + CHECK( !readx( t.h, &smp, buf, g.size, 0, &hr ), "read" ); + if (hr == S_OK) + { + CHECK( !check_frame( "threads", &g, buf, 0, &wmv2.ref[n], 0 ) && smp.pts == (INT64)n * TICK, "picture %d", n ); + n++; + } + else spins++; + } + pthread_join( thread, NULL ); + CHECK( n == FRAMES, "%d pictures read while another thread pushed", n ); + destroy( t.h ); + free( buf ); + PASS( "push on one thread, read on another: all %d pictures, in order", n ); + return 0; +} + +static int test_refusals(void) +{ + static const BYTE bad_header[4] = { 0, 0, 0, 0 }; + static const struct { UINT32 in, out; UINT32 w, h; const BYTE *extra; UINT32 extra_size; const char *what; } cases[] = + { + { FCC('H','2','6','4'), FCC('N','V','1','2'), W, H, NULL, 0, "H.264 in" }, + { FCC('W','M','V','P'), FCC('N','V','1','2'), W, H, NULL, 0, "WMVP in" }, + { FCC('V','C','1','S'), FCC('N','V','1','2'), W, H, NULL, 0, "VC1S in" }, + { FCC('N','V','1','2'), FCC('I','4','2','0'), W, H, NULL, 0, "raw NV12 in (a video processor)" }, + { FCC('W','M','V','2'), FCC('N','V','1','1'), W, H, NULL, 0, "NV11 out" }, + { FCC('W','M','V','2'), 41 /* D3DFMT_P8 */, W, H, NULL, 0, "RGB8 out" }, + { FCC('W','M','V','2'), FCC('A','Y','U','V'), W, H, NULL, 0, "AYUV out" }, + { FCC('W','M','V','2'), FCC('N','V','1','2'), 0, 0, NULL, 0, "no frame size" }, + { FCC('W','M','V','3'), FCC('N','V','1','2'), W, H, bad_header, 4, "a WMV3 sequence header libavcodec refuses" }, + }; + static const GUID wmv_unknown = { 0x7ce12ca9, 0xbfbf, 0x43d9, { 0x9d, 0x00, 0x82, 0xb8, 0xed, 0x54, 0x31, 0x6b } }; + struct vfmt vi, vo; + struct wg_media_type in, out; + struct { WAVEFORMATEX wfx; BYTE extra[16]; } pcm = { { WAVE_FORMAT_PCM, 2, 44100, 176400, 4, 16, 0 } }; + wg_transform_t h, bogus_handle; + UINT32 bogus[16] = { 0x12345678 }; + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(cases); i++) + { + in = make_video( &vi, cases[i].in, cases[i].w, cases[i].h, FPS, 1, cases[i].extra, cases[i].extra_size, FALSE ); + out = make_video( &vo, cases[i].out, W, H, 0, 0, NULL, 0, FALSE ); + h = 0xdeadbeef; + CHECK( create( &h, &in, &out, &decoder_attrs ) == STATUS_NOT_SUPPORTED && !h, "%s: not refused", cases[i].what ); + } + in = make_video( &vi, 0, W, H, FPS, 1, NULL, 0, FALSE ); + vi.f.guidFormat = wmv_unknown; + CHECK( create( &h, &in, &out, &decoder_attrs ) == STATUS_NOT_SUPPORTED && !h, "MEDIASUBTYPE_WMV_Unknown in" ); + /* audio in, video out: the WMA kind's to refuse */ + in.major = madeira_MFMediaType_Audio; in.format_size = sizeof(pcm.wfx); in.u.audio = &pcm.wfx; + CHECK( create( &h, &in, &out, &decoder_attrs ) == STATUS_NOT_SUPPORTED && !h, "PCM in, video out" ); + /* neither audio nor video */ + in.major = video_base; in.major.Data1 = 0x12345678; + CHECK( create( &h, &in, &out, &decoder_attrs ) == STATUS_NOT_SUPPORTED && !h, "an unknown major type" ); + /* a handle no kind made */ + bogus_handle = (wg_transform_t)(UINT_PTR)bogus; + CHECK( call64( unix_wg_transform_drain, &bogus_handle ) == STATUS_INVALID_HANDLE + && call64( unix_wg_transform_destroy, &bogus_handle ) == STATUS_INVALID_HANDLE, "a foreign handle" ); + PASS( "refused: H.264, WMVP, VC1S, WMV_Unknown and raw video in; NV11, RGB8 and AYUV out; no frame size; a bad WMV3 " + "sequence header; PCM in with video out; an unknown major type; a foreign handle is STATUS_INVALID_HANDLE" ); + return 0; +} + +/* WMV3 / VC-1: FFmpeg has no encoder, so codec-id plumbing only. */ +static int test_wmv9_plumbing(void) +{ + static const BYTE wmv3_main[4] = { 0x40, 0x09, 0x88, 0x01 }; /* STRUCT_C: main profile, loop filter, ... */ + static const BYTE vc1_adv[18] = /* sequence header (0x0000010f) + entry point (0x0000010e), 320x240 */ + { 0x00, 0x00, 0x01, 0x0f, 0xca, 0x00, 0x09, 0xf0, 0x77, 0x08, 0x80, 0x00, 0x00, 0x01, 0x0e, 0x4c, 0x40, 0x80 }; + static const struct { UINT32 fourcc; UINT32 w, h; const BYTE *extra; UINT32 extra_size; enum AVCodecID id; const char *what; } cases[] = + { + { FCC('W','M','V','3'), 1920, 1080, NULL, 0, AV_CODEC_ID_NONE, "WMV3 1920x1080 without a sequence header (wmv_decoder_create's probe)" }, + { FCC('W','V','C','1'), 320, 240, NULL, 0, AV_CODEC_ID_NONE, "WVC1 without a sequence header" }, + { FCC('W','M','V','3'), 320, 240, wmv3_main, 4, AV_CODEC_ID_WMV3, "WMV3 main profile" }, + { FCC('W','V','C','1'), 320, 240, vc1_adv, sizeof(vc1_adv), AV_CODEC_ID_VC1, "WVC1 advanced profile" }, + { FCC('W','M','V','A'), 320, 240, vc1_adv, sizeof(vc1_adv), AV_CODEC_ID_VC1, "WMVA" }, + }; + struct vfmt vi, vo; + struct wg_media_type in, out; + struct wg_transform_attrs probe_attrs = { 0 }; + struct packet garbage; + struct wg_sample smp; + struct wmv_transform *t; + uint8_t *buf = malloc( 1920 * 1088 * 2 ), junk[3000]; + unsigned int i, k, seed = 7; + wg_transform_t h; + HRESULT hr; + + for (k = 0; k < sizeof(junk); k++) junk[k] = (uint8_t)((seed = seed * 1103515245 + 12345) >> 16); + garbage.data = junk; garbage.size = sizeof(junk); garbage.key = 1; + for (i = 0; i < ARRAY_SIZE(cases); i++) + { + in = make_video( &vi, cases[i].fourcc, cases[i].w, cases[i].h, 30000, 1001, cases[i].extra, cases[i].extra_size, FALSE ); + out = make_video( &vo, FCC('I','4','2','0'), cases[i].w, cases[i].h, 0, 0, NULL, 0, FALSE ); + CHECK( !create( &h, &in, &out, i ? &decoder_attrs : &probe_attrs ) && h, "%s: create", cases[i].what ); + t = get_wmv_transform( h ); + CHECK( t, "%s: not a WMV transform", cases[i].what ); + CHECK( t->codec == (cases[i].fourcc == FCC('W','M','V','3') ? MAV_LAVC_WMV3 : MAV_LAVC_VC1), "%s: codec %d", cases[i].what, t->codec ); + if (cases[i].id == AV_CODEC_ID_NONE) CHECK( !t->dec, "%s: a decoder without a sequence header?", cases[i].what ); + else CHECK( t->dec && ((struct mav_lavc_vdec *)t->dec)->ctx->codec_id == cases[i].id, "%s: decoder not open", cases[i].what ); + for (k = 0; k < 3; k++) + { + CHECK( push( h, &garbage, k * 333667, 333667, 0 ) == S_OK, "%s: push", cases[i].what ); + CHECK( !readx( h, &smp, buf, 1920 * 1088 * 2, 0, &hr ) && (hr == MF_E_TRANSFORM_NEED_MORE_INPUT || hr == S_OK), + "%s: read %#x", cases[i].what, (unsigned)hr ); + } + { wg_transform_t hh = h; CHECK( !call64( unix_wg_transform_drain, &hh ), "drain" ); } + while (!readx( h, &smp, buf, 1920 * 1088 * 2, 0, &hr ) && hr == S_OK) {} + destroy( h ); + } + free( buf ); + PASS( "WMV3/WVC1/WMVA plumbing (no real stream: FFmpeg cannot encode them): the probe and WVC1 without a sequence " + "header are accepted with the decoder closed and swallow input; with one, libavcodec's wmv3 / vc1 decoder " + "opens; garbage frames neither crash nor hang" ); + return 0; +} + +/* The same decode through the wow64 table, with 32-bit argument blocks below 4 GB. */ +static int test_wow64(void) +{ +#ifdef MAP_32BIT + const size_t arena_size = 32 << 20; + uint8_t *arena = mmap( NULL, arena_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_32BIT, -1, 0 ); + size_t used = 0; +#define LOW(n) (used += ((n) + 15) & ~(size_t)15, (void *)(arena + used - (((n) + 15) & ~(size_t)15))) +#define G(p) ((ULONG)(UINT_PTR)(p)) + struct wg_transform_create_params32 *c32; + struct wg_transform_sample_params32 *s32; + struct wg_transform_output_type_params32 *o32; + struct wg_transform_get_status_params *st; + struct wg_sample *smp; + struct vfmt *vi, *vo, *got; + wg_transform_t *h; + uint8_t *buf, *data; + struct geom g; + int i, n = 0; + + CHECK( arena != MAP_FAILED && (UINT_PTR)arena + arena_size < ((UINT64)1 << 32), "MAP_32BIT arena" ); + vi = LOW( sizeof(*vi) ); vo = LOW( sizeof(*vo) ); got = LOW( sizeof(*got) ); + c32 = LOW( sizeof(*c32) ); s32 = LOW( sizeof(*s32) ); o32 = LOW( sizeof(*o32) ); st = LOW( sizeof(*st) ); + smp = LOW( sizeof(*smp) ); h = LOW( sizeof(*h) ); + geom_init( &g, F_BGRX, W, H, 1, 0 ); + buf = LOW( g.size + 64 ); data = LOW( 65536 ); + make_video( vi, wmv2.fourcc, W, H, FPS, 1, wmv2.extradata, wmv2.extradata_size, FALSE ); + make_video( vo, 22, W, H, FPS, 1, NULL, 0, TRUE ); + + memset( c32, 0, sizeof(*c32) ); + c32->input_type.major = madeira_MFMediaType_Video; c32->input_type.format_size = vi->f.dwSize; c32->input_type.format = G( &vi->f ); + c32->output_type.major = madeira_MFMediaType_Video; c32->output_type.format_size = vo->f.dwSize; c32->output_type.format = G( &vo->f ); + c32->attrs = decoder_attrs; + CHECK( !call32( unix_wg_transform_create, c32 ) && c32->transform, "wow64 create" ); + *h = c32->transform; + for (i = 0; i < FRAMES; i++) + { + memset( smp, 0, sizeof(*smp) ); + memcpy( data, wmv2.packets[i].data, wmv2.packets[i].size ); + smp->size = smp->max_size = wmv2.packets[i].size; + smp->data = G( data ); + smp->flags = WG_SAMPLE_FLAG_HAS_PTS | WG_SAMPLE_FLAG_HAS_DURATION; + smp->pts = (INT64)i * TICK; smp->duration = TICK; + memset( s32, 0, sizeof(*s32) ); + s32->transform = *h; s32->sample = G( smp ); + CHECK( !call32( unix_wg_transform_push_data, s32 ) && s32->result == S_OK, "wow64 push %d", i ); + memset( smp, 0, sizeof(*smp) ); + smp->max_size = g.size; smp->data = G( buf ); + memset( buf, 0xcd, g.size + 64 ); + s32->result = E_FAIL; + CHECK( !call32( unix_wg_transform_read_data, s32 ) && s32->result == S_OK && smp->size == g.size, "wow64 read %d", i ); + CHECK( !check_frame( "wow64", &g, buf, 64, &wmv2.ref[n], 0 ) && smp->pts == (INT64)i * TICK + && smp->flags == (WG_SAMPLE_FLAG_SYNC_POINT | WG_SAMPLE_FLAG_HAS_PTS | WG_SAMPLE_FLAG_HAS_DURATION + | WG_SAMPLE_FLAG_PRESERVE_TIMESTAMPS), "wow64 picture %d", i ); + n++; + } + memset( o32, 0, sizeof(*o32) ); + o32->transform = *h; + CHECK( call32( unix_wg_transform_get_output_type, o32 ) == STATUS_BUFFER_TOO_SMALL && o32->media_type.format_size == vo->f.dwSize, + "wow64 get_output_type: size" ); + o32->media_type.format = G( got ); + CHECK( !call32( unix_wg_transform_get_output_type, o32 ) && !memcmp( &got->f, &vo->f, vo->f.dwSize ), "wow64 get_output_type" ); + make_video( vo, FCC('N','V','1','2'), W, H, 0, 0, NULL, 0, FALSE ); + o32->media_type.format_size = vo->f.dwSize; o32->media_type.format = G( &vo->f ); + CHECK( !call32( unix_wg_transform_set_output_type, o32 ), "wow64 set_output_type" ); + st->transform = *h; + CHECK( !call32( unix_wg_transform_get_status, st ) && st->accepts_input, "wow64 get_status" ); + CHECK( !call32( unix_wg_transform_drain, h ) && !call32( unix_wg_transform_flush, h ), "wow64 drain, flush" ); + CHECK( !call32( unix_wg_transform_destroy, h ), "wow64 destroy" ); + munmap( arena, arena_size ); + PASS( "wow64 thunks (32-bit argument blocks below 4 GB): create, %d pushes and reads of RGB32 bottom-up pictures " + "identical to the 64-bit path, get/set_output_type, get_status, drain, flush, destroy", n ); +#undef LOW +#undef G +#else + printf( "SKIP wow64 thunks: no MAP_32BIT on this host\n" ); +#endif + return 0; +} + +/* WMA through the same dispatcher (check-wma-decoder.py is the full WMA check). */ +static int test_wma( const char *label ) +{ + const AVCodec *codec = avcodec_find_encoder( AV_CODEC_ID_WMAV2 ); + AVCodecContext *c = avcodec_alloc_context3( codec ); + AVFrame *frame = av_frame_alloc(); + AVPacket *pkt = av_packet_alloc(); + struct { WAVEFORMATEX wfx; BYTE extra[64]; } in = { { 0 } }, out = { { 0 } }; + struct wg_transform_create_params cp = { 0 }; + struct wg_transform_attrs attrs = { 0 }; + struct wg_sample smp; + wg_transform_t h; + int16_t pcm[16384]; + double energy = 0; + size_t frames = 0; + HRESULT hr; + int i, k, n = 0; + + c->sample_rate = 44100; c->bit_rate = 128000; c->sample_fmt = AV_SAMPLE_FMT_FLTP; + av_channel_layout_default( &c->ch_layout, 2 ); + CHECK( avcodec_open2( c, codec, NULL ) >= 0, "wmav2 encoder" ); + in.wfx.wFormatTag = WAVE_FORMAT_WMAUDIO2; in.wfx.nChannels = 2; in.wfx.nSamplesPerSec = 44100; + in.wfx.nAvgBytesPerSec = 16000; in.wfx.nBlockAlign = c->block_align; in.wfx.wBitsPerSample = 16; + in.wfx.cbSize = c->extradata_size; memcpy( in.extra, c->extradata, c->extradata_size ); + out.wfx.wFormatTag = WAVE_FORMAT_PCM; out.wfx.nChannels = 2; out.wfx.nSamplesPerSec = 44100; + out.wfx.wBitsPerSample = 16; out.wfx.nBlockAlign = 4; out.wfx.nAvgBytesPerSec = 176400; + cp.input_type.major = madeira_MFMediaType_Audio; cp.input_type.format_size = sizeof(WAVEFORMATEX) + c->extradata_size; + cp.input_type.u.audio = &in.wfx; + cp.output_type.major = madeira_MFMediaType_Audio; cp.output_type.format_size = sizeof(WAVEFORMATEX); + cp.output_type.u.audio = &out.wfx; + cp.attrs = attrs; + CHECK( !call64( unix_wg_transform_create, &cp ) && cp.transform, "%s: WMA create", label ); + h = cp.transform; + CHECK( !get_wmv_transform( h ) && get_wma_transform( h ), "%s: a WMA transform", label ); + frame->nb_samples = c->frame_size; frame->format = c->sample_fmt; + av_channel_layout_copy( &frame->ch_layout, &c->ch_layout ); + av_frame_get_buffer( frame, 0 ); + for (i = 0; i < 40; i++) + { + for (k = 0; k < frame->nb_samples; k++) + ((float *)frame->data[0])[k] = ((float *)frame->data[1])[k] = 0.5f * (float)sin( 2 * M_PI * 440.0 * (n++) / 44100 ); + avcodec_send_frame( c, frame ); + while (avcodec_receive_packet( c, pkt ) >= 0) + { + struct packet p = { pkt->data, pkt->size, 1 }; + CHECK( push( h, &p, INT64_MIN, INT64_MIN, 0 ) == S_OK, "%s: WMA push", label ); + for (;;) + { + CHECK( !readx( h, &smp, (uint8_t *)pcm, sizeof(pcm), 0, &hr ), "%s: WMA read", label ); + if (hr != S_OK) break; + for (k = 0; k < (int)(smp.size / 2); k++) energy += (double)pcm[k] * pcm[k]; + frames += smp.size / 4; + } + av_packet_unref( pkt ); + } + } + destroy( h ); + avcodec_free_context( &c ); av_frame_free( &frame ); av_packet_free( &pkt ); + energy = sqrt( energy / (frames * 2 + 1) ) / 32768; + CHECK( frames > 44100 / 2 && energy > 0.2, "%s: WMA gave %zu frames at rms %.3f", label, frames, energy ); + PASS( "%s: a WMA v2 stream through the same dispatcher: %zu frames of PCM, rms %.3f", label, frames, energy ); + return 0; +} + +/* MADEIRA_WG_WMV_TRANSFORM=0: every video transform is refused again; WMA is not affected. */ +static int test_switched_off(void) +{ + static const BYTE wmv3_main[4] = { 0x40, 0x09, 0x88, 0x01 }; + struct vfmt vi, vo; + struct wg_media_type in, out; + wg_transform_t h = 1; + + out = make_video( &vo, FCC('N','V','1','2'), W, H, 0, 0, NULL, 0, FALSE ); + in = make_video( &vi, wmv1.fourcc, W, H, FPS, 1, NULL, 0, FALSE ); + CHECK( create( &h, &in, &out, &decoder_attrs ) == STATUS_NOT_SUPPORTED && !h, "WMV1 refused" ); + in = make_video( &vi, wmv2.fourcc, W, H, FPS, 1, wmv2.extradata, wmv2.extradata_size, FALSE ); + CHECK( create( &h, &in, &out, &decoder_attrs ) == STATUS_NOT_SUPPORTED && !h, "WMV2 refused" ); + in = make_video( &vi, FCC('W','M','V','3'), 320, 240, FPS, 1, wmv3_main, 4, FALSE ); + CHECK( create( &h, &in, &out, &decoder_attrs ) == STATUS_NOT_SUPPORTED && !h, "WMV3 refused" ); + in = make_video( &vi, FCC('W','M','V','3'), 1920, 1080, 0, 0, NULL, 0, FALSE ); + out = make_video( &vo, FCC('I','4','2','0'), 1920, 1080, 0, 0, NULL, 0, FALSE ); + CHECK( create( &h, &in, &out, NULL ) == STATUS_NOT_SUPPORTED && !h, "the probe refused" ); + PASS( "MADEIRA_WG_WMV_TRANSFORM=0: WMV1, WMV2, WMV3 and wmv_decoder_create's probe are refused" ); + return 0; +} + +int main( int argc, char **argv ) +{ + int off = argc > 1 && !strcmp( argv[1], "off" ), err; + + wmv1.fourcc = FCC('W','M','V','1'); + wmv2.fourcc = FCC('W','M','V','2'); + if ((err = encode( AV_CODEC_ID_WMV1, &wmv1 )) || (err = encode( AV_CODEC_ID_WMV2, &wmv2 ))) + { + printf( "FAIL: the test streams could not be made (%d)\n", err ); + return 1; + } + if (off) + { + test_switched_off(); + test_wma( "switched off" ); + } + else + { + test_decode( &wmv1, "WMV1" ); + test_decode( &wmv2, "WMV2" ); + /* before the format sweep, whose hundred-odd transforms use up the [wmv] log cap */ + test_refusals(); + test_wmv9_plumbing(); + test_formats(); + test_timestamps(); + test_queue_drain_flush(); + test_set_output_type(); + test_format_change_and_small_buffer(); + test_dmo_loop(); + test_threads(); + test_wow64(); + test_wma( "default" ); + } + for (err = 0; err < FRAMES; err++) { free( wmv1.packets[err].data ); free( wmv2.packets[err].data ); } + printf( "%s: %d failure(s), %d checks\n", failures ? "FAIL" : "PASS", failures, checks ); + return failures ? 1 : 0; +} +""" + +with tempfile.TemporaryDirectory() as tmp: + h = Path(tmp) / "wmv_host.c" + h.write_text(harness) + exe = Path(tmp) / "wmv_host" + cc = os.environ.get("CC", "cc") + cmd = [cc, "-O1", "-g", "-fsanitize=address,undefined", "-fno-sanitize-recover=undefined", + "-fno-strict-aliasing", "-Wno-int-conversion", "-Wno-implicit-function-declaration", + "-include", str(wine_build / "include/config.h"), + "-I" + str(ntdll_unix), "-I" + str(wine / "dlls/winegstreamer"), + "-I" + str(wine_build / "include"), "-I" + str(wine / "include"), "-I" + str(inc), + "-D__WINESRC__", "-D_NTSYSTEM_", "-D_ACRTIMP=", "-DWINBASEAPI=", "-DWINE_UNIX_LIB", + str(h), "-o", str(exe), + str(lib / "libavformat.a"), str(lib / "libavcodec.a"), str(lib / "libswresample.a"), str(lib / "libavutil.a"), + "-lm", "-lpthread"] + r = subprocess.run(cmd, capture_output=True, text=True) + if r.returncode: + print(r.stdout[-6000:], r.stderr[-6000:]) + print("FAIL: harness did not compile") + sys.exit(1) + env = dict(os.environ, ASAN_OPTIONS="detect_leaks=1") + env.pop("MADEIRA_WG_WMV_TRANSFORM", None) + for label, extra_env, args, needles in [ + ("default", {}, [], ["[wmv] decoder created fmt=WMV2 176x144 fps=25/1 codec_data=4 -> nv12 176x144", + "[decoder not open: no sequence header", + "is not a Windows Media video stream", + "[wmv] further lines suppressed after 100"]), + ("MADEIRA_WG_WMV_TRANSFORM=0", {"MADEIRA_WG_WMV_TRANSFORM": "0"}, ["off"], + ["[wmv] video transform refused: MADEIRA_WG_WMV_TRANSFORM=0"]), + ]: + print("--- %s ---" % label, flush=True) + r = subprocess.run([str(exe)] + args, env=dict(env, **extra_env), capture_output=True, text=True) + sys.stdout.write(r.stdout) + check(r.returncode == 0, "harness (%s) exits 0" % label) + if r.returncode: + print("\n".join(r.stderr.splitlines()[-40:])) + for needle in needles: + check(needle in r.stderr, "log (%s): %s" % (label, needle)) + wmv_lines = [l for l in r.stderr.splitlines() if l.startswith("[wmv]")] + print("first [wmv] lines (%d in all):\n " % len(wmv_lines) + "\n ".join(wmv_lines[:12])) + +if failures: + print("FAILED: %d" % len(failures)) + sys.exit(1) +print("PASS: the WMV video transform") From 6ecb5f0bf268d363521389233179e6ec88b86e45 Mon Sep 17 00:00:00 2001 From: allen Date: Sun, 22 Nov 2026 05:42:51 +0800 Subject: [PATCH 5/9] winegstreamer iOS: compressed WMV/WMA samples for the WM reader KiriKiri's movie plugin (krmovie.dll) reads a WMV through the WM sync reader as compressed samples of both streams and decodes them with the WMV and WMA decoder DMOs (Sabbat of the Witch's video CGs). The reader then opens a compressed-output parser, which this port refused for every ASF; Wine's reader freed its streams on that failure and the next call crashed. - wg_parser core: a compressed-output parser exposes an ASF's streams as the decoding one does (the reader asserts the counts match). Its WMA, WMV1/2/3, WMVA and WVC1 streams start in compressed mode and hand out the demuxer's packets as they are: the file's bytes, keyframe flags as `delta`, timestamps. After a seek the video starts at a keyframe (at most 300 delta frames are dropped waiting for one). A stream enabled with a raw format in the same parser is decoded as before; MS-MPEG4 has no wg_format and always is. - glue: get_current_format reports the codec format for such a stream, stream_enable takes WG_MAJOR_TYPE_VIDEO_WMV / WG_MAJOR_TYPE_AUDIO_WMA. MADEIRA_WG_COMPRESSED=0 refuses compressed output for an ASF again. - wine pin: willfaust/wine `winegstreamer: Read compressed samples per stream; keep the reader's streams when a reinit fails`: the reader chooses compressed or decoded per stream, keeps its streams when a reinit fails and goes back to the previous parser, and fails instead of asserting when the stream counts differ. - tests/host/check-wg-parser-asf.py: every packet of WMV7, WMV8, a WMV3 stream and WMA2 against an independent demux of the same file; compressed video beside decoded audio; a seek; back to decoded pictures, bit-exact; MS-MPEG4 refused compressed; the switch; source checks on the reader. Co-Authored-By: Claude Opus 5.5 Signed-off-by: allen --- app/Madeira/ConfigCatalog.generated.swift | 1 + build/ntdll-unix/wg_parser_av_ios.c | 175 +++++++++++++- build/ntdll-unix/winegstreamer_unixlib_ios.c | 41 +++- build/tools/gen-config-catalog.py | 3 + docs/MEDIA.md | 30 +++ tests/host/check-wg-parser-asf.py | 226 ++++++++++++++++++- wine | 2 +- 7 files changed, 463 insertions(+), 15 deletions(-) diff --git a/app/Madeira/ConfigCatalog.generated.swift b/app/Madeira/ConfigCatalog.generated.swift index 1145b9dfb4..bac166e071 100644 --- a/app/Madeira/ConfigCatalog.generated.swift +++ b/app/Madeira/ConfigCatalog.generated.swift @@ -400,6 +400,7 @@ extension ConfigCatalog { ConfigOption(key: "env.MADEIRA_GL_QUERY_BUFFER_OFFSETS", title: "32-bit GL query results as buffer offsets", kind: .bool, defaultValue: "1", category: "Graphics", note: "On (default): a 32-bit program's glGetQueryObject*v result pointer is an offset into the bound GL_QUERY_BUFFER (wined3d reads occlusion results that way; converting it as a pointer left the game spinning at 1 fps, ml1340). 0: the old pointer conversion.", choices: [], sources: []), ConfigOption(key: "gl-vulkan", title: "Vulkan driver for OpenGL (Zink)", kind: .choice, defaultValue: "", category: "Graphics", note: "The Vulkan driver Zink runs desktop OpenGL (and d3d9 = wined3d) on: MoltenVK (default) or KosmicKrisp (gl/libvulkan_kosmickrisp.dylib); any other value is a .dylib name in the gl folder or an absolute path. env.MADEIRA_GL_VULKAN is the fallback. Read when a program first creates an OpenGL context; the log says \"ml1344 zink Vulkan library: ...\".", choices: [("", "MoltenVK (default)"), ("moltenvk", "MoltenVK"), ("kosmickrisp", "KosmicKrisp")], sources: ["build/win32u-unix/opengl_ios.c"]), ConfigOption(key: "env.MADEIRA_DIAG", title: "", kind: .text, defaultValue: "", category: "Media", note: "MADEIRA_DIAG=1 lifts the cap; read once. Local to this file so the media unix side links against nothing but upstream's libntdll_unix.a.", choices: [], sources: ["build/ntdll-unix/winegstreamer_unixlib_ios.c"]), + ConfigOption(key: "env.MADEIRA_WG_COMPRESSED", title: "Media: compressed WMV/WMA samples (32-bit programs)", kind: .text, defaultValue: "", category: "Media", note: "0 refuses the WM reader's compressed samples of an ASF again; by default an application that decodes them itself (KiriKiri's movie plugin, through the WMV/WMA decoder DMOs) gets the file's packets.", choices: [], sources: ["build/ntdll-unix/winegstreamer_unixlib_ios.c"]), ConfigOption(key: "env.MADEIRA_WG_PARSER", title: "", kind: .text, defaultValue: "", category: "Media", note: "", choices: [], sources: ["build/ntdll-unix/winegstreamer_unixlib_ios.c"]), ConfigOption(key: "env.MADEIRA_WG_VIDEO", title: "Media: MP4 video (32-bit programs)", kind: .text, defaultValue: "", category: "Media", note: "0 limits the media parser to MP3/WAV; by default MP4 with H.264/HEVC video decodes through VideoToolbox.", choices: [], sources: ["build/ntdll-unix/winegstreamer_unixlib_ios.c"]), ConfigOption(key: "env.MADEIRA_WG_VIDEO_FORMAT", title: "", kind: .text, defaultValue: "", category: "Media", note: "", choices: [], sources: ["build/ntdll-unix/winegstreamer_unixlib_ios.c"]), diff --git a/build/ntdll-unix/wg_parser_av_ios.c b/build/ntdll-unix/wg_parser_av_ios.c index e6075e825f..82d8dd569f 100644 --- a/build/ntdll-unix/wg_parser_av_ios.c +++ b/build/ntdll-unix/wg_parser_av_ios.c @@ -82,7 +82,11 @@ * - "output_compressed" parsers (MPEG-I splitter, WAVE parser, AVI * splitter) hand the COMPRESSED stream to a separate decoder filter. This * port has no such decoder filters, so they accept PCM only; MP3 and MP4 - * are refused there and quartz then tries the decoding splitter. + * are refused there and quartz then tries the decoding splitter. The WM + * reader's is the exception: an application that reads compressed samples + * (KiriKiri's movie plugin, into the WMV / WMA decoder DMOs) gets an + * ASF's Windows Media streams as the demuxer's packets + * (mav_enable_compressed); its other streams are decoded as usual. * * - seek is accurate: the demuxer seeks at or before the target (to a video * keyframe when there is video), decoders are flushed, and decoded output @@ -248,6 +252,8 @@ struct mav_parser; static void mav_configure( int video_allowed, const struct mav_video_backend *video, const struct mav_audio_backend *audio, enum mav_pixel_format native ); +/* 0: a compressed-output parser refuses an ASF too, as before the WM reader's compressed samples */ +static void mav_allow_compressed_asf( int allowed ); static struct mav_parser *mav_create( int output_compressed ); static void mav_destroy( struct mav_parser *p ); static int mav_connect( struct mav_parser *p, uint64_t file_size ); @@ -261,6 +267,9 @@ static int mav_current_video( struct mav_parser *p, unsigned int stream, struct static int mav_enable( struct mav_parser *p, unsigned int stream, const struct mav_output *out ); static int mav_enable_video( struct mav_parser *p, unsigned int stream, const struct mav_video_output *out ); static void mav_disable( struct mav_parser *p, unsigned int stream ); +/* compressed-output parsers: can the stream hand out its packets, and do so */ +static int mav_can_pass_compressed( struct mav_parser *p, unsigned int stream ); +static int mav_enable_compressed( struct mav_parser *p, unsigned int stream ); /* stream < 0: the earliest buffer of any enabled stream (buffer->stream says which) */ static int mav_get_buffer( struct mav_parser *p, int stream, struct mav_buffer *buffer ); static int mav_copy_buffer( struct mav_parser *p, unsigned int stream, void *dst, uint32_t offset, uint32_t size ); @@ -325,6 +334,7 @@ static int mav_video_allowed = 1; static const struct mav_video_backend *mav_vbackend; static const struct mav_audio_backend *mav_abackend; static enum mav_pixel_format mav_native_pix = MAV_PIX_NV12; +static int mav_compressed_asf = 1; static void mav_configure( int video_allowed, const struct mav_video_backend *video, const struct mav_audio_backend *audio, enum mav_pixel_format native ) @@ -335,6 +345,11 @@ static void mav_configure( int video_allowed, const struct mav_video_backend *vi mav_native_pix = native ? native : MAV_PIX_NV12; } +static void mav_allow_compressed_asf( int allowed ) +{ + mav_compressed_asf = !!allowed; +} + /* ---- the log: bounded, and deduplicated ---- */ static pthread_mutex_t mav_log_lock = PTHREAD_MUTEX_INITIALIZER; static struct { uint32_t hash; uint32_t count; } mav_log_seen[MAV_MAX_LOGS]; @@ -661,6 +676,8 @@ struct mav_stream int has_buffer; int enabled, eos, draining, discontinuity; + int compressed; /* hands out the demuxer's packets (mav_enable_compressed) */ + unsigned int skipped; /* compressed video: delta frames dropped after a seek */ int64_t next_pts; /* 100 ns */ int64_t seek_target; /* 100 ns, -1 = none */ unsigned int decode_errors, errors_logged; @@ -1117,6 +1134,15 @@ static int64_t mav_to_100ns( const struct mav_stream *s, int64_t ts ) return av_rescale_q( ts - s->origin, s->time_base, (AVRational){ 1, 10000000 } ); } +/* A compressed-output parser's ASF hands out its Windows Media streams as + * they are: the formats wg_format can describe (WMA, WMV1/2/3, WMVA, WVC1), + * for the WM reader's compressed samples. MS-MPEG4 has no wg_format. */ +static int mav_passes_compressed( const struct mav_parser *p, const struct mav_stream *s ) +{ + return p->output_compressed && p->is_asf + && (s->info.kind == MAV_CODEC_WMA || (s->info.kind == MAV_CODEC_WMV && s->info.wmv != MAV_WMV_NONE)); +} + /*********************************************************************** * connect */ @@ -1179,7 +1205,9 @@ static int mav_open_audio( struct mav_parser *p, struct mav_stream *s, AVStream snprintf( why, why_size, "no decoder for it in this port" ); return MAV_E_UNSUPPORTED; } - if (p->output_compressed && s->info.kind != MAV_CODEC_PCM) + /* An ASF's streams are all exposed either way (the WM reader asks for + * the same streams again with compressed output); see mav_passes_compressed. */ + if (p->output_compressed && !p->is_asf && s->info.kind != MAV_CODEC_PCM) { snprintf( why, why_size, "compressed output requested and no decoder filter exists; " "the decoding splitter is tried next" ); @@ -1397,10 +1425,11 @@ static int mav_connect_locked( struct mav_parser *p ) p->is_mov || p->is_asf ? MAV_MIN_MOV_PROBE_SCORE : MAV_MIN_PROBE_SCORE ); return mav_refuse( p, MAV_E_UNSUPPORTED, why ); } - /* The mp3 demuxer only ever carries MPEG audio and an MP4 or ASF only + /* The mp3 demuxer only ever carries MPEG audio and an MP4 only * compressed streams: a compressed-output parser is refused before the - * stream analysis reads anything more. */ - if (p->output_compressed && (is_mp3 || p->is_mov || p->is_asf)) + * stream analysis reads anything more. An ASF is the WM reader's, which + * asks for compressed samples of its Windows Media streams. */ + if (p->output_compressed && (is_mp3 || p->is_mov || (p->is_asf && !mav_compressed_asf))) return mav_refuse( p, MAV_E_UNSUPPORTED, "compressed output requested and no decoder filter exists; " "the decoding splitter is tried next" ); @@ -1486,6 +1515,7 @@ static int mav_connect_locked( struct mav_parser *p ) struct mav_stream *s = p->streams[i]; s->enabled = 1; + s->compressed = mav_passes_compressed( p, s ); s->discontinuity = 1; s->next_pts = 0; /* MP4 audio carries its encoder delay as packets before time 0 @@ -1496,14 +1526,15 @@ static int mav_connect_locked( struct mav_parser *p ) "duration=%llums bitrate=%u profile=%u level=%u", s->info.container, i, s->info.codec, s->info.backend, s->info.vnative.width, s->info.vnative.height, s->info.vnative.fps_n, s->info.vnative.fps_d, - mav_pix_name( s->vout.fmt ), (unsigned long long)(s->info.duration / 10000), + s->compressed ? "compressed" : mav_pix_name( s->vout.fmt ), (unsigned long long)(s->info.duration / 10000), s->info.bitrate, s->info.profile, s->info.level ); else mav_log( "connect container=%s codec=%s layer=%u rate=%u channels=%u mask=%#x out=%s " "duration=%llums bitrate=%u compressed_out=%d stream=%u backend=%s", s->info.container, s->info.codec, s->info.layer, s->info.native.rate, s->info.native.channels, s->info.native.channel_mask, - mav_format_name( s->out.fmt ), (unsigned long long)(s->info.duration / 10000), + s->compressed ? "compressed" : mav_format_name( s->out.fmt ), + (unsigned long long)(s->info.duration / 10000), s->info.bitrate, p->output_compressed, i, s->info.backend ); } p->stop = -1; @@ -1617,13 +1648,14 @@ static int mav_enable( struct mav_parser *p, unsigned int stream, const struct m } else { - if (memcmp( out, &s->out, sizeof(*out) )) + if (memcmp( out, &s->out, sizeof(*out) ) || s->compressed) { /* the held buffer is in the old format */ s->has_buffer = 0; swr_free( &s->swr ); s->out = *out; } + s->compressed = 0; s->enabled = 1; } pthread_mutex_unlock( &p->lock ); @@ -1651,8 +1683,52 @@ static int mav_enable_video( struct mav_parser *p, unsigned int stream, const st } else { - if (out->fmt != s->vout.fmt || out->height != s->vout.height) s->has_buffer = 0; + if (out->fmt != s->vout.fmt || out->height != s->vout.height || s->compressed) s->has_buffer = 0; s->vout = *out; + s->compressed = 0; + s->enabled = 1; + } + pthread_mutex_unlock( &p->lock ); + return status; +} + +static int mav_can_pass_compressed( struct mav_parser *p, unsigned int stream ) +{ + struct mav_stream *s; + int ret; + + pthread_mutex_lock( &p->lock ); + ret = (s = mav_get_stream( p, stream )) && mav_passes_compressed( p, s ); + pthread_mutex_unlock( &p->lock ); + return ret; +} + +static int mav_enable_compressed( struct mav_parser *p, unsigned int stream ) +{ + struct mav_stream *s; + int status = MAV_OK; + + pthread_mutex_lock( &p->lock ); + if (!(s = mav_get_stream( p, stream ))) + status = MAV_E_STATE; + else if (!mav_passes_compressed( p, s )) + { + /* as a refused decoded format: the stream stays disabled */ + s->enabled = 0; + s->has_buffer = 0; + status = MAV_E_PARAM; + } + else + { + if (!s->compressed) + { + /* the held buffer, and what the decoder holds, were decoded output */ + s->has_buffer = 0; + if (s->pkt_pending) av_packet_unref( s->pkt ); + s->pkt_pending = 0; + mav_reorder_clear( s ); + } + s->compressed = 1; s->enabled = 1; } pthread_mutex_unlock( &p->lock ); @@ -2431,6 +2507,80 @@ static int mav_video_next( struct mav_parser *p, struct mav_stream *s ) } } +/*********************************************************************** + * compressed + */ +/* After a seek, this many delta frames are dropped at most while waiting for + * a keyframe (a file that flags none still plays). */ +#define MAV_MAX_SEEK_SKIP 300 + +/* The next packet as it is, for the caller's decoder. After a seek the + * demuxer is at or before the target, and everything from the first keyframe + * on is handed out, since a decoder needs it (the WM reader does not trim). */ +static int mav_compressed_next( struct mav_parser *p, struct mav_stream *s ) +{ + int64_t ts, pts, dur; + + for (;;) + { + if (s->eos) return MAV_NO_BUFFER; + if (!mav_next_packet( p, s, s->pkt )) + { + s->eos = 1; + return MAV_NO_BUFFER; + } + if (!s->pkt->size) + { + av_packet_unref( s->pkt ); + continue; + } + if (s->seek_target >= 0 && s->type == MAV_STREAM_VIDEO && !(s->pkt->flags & AV_PKT_FLAG_KEY) + && s->skipped < MAV_MAX_SEEK_SKIP) + { + s->skipped++; + av_packet_unref( s->pkt ); + continue; + } + if (s->skipped >= MAV_MAX_SEEK_SKIP && s->errors_logged < 3) + { + s->errors_logged++; + mav_log( "stream %u: no keyframe in %u packets after a seek; handing out delta frames", s->number, + s->skipped ); + } + s->seek_target = -1; + s->skipped = 0; + ts = s->pkt->pts != AV_NOPTS_VALUE ? s->pkt->pts : s->pkt->dts; + pts = ts != AV_NOPTS_VALUE ? mav_to_100ns( s, ts ) : s->next_pts; + dur = s->pkt->duration > 0 ? av_rescale_q( s->pkt->duration, s->time_base, (AVRational){ 1, 10000000 } ) + : s->type == MAV_STREAM_VIDEO ? s->frame_duration : 0; + if (p->stop >= 0 && pts >= p->stop) + { + av_packet_unref( s->pkt ); + s->eos = 1; + return MAV_NO_BUFFER; + } + if (!mav_reserve( s, (size_t)s->pkt->size )) + { + av_packet_unref( s->pkt ); + s->eos = 1; + mav_log( "stream %u: cannot hold a %d-byte packet; ending the stream", s->number, s->pkt->size ); + return MAV_NO_BUFFER; + } + memcpy( s->buf, s->pkt->data, s->pkt->size ); + s->next_pts = pts + dur; + s->cur.pts = pts > 0 ? (uint64_t)pts : 0; + s->cur.duration = dur; + s->cur.size = (uint32_t)s->pkt->size; + s->cur.stream = s->number; + s->cur.discontinuity = s->discontinuity; + s->cur.delta = !(s->pkt->flags & AV_PKT_FLAG_KEY); + s->discontinuity = 0; + s->has_buffer = 1; + av_packet_unref( s->pkt ); + return MAV_OK; + } +} + /*********************************************************************** * buffers */ @@ -2438,6 +2588,7 @@ static int mav_stream_next( struct mav_parser *p, struct mav_stream *s ) { if (!s->enabled) return MAV_NO_BUFFER; if (s->has_buffer) return MAV_OK; + if (s->compressed) return mav_compressed_next( p, s ); return s->type == MAV_STREAM_VIDEO ? mav_video_next( p, s ) : mav_audio_next( p, s ); } @@ -2492,7 +2643,10 @@ static int mav_get_buffer( struct mav_parser *p, int stream, struct mav_buffer * if (!s->delivered) { s->delivered = 1; - if (s->type == MAV_STREAM_VIDEO) + if (s->compressed) + mav_log( "stream %u: first compressed packet delivered (%s, %u bytes)", s->number, s->info.codec, + s->cur.size ); + else if (s->type == MAV_STREAM_VIDEO) mav_log( "stream %u: first picture delivered (%s %dx%d)", s->number, mav_pix_name( s->vout.fmt ), s->vout.width, s->vout.height ); else @@ -2599,6 +2753,7 @@ static int mav_seek( struct mav_parser *p, unsigned int stream, int set_start, u c->decode_errors = 0; c->discontinuity = 1; c->seek_target = target; + c->skipped = 0; c->next_pts = target; c->last_dts = c->last_vpts = INT64_MIN; } diff --git a/build/ntdll-unix/winegstreamer_unixlib_ios.c b/build/ntdll-unix/winegstreamer_unixlib_ios.c index 2f9c187362..977a1958f8 100644 --- a/build/ntdll-unix/winegstreamer_unixlib_ios.c +++ b/build/ntdll-unix/winegstreamer_unixlib_ios.c @@ -3330,6 +3330,15 @@ static BOOL wg_video_switch_on(void) return !(v && v[0] == '0' && !v[1]); } +/* The WM reader's compressed samples of an ASF's WMV / WMA streams, for an + * application's own decoder (KiriKiri's movie plugin and the decoder DMOs). + * 0 refuses them as before: the reader then keeps its decoded streams. */ +static BOOL wg_compressed_switch_on(void) +{ + const char *v = getenv( "MADEIRA_WG_COMPRESSED" ); + return !(v && v[0] == '0' && !v[1]); +} + static enum mav_pixel_format wg_video_native_format(void) { static const struct { const char *name; enum mav_pixel_format fmt; } names[] = @@ -3355,6 +3364,10 @@ static void wgp_configure(void) BOOL video = wg_video_switch_on(); enum mav_pixel_format native = wg_video_native_format(); + mav_allow_compressed_asf( wg_compressed_switch_on() ); + if (!wg_compressed_switch_on()) + mav_log( "compressed ASF output disabled by MADEIRA_WG_COMPRESSED=0" ); + #ifdef __APPLE__ mav_configure( video, &mav_apple_video_backend, &mav_apple_audio_backend, native ); mav_log( "mp4/mov %s (MADEIRA_WG_VIDEO=0 disables): video on %s, aac on %s, native video format %s", @@ -3545,6 +3558,8 @@ static NTSTATUS wgp_get_stream( void *args ) return S_OK; } +static NTSTATUS wgp_get_codec_format( wg_parser_stream_t handle, struct wg_format *format ); + static NTSTATUS wgp_get_current_format( wg_parser_stream_t handle, struct wg_format *format ) { UINT32 index; @@ -3555,6 +3570,9 @@ static NTSTATUS wgp_get_current_format( wg_parser_stream_t handle, struct wg_for if (!parser) return STATUS_INVALID_HANDLE; if (!format) return STATUS_INVALID_PARAMETER; + /* wg_parser.c: a compressed-output parser's pad has the compressed caps + * (what the WM reader enables a compressed-reading stream with) */ + if (mav_can_pass_compressed( parser->core, index )) return wgp_get_codec_format( handle, format ); /* wg_parser.c: a stream without caps reports an all-zero format (UNKNOWN) */ memset( format, 0, sizeof(*format) ); if (mav_stream_info( parser->core, index, &info )) return S_OK; @@ -3678,13 +3696,31 @@ static NTSTATUS wgp_enable( wg_parser_stream_t handle, const struct wg_format *f if (!format) return STATUS_INVALID_PARAMETER; if (mav_stream_info( parser->core, index, &info )) return VFW_E_WRONG_STATE; + if (format->major_type == WG_MAJOR_TYPE_VIDEO_WMV || format->major_type == WG_MAJOR_TYPE_AUDIO_WMA) + { + /* the demuxer's packets, as get_current_format describes them */ + if ((format->major_type == WG_MAJOR_TYPE_VIDEO_WMV) != (info.type == MAV_STREAM_VIDEO)) + status = MAV_E_PARAM; + else + status = mav_enable_compressed( parser->core, index ); + if (status) + { + mav_disable( parser->core, index ); + mav_log( "stream %u: enable refused: compressed output (major type %u) of %s", index, + format->major_type, info.codec ); + return wgp_status( status ); + } + return S_OK; + } + if (info.type == MAV_STREAM_VIDEO) { struct mav_video_output out; if (format->major_type != WG_MAJOR_TYPE_VIDEO) { - /* only decoded pictures are produced here; the stream stays disabled */ + /* only decoded pictures and Windows Media packets are produced + * here; the stream stays disabled */ mav_disable( parser->core, index ); mav_log( "stream %u: enable refused: major type %u is not raw video", index, format->major_type ); return STATUS_NOT_SUPPORTED; @@ -3709,7 +3745,8 @@ static NTSTATUS wgp_enable( wg_parser_stream_t handle, const struct wg_format *f if (format->major_type != WG_MAJOR_TYPE_AUDIO) { - /* only decoded PCM is produced here; the stream stays disabled */ + /* only decoded PCM and Windows Media packets are produced here; + * the stream stays disabled */ mav_disable( parser->core, index ); mav_log( "enable refused: major type %u is not PCM audio", format->major_type ); return STATUS_NOT_SUPPORTED; diff --git a/build/tools/gen-config-catalog.py b/build/tools/gen-config-catalog.py index 798cf0a03c..c50a30a66a 100644 --- a/build/tools/gen-config-catalog.py +++ b/build/tools/gen-config-catalog.py @@ -589,6 +589,9 @@ "created. By default they decode WMV1/2/3, WMVA and WVC1 with libavcodec. WMA is unaffected."}, "env.MADEIRA_WG_VIDEO": {"title": "Media: MP4 video (32-bit programs)", "note": "0 limits the media parser to MP3/WAV; by default MP4 with H.264/HEVC video decodes through VideoToolbox."}, + "env.MADEIRA_WG_COMPRESSED": {"title": "Media: compressed WMV/WMA samples (32-bit programs)", + "note": "0 refuses the WM reader's compressed samples of an ASF again; by default an application that " + "decodes them itself (KiriKiri's movie plugin, through the WMV/WMA decoder DMOs) gets the file's packets."}, "env.MADEIRA_WOW_RWX_PLAIN": {"category": "Memory & JIT pool", "note": "Unset: a 32-bit window's anonymous RWX memory is plain read/write to the host once Wine Mono's libmono-2.0-x86.dll is mapped there (ml1279/ml1282). 1: in every 32-bit window. 0: never (stores go through the JIT pool's alias, and FEX's Mono bridge stays off)."}, "env.MADEIRA_WINEMONO_BRIDGE": {"note": "FEX's Mono backpatcher bridge (ml712). On by itself for Wine Mono, 32- and 64-bit (ml1282/ml1286); for the 32-bit runtime in a guest window it also turns SMC detection off once the backpatcher is found (ml1280). 0 keeps it off."}, "env.MADEIRA_MONO_DEFAULTS": {"category": "Wine libraries", "note": "Wine Mono, 32- and 64-bit: mscoree sets MONO_THREADS_SUSPEND=coop and adds keep-delegates to MONO_DEBUG before Mono loads, and puts the previous values back once Mono has read them (ml1282); values already set win. 0 sets nothing."}, diff --git a/docs/MEDIA.md b/docs/MEDIA.md index fad852e3a9..af1fc6cbc1 100644 --- a/docs/MEDIA.md +++ b/docs/MEDIA.md @@ -77,6 +77,29 @@ asks for NV12 still gets it from the YUV types listed after the native one. `stream N: first picture delivered` (or `first audio buffer delivered`) once, so a device log shows whether any sample was ever requested. +**Compressed samples from the WM reader.** An application can ask the WM +reader (`IWMSyncReader::SetReadStreamSamples`) for a stream's compressed +samples and decode them itself. KiriKiri's movie plugin (`krmovie.dll`) does +this for both streams of a WMV and feeds them to the WMV and WMA decoder DMOs +(Sabbat of the Witch's video CGs). The reader then opens a compressed-output +parser. This port's parser refused every compressed-output parser for an ASF, +and Wine's reader freed its streams when that reinit failed but kept their +count, so the next call wrote through a NULL array. Now: +- a compressed-output parser exposes an ASF's streams as the decoding one does + (Wine's reader asserts the counts match); +- its WMA, WMV1/2/3, WMVA and WVC1 streams report their codec format as the + current format and, enabled with it, hand out the demuxer's packets as they + are: the file's bytes, keyframe flags (`delta`) and timestamps; +- after a seek the video starts at a keyframe; +- a stream enabled with a raw format in the same parser is decoded as usual + (MS-MPEG4, which has no `wg_format`, always is); +- Wine's reader (in the wine submodule) chooses compressed or decoded per + stream, keeps its streams when a reinit fails, goes back to the previous + parser, and fails instead of asserting when the stream counts differ. + +Each compressed stream logs `first compressed packet delivered` once. +`MADEIRA_WG_COMPRESSED=0` refuses compressed output for an ASF again. + **The WMV decoder (`wg_transform`).** `video_decoder.c` probes a WMV3 1920x1080 to I420 transform without codec private data when the DMO is created (`check_video_transform_support`), and libavcodec cannot open `wmv3` @@ -141,6 +164,7 @@ Environment variables (`env.NAME = value` in `madeira.cfg`): | `MADEIRA_WG_PARSER` | on | `0`: `wg_parser_create` returns `STATUS_NOT_IMPLEMENTED` again, as before this series; quartz and the MF source then fail the way they did. The WMA decoder is unaffected. | | `MADEIRA_WG_VIDEO` | on | `0`: MP3/WAV only; an MP4/MOV or ASF is refused at connect. | | `MADEIRA_WG_WMV_TRANSFORM` | on | `0`: every video `wg_transform` is refused at create again, so the WMVideo Decoder DMO/MFT cannot be created, as before. Read once per process. WMA is unaffected. | +| `MADEIRA_WG_COMPRESSED` | on | `0`: a compressed-output parser refuses an ASF, as before: the WM reader's compressed samples are not available (see above). | | `MADEIRA_WG_VIDEO_FORMAT` | `rgb32` | Native format a video stream reports: `nv12`, `i420`, `yv12`, `yuy2`, `rgb32`, `argb32` or `abgr32` (see above for why the default is `rgb32`). | | `MADEIRA_WMA_SEARCH` | on | `0`: keep the WMA v1/v2 decoder at the bit rate and flags it opened with; no search over other candidates when a bit-reservoir stream fails. A packet that fails is concealed with silence of its length and the next one is decoded as usual. (An xWMA stream still opens at the rate libavformat's xWMA table normalises to.) | | `MADEIRA_WMA_DUMP` | off | Set: write each WMA decoder's input to `wma-dump-.bin` in the Documents folder, for reproducing a decode failure on a host. | @@ -170,6 +194,12 @@ and `[wmv]` caps). small queue limits, the back-pressure cases (a slow video reader loses nothing, while the same build without back-pressure drops pictures; an unread stream; one thread reading both; disconnect while a reader waits). + Compressed output: every packet of WMV7, WMV8, the WMV3 garbage stream and + WMA2 against an independent demux of the same file (bytes, keyframe flags, + timestamps); compressed video with decoded audio; a seek starting at a + keyframe; back to decoded pictures, bit-exact; MS-MPEG4 refused compressed; + `MADEIRA_WG_COMPRESSED=0`. Also source checks on Wine's reader (per-stream + compressed reading, no `free_streams` in a failed reinit). WMV9/VC-1 streams themselves are not covered: FFmpeg cannot encode them. - `tests/host/check-wma-decoder.py` (Linux or macOS, needs a configured Wine tree for the generated headers): compiles the production diff --git a/tests/host/check-wg-parser-asf.py b/tests/host/check-wg-parser-asf.py index 29c18dba5f..a51761c12d 100644 --- a/tests/host/check-wg-parser-asf.py +++ b/tests/host/check-wg-parser-asf.py @@ -21,6 +21,13 @@ pixel-checked; keyframe seek with exact trim; the codec formats (WMV2, WMA v2); - WMV7 (wmv1) and MS-MPEG4 v3 video decode bit-exact; - a WMV3 stream of undecodable data ends the stream (no crash, no hang); + - compressed output (the WM reader's compressed samples: KiriKiri's movie plugin feeds them to the + WMV / WMA decoder DMOs): a compressed-output parser exposes the same streams, and every + packet of WMV8, WMV9 (the undecodable WMV3 too: it is not decoded here) and WMA2 comes out with + the file's bytes, keyframe flags and timestamps, in order, to the end; compressed video next + to decoded S16 audio; a seek starts the video at a keyframe; back to decoded pictures, bit-exact; + MS-MPEG4 (no wg_format) is refused compressed and still decodes; MADEIRA_WG_COMPRESSED=0's + refusal; and, built with small queue limits (a stream that falls behind used to lose packets): - a slow video reader and a fast audio reader on two threads: no packet dropped, every picture delivered (the same file without back-pressure drops); @@ -48,12 +55,34 @@ for flag in ["--disable-gpl", "--disable-nonfree", "--disable-version3", "--disable-everything"]: assert flag in args, ("LGPL-only configuration", flag) assert "(int)MAV_PIX_BGR == (int)WG_VIDEO_FORMAT_BGR" in glue and "(int)MAV_PIX_YVYU == (int)WG_VIDEO_FORMAT_YVYU" in glue -codec_fmt = glue[glue.index("static NTSTATUS wgp_get_codec_format("):] +codec_fmt = glue[glue.rindex("static NTSTATUS wgp_get_codec_format("):] # the definition, after a declaration codec_fmt = codec_fmt[:codec_fmt.index("\n}\n")] assert "case MAV_CODEC_WMA:" in codec_fmt and "WG_MAJOR_TYPE_AUDIO_WMA" in codec_fmt assert "case MAV_CODEC_WMV:" in codec_fmt and "WG_MAJOR_TYPE_VIDEO_WMV" in codec_fmt +enable = glue[glue.index("static NTSTATUS wgp_enable("):] +enable = enable[:enable.index("\n}\n")] +assert "WG_MAJOR_TYPE_VIDEO_WMV" in enable and "WG_MAJOR_TYPE_AUDIO_WMA" in enable and "mav_enable_compressed(" in enable, \ + "stream_enable takes the compressed formats" +current = glue[glue.index("static NTSTATUS wgp_get_current_format("):] +current = current[:current.index("\n}\n")] +assert "mav_can_pass_compressed(" in current and "wgp_get_codec_format(" in current, \ + "a compressed-output parser's current format is the codec format" +assert 'getenv( "MADEIRA_WG_COMPRESSED" )' in glue and "mav_allow_compressed_asf(" in glue +# Wine's WM reader (the submodule): compressed reading per stream, and a failed reinit keeps the streams +wm = root / "wine/dlls/winegstreamer/wm_reader.c" +if wm.exists(): + w = wm.read_text() + reinit = w[w.index("static HRESULT reinit_stream("):] + reinit = reinit[:reinit.index("\n}\n")] + assert "free_streams(" not in reinit, "a failed reinit must not free the reader's streams" + assert "stream->read_compressed ? &format : &stream->format" in reinit, "compressed reading is per stream" + assert "assert(reader->stream_count == wg_parser_get_stream_count" not in reinit, "a stream count mismatch fails, not aborts" + sss = w[w.index("static HRESULT WINAPI reader_SetReadStreamSamples("):] + sss = sss[:sss.index("\n}\n")] + assert "old_compressed" in sss, "SetReadStreamSamples goes back to the previous parser on failure" + print("PASS: Wine's WM reader reads compressed per stream and keeps its streams when a reinit fails") print("PASS: FFmpeg has the asf demuxer and the Windows Media decoders (still no H.264/HEVC/AAC); " - "the glue maps the new pixel formats and the WMV / WMA codec formats") + "the glue maps the new pixel formats, the WMV / WMA codec formats and compressed output") # ------------------------------------------------------------------ 2. host FFmpeg tarball = os.environ.get("MADEIRA_FFMPEG_TARBALL") or str(root / "build/ffmpeg/src/ffmpeg-7.1.5.tar.xz") @@ -586,6 +615,189 @@ return 0; } + +/* ================= compressed output (the WM reader's compressed samples) ================= */ +struct refpkt { int stream, key, size; int64_t pts; uint8_t *data; }; +static struct refpkt *ref_pkts; +static int ref_pkt_count; + +static void free_packet_reference( void ) +{ + int i; + for (i = 0; i < ref_pkt_count; i++) free( ref_pkts[i].data ); + free( ref_pkts ); ref_pkts = NULL; ref_pkt_count = 0; +} + +/* every packet of the file, as libavformat demuxes it on its own */ +static int make_packet_reference( const uint8_t *data, size_t size ) +{ + struct membuf m = { (uint8_t *)data, size, size, 0 }; + AVFormatContext *fc = avformat_alloc_context(); AVPacket *pkt = av_packet_alloc(); + + free_packet_reference(); + fc->pb = avio_alloc_context( av_malloc( 4096 ), 4096, 0, &m, mem_read, NULL, mem_seek ); + CHECK( avformat_open_input( &fc, NULL, NULL, NULL ) == 0 && avformat_find_stream_info( fc, NULL ) >= 0, "reference open" ); + while (av_read_frame( fc, pkt ) >= 0) + { + if (pkt->size) + { + struct refpkt *r; + ref_pkts = realloc( ref_pkts, (ref_pkt_count + 1) * sizeof(*ref_pkts) ); + r = &ref_pkts[ref_pkt_count++]; + r->stream = pkt->stream_index; r->key = !!(pkt->flags & AV_PKT_FLAG_KEY); r->size = pkt->size; + r->pts = av_rescale_q( pkt->pts, fc->streams[pkt->stream_index]->time_base, (AVRational){ 1, 10000000 } ); + r->data = malloc( pkt->size ); memcpy( r->data, pkt->data, pkt->size ); + } + av_packet_unref( pkt ); + } + av_packet_free( &pkt ); + av_freep( &fc->pb->buffer ); avio_context_free( &fc->pb ); avformat_close_input( &fc ); + return 0; +} + +/* KiriKiri's way: both streams compressed, earliest-buffer reads to the end */ +static int test_compressed( const uint8_t *asf, size_t size, const char *codec, int streams ) +{ + struct mav_parser *p = mav_create( 1 ); struct source s; struct mav_stream_info vi; struct mav_buffer b; + uint8_t *buf = malloc( 1 << 20 ); int next[2] = { 0, 0 }, count[2] = { 0, 0 }, want[2] = { 0, 0 }, i; + int64_t last_v = -1; + + CHECK( !make_packet_reference( asf, size ), "packet reference" ); + for (i = 0; i < ref_pkt_count; i++) want[ref_pkts[i].stream]++; + src_start( &s, p, asf, size ); + CHECK( mav_connect( p, size ) == MAV_OK, "%s: a compressed-output parser connects", codec ); + CHECK( (int)mav_stream_count( p ) == streams, "%s: %u streams, as decoded", codec, mav_stream_count( p ) ); + CHECK( mav_stream_info( p, 0, &vi ) == MAV_OK && vi.kind == MAV_CODEC_WMV && !strcmp( vi.codec, codec ) + && vi.vnative.width == W && vi.vnative.height == H, "%s: video info", codec ); + for (i = 0; i < streams; i++) + { + CHECK( mav_can_pass_compressed( p, i ), "%s: stream %d passes compressed", codec, i ); + CHECK( mav_enable_compressed( p, i ) == MAV_OK, "%s: stream %d enabled compressed", codec, i ); + } + CHECK( mav_seek( p, 0, 1, 0, 0, 0 ) == MAV_OK, "seek to 0 (wm_reader.c after enabling)" ); + while (mav_get_buffer( p, -1, &b ) == MAV_OK) + { + int st = b.stream; const struct refpkt *r; + CHECK( st < streams, "stream %d", st ); + while (next[st] < ref_pkt_count && ref_pkts[next[st]].stream != st) next[st]++; + CHECK( next[st] < ref_pkt_count, "%s: stream %d: more packets than the file has", codec, st ); + r = &ref_pkts[next[st]++]; + CHECK( b.size == (uint32_t)r->size && b.size <= (1 << 20) && mav_copy_buffer( p, st, buf, 0, b.size ) == MAV_OK + && !memcmp( buf, r->data, b.size ), "%s: stream %d packet %d: the file's %d bytes (got %u)", codec, st, + count[st], r->size, b.size ); + CHECK( b.delta == !r->key, "%s: stream %d packet %d: keyframe flag", codec, st, count[st] ); + CHECK( llabs( (long long)b.pts - (long long)(r->pts > 0 ? r->pts : 0) ) <= 1, "%s: stream %d packet %d: pts %llu, file %lld", + codec, st, count[st], (unsigned long long)b.pts, (long long)r->pts ); + if (!count[st]) CHECK( b.discontinuity, "%s: stream %d starts with a discontinuity", codec, st ); + else CHECK( !b.discontinuity, "%s: stream %d packet %d: no discontinuity", codec, st, count[st] ); + if (st == 0) + { + if (!count[0]) CHECK( !b.delta, "%s: the first picture is a keyframe", codec ); + CHECK( (int64_t)b.pts > last_v && b.duration == 10000000 / FPS, "%s: picture %d pts %llu dur %llu", codec, + count[0], (unsigned long long)b.pts, (unsigned long long)b.duration ); + last_v = b.pts; + } + count[st]++; + mav_release_buffer( p, st ); + } + CHECK( count[0] == FRAMES && count[0] == want[0], "%s: %d pictures, the file has %d", codec, count[0], want[0] ); + if (streams > 1) CHECK( count[1] == want[1] && count[1] > 0, "%s: %d WMA packets, the file has %d", codec, count[1], want[1] ); + src_stop( &s ); mav_destroy( p ); free( buf ); + printf( "PASS: compressed %s%s in ASF: all %d pictures%s with the file's bytes, keyframe flags and timestamps, in order\n", + codec, streams > 1 ? " + WMA2" : "", count[0], streams > 1 ? " and WMA packets" : "" ); + return 0; +} + +/* compressed video next to decoded audio; a seek; back to decoded video */ +static int test_compressed_mixed( const uint8_t *asf, size_t size ) +{ + struct mav_parser *p = mav_create( 1 ); struct source s; struct mav_stream_info vi; struct mav_buffer b; + uint8_t *buf = malloc( 1 << 20 ); int pictures = 0, n = 0; int64_t samples = 0, target = 2 * 10000000LL; double sq = 0; + + CHECK( !make_reference( asf, size ) && ref_count == FRAMES, "reference" ); + src_start( &s, p, asf, size ); + CHECK( mav_connect( p, size ) == MAV_OK && mav_stream_info( p, 0, &vi ) == MAV_OK, "connect" ); + CHECK( mav_enable_compressed( p, 0 ) == MAV_OK, "video compressed" ); + CHECK( mav_enable( p, 1, &(struct mav_output){ MAV_FMT_S16, RATE, 2, 3 } ) == MAV_OK, "audio decoded in the same parser" ); + CHECK( mav_seek( p, 0, 1, 0, 0, 0 ) == MAV_OK, "seek to 0" ); + while (mav_get_buffer( p, -1, &b ) == MAV_OK) + { + CHECK( b.size <= (1 << 20) && mav_copy_buffer( p, b.stream, buf, 0, b.size ) == MAV_OK, "copy" ); + if (b.stream == 0) pictures++; + else + { + int k; const int16_t *pcm = (const int16_t *)buf; + for (k = 0; k < (int)(b.size / 2); k++) sq += (double)pcm[k] * pcm[k]; + samples += b.size / 4; + } + mav_release_buffer( p, b.stream ); + } + CHECK( pictures == FRAMES, "%d packets", pictures ); + CHECK( llabs( samples - (int64_t)RATE * FRAMES / FPS ) < 4096 && sqrt( sq / (samples * 2) ) > 4000, + "%lld audio frames of the tone", (long long)samples ); + + /* a seek: the video starts at a keyframe at or before the target */ + CHECK( mav_seek( p, 0, 1, (uint64_t)target, 0, 0 ) == MAV_OK, "seek to 2 s" ); + CHECK( mav_get_buffer( p, 0, &b ) == MAV_OK && !b.delta && b.discontinuity && (int64_t)b.pts <= target + 10000 + && (int64_t)b.pts > target - 2 * GOP * 10000000LL / FPS, "after the seek: delta %d disc %d pts %llu", b.delta, + b.discontinuity, (unsigned long long)b.pts ); + mav_release_buffer( p, 0 ); + + /* decoded pictures again: a seek to 0 and every picture bit-exact */ + { + struct mav_video_output o = vi.vnative; o.fmt = MAV_PIX_NV12; + CHECK( mav_enable_video( p, 0, &o ) == MAV_OK, "back to NV12" ); + } + mav_disable( p, 1 ); + CHECK( mav_seek( p, 0, 1, 0, 0, 0 ) == MAV_OK, "seek to 0" ); + while (mav_get_buffer( p, 0, &b ) == MAV_OK) + { + CHECK( mav_copy_buffer( p, 0, buf, 0, b.size ) == MAV_OK, "copy" ); + if (check_picture( buf, b.size, MAV_PIX_NV12, 0, n, "nv12 after compressed" )) return 1; + mav_release_buffer( p, 0 ); n++; + } + CHECK( n == FRAMES, "%d pictures after compressed reading", n ); + src_stop( &s ); mav_destroy( p ); free( buf ); + printf( "PASS: compressed WMV8 next to decoded S16 (%.2f s, rms %.0f) in one parser; a seek to 2 s starts the video " + "at a keyframe; back to decoded, %d pictures bit-exact\n", (double)samples / RATE, sqrt( sq / (samples * 2) ), n ); + return 0; +} + +/* MS-MPEG4 has no wg_format: refused compressed, decoded in the same parser; the kill switch */ +static int test_compressed_refusals( const uint8_t *mp43, size_t n3, const uint8_t *wmv2, size_t n2 ) +{ + struct mav_parser *p = mav_create( 1 ); struct source s; struct mav_stream_info vi; struct mav_buffer b; int n = 0; + + src_start( &s, p, mp43, n3 ); + CHECK( mav_connect( p, n3 ) == MAV_OK && mav_stream_count( p ) == 2 && mav_stream_info( p, 0, &vi ) == MAV_OK, + "msmpeg4v3: a compressed-output parser connects, both streams" ); + CHECK( !mav_can_pass_compressed( p, 0 ) && mav_can_pass_compressed( p, 1 ), "msmpeg4v3 video is not passed compressed, WMA is" ); + CHECK( mav_enable_compressed( p, 0 ) == MAV_E_PARAM, "msmpeg4v3: compressed refused" ); + CHECK( mav_get_buffer( p, 0, &b ) == MAV_NO_BUFFER, "and the stream is disabled" ); + { + struct mav_video_output o = vi.vnative; o.fmt = MAV_PIX_NV12; + CHECK( mav_enable_video( p, 0, &o ) == MAV_OK, "msmpeg4v3 decoded" ); + } + mav_disable( p, 1 ); + CHECK( mav_seek( p, 0, 1, 0, 0, 0 ) == MAV_OK, "seek" ); + while (mav_get_buffer( p, 0, &b ) == MAV_OK) { CHECK( b.size == W * H * 3 / 2, "nv12 size" ); mav_release_buffer( p, 0 ); n++; } + CHECK( n == FRAMES, "%d msmpeg4v3 pictures", n ); + src_stop( &s ); mav_destroy( p ); + + mav_allow_compressed_asf( 0 ); + p = mav_create( 1 ); src_start( &s, p, wmv2, n2 ); + CHECK( mav_connect( p, n2 ) == MAV_E_UNSUPPORTED, "MADEIRA_WG_COMPRESSED=0: a compressed-output parser refuses an ASF" ); + src_stop( &s ); mav_destroy( p ); + mav_allow_compressed_asf( 1 ); + p = mav_create( 0 ); src_start( &s, p, wmv2, n2 ); + CHECK( mav_connect( p, n2 ) == MAV_OK && !mav_can_pass_compressed( p, 0 ) && mav_enable_compressed( p, 0 ) == MAV_E_PARAM, + "a decoding parser does not pass compressed" ); + src_stop( &s ); mav_destroy( p ); + printf( "PASS: MS-MPEG4 refused compressed and decoded in the same parser (%d pictures); MADEIRA_WG_COMPRESSED=0 " + "refuses the ASF; a decoding parser never passes compressed\n", n ); + return 0; +} + int main( int argc, char **argv ) { size_t n2, n1, n3, ng; @@ -610,6 +822,11 @@ CHECK( mav_lavc_supports( MAV_LAVC_WMV3 ) && mav_lavc_supports( MAV_LAVC_VC1 ), "WMV9 / VC-1 decoders are built" ); if (test_wmv( wmv2, n2, "wmv2" ) || test_wm_reader( wmv2, n2 ) || test_formats( wmv2, n2 )) return 1; if (test_wmv( wmv1, n1, "wmv1" ) || test_wmv( mp43, n3, "msmpeg4v3" ) || test_garbage_wmv3( garbage, ng )) return 1; + if (test_compressed( wmv2, n2, "wmv2", 2 ) || test_compressed( wmv1, n1, "wmv1", 2 ) + || test_compressed( garbage, ng, "wmv3", 1 ) || test_compressed_mixed( wmv2, n2 ) + || test_compressed_refusals( mp43, n3, wmv2, n2 )) + return 1; + free_packet_reference(); free( wmv2 ); free( wmv1 ); free( mp43 ); free( garbage ); free( ref_frames ); return failures != 0; } @@ -639,6 +856,11 @@ assert any("video codec=wmv1 backend=libavcodec" in l for l in lines) and any("video codec=msmpeg4v3 backend=libavcodec" in l for l in lines), lines assert any("wmv3" in l and ("packet rejected" in l or "undecodable" in l or "connect refused" in l) for l in lines), lines assert not any("dropping further packets" in l for l in lines), lines + assert any("connect container=asf stream=0 video codec=wmv2 backend=libavcodec 320x240 fps=25/1 out=compressed" in l + for l in lines), lines + assert any("first compressed packet delivered (wmv2" in l for l in lines) and \ + any("first compressed packet delivered (wmav2" in l for l in lines), lines + assert any("connect refused (asf, compressed_out=1): compressed output requested" in l for l in lines), lines assert "ERROR: AddressSanitizer" not in out.stderr and "runtime error" not in out.stderr, out.stderr[-4000:] out = subprocess.run([str(bp), "bp"], env=env, capture_output=True, text=True, timeout=300) diff --git a/wine b/wine index 18689a0897..b0d33cbd85 160000 --- a/wine +++ b/wine @@ -1 +1 @@ -Subproject commit 18689a08977f6b0756788f63c9c6f6a7f7c76e81 +Subproject commit b0d33cbd85acf4339150507cac9bab137c6021d0 From 3dab91559dac507f1be06cb8dd9f1a20d65fabec Mon Sep 17 00:00:00 2001 From: allen Date: Sun, 22 Nov 2026 05:43:47 +0800 Subject: [PATCH 6/9] winegstreamer iOS: the audio resampler transform on libswresample Media Foundation's topology loader puts winegstreamer's resampler (CLSID_CResamplerMediaObject, wg_resampler) between a source's PCM and the audio renderer, which takes only the device mix format. The wg_transform behind it was refused here ("input format tag 0x1 is not a WMA family stream"), resampler_create failed, and Senren Banka's WMV movie (48 kHz S16 from its WMA stream) lost the audio branch of its topology: no presentation clock, and the video renderer never presented. Raw audio in is now a third transform kind, the first row of transform_kinds (the WMA decoder claims all other audio), converted with libswresample: integer PCM of 8, 16, 24 or 32 bits and float of 32 or 64, WAVEFORMATEX or WAVEFORMATEXTENSIBLE, any rate, 1 to 8 channels, in and out. Timestamps run from the input's, less what the resampler still holds, and are computed from a frame count so rounding never adds up. Push, read, back-pressure, drain, flush and the output type follow the WMA decoder's protocol. MADEIRA_WG_RESAMPLER=0 refuses it again. tests/host/check-wg-resampler.py drives it under ASan/UBSan through the unix entries: Senren's case to 48 and 44.1 kHz float (frequency, level, frame count, timestamps), all 36 sample-format pairs (identity bit-exact), channel up/downmix, check_audio_transform_support()'s probe, back-pressure, flush, a new output type, drain, the refusals and the switch. Co-Authored-By: Claude Opus 5.5 Signed-off-by: allen --- app/Madeira/ConfigCatalog.generated.swift | 1 + build/ntdll-unix/winegstreamer_unixlib_ios.c | 512 ++++++++++++++++++- build/tools/gen-config-catalog.py | 3 + docs/MEDIA.md | 36 +- tests/host/check-wg-resampler.py | 505 ++++++++++++++++++ 5 files changed, 1043 insertions(+), 14 deletions(-) create mode 100755 tests/host/check-wg-resampler.py diff --git a/app/Madeira/ConfigCatalog.generated.swift b/app/Madeira/ConfigCatalog.generated.swift index bac166e071..bff4e4ce9d 100644 --- a/app/Madeira/ConfigCatalog.generated.swift +++ b/app/Madeira/ConfigCatalog.generated.swift @@ -402,6 +402,7 @@ extension ConfigCatalog { ConfigOption(key: "env.MADEIRA_DIAG", title: "", kind: .text, defaultValue: "", category: "Media", note: "MADEIRA_DIAG=1 lifts the cap; read once. Local to this file so the media unix side links against nothing but upstream's libntdll_unix.a.", choices: [], sources: ["build/ntdll-unix/winegstreamer_unixlib_ios.c"]), ConfigOption(key: "env.MADEIRA_WG_COMPRESSED", title: "Media: compressed WMV/WMA samples (32-bit programs)", kind: .text, defaultValue: "", category: "Media", note: "0 refuses the WM reader's compressed samples of an ASF again; by default an application that decodes them itself (KiriKiri's movie plugin, through the WMV/WMA decoder DMOs) gets the file's packets.", choices: [], sources: ["build/ntdll-unix/winegstreamer_unixlib_ios.c"]), ConfigOption(key: "env.MADEIRA_WG_PARSER", title: "", kind: .text, defaultValue: "", category: "Media", note: "", choices: [], sources: ["build/ntdll-unix/winegstreamer_unixlib_ios.c"]), + ConfigOption(key: "env.MADEIRA_WG_RESAMPLER", title: "Media: audio resampler", kind: .text, defaultValue: "", category: "Media", note: "0 refuses the resampler transform again; by default Media Foundation converts a movie's audio to the device mix format with libswresample.", choices: [], sources: ["build/ntdll-unix/winegstreamer_unixlib_ios.c"]), ConfigOption(key: "env.MADEIRA_WG_VIDEO", title: "Media: MP4 video (32-bit programs)", kind: .text, defaultValue: "", category: "Media", note: "0 limits the media parser to MP3/WAV; by default MP4 with H.264/HEVC video decodes through VideoToolbox.", choices: [], sources: ["build/ntdll-unix/winegstreamer_unixlib_ios.c"]), ConfigOption(key: "env.MADEIRA_WG_VIDEO_FORMAT", title: "", kind: .text, defaultValue: "", category: "Media", note: "", choices: [], sources: ["build/ntdll-unix/winegstreamer_unixlib_ios.c"]), ConfigOption(key: "env.MADEIRA_WG_WMV_TRANSFORM", title: "Media: WMV video decoder", kind: .text, defaultValue: "", category: "Media", note: "0 refuses every video transform again, as before: the WMVideo Decoder DMO and MFT cannot be created. By default they decode WMV1/2/3, WMVA and WVC1 with libavcodec. WMA is unaffected.", choices: [], sources: ["build/ntdll-unix/winegstreamer_unixlib_ios.c"]), diff --git a/build/ntdll-unix/winegstreamer_unixlib_ios.c b/build/ntdll-unix/winegstreamer_unixlib_ios.c index 977a1958f8..95030e69c0 100644 --- a/build/ntdll-unix/winegstreamer_unixlib_ios.c +++ b/build/ntdll-unix/winegstreamer_unixlib_ios.c @@ -44,9 +44,10 @@ * video_decoder.c's WMV decoder use: create / destroy / push_data / * read_data / get_output_type / set_output_type / drain / flush / get_status * (+ notify_qos as a no-op, and wg_init_gstreamer as a benign success so - * main.c's init_gstreamer_proc lets the DLL load), for two kinds of - * transform: WMA audio (below) and WMV video (the section "the WMV decoder"; - * "transform kinds" after it is how a call finds its kind). The wg_muxer + * main.c's init_gstreamer_proc lets the DLL load), for three kinds of + * transform: WMA audio (below), WMV video (the section "the WMV decoder") and + * the audio resampler (resampler.c's; the section after it). "Transform + * kinds" is how a call finds its kind. The wg_muxer * side returns STATUS_NOT_IMPLEMENTED. Those callers already handle a * component that is not available; what they must never get is a success * with an untouched output field (no fake success). @@ -61,12 +62,14 @@ * wg_parser_apple_ios.c) for the Media Foundation source; MADEIRA_WG_VIDEO=0 * restores the MP3/WAV-only parser. * - * wg_transform_create also REFUSES anything that is neither a WMA family - * stream nor Windows Media video (WMV1/WMV2/WMV3/WMVA/WVC1). winegstreamer's - * other transforms (aac, h264, the resampler, the colour converter) are real - * GStreamer pipelines with no replacement here, and a transform that accepts - * an H.264 stream and then emits nothing is worse for the caller than one - * that never opened. MADEIRA_WG_WMV_TRANSFORM=0 refuses the WMV one too. + * wg_transform_create also REFUSES anything that is not a WMA family + * stream, Windows Media video (WMV1/WMV2/WMV3/WMVA/WVC1) or raw audio (the + * resampler, on libswresample). winegstreamer's other transforms (aac, h264, + * the colour converter) are real GStreamer pipelines with no replacement + * here, and a transform that accepts an H.264 stream and then emits nothing + * is worse for the caller than one that never opened. + * MADEIRA_WG_WMV_TRANSFORM=0 refuses the WMV one too, MADEIRA_WG_RESAMPLER=0 + * the resampler. * * DECODING * -------- @@ -3051,6 +3054,488 @@ static BOOL wmv_claims( const struct wg_transform_create_params *params ) return IsEqualGUID( ¶ms->input_type.major, &madeira_MFMediaType_Video ) && wmv_transform_switch_on(); } +/*********************************************************************** + * wg_transform: the audio resampler (MADEIRA) + * + * winegstreamer's resampler -- CLSID_CResamplerMediaObject and wg_resampler, + * the converter Media Foundation's topology loader puts between a source's + * PCM and the audio renderer, which takes nothing but the device mix format -- + * is a GStreamer audioconvert ! audioresample pipeline upstream. Here it is + * libswresample: integer PCM of 8, 16, 24 or 32 bits and float of 32 or 64, + * WAVEFORMATEX or WAVEFORMATEXTENSIBLE, any rate, 1 to 8 channels, in and out. + * Without it a movie whose audio is not in the mix format loses its whole + * topology: no audio branch, no presentation clock, and the video renderer + * never presents (Senren Banka's WMV movies: 48 kHz S16 from the WMA decoder). + * MADEIRA_WG_RESAMPLER=0 refuses it again. + * + * Same protocol as the WMA decoder: push converts at once, and refuses more + * input (MF_E_NOTACCEPTING) while converted audio waits to be read. It is the + * first row of transform_kinds, so raw audio never reaches the WMA decoder. + */ +#define MADEIRA_WG_RESAMPLER_MAGIC 0x52534d50 /* 'RSMP' */ +#define RS_MAX_CHANNELS 8 +#define RS_MAX_LOGS 32 + +static unsigned int rs_log_count; + +#define RS_LOG( fmt, ... ) \ + do { \ + unsigned int _n = __atomic_add_fetch( &rs_log_count, 1, __ATOMIC_RELAXED ); \ + if (_n <= RS_MAX_LOGS || wma_diag_on()) \ + dprintf( 2, "[resampler] " fmt, ## __VA_ARGS__ ); \ + } while (0) + +struct rs_format +{ + enum AVSampleFormat fmt; /* what libswresample sees: 24-bit PCM goes through S32 */ + UINT32 bits; /* bits per sample in the caller's buffers */ + UINT32 rate, channels; + UINT32 frame_size; /* bytes per frame in the caller's buffers */ + AVChannelLayout layout; +}; + +struct rs_transform +{ + UINT32 magic; + pthread_mutex_t lock; + SwrContext *swr; + struct rs_format in, out; + + /* the output type as the caller set it, handed back verbatim */ + BYTE *out_format; + UINT32 out_format_size; + + BYTE *wide; /* 24-bit input widened to S32 */ + size_t wide_cap; + BYTE *pcm_buf; /* converted audio, consumed by read_data */ + size_t pcm_cap, pcm_pos, pcm_len; + + /* timestamps: the output frame `anchor_frames` before the next one read + * starts at `anchor`, so that rounding never adds up */ + INT64 anchor; /* 100 ns */ + UINT64 anchor_frames; + BOOL have_pts; + BOOL discontinuity; + UINT32 partial_logged; +}; + +/* MADEIRA_WG_RESAMPLER=0 refuses the resampler again: raw audio in fails at + * create, as before, and a media session with no matching mix format loses its + * audio branch. */ +static BOOL rs_switch_on(void) +{ + const char *v = getenv( "MADEIRA_WG_RESAMPLER" ); + return !(v && v[0] == '0' && !v[1]); +} + +static struct rs_transform *get_rs_transform( wg_transform_t handle ) +{ + struct rs_transform *transform = (struct rs_transform *)(UINT_PTR)handle; + + if (!transform || transform->magic != MADEIRA_WG_RESAMPLER_MAGIC) return NULL; + return transform; +} + +/* Raw audio in: a resampler's input, not a decoder's. */ +static BOOL rs_is_raw_audio( const struct wg_media_type *type ) +{ + const WAVEFORMATEX *wfx = audio_format( type ); + UINT tag; + + if (!wfx) return FALSE; + tag = format_tag( wfx, type->format_size ); + return tag == WAVE_FORMAT_PCM || tag == WAVE_FORMAT_IEEE_FLOAT; +} + +static BOOL rs_parse( const struct wg_media_type *type, struct rs_format *f ) +{ + const WAVEFORMATEX *wfx = audio_format( type ); + UINT tag; + + memset( f, 0, sizeof(*f) ); + if (!wfx) return FALSE; + tag = format_tag( wfx, type->format_size ); + if (tag == WAVE_FORMAT_PCM) + { + switch (wfx->wBitsPerSample) + { + case 8: f->fmt = AV_SAMPLE_FMT_U8; break; + case 16: f->fmt = AV_SAMPLE_FMT_S16; break; + case 24: + case 32: f->fmt = AV_SAMPLE_FMT_S32; break; + default: return FALSE; + } + } + else if (tag == WAVE_FORMAT_IEEE_FLOAT) + { + switch (wfx->wBitsPerSample) + { + case 32: f->fmt = AV_SAMPLE_FMT_FLT; break; + case 64: f->fmt = AV_SAMPLE_FMT_DBL; break; + default: return FALSE; + } + } + else return FALSE; + /* nBlockAlign is not trusted: check_audio_transform_support() leaves it 0 */ + if (!wfx->nChannels || wfx->nChannels > RS_MAX_CHANNELS || !wfx->nSamplesPerSec || wfx->nSamplesPerSec > 768000) + return FALSE; + f->bits = wfx->wBitsPerSample; + f->rate = wfx->nSamplesPerSec; + f->channels = wfx->nChannels; + f->frame_size = f->channels * (f->bits / 8); + layout_from_mask( &f->layout, channel_mask( wfx, type->format_size ), f->channels ); + return TRUE; +} + +static const char *rs_format_name( const struct rs_format *f ) +{ + switch (f->fmt) + { + case AV_SAMPLE_FMT_U8: return "u8"; + case AV_SAMPLE_FMT_S16: return "s16"; + case AV_SAMPLE_FMT_S32: return f->bits == 24 ? "s24" : "s32"; + case AV_SAMPLE_FMT_FLT: return "f32"; + case AV_SAMPLE_FMT_DBL: return "f64"; + default: return "?"; + } +} + +static int rs_open( struct rs_transform *transform ) +{ + int err; + + swr_free( &transform->swr ); + if ((err = swr_alloc_set_opts2( &transform->swr, &transform->out.layout, transform->out.fmt, + transform->out.rate, &transform->in.layout, transform->in.fmt, + transform->in.rate, 0, NULL )) < 0) + return err; + if ((err = swr_init( transform->swr )) < 0) swr_free( &transform->swr ); + return err; +} + +/* Converts `frames` frames of the caller's input (NULL: what libswresample + * still holds) onto the end of pcm_buf. */ +static NTSTATUS rs_convert( struct rs_transform *transform, const BYTE *data, UINT32 frames ) +{ + const uint8_t *in = data; + uint8_t *out; + UINT32 swr_frame = transform->out.channels * av_get_bytes_per_sample( transform->out.fmt ); + int max, n, i; + + if (data && transform->in.bits == 24) + { + /* little-endian 24-bit to the top of an S32 */ + size_t samples = (size_t)frames * transform->in.channels; + INT32 *w; + if (!buffer_reserve( &transform->wide, &transform->wide_cap, samples * 4 )) return STATUS_NO_MEMORY; + w = (INT32 *)transform->wide; + for (i = 0; i < (int)samples; i++) + w[i] = (INT32)((UINT32)data[3 * i] << 8 | (UINT32)data[3 * i + 1] << 16 | (UINT32)data[3 * i + 2] << 24); + in = transform->wide; + } + if ((max = swr_get_out_samples( transform->swr, data ? (int)frames : 0 )) < 0) return STATUS_INTERNAL_ERROR; + if (!max) return STATUS_SUCCESS; + if (!buffer_reserve( &transform->pcm_buf, &transform->pcm_cap, transform->pcm_len + (size_t)max * swr_frame )) + return STATUS_NO_MEMORY; + out = transform->pcm_buf + transform->pcm_len; + if ((n = swr_convert( transform->swr, &out, max, data ? &in : NULL, data ? (int)frames : 0 )) < 0) + { + RS_LOG( "swr_convert failed (%d) on %u frames (transform %p)\n", n, frames, transform ); + return STATUS_INTERNAL_ERROR; + } + if (transform->out.bits == 24) + { + /* back down from S32, in place: each 3-byte sample lands at or before its source */ + size_t samples = (size_t)n * transform->out.channels; + for (i = 0; i < (int)samples; i++) + { + UINT32 v = ((UINT32 *)out)[i]; + out[3 * i] = (BYTE)(v >> 8); + out[3 * i + 1] = (BYTE)(v >> 16); + out[3 * i + 2] = (BYTE)(v >> 24); + } + } + transform->pcm_len += (size_t)n * transform->out.frame_size; + return STATUS_SUCCESS; +} + +static void rs_compact( struct rs_transform *transform ) +{ + if (transform->pcm_pos == transform->pcm_len) + transform->pcm_pos = transform->pcm_len = 0; +} + +static BOOL rs_claims( const struct wg_transform_create_params *params ) +{ + return rs_is_raw_audio( ¶ms->input_type ); +} + +static NTSTATUS rs_create( struct wg_transform_create_params *params ) +{ + const WAVEFORMATEX *out = audio_format( ¶ms->output_type ); + struct rs_transform *transform; + struct rs_format fin, fout; + int err; + + params->transform = 0; + if (!rs_switch_on()) + { + RS_LOG( "disabled by MADEIRA_WG_RESAMPLER=0; refusing\n" ); + return STATUS_NOT_SUPPORTED; + } + if (!rs_parse( ¶ms->input_type, &fin )) + { + RS_LOG( "input is not 8/16/24/32-bit PCM or 32/64-bit float, 1-%u channels; refusing\n", RS_MAX_CHANNELS ); + return STATUS_NOT_SUPPORTED; + } + if (!rs_parse( ¶ms->output_type, &fout )) + { + RS_LOG( "output is not 8/16/24/32-bit PCM or 32/64-bit float, 1-%u channels; refusing\n", RS_MAX_CHANNELS ); + av_channel_layout_uninit( &fin.layout ); + return STATUS_NOT_SUPPORTED; + } + if (!(transform = calloc( 1, sizeof(*transform) )) + || !(transform->out_format = malloc( params->output_type.format_size ))) + { + free( transform ); + av_channel_layout_uninit( &fin.layout ); + av_channel_layout_uninit( &fout.layout ); + return STATUS_NO_MEMORY; + } + transform->in = fin; + transform->out = fout; + memcpy( transform->out_format, out, params->output_type.format_size ); + transform->out_format_size = params->output_type.format_size; + if ((err = rs_open( transform )) < 0) + { + RS_LOG( "libswresample refused %s %u Hz %uch -> %s %u Hz %uch (%d)\n", rs_format_name( &fin ), fin.rate, + fin.channels, rs_format_name( &fout ), fout.rate, fout.channels, err ); + av_channel_layout_uninit( &transform->in.layout ); + av_channel_layout_uninit( &transform->out.layout ); + free( transform->out_format ); + free( transform ); + return STATUS_NOT_SUPPORTED; + } + pthread_mutex_init( &transform->lock, NULL ); + transform->magic = MADEIRA_WG_RESAMPLER_MAGIC; + transform->discontinuity = TRUE; + params->transform = (wg_transform_t)(UINT_PTR)transform; + RS_LOG( "created %s %u Hz %uch -> %s %u Hz %uch (transform %p)\n", rs_format_name( &fin ), fin.rate, + fin.channels, rs_format_name( &fout ), fout.rate, fout.channels, transform ); + return STATUS_SUCCESS; +} + +static NTSTATUS rs_destroy( wg_transform_t handle ) +{ + struct rs_transform *transform = get_rs_transform( handle ); + + if (!transform) return STATUS_INVALID_HANDLE; + pthread_mutex_lock( &transform->lock ); + transform->magic = 0; + swr_free( &transform->swr ); + av_channel_layout_uninit( &transform->in.layout ); + av_channel_layout_uninit( &transform->out.layout ); + free( transform->out_format ); + free( transform->wide ); + free( transform->pcm_buf ); + pthread_mutex_unlock( &transform->lock ); + pthread_mutex_destroy( &transform->lock ); + free( transform ); + return STATUS_SUCCESS; +} + +static NTSTATUS rs_push_data( wg_transform_t handle, struct wg_sample *sample, const void *data, HRESULT *result ) +{ + struct rs_transform *transform = get_rs_transform( handle ); + UINT32 frames; + NTSTATUS status; + + if (!transform || !sample) return STATUS_INVALID_HANDLE; + if (sample->size && !data) return STATUS_INVALID_PARAMETER; + + pthread_mutex_lock( &transform->lock ); + if (transform->pcm_len > transform->pcm_pos) + { + *result = MF_E_NOTACCEPTING; + pthread_mutex_unlock( &transform->lock ); + return STATUS_SUCCESS; + } + rs_compact( transform ); + frames = sample->size / transform->in.frame_size; + if (sample->size % transform->in.frame_size && transform->partial_logged++ < 3) + RS_LOG( "a %u-byte sample is not whole %u-byte frames; the tail is dropped (transform %p)\n", + (UINT)sample->size, transform->in.frame_size, transform ); + /* The first frame out of this push is what libswresample still holds from + * earlier ones, so it starts that much before this sample. */ + if (sample->flags & WG_SAMPLE_FLAG_HAS_PTS) + { + transform->anchor = sample->pts - swr_get_delay( transform->swr, 10000000 ); + transform->anchor_frames = 0; + transform->have_pts = TRUE; + } + if (sample->flags & WG_SAMPLE_FLAG_DISCONTINUITY) transform->discontinuity = TRUE; + status = frames ? rs_convert( transform, data, frames ) : STATUS_SUCCESS; + pthread_mutex_unlock( &transform->lock ); + + *result = status ? E_FAIL : S_OK; + return status; +} + +static NTSTATUS rs_read_data( wg_transform_t handle, struct wg_sample *sample, void *data, HRESULT *result ) +{ + struct rs_transform *transform = get_rs_transform( handle ); + size_t avail, copy; + + if (!transform || !sample) return STATUS_INVALID_HANDLE; + if (sample->max_size && !data) return STATUS_INVALID_PARAMETER; + + pthread_mutex_lock( &transform->lock ); + avail = transform->pcm_len - transform->pcm_pos; + copy = avail < sample->max_size ? avail : sample->max_size; + copy -= copy % transform->out.frame_size; + if (!copy) + { + sample->size = 0; + pthread_mutex_unlock( &transform->lock ); + *result = MF_E_TRANSFORM_NEED_MORE_INPUT; + return STATUS_SUCCESS; + } + memcpy( data, transform->pcm_buf + transform->pcm_pos, copy ); + sample->size = copy; + sample->flags &= ~(WG_SAMPLE_FLAG_INCOMPLETE | WG_SAMPLE_FLAG_HAS_PTS | + WG_SAMPLE_FLAG_HAS_DURATION | WG_SAMPLE_FLAG_DISCONTINUITY); + sample->flags |= WG_SAMPLE_FLAG_SYNC_POINT | WG_SAMPLE_FLAG_HAS_DURATION; + { + UINT64 frames = copy / transform->out.frame_size, rate = transform->out.rate; + INT64 start = transform->anchor + (INT64)((transform->anchor_frames * 10000000 + rate / 2) / rate); + INT64 end = transform->anchor + (INT64)(((transform->anchor_frames + frames) * 10000000 + rate / 2) / rate); + + sample->duration = end - start; + if (transform->have_pts) + { + sample->flags |= WG_SAMPLE_FLAG_HAS_PTS; + sample->pts = start; + } + transform->anchor_frames += frames; + } + if (transform->discontinuity) + { + sample->flags |= WG_SAMPLE_FLAG_DISCONTINUITY; + transform->discontinuity = FALSE; + } + transform->pcm_pos += copy; + if (transform->pcm_pos < transform->pcm_len) sample->flags |= WG_SAMPLE_FLAG_INCOMPLETE; + else rs_compact( transform ); + pthread_mutex_unlock( &transform->lock ); + *result = S_OK; + return STATUS_SUCCESS; +} + +static NTSTATUS rs_get_output_type( wg_transform_t handle, struct wg_media_type *type ) +{ + struct rs_transform *transform = get_rs_transform( handle ); + UINT32 size; + + if (!transform) return STATUS_INVALID_HANDLE; + pthread_mutex_lock( &transform->lock ); + size = transform->out_format_size; + type->major = madeira_MFMediaType_Audio; + if (!type->u.format || type->format_size < size) + { + type->format_size = size; + pthread_mutex_unlock( &transform->lock ); + return STATUS_BUFFER_TOO_SMALL; + } + memcpy( type->u.format, transform->out_format, size ); + type->format_size = size; + pthread_mutex_unlock( &transform->lock ); + return STATUS_SUCCESS; +} + +static NTSTATUS rs_set_output_type( wg_transform_t handle, const struct wg_media_type *type ) +{ + struct rs_transform *transform = get_rs_transform( handle ); + struct rs_format fout, old; + BYTE *copy; + int err; + + if (!transform) return STATUS_INVALID_HANDLE; + if (!rs_parse( type, &fout )) return STATUS_NOT_SUPPORTED; + if (!(copy = malloc( type->format_size ))) + { + av_channel_layout_uninit( &fout.layout ); + return STATUS_NO_MEMORY; + } + memcpy( copy, type->u.format, type->format_size ); + + pthread_mutex_lock( &transform->lock ); + old = transform->out; + transform->out = fout; + if ((err = rs_open( transform )) < 0) + { + transform->out = old; + rs_open( transform ); + pthread_mutex_unlock( &transform->lock ); + av_channel_layout_uninit( &fout.layout ); + free( copy ); + RS_LOG( "libswresample refused the new output type (%d); keeping the old one\n", err ); + return STATUS_NOT_SUPPORTED; + } + av_channel_layout_uninit( &old.layout ); + /* anything converted is in the old format */ + transform->pcm_pos = transform->pcm_len = 0; + transform->discontinuity = TRUE; + free( transform->out_format ); + transform->out_format = copy; + transform->out_format_size = type->format_size; + pthread_mutex_unlock( &transform->lock ); + RS_LOG( "output type set to %s %u Hz %uch (transform %p)\n", rs_format_name( &fout ), fout.rate, + fout.channels, transform ); + return STATUS_SUCCESS; +} + +static NTSTATUS rs_get_status( wg_transform_t handle, UINT32 *accepts_input ) +{ + struct rs_transform *transform = get_rs_transform( handle ); + + if (!transform) return STATUS_INVALID_HANDLE; + pthread_mutex_lock( &transform->lock ); + *accepts_input = transform->pcm_len == transform->pcm_pos; + pthread_mutex_unlock( &transform->lock ); + return STATUS_SUCCESS; +} + +/* What libswresample still holds comes out, and it starts afresh. */ +static NTSTATUS rs_drain( wg_transform_t handle ) +{ + struct rs_transform *transform = get_rs_transform( handle ); + NTSTATUS status; + + if (!transform) return STATUS_INVALID_HANDLE; + pthread_mutex_lock( &transform->lock ); + status = rs_convert( transform, NULL, 0 ); + if (swr_init( transform->swr ) < 0) status = STATUS_INTERNAL_ERROR; + pthread_mutex_unlock( &transform->lock ); + return status; +} + +static NTSTATUS rs_flush( wg_transform_t handle ) +{ + struct rs_transform *transform = get_rs_transform( handle ); + NTSTATUS status = STATUS_SUCCESS; + + if (!transform) return STATUS_INVALID_HANDLE; + pthread_mutex_lock( &transform->lock ); + transform->pcm_pos = transform->pcm_len = 0; + transform->have_pts = FALSE; + transform->anchor = 0; + transform->anchor_frames = 0; + transform->discontinuity = TRUE; + if (swr_init( transform->swr ) < 0) status = STATUS_INTERNAL_ERROR; + pthread_mutex_unlock( &transform->lock ); + return status; +} + /*********************************************************************** * transform kinds * @@ -3078,6 +3563,12 @@ struct wg_transform_ops NTSTATUS (*flush)( wg_transform_t handle ); }; +static const struct wg_transform_ops rs_transform_ops = +{ + "resampler", MADEIRA_WG_RESAMPLER_MAGIC, rs_claims, rs_create, rs_destroy, rs_get_output_type, + rs_set_output_type, rs_push_data, rs_read_data, rs_get_status, rs_drain, rs_flush, +}; + static const struct wg_transform_ops wma_transform_ops = { "wma", MADEIRA_WG_TRANSFORM_MAGIC, wma_claims, wma_create, wma_destroy, wma_get_output_type, @@ -3090,9 +3581,10 @@ static const struct wg_transform_ops wmv_transform_ops = wmv_set_output_type, wmv_push_data, wmv_read_data, wmv_get_status, wmv_drain, wmv_flush, }; -/* In claim order. */ +/* In claim order: raw audio is the resampler's, other audio the WMA decoder's. */ static const struct wg_transform_ops *const transform_kinds[] = { + &rs_transform_ops, &wma_transform_ops, &wmv_transform_ops, }; diff --git a/build/tools/gen-config-catalog.py b/build/tools/gen-config-catalog.py index c50a30a66a..7cbc1c0c9d 100644 --- a/build/tools/gen-config-catalog.py +++ b/build/tools/gen-config-catalog.py @@ -589,6 +589,9 @@ "created. By default they decode WMV1/2/3, WMVA and WVC1 with libavcodec. WMA is unaffected."}, "env.MADEIRA_WG_VIDEO": {"title": "Media: MP4 video (32-bit programs)", "note": "0 limits the media parser to MP3/WAV; by default MP4 with H.264/HEVC video decodes through VideoToolbox."}, + "env.MADEIRA_WG_RESAMPLER": {"title": "Media: audio resampler", + "note": "0 refuses the resampler transform again; by default Media Foundation converts a movie's audio to the " + "device mix format with libswresample."}, "env.MADEIRA_WG_COMPRESSED": {"title": "Media: compressed WMV/WMA samples (32-bit programs)", "note": "0 refuses the WM reader's compressed samples of an ASF again; by default an application that " "decodes them itself (KiriKiri's movie plugin, through the WMV/WMA decoder DMOs) gets the file's packets."}, diff --git a/docs/MEDIA.md b/docs/MEDIA.md index af1fc6cbc1..6d5cfa259e 100644 --- a/docs/MEDIA.md +++ b/docs/MEDIA.md @@ -38,7 +38,7 @@ before unless `MADEIRA_WG_64BIT=1`. | File | What it is | |---|---| -| `build/ntdll-unix/winegstreamer_unixlib_ios.c` | Both unix call tables (entry for entry with `dlls/winegstreamer/unixlib.h`), the wow64 thunks, and two kinds of `wg_transform` on libavcodec: the WMA decoder `wma_decoder.c` uses (WMA v1/v2/Pro/Lossless, XMA1/2) and the WMV decoder `video_decoder.c`'s WMVideo Decoder DMO/MFT uses (WMV1, WMV2, WMV3, WMVA, WVC1; see below). `transform_create` gives a create to the first kind that claims its input type; every other entry finds the kind by the magic its object starts with. Other transforms (AAC, H.264, the resampler, the colour converter) are refused at create, and `wg_muxer` returns `STATUS_NOT_IMPLEMENTED`. | +| `build/ntdll-unix/winegstreamer_unixlib_ios.c` | Both unix call tables (entry for entry with `dlls/winegstreamer/unixlib.h`), the wow64 thunks, and two kinds of `wg_transform` on libavcodec: the WMA decoder `wma_decoder.c` uses (WMA v1/v2/Pro/Lossless, XMA1/2) and the WMV decoder `video_decoder.c`'s WMVideo Decoder DMO/MFT uses (WMV1, WMV2, WMV3, WMVA, WVC1; see below). `transform_create` gives a create to the first kind that claims its input type; every other entry finds the kind by the magic its object starts with. Raw audio in is a third kind, the resampler `resampler.c` uses, on libswresample (see below). Other transforms (AAC, H.264, the colour converter) are refused at create, and `wg_muxer` returns `STATUS_NOT_IMPLEMENTED`. | | `build/ntdll-unix/wg_parser_av_ios.c` | The `wg_parser` core, `#include`d by the file above: the PE read thread's pull protocol as an AVIOContext, libavformat demux (mp3, wav, mov, asf), MPEG audio / PCM / WMA decode through libavcodec + libswresample, Windows Media video (WMV7/8/9, VC-1, MS-MPEG4 v1-v3) decoded in software by libavcodec (`mav_lavc_video`), a packet queue with back-pressure, B-frame reordering, keyframe seek with exact trim, and conversion (`mav_convert_picture`, which the WMV transform uses too) to the formats `quartz_parser.c`, `media_source.c` and `wm_reader.c` ask for: NV12, I420, YV12, YUY2, UYVY, YVYU, BGRx, BGRA, RGBA, 24-bit BGR (the WM reader's default, bottom-up), RGB565 and RGB555. | | `build/ntdll-unix/wg_parser_apple_ios.c` | H.264/HEVC on VideoToolbox (NV12 out) and AAC on an AudioToolbox AudioConverter (float PCM out). Its own translation unit with no Wine or FFmpeg header. | | `build/ntdll-unix/wg_parser_backend_ios.h` | The contract between the core and a decoder backend; plain C types only, so the host test can supply stub backends. | @@ -133,6 +133,22 @@ B-frames) is lost at the end of a stream, as with GStreamer. When the DMO wrapper meets a new output media type, `video_decoder.c` makes a new transform, whose new decoder waits for a keyframe. +**The resampler.** Media Foundation's topology loader puts winegstreamer's +resampler (`CLSID_CResamplerMediaObject`, `wg_resampler`) between a source's +PCM and the audio renderer, which takes only the device mix format. Its +`wg_transform` was refused here ("input format tag 0x1 is not a WMA family +stream"), so `resampler_create` failed. For Senren Banka's WMV movie (48 kHz +S16 from the WMA stream) the topology then had no audio branch and no +presentation clock, and the video renderer never presented. The resampler is +now libswresample: +- integer PCM of 8, 16, 24 or 32 bits and float of 32 or 64, in and out; +- `WAVEFORMATEX` or `WAVEFORMATEXTENSIBLE`, any rate, 1 to 8 channels; +- timestamps run from the input's, less what the resampler holds back, and do + not drift. + +It logs one `[resampler] created ...` line per transform. +`MADEIRA_WG_RESAMPLER=0` refuses it again. + **One demuxer, several readers: back-pressure.** Each stream is read on its own thread by quartz and Media Foundation; a packet read for another stream is queued for it. A stream whose reader falls behind (a video decoded slower @@ -164,15 +180,17 @@ Environment variables (`env.NAME = value` in `madeira.cfg`): | `MADEIRA_WG_PARSER` | on | `0`: `wg_parser_create` returns `STATUS_NOT_IMPLEMENTED` again, as before this series; quartz and the MF source then fail the way they did. The WMA decoder is unaffected. | | `MADEIRA_WG_VIDEO` | on | `0`: MP3/WAV only; an MP4/MOV or ASF is refused at connect. | | `MADEIRA_WG_WMV_TRANSFORM` | on | `0`: every video `wg_transform` is refused at create again, so the WMVideo Decoder DMO/MFT cannot be created, as before. Read once per process. WMA is unaffected. | +| `MADEIRA_WG_RESAMPLER` | on | `0`: the resampler transform is refused at create, as before. | | `MADEIRA_WG_COMPRESSED` | on | `0`: a compressed-output parser refuses an ASF, as before: the WM reader's compressed samples are not available (see above). | | `MADEIRA_WG_VIDEO_FORMAT` | `rgb32` | Native format a video stream reports: `nv12`, `i420`, `yv12`, `yuy2`, `rgb32`, `argb32` or `abgr32` (see above for why the default is `rgb32`). | | `MADEIRA_WMA_SEARCH` | on | `0`: keep the WMA v1/v2 decoder at the bit rate and flags it opened with; no search over other candidates when a bit-reservoir stream fails. A packet that fails is concealed with silence of its length and the next one is decoded as usual. (An xWMA stream still opens at the rate libavformat's xWMA table normalises to.) | | `MADEIRA_WMA_DUMP` | off | Set: write each WMA decoder's input to `wma-dump-.bin` in the Documents folder, for reproducing a decode failure on a host. | Log tags: `[wma]` for the WMA decoder, `[wmv]` for the WMV decoder (one line -per create and per destroy, refusals with their reason), `[wg-parser]` for the -parser. All are rate-limited per process (`MADEIRA_DIAG=1` lifts the `[wma]` -and `[wmv]` caps). +per create and per destroy, refusals with their reason), `[resampler]` for the +resampler (one line per create), `[wg-parser]` for the parser. All are +rate-limited per process (`MADEIRA_DIAG=1` lifts the `[wma]`, `[wmv]` and +`[resampler]` caps). ## Tests @@ -227,6 +245,16 @@ and `[wmv]` caps). `MADEIRA_WG_WMV_TRANSFORM=0`. WMV3/WVC1/WMVA are covered by codec-id plumbing only (the DMO's probe, hand-built sequence headers, garbage frames): FFmpeg cannot encode them. +- `tests/host/check-wg-resampler.py` (needs a configured Wine tree, like + the WMA test): drives the resampler through the `wg_transform` entries under + ASan/UBSan. It covers: + - 48 kHz S16 stereo to 48 and 44.1 kHz float (Senren's case): the tone's + frequency and level, the frame count, timestamps without gaps or drift; + - all 36 pairs of u8/s16/s24/s32/f32/f64, with identity bit-exact; + - 5.1 to stereo, mono to stereo, stereo to mono; + - `check_audio_transform_support()`'s probe, back-pressure, flush, a new + output type mid-stream, drain; + - refusals and `MADEIRA_WG_RESAMPLER=0`. - `tests/x86/wma-x86.c` (`build-wma-test.sh`): a 32-bit program that reaches the WMA decoder exactly as FAudio does and checks that the decoded PCM has the 440 Hz fundamental it was encoded from. Exit 62 pass, 63 decode diff --git a/tests/host/check-wg-resampler.py b/tests/host/check-wg-resampler.py new file mode 100755 index 0000000000..12e2415e57 --- /dev/null +++ b/tests/host/check-wg-resampler.py @@ -0,0 +1,505 @@ +#!/usr/bin/env python3 +"""The wg_transform audio resampler (winegstreamer's resampler: CLSID_CResamplerMediaObject and +wg_resampler) on libswresample, through the unix call entries; no Wine runs. + +Media Foundation's topology loader puts the resampler between a source's PCM and the audio +renderer, which takes only the device mix format. This port's wg_transform refused PCM input +("input format tag 0x1 is not a WMA family stream"), resampler_create failed, the audio branch of +Senren Banka's WMV movie topology failed with it, and the movie never presented. The transform now +converts PCM and float of any rate and 1 to 8 channels with libswresample. + +Checks, under ASan/UBSan: + - Senren's case (48 kHz S16 stereo -> 44.1 and 48 kHz float stereo): the tone's frequency and level, + the frame count after drain, gap-free timestamps from the input's, chunked reads; + - formats in and out: u8, s16, s24 (packed), s32, f32, f64; identity is bit-exact; s24 out within + one step; WAVE_FORMAT_EXTENSIBLE (5.1 to stereo, stereo float to mono); + - check_audio_transform_support()'s probe (nBlockAlign and nAvgBytesPerSec 0) is accepted; + - back-pressure (MF_E_NOTACCEPTING, get_status), flush, a new output type mid-stream (and + get_output_type's two-phase answer), drain; + - refusals: 12-bit PCM, 9 channels, PCM to AAC; MADEIRA_WG_RESAMPLER=0; a WMA stream still + reaches the WMA decoder. +Needs MADEIRA_WINE_BUILD (a configured Wine tree), a C compiler and the FFmpeg tarball, as +check-wma-decoder.py. +""" +from pathlib import Path +import hashlib, os, subprocess, sys, tempfile + +root = Path(__file__).resolve().parents[2] +ntdll_unix = root / "build/ntdll-unix" +glue = (ntdll_unix / "winegstreamer_unixlib_ios.c").read_text() +wine = Path(os.environ.get("MADEIRA_WINE_SRC") or root / "wine") +wine_build = Path(os.environ.get("MADEIRA_WINE_BUILD") or wine / "build-macos") +for need in [wine_build / "include/config.h", wine_build / "include/mfobjects.h", wine / "dlls/winegstreamer/unixlib.h"]: + if not need.exists(): + sys.exit("SKIP-FAIL: %s is missing; point MADEIRA_WINE_BUILD at a configured Wine tree" % need) + +# ------------------------------------------------------------------ source checks +row = glue[glue.index("static const struct wg_transform_ops rs_transform_ops ="):] +row = row[:row.index("};")] +for fn in ["rs_claims", "rs_create", "rs_destroy", "rs_get_output_type", "rs_set_output_type", "rs_push_data", + "rs_read_data", "rs_get_status", "rs_drain", "rs_flush"]: + assert fn in row, ("the resampler's row", fn) +kinds = glue[glue.index("static const struct wg_transform_ops *const transform_kinds[] ="):] +kinds = kinds[:kinds.index("};")] +assert kinds.index("&rs_transform_ops") < kinds.index("&wma_transform_ops"), \ + "the resampler claims raw audio before the WMA decoder claims all audio" +print("PASS: the resampler is a row of transform_kinds, ahead of the WMA decoder (the 64-bit entries and the " + "wow64 thunks go through the same dispatch)") + +# ------------------------------------------------------------------ host FFmpeg (check-wma-decoder.py's, shared cache) +tarball = os.environ.get("MADEIRA_FFMPEG_TARBALL") or str(root / "build/ffmpeg/src/ffmpeg-7.1.5.tar.xz") +FLAGS = [ + "--disable-everything", "--disable-autodetect", "--disable-gpl", "--disable-nonfree", "--disable-version3", + "--enable-decoder=wmav1,wmav2,wmapro,wmalossless,xma1,xma2", + "--enable-decoder=mp1,mp2,mp3", "--enable-decoder=pcm_u8,pcm_s16le,pcm_s24le,pcm_s32le,pcm_f32le,pcm_f64le", + "--enable-demuxer=mp3,wav,mov", "--enable-parser=mpegaudio", + "--enable-encoder=wmav1,wmav2", + "--disable-programs", "--disable-doc", "--disable-network", "--disable-avdevice", "--disable-swscale", + "--disable-avfilter", "--disable-postproc", "--enable-avformat", "--enable-avcodec", "--enable-swresample", + "--disable-asm", "--disable-shared", "--enable-static", "--enable-pic", "--disable-debug", +] +prefix = os.environ.get("MADEIRA_HOST_FFMPEG") +if not prefix: + key = hashlib.sha256(" ".join(FLAGS).encode()).hexdigest()[:12] + prefix = str(Path.home() / ".cache/madeira-host-ffmpeg" / ("7.1.5-" + key)) + if not (Path(prefix) / "lib/libavcodec.a").exists(): + assert Path(tarball).exists(), "no FFmpeg tarball at %s" % tarball + src = Path(prefix + "-src") + src.mkdir(parents=True, exist_ok=True) + if not (src / "ffmpeg-7.1.5/configure").exists(): + subprocess.run(["tar", "-xJf", tarball, "-C", str(src)], check=True) + bld = Path(prefix + "-build"); bld.mkdir(parents=True, exist_ok=True) + print("building host FFmpeg into", prefix, flush=True) + log = open(str(bld) + ".log", "w") + subprocess.run([str(src / "ffmpeg-7.1.5/configure"), "--prefix=" + prefix, "--cc=cc"] + FLAGS, + cwd=bld, check=True, stdout=log, stderr=subprocess.STDOUT) + subprocess.run(["make", "-j%d" % (os.cpu_count() or 4)], cwd=bld, check=True, stdout=log, stderr=subprocess.STDOUT) + subprocess.run(["make", "install"], cwd=bld, check=True, stdout=log, stderr=subprocess.STDOUT) +inc, lib = Path(prefix) / "include", Path(prefix) / "lib" + +# ------------------------------------------------------------------ harness +harness = r""" +#include "winegstreamer_unixlib_ios.c" +#include + +const struct mav_video_backend mav_apple_video_backend; +const struct mav_audio_backend mav_apple_audio_backend; + +static int failures; +#define CHECK(c, ...) do { if (!(c)) { printf( "FAIL %s:%d: ", __func__, __LINE__ ); printf( __VA_ARGS__ ); printf( "\n" ); failures++; return 1; } } while (0) + +static const GUID sub_pcm = { WAVE_FORMAT_PCM, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } }; +static const GUID sub_float = { WAVE_FORMAT_IEEE_FLOAT, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } }; + +enum fmt { U8, S16, S24, S32, F32, F64 }; +static const int fmt_bits[] = { 8, 16, 24, 32, 32, 64 }; +static const char *fmt_name[] = { "u8", "s16", "s24", "s32", "f32", "f64" }; + +/* A WAVEFORMATEX, or WAVEFORMATEXTENSIBLE with `mask`; `probe`: as check_audio_transform_support() (no + * nBlockAlign / nAvgBytesPerSec). */ +static struct wg_media_type make_type( WAVEFORMATEXTENSIBLE *w, enum fmt f, int rate, int channels, DWORD mask, int probe ) +{ + struct wg_media_type t = {0}; + memset( w, 0, sizeof(*w) ); + w->Format.wFormatTag = f >= F32 ? WAVE_FORMAT_IEEE_FLOAT : WAVE_FORMAT_PCM; + w->Format.nChannels = channels; + w->Format.nSamplesPerSec = rate; + w->Format.wBitsPerSample = fmt_bits[f]; + if (!probe) + { + w->Format.nBlockAlign = channels * fmt_bits[f] / 8; + w->Format.nAvgBytesPerSec = rate * w->Format.nBlockAlign; + } + t.major = madeira_MFMediaType_Audio; + t.u.audio = &w->Format; + t.format_size = sizeof(WAVEFORMATEX); + if (mask) + { + w->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; + w->Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX); + w->Samples.wValidBitsPerSample = fmt_bits[f]; + w->dwChannelMask = mask; + w->SubFormat = f >= F32 ? sub_float : sub_pcm; + t.format_size = sizeof(WAVEFORMATEXTENSIBLE); + } + return t; +} + +static void put( uint8_t *p, enum fmt f, double v ) +{ + double c = v > 1 ? 1 : v < -1 ? -1 : v; + int32_t i; + switch (f) + { + case U8: *p = (uint8_t)lrint( c * 127 + 128 ); break; + case S16: i = (int32_t)lrint( c * 32767 ); memcpy( p, &i, 2 ); break; + case S24: i = (int32_t)lrint( c * 8388607 ); p[0] = (uint8_t)i; p[1] = (uint8_t)(i >> 8); p[2] = (uint8_t)(i >> 16); break; + case S32: i = (int32_t)lrint( c * 2147483647.0 ); memcpy( p, &i, 4 ); break; + case F32: { float x = (float)v; memcpy( p, &x, 4 ); break; } + case F64: memcpy( p, &v, 8 ); break; + } +} + +static double get( const uint8_t *p, enum fmt f ) +{ + int32_t i = 0; float x; double d; + switch (f) + { + case U8: return (p[0] - 128) / 128.0; + case S16: { int16_t s; memcpy( &s, p, 2 ); return s / 32768.0; } + case S24: i = (int32_t)((uint32_t)p[0] << 8 | (uint32_t)p[1] << 16 | (uint32_t)p[2] << 24) >> 8; return i / 8388608.0; + case S32: memcpy( &i, p, 4 ); return i / 2147483648.0; + case F32: memcpy( &x, p, 4 ); return x; + case F64: memcpy( &d, p, 8 ); return d; + } + return 0; +} + +struct run +{ + wg_transform_t t; + uint8_t *out; size_t out_frames, out_cap; /* every output frame, in order */ + int64_t first_pts, next_pts, max_gap; int pts_gaps, have_pts, discontinuities, incomplete; + int out_frame; +}; + +static int read_all( struct run *r, size_t max_read ) +{ + for (;;) + { + struct wg_transform_read_data_params read = {0}; + struct wg_sample sample = {0}; + uint8_t buf[65536]; + sample.max_size = (UINT32)(max_read < sizeof(buf) ? max_read : sizeof(buf)); + sample.data = (UINT64)(UINT_PTR)buf; + read.transform = r->t; read.sample = &sample; + CHECK( !wg_transform_read_data( &read ), "read_data" ); + if (read.result == MF_E_TRANSFORM_NEED_MORE_INPUT) { CHECK( !sample.size, "size with NEED_MORE_INPUT" ); return 0; } + CHECK( read.result == S_OK && sample.size && sample.size % r->out_frame == 0, "read %#x size %u", (unsigned)read.result, sample.size ); + CHECK( sample.flags & WG_SAMPLE_FLAG_HAS_DURATION, "duration flag" ); + if (sample.flags & WG_SAMPLE_FLAG_HAS_PTS) + { + if (!r->have_pts) r->first_pts = sample.pts; + else + { + /* a frame at 44.1 kHz is 226.76 ticks: where a push re-anchors, rounding moves a + * boundary by a tick or two, never by a frame */ + int64_t gap = llabs( (long long)(sample.pts - r->next_pts) ); + if (gap > r->max_gap) r->max_gap = gap; + if (gap > 2) r->pts_gaps++; + } + r->have_pts = 1; + r->next_pts = sample.pts + sample.duration; + } + if (sample.flags & WG_SAMPLE_FLAG_DISCONTINUITY) r->discontinuities++; + if (sample.flags & WG_SAMPLE_FLAG_INCOMPLETE) r->incomplete++; + if ((r->out_frames + sample.size / r->out_frame) * r->out_frame > r->out_cap) + { + r->out_cap = ((r->out_frames + sample.size / r->out_frame) * r->out_frame) * 2; + r->out = realloc( r->out, r->out_cap ); + } + memcpy( r->out + r->out_frames * r->out_frame, buf, sample.size ); + r->out_frames += sample.size / r->out_frame; + } +} + +/* Pushes `in` (`frames` frames of `in_frame` bytes) in `chunk`-frame samples with pts, reading after + * each push; drains at the end. */ +static int stream( struct run *r, const uint8_t *in, size_t frames, int in_frame, int rate, size_t chunk, size_t max_read, + int64_t pts0 ) +{ + size_t off = 0; + while (off < frames) + { + struct wg_transform_push_data_params push = {0}; + struct wg_transform_get_status_params status = {0}; + struct wg_sample sample = {0}; + size_t n = frames - off < chunk ? frames - off : chunk; + sample.size = sample.max_size = (UINT32)(n * in_frame); + sample.data = (UINT64)(UINT_PTR)(in + off * in_frame); + sample.flags = WG_SAMPLE_FLAG_HAS_PTS | (off ? 0 : WG_SAMPLE_FLAG_DISCONTINUITY); + sample.pts = pts0 + (int64_t)off * 10000000 / rate; + push.transform = r->t; push.sample = &sample; + CHECK( !wg_transform_push_data( &push ) && push.result == S_OK, "push %#x", (unsigned)push.result ); + status.transform = r->t; + CHECK( !wg_transform_get_status( &status ), "get_status" ); + if (read_all( r, max_read )) return 1; + off += n; + } + CHECK( !wg_transform_drain( &r->t ), "drain" ); + return read_all( r, max_read ); +} + +static int create( struct run *r, struct wg_media_type in, struct wg_media_type out ) +{ + struct wg_transform_create_params c = {0}; + c.input_type = in; c.output_type = out; + memset( r, 0, sizeof(*r) ); + CHECK( !wg_transform_create( &c ) && c.transform, "create" ); + r->t = c.transform; + r->out_frame = out.u.audio->nChannels * out.u.audio->wBitsPerSample / 8; + return 0; +} + +static void destroy( struct run *r ) { wg_transform_destroy( &r->t ); free( r->out ); } + +/* frequency (zero crossings) and rms of channel `ch` over the middle half */ +static void analyse( const struct run *r, enum fmt f, int channels, int ch, int rate, double *freq, double *rms ) +{ + size_t a = r->out_frames / 4, b = r->out_frames - r->out_frames / 4, i, crossings = 0; + double e = 0, prev = 0; + int bps = fmt_bits[f] / 8; + for (i = a; i < b; i++) + { + double v = get( r->out + (i * channels + ch) * bps, f ); + e += v * v; + if (i > a && (prev < 0) != (v < 0)) crossings++; + prev = v; + } + *rms = sqrt( e / (b - a) ); + *freq = crossings / 2.0 * rate / (b - a); +} + +static uint8_t *tone( enum fmt f, int rate, int channels, double seconds, size_t *frames ) +{ + size_t n = (size_t)(seconds * rate), i; int c, bps = fmt_bits[f] / 8; + uint8_t *buf = malloc( n * channels * bps ); + for (i = 0; i < n; i++) + for (c = 0; c < channels; c++) + put( buf + (i * channels + c) * bps, f, 0.5 * sin( 2 * M_PI * 440 * (double)i / rate ) * (c == 0 || channels < 3 ? 1 : 0.5) ); + *frames = n; + return buf; +} + +/* Senren's: 48 kHz S16 stereo from the WMA decoder to the mix format */ +static int test_senren( int out_rate ) +{ + WAVEFORMATEXTENSIBLE wi, wo; struct run r; size_t frames; double freq, rms, want; + uint8_t *in = tone( S16, 48000, 2, 2.0, &frames ); + int64_t pts0 = 1234567; + + if (create( &r, make_type( &wi, S16, 48000, 2, 0, 0 ), make_type( &wo, F32, out_rate, 2, 0, 0 ) )) return 1; + if (stream( &r, in, frames, 4, 48000, 1024, 3000, pts0 )) return 1; + want = (double)frames * out_rate / 48000; + CHECK( fabs( r.out_frames - want ) <= 2, "%zu frames out, want %.0f", r.out_frames, want ); + analyse( &r, F32, 2, 1, out_rate, &freq, &rms ); + CHECK( fabs( freq - 440 ) < 1.0 && fabs( rms - 0.5 / sqrt( 2 ) ) < 0.01, "%.2f Hz rms %.4f", freq, rms ); + CHECK( r.have_pts && llabs( (long long)(r.first_pts - pts0) ) < 20000 && !r.pts_gaps, + "pts: first %lld (in %lld), %d gaps, largest %lld", (long long)r.first_pts, (long long)pts0, r.pts_gaps, + (long long)r.max_gap ); + CHECK( llabs( (long long)(r.next_pts - (pts0 + (int64_t)r.out_frames * 10000000 / out_rate)) ) <= 2 + 10000000 / out_rate, + "pts at the end %lld, frames say %lld", (long long)r.next_pts, (long long)(pts0 + (int64_t)r.out_frames * 10000000 / out_rate) ); + CHECK( r.discontinuities == 1 && r.incomplete > 0, "discontinuities %d, incomplete reads %d", r.discontinuities, r.incomplete ); + destroy( &r ); free( in ); + printf( "PASS: s16 48000 Hz 2ch -> f32 %d Hz 2ch: %zu frames for %zu, 440 Hz at rms %.4f, pts from the input's without " + "gaps (largest step error %lld x 100 ns) or drift, chunked reads\n", out_rate, r.out_frames, frames, rms, + (long long)r.max_gap ); + return 0; +} + +static int test_formats( void ) +{ + static const enum fmt all[] = { U8, S16, S24, S32, F32, F64 }; + unsigned int i, j; int tested = 0; + for (i = 0; i < 6; i++) + for (j = 0; j < 6; j++) + { + WAVEFORMATEXTENSIBLE wi, wo; struct run r; size_t frames, k; double freq, rms, maxerr = 0; + enum fmt fi = all[i], fo = all[j]; + uint8_t *in = tone( fi, 44100, 2, 1.0, &frames ); + int ib = fmt_bits[fi] / 8, ob = fmt_bits[fo] / 8; + /* step of the coarser side, plus libswresample's rounding on the way */ + double tol = (fi == U8 || fo == U8) ? 2.0 / 128 : (fi == S16 || fo == S16) ? 2.0 / 32768 : 2.0 / 8388608; + + if (create( &r, make_type( &wi, fi, 44100, 2, 0, 0 ), make_type( &wo, fo, 44100, 2, 0, 0 ) )) return 1; + if (stream( &r, in, frames, 2 * ib, 44100, 4410, 1 << 20, 0 )) return 1; + CHECK( r.out_frames == frames, "%s -> %s: %zu frames for %zu", fmt_name[fi], fmt_name[fo], r.out_frames, frames ); + for (k = 0; k < frames * 2; k++) + { + double e = fabs( get( r.out + k * ob, fo ) - get( in + k * ib, fi ) ); + if (e > maxerr) maxerr = e; + } + CHECK( maxerr <= tol, "%s -> %s: error %.3g > %.3g", fmt_name[fi], fmt_name[fo], maxerr, tol ); + if (fi == fo) CHECK( !memcmp( r.out, in, frames * 2 * ib ), "%s -> %s is not bit-exact", fmt_name[fi], fmt_name[fo] ); + /* 1 Hz per zero crossing in this window, and u8's quantisation sits on 0 */ + analyse( &r, fo, 2, 0, 44100, &freq, &rms ); + CHECK( fabs( freq - 440 ) < 2.5, "%s -> %s: %.2f Hz", fmt_name[fi], fmt_name[fo], freq ); + destroy( &r ); free( in ); tested++; + } + printf( "PASS: %d format pairs of u8 s16 s24 s32 f32 f64 at 44100 Hz: every sample within the coarser format's step; " + "identity bit-exact\n", tested ); + return 0; +} + +static int test_channels( void ) +{ + WAVEFORMATEXTENSIBLE wi, wo; struct run r; size_t frames; double freq, rms, rms_r; + uint8_t *in; + + /* 5.1 (EXTENSIBLE, float) to stereo S16 */ + in = tone( F32, 48000, 6, 1.0, &frames ); + if (create( &r, make_type( &wi, F32, 48000, 6, 0x3f, 0 ), make_type( &wo, S16, 48000, 2, 0, 0 ) )) return 1; + if (stream( &r, in, frames, 24, 48000, 960, 1 << 20, 0 )) return 1; + analyse( &r, S16, 2, 0, 48000, &freq, &rms ); analyse( &r, S16, 2, 1, 48000, &freq, &rms_r ); + CHECK( r.out_frames == frames && fabs( freq - 440 ) < 2.5 && rms > 0.05 && rms_r > 0.05, "5.1 -> stereo: %zu frames, %.1f Hz, rms %.3f / %.3f", + r.out_frames, freq, rms, rms_r ); + destroy( &r ); free( in ); + + /* mono to stereo, both channels the tone; stereo EXTENSIBLE float to mono */ + in = tone( S16, 22050, 1, 1.0, &frames ); + if (create( &r, make_type( &wi, S16, 22050, 1, 0, 0 ), make_type( &wo, F32, 44100, 2, 0x3, 0 ) )) return 1; + if (stream( &r, in, frames, 2, 22050, 500, 1 << 20, 0 )) return 1; + analyse( &r, F32, 2, 0, 44100, &freq, &rms ); analyse( &r, F32, 2, 1, 44100, &freq, &rms_r ); + CHECK( fabs( (double)r.out_frames - 2.0 * frames ) <= 2 && fabs( freq - 440 ) < 2.5 && fabs( rms - rms_r ) < 1e-6 && rms > 0.2, + "mono 22050 -> stereo 44100: %zu frames, %.1f Hz, rms %.3f / %.3f", r.out_frames, freq, rms, rms_r ); + destroy( &r ); free( in ); + + in = tone( F32, 44100, 2, 1.0, &frames ); + if (create( &r, make_type( &wi, F32, 44100, 2, 0x3, 0 ), make_type( &wo, S16, 44100, 1, 0, 0 ) )) return 1; + if (stream( &r, in, frames, 8, 44100, 441, 1 << 20, 0 )) return 1; + analyse( &r, S16, 1, 0, 44100, &freq, &rms ); + CHECK( r.out_frames == frames && fabs( freq - 440 ) < 2.5 && rms > 0.2, "stereo -> mono: %.1f Hz rms %.3f", freq, rms ); + destroy( &r ); free( in ); + printf( "PASS: channels: 5.1 (EXTENSIBLE) -> stereo, mono 22050 -> stereo 44100 (EXTENSIBLE), stereo -> mono\n" ); + return 0; +} + +static int test_protocol( void ) +{ + WAVEFORMATEXTENSIBLE wi, wo, w2; struct run r; size_t frames; double freq, rms; + struct wg_transform_create_params c = {0}; + struct wg_transform_push_data_params push = {0}; + struct wg_transform_get_status_params status = {0}; + struct wg_transform_get_output_type_params got = {0}; + struct wg_transform_set_output_type_params set = {0}; + struct wg_sample sample = {0}; + uint8_t *in = tone( S16, 48000, 2, 1.0, &frames ), fmtbuf[64]; + + /* resampler_create()'s probe: no nBlockAlign, no nAvgBytesPerSec */ + c.input_type = make_type( &wi, S16, 44100, 1, 0, 1 ); c.output_type = make_type( &wo, F32, 44100, 1, 0, 1 ); + CHECK( !wg_transform_create( &c ) && c.transform, "check_audio_transform_support()'s probe" ); + CHECK( !wg_transform_destroy( &c.transform ), "destroy" ); + + if (create( &r, make_type( &wi, S16, 48000, 2, 0, 0 ), make_type( &wo, F32, 48000, 2, 0, 0 ) )) return 1; + /* back-pressure */ + sample.size = sample.max_size = 4800 * 4; sample.data = (UINT64)(UINT_PTR)in; + sample.flags = WG_SAMPLE_FLAG_HAS_PTS; sample.pts = 0; + push.transform = r.t; push.sample = &sample; + CHECK( !wg_transform_push_data( &push ) && push.result == S_OK, "push" ); + status.transform = r.t; + CHECK( !wg_transform_get_status( &status ) && !status.accepts_input, "accepts input with output waiting" ); + CHECK( !wg_transform_push_data( &push ) && push.result == MF_E_NOTACCEPTING, "second push: %#x", (unsigned)push.result ); + /* flush: nothing waits, and the next push starts at its own pts */ + CHECK( !wg_transform_flush( &r.t ), "flush" ); + CHECK( !wg_transform_get_status( &status ) && status.accepts_input, "accepts input after flush" ); + if (read_all( &r, 1 << 20 ) || r.out_frames) { printf( "FAIL: output after flush\n" ); return 1; } + sample.pts = 50000000; + CHECK( !wg_transform_push_data( &push ) && push.result == S_OK, "push after flush" ); + if (read_all( &r, 1 << 20 )) return 1; + CHECK( r.have_pts && r.first_pts == 50000000 && r.discontinuities == 1, "after flush: pts %lld, %d discontinuities", + (long long)r.first_pts, r.discontinuities ); + + /* get_output_type: two-phase */ + got.transform = r.t; + CHECK( wg_transform_get_output_type( &got ) == STATUS_BUFFER_TOO_SMALL && got.media_type.format_size == sizeof(WAVEFORMATEX), + "size query" ); + got.media_type.u.format = fmtbuf; + CHECK( !wg_transform_get_output_type( &got ) && !memcmp( fmtbuf, &wo, sizeof(WAVEFORMATEX) ), "output type verbatim" ); + + /* a new output type: 44.1 kHz S16 mono from here on */ + set.transform = r.t; set.media_type = make_type( &w2, S16, 44100, 1, 0, 0 ); + CHECK( !wg_transform_set_output_type( &set ), "set_output_type" ); + got.media_type.format_size = sizeof(fmtbuf); + CHECK( !wg_transform_get_output_type( &got ) && !memcmp( fmtbuf, &w2, sizeof(WAVEFORMATEX) ), "new output type verbatim" ); + free( r.out ); r.out = NULL; r.out_frames = r.out_cap = 0; r.have_pts = 0; r.out_frame = 2; + if (stream( &r, in, frames, 4, 48000, 2048, 1 << 20, 0 )) return 1; + analyse( &r, S16, 1, 0, 44100, &freq, &rms ); + CHECK( fabs( (double)r.out_frames - frames * 44100.0 / 48000 ) <= 2 && fabs( freq - 440 ) < 2.5 && rms > 0.3, + "after set_output_type: %zu frames, %.1f Hz, rms %.3f", r.out_frames, freq, rms ); + set.media_type = make_type( &w2, S16, 44100, 12, 0, 0 ); + CHECK( wg_transform_set_output_type( &set ) == STATUS_NOT_SUPPORTED, "12-channel output type refused" ); + destroy( &r ); free( in ); + printf( "PASS: check_audio_transform_support()'s probe; back-pressure; flush; get_output_type two-phase and verbatim; " + "a new output type mid-stream (48000 stereo f32 -> 44100 mono s16)\n" ); + return 0; +} + +static int test_refusals( int disabled ) +{ + WAVEFORMATEXTENSIBLE wi, wo; struct wg_transform_create_params c = {0}; + NTSTATUS st; + + c.input_type = make_type( &wi, S16, 44100, 2, 0, 0 ); c.output_type = make_type( &wo, F32, 44100, 2, 0, 0 ); + st = wg_transform_create( &c ); + if (disabled) + { + CHECK( st == STATUS_NOT_SUPPORTED && !c.transform, "MADEIRA_WG_RESAMPLER=0 refuses: %#x", (unsigned)st ); + printf( "PASS: MADEIRA_WG_RESAMPLER=0 refuses the resampler\n" ); + return 0; + } + CHECK( !st && c.transform, "create" ); wg_transform_destroy( &c.transform ); + wi.Format.wBitsPerSample = 12; + CHECK( wg_transform_create( &c ) == STATUS_NOT_SUPPORTED && !c.transform, "12-bit PCM refused" ); + c.input_type = make_type( &wi, S16, 44100, 9, 0, 0 ); + CHECK( wg_transform_create( &c ) == STATUS_NOT_SUPPORTED && !c.transform, "9 channels refused" ); + c.input_type = make_type( &wi, S16, 44100, 2, 0, 0 ); + wo.Format.wFormatTag = 0x1610; /* AAC */ + CHECK( wg_transform_create( &c ) == STATUS_NOT_SUPPORTED && !c.transform, "PCM to AAC refused" ); + /* a WMA stream still reaches the WMA decoder (its own test decodes it) */ + { + struct { WAVEFORMATEX wfx; BYTE extra[6]; } wma = {{ WAVE_FORMAT_WMAUDIO2, 2, 44100, 16000, 2973, 16, 6 }, { 0, 0, 0, 0, 0x1f, 0 }}; + c.input_type.u.audio = &wma.wfx; c.input_type.format_size = sizeof(wma); + c.output_type = make_type( &wo, S16, 44100, 2, 0, 0 ); + CHECK( !wg_transform_create( &c ) && c.transform && get_wma_transform( c.transform ) && !get_rs_transform( c.transform ), + "WMA still goes to the WMA decoder" ); + wg_transform_destroy( &c.transform ); + } + printf( "PASS: refused: 12-bit PCM, 9 channels, PCM to AAC; a WMA stream still reaches the WMA decoder\n" ); + return 0; +} + +int main( int argc, char **argv ) +{ + setvbuf( stdout, NULL, _IONBF, 0 ); + if (argc > 1) return test_refusals( 1 ); + if (test_senren( 48000 ) || test_senren( 44100 ) || test_formats() || test_channels() || test_protocol() + || test_refusals( 0 )) + return 1; + return failures != 0; +} +""" + +with tempfile.TemporaryDirectory() as tmp: + h = Path(tmp) / "resampler_host.c" + h.write_text(harness) + exe = Path(tmp) / "resampler_host" + cc = os.environ.get("CC", "cc") + cmd = [cc, "-O1", "-g", "-fsanitize=address,undefined", "-fno-sanitize-recover=undefined", + "-fno-strict-aliasing", "-Wno-int-conversion", "-Wno-implicit-function-declaration", + "-include", str(wine_build / "include/config.h"), + "-I" + str(ntdll_unix), "-I" + str(wine / "dlls/winegstreamer"), + "-I" + str(wine_build / "include"), "-I" + str(wine / "include"), "-I" + str(inc), + "-D__WINESRC__", "-D_NTSYSTEM_", "-D_ACRTIMP=", "-DWINBASEAPI=", "-DWINE_UNIX_LIB", + str(h), "-o", str(exe), + str(lib / "libavformat.a"), str(lib / "libavcodec.a"), str(lib / "libswresample.a"), str(lib / "libavutil.a"), + "-lm", "-lpthread"] + r = subprocess.run(cmd, capture_output=True, text=True) + if r.returncode: + print(r.stdout[-6000:], r.stderr[-6000:]) + sys.exit("FAIL: harness did not compile") + env = {k: v for k, v in os.environ.items() if not k.startswith("MADEIRA_")} + env["ASAN_OPTIONS"] = "detect_leaks=1" + ok = True + for args, extra in [([], {}), (["off"], {"MADEIRA_WG_RESAMPLER": "0"})]: + r = subprocess.run([str(exe)] + args, env=dict(env, **extra), capture_output=True, text=True, timeout=300) + sys.stdout.write(r.stdout) + bad = "ERROR: AddressSanitizer" in r.stderr or "runtime error" in r.stderr + if r.returncode or bad: + ok = False + print(r.stderr[-4000:]) + if not args: + lines = [l for l in r.stderr.splitlines() if l.startswith("[resampler]")] + assert any("created s16 48000 Hz 2ch -> f32 44100 Hz 2ch" in l for l in lines), lines + for l in lines[:6]: + print(" " + l) + sys.exit(0 if ok else "FAIL: resampler host test") From a8e71c866089910a1dd38546638c12bc7269d1e6 Mon Sep 17 00:00:00 2001 From: allen Date: Sun, 22 Nov 2026 05:48:30 +0800 Subject: [PATCH 7/9] tests: build the shared host FFmpeg under a lock check-wma-decoder.py and check-wg-resampler.py share one host FFmpeg build (the same configure flags), and so do check-wg-parser-asf.py and check-wmv-transform.py. Run at the same time on a cold cache (a parallel runner, or CI), both configured into one build directory: ffbuild/config.mak broke ("extraneous 'endif'"), and both checks failed. tests/host/host_ffmpeg.py builds it once for all five media checks: under a lock on the prefix, from a clean build directory, and a check waits for a build in progress instead of linking against a half-installed prefix. The cache paths do not change. All five, run at once on an empty cache, now pass with one build per prefix. Co-Authored-By: Claude Opus 5.5 Signed-off-by: allen --- tests/host/check-wg-parser-asf.py | 23 ++++---------- tests/host/check-wg-parser.py | 24 ++++----------- tests/host/check-wg-resampler.py | 24 ++++----------- tests/host/check-wma-decoder.py | 24 ++++----------- tests/host/check-wmv-transform.py | 23 ++++---------- tests/host/host_ffmpeg.py | 50 +++++++++++++++++++++++++++++++ 6 files changed, 75 insertions(+), 93 deletions(-) create mode 100644 tests/host/host_ffmpeg.py diff --git a/tests/host/check-wg-parser-asf.py b/tests/host/check-wg-parser-asf.py index a51761c12d..feb29cf5f2 100644 --- a/tests/host/check-wg-parser-asf.py +++ b/tests/host/check-wg-parser-asf.py @@ -37,7 +37,9 @@ Needs python3, a C compiler and the FFmpeg tarball (build/ffmpeg/src). """ from pathlib import Path -import hashlib, os, re, subprocess, sys, tempfile +import os, re, subprocess, sys, tempfile +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from host_ffmpeg import host_ffmpeg # the shared host build, made under a lock root = Path(__file__).resolve().parents[2] core = root / "build/ntdll-unix/wg_parser_av_ios.c" @@ -98,23 +100,8 @@ "--disable-avfilter", "--disable-postproc", "--enable-avformat", "--enable-avcodec", "--enable-swresample", "--disable-asm", "--disable-shared", "--enable-static", "--enable-pic", "--disable-debug", ] -prefix = os.environ.get("MADEIRA_HOST_FFMPEG_ASF") -if not prefix: - key = hashlib.sha256(" ".join(FLAGS).encode()).hexdigest()[:12] - prefix = str(Path.home() / ".cache/madeira-host-ffmpeg" / ("7.1.5-asf-" + key)) - if not (Path(prefix) / "lib/libavformat.a").exists(): - assert Path(tarball).exists(), "no FFmpeg tarball at build/ffmpeg/src (tracked) and no MADEIRA_FFMPEG_TARBALL" - src = Path(prefix + "-src"); src.mkdir(parents=True, exist_ok=True) - if not (src / "ffmpeg-7.1.5/configure").exists(): - subprocess.run(["tar", "-xJf", tarball, "-C", str(src)], check=True) - bld = Path(prefix + "-build"); bld.mkdir(parents=True, exist_ok=True) - print("building host FFmpeg into", prefix, flush=True) - log = open(str(bld) + ".log", "w") - subprocess.run([str(src / "ffmpeg-7.1.5/configure"), "--prefix=" + prefix, "--cc=cc"] + FLAGS, - cwd=bld, check=True, stdout=log, stderr=subprocess.STDOUT) - subprocess.run(["make", "-j%d" % (os.cpu_count() or 4)], cwd=bld, check=True, stdout=log, stderr=subprocess.STDOUT) - subprocess.run(["make", "install"], cwd=bld, check=True, stdout=log, stderr=subprocess.STDOUT) -inc, lib = Path(prefix) / "include", Path(prefix) / "lib" +prefix = host_ffmpeg(FLAGS, tarball, tag="asf-", override=os.environ.get("MADEIRA_HOST_FFMPEG_ASF")) +inc, lib = prefix / "include", prefix / "lib" # ------------------------------------------------------------------ 3. the core under ASan harness = r""" diff --git a/tests/host/check-wg-parser.py b/tests/host/check-wg-parser.py index 2bf8981d36..6561ecb530 100644 --- a/tests/host/check-wg-parser.py +++ b/tests/host/check-wg-parser.py @@ -36,7 +36,9 @@ default: a Windows system MP3 under /mnt/c when present, otherwise the real-MP3 case is skipped). """ from pathlib import Path -import hashlib, os, re, subprocess, sys, tempfile +import os, re, subprocess, sys, tempfile +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from host_ffmpeg import host_ffmpeg # the shared host build, made under a lock root = Path(__file__).resolve().parents[2] core = root / "build/ntdll-unix/wg_parser_av_ios.c" @@ -137,24 +139,8 @@ def table(name): "--disable-avfilter", "--disable-postproc", "--enable-avformat", "--enable-avcodec", "--enable-swresample", "--disable-asm", "--disable-shared", "--enable-static", "--enable-pic", "--disable-debug", ] -prefix = os.environ.get("MADEIRA_HOST_FFMPEG") -if not prefix: - key = hashlib.sha256(" ".join(FLAGS).encode()).hexdigest()[:12] - prefix = str(Path.home() / ".cache/madeira-host-ffmpeg" / ("7.1.5-" + key)) - if not (Path(prefix) / "lib/libavformat.a").exists(): - assert tarball and Path(tarball).exists(), "no FFmpeg tarball at build/ffmpeg/src (tracked) and no MADEIRA_FFMPEG_TARBALL" - src = Path(prefix + "-src") - src.mkdir(parents=True, exist_ok=True) - if not (src / "ffmpeg-7.1.5/configure").exists(): - subprocess.run(["tar", "-xJf", tarball, "-C", str(src)], check=True) - bld = Path(prefix + "-build"); bld.mkdir(parents=True, exist_ok=True) - print("building host FFmpeg into", prefix, flush=True) - log = open(str(bld) + ".log", "w") - subprocess.run([str(src / "ffmpeg-7.1.5/configure"), "--prefix=" + prefix, "--cc=cc"] + FLAGS, - cwd=bld, check=True, stdout=log, stderr=subprocess.STDOUT) - subprocess.run(["make", "-j%d" % (os.cpu_count() or 4)], cwd=bld, check=True, stdout=log, stderr=subprocess.STDOUT) - subprocess.run(["make", "install"], cwd=bld, check=True, stdout=log, stderr=subprocess.STDOUT) -inc, lib = Path(prefix) / "include", Path(prefix) / "lib" +prefix = host_ffmpeg(FLAGS, tarball, tag="", override=os.environ.get("MADEIRA_HOST_FFMPEG")) +inc, lib = prefix / "include", prefix / "lib" # ------------------------------------------------------------------ 3. the core under ASan harness = r""" diff --git a/tests/host/check-wg-resampler.py b/tests/host/check-wg-resampler.py index 12e2415e57..cba7eb0000 100755 --- a/tests/host/check-wg-resampler.py +++ b/tests/host/check-wg-resampler.py @@ -22,7 +22,9 @@ check-wma-decoder.py. """ from pathlib import Path -import hashlib, os, subprocess, sys, tempfile +import os, subprocess, sys, tempfile +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from host_ffmpeg import host_ffmpeg # the shared host build, made under a lock root = Path(__file__).resolve().parents[2] ntdll_unix = root / "build/ntdll-unix" @@ -58,24 +60,8 @@ "--disable-avfilter", "--disable-postproc", "--enable-avformat", "--enable-avcodec", "--enable-swresample", "--disable-asm", "--disable-shared", "--enable-static", "--enable-pic", "--disable-debug", ] -prefix = os.environ.get("MADEIRA_HOST_FFMPEG") -if not prefix: - key = hashlib.sha256(" ".join(FLAGS).encode()).hexdigest()[:12] - prefix = str(Path.home() / ".cache/madeira-host-ffmpeg" / ("7.1.5-" + key)) - if not (Path(prefix) / "lib/libavcodec.a").exists(): - assert Path(tarball).exists(), "no FFmpeg tarball at %s" % tarball - src = Path(prefix + "-src") - src.mkdir(parents=True, exist_ok=True) - if not (src / "ffmpeg-7.1.5/configure").exists(): - subprocess.run(["tar", "-xJf", tarball, "-C", str(src)], check=True) - bld = Path(prefix + "-build"); bld.mkdir(parents=True, exist_ok=True) - print("building host FFmpeg into", prefix, flush=True) - log = open(str(bld) + ".log", "w") - subprocess.run([str(src / "ffmpeg-7.1.5/configure"), "--prefix=" + prefix, "--cc=cc"] + FLAGS, - cwd=bld, check=True, stdout=log, stderr=subprocess.STDOUT) - subprocess.run(["make", "-j%d" % (os.cpu_count() or 4)], cwd=bld, check=True, stdout=log, stderr=subprocess.STDOUT) - subprocess.run(["make", "install"], cwd=bld, check=True, stdout=log, stderr=subprocess.STDOUT) -inc, lib = Path(prefix) / "include", Path(prefix) / "lib" +prefix = host_ffmpeg(FLAGS, tarball, tag="", override=os.environ.get("MADEIRA_HOST_FFMPEG")) +inc, lib = prefix / "include", prefix / "lib" # ------------------------------------------------------------------ harness harness = r""" diff --git a/tests/host/check-wma-decoder.py b/tests/host/check-wma-decoder.py index ad0eced89c..cca32c007d 100755 --- a/tests/host/check-wma-decoder.py +++ b/tests/host/check-wma-decoder.py @@ -19,7 +19,9 @@ widl-generated headers; default: wine/build-macos, the tree build/ntdll-unix/build.sh uses). """ from pathlib import Path -import hashlib, os, subprocess, sys, tempfile +import os, subprocess, sys, tempfile +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from host_ffmpeg import host_ffmpeg # the shared host build, made under a lock root = Path(__file__).resolve().parents[2] ntdll_unix = root / "build/ntdll-unix" @@ -72,24 +74,8 @@ "--disable-avfilter", "--disable-postproc", "--enable-avformat", "--enable-avcodec", "--enable-swresample", "--disable-asm", "--disable-shared", "--enable-static", "--enable-pic", "--disable-debug", ] -prefix = os.environ.get("MADEIRA_HOST_FFMPEG") -if not prefix: - key = hashlib.sha256(" ".join(FLAGS).encode()).hexdigest()[:12] - prefix = str(Path.home() / ".cache/madeira-host-ffmpeg" / ("7.1.5-" + key)) - if not (Path(prefix) / "lib/libavcodec.a").exists(): - assert Path(tarball).exists(), "no FFmpeg tarball at %s" % tarball - src = Path(prefix + "-src") - src.mkdir(parents=True, exist_ok=True) - if not (src / "ffmpeg-7.1.5/configure").exists(): - subprocess.run(["tar", "-xJf", tarball, "-C", str(src)], check=True) - bld = Path(prefix + "-build"); bld.mkdir(parents=True, exist_ok=True) - print("building host FFmpeg into", prefix, flush=True) - log = open(str(bld) + ".log", "w") - subprocess.run([str(src / "ffmpeg-7.1.5/configure"), "--prefix=" + prefix, "--cc=cc"] + FLAGS, - cwd=bld, check=True, stdout=log, stderr=subprocess.STDOUT) - subprocess.run(["make", "-j%d" % (os.cpu_count() or 4)], cwd=bld, check=True, stdout=log, stderr=subprocess.STDOUT) - subprocess.run(["make", "install"], cwd=bld, check=True, stdout=log, stderr=subprocess.STDOUT) -inc, lib = Path(prefix) / "include", Path(prefix) / "lib" +prefix = host_ffmpeg(FLAGS, tarball, tag="", override=os.environ.get("MADEIRA_HOST_FFMPEG")) +inc, lib = prefix / "include", prefix / "lib" # ------------------------------------------------------------------ harness harness = r""" diff --git a/tests/host/check-wmv-transform.py b/tests/host/check-wmv-transform.py index fe5e16719e..d7bb688d57 100644 --- a/tests/host/check-wmv-transform.py +++ b/tests/host/check-wmv-transform.py @@ -45,7 +45,9 @@ widl-generated headers; default: wine/build-macos). """ from pathlib import Path -import hashlib, os, re, subprocess, sys, tempfile +import os, re, subprocess, sys, tempfile +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from host_ffmpeg import host_ffmpeg # the shared host build, made under a lock root = Path(__file__).resolve().parents[2] ntdll_unix = root / "build/ntdll-unix" @@ -150,23 +152,8 @@ def table(name): "--disable-avfilter", "--disable-postproc", "--enable-avformat", "--enable-avcodec", "--enable-swresample", "--disable-asm", "--disable-shared", "--enable-static", "--enable-pic", "--disable-debug", ] -prefix = os.environ.get("MADEIRA_HOST_FFMPEG_ASF") -if not prefix: - key = hashlib.sha256(" ".join(FLAGS).encode()).hexdigest()[:12] - prefix = str(Path.home() / ".cache/madeira-host-ffmpeg" / ("7.1.5-asf-" + key)) - if not (Path(prefix) / "lib/libavformat.a").exists(): - assert Path(tarball).exists(), "no FFmpeg tarball at build/ffmpeg/src (tracked) and no MADEIRA_FFMPEG_TARBALL" - src = Path(prefix + "-src"); src.mkdir(parents=True, exist_ok=True) - if not (src / "ffmpeg-7.1.5/configure").exists(): - subprocess.run(["tar", "-xJf", tarball, "-C", str(src)], check=True) - bld = Path(prefix + "-build"); bld.mkdir(parents=True, exist_ok=True) - print("building host FFmpeg into", prefix, flush=True) - log = open(str(bld) + ".log", "w") - subprocess.run([str(src / "ffmpeg-7.1.5/configure"), "--prefix=" + prefix, "--cc=cc"] + FLAGS, - cwd=bld, check=True, stdout=log, stderr=subprocess.STDOUT) - subprocess.run(["make", "-j%d" % (os.cpu_count() or 4)], cwd=bld, check=True, stdout=log, stderr=subprocess.STDOUT) - subprocess.run(["make", "install"], cwd=bld, check=True, stdout=log, stderr=subprocess.STDOUT) -inc, lib = Path(prefix) / "include", Path(prefix) / "lib" +prefix = host_ffmpeg(FLAGS, tarball, tag="asf-", override=os.environ.get("MADEIRA_HOST_FFMPEG_ASF")) +inc, lib = prefix / "include", prefix / "lib" # ------------------------------------------------------------------ 3. harness harness = r""" diff --git a/tests/host/host_ffmpeg.py b/tests/host/host_ffmpeg.py new file mode 100644 index 0000000000..f4090f64b0 --- /dev/null +++ b/tests/host/host_ffmpeg.py @@ -0,0 +1,50 @@ +"""The host FFmpeg the media checks link against: built from the tracked tarball with a check's +configure flags, and cached in ~/.cache/madeira-host-ffmpeg/7.1.5-. + +Checks with the same flags share one build (check-wma-decoder.py and check-wg-resampler.py; +check-wg-parser-asf.py and check-wmv-transform.py), and run-all.py runs checks at the same time. +Two configures in one build directory break it ("extraneous 'endif'" in ffbuild/config.mak) and +both checks fail, and a check that saw a library appear could link against a half-installed +prefix. So the prefix is looked at and built under a lock: a check waits for a build in progress, +and a build starts from a clean build directory. +""" +import fcntl, hashlib, os, shutil, subprocess +from pathlib import Path + +VERSION = "7.1.5" + + +def host_ffmpeg(flags, tarball, tag="", override=None): + """The prefix (include/, lib/) of the host build for `flags`, built if needed. + `override`: a prefix named in the environment, used as it is.""" + if override: + return Path(override) + key = hashlib.sha256(" ".join(flags).encode()).hexdigest()[:12] + prefix = Path.home() / ".cache/madeira-host-ffmpeg" / ("%s-%s%s" % (VERSION, tag, key)) + prefix.parent.mkdir(parents=True, exist_ok=True) + with open(str(prefix) + ".lock", "w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + if not all((prefix / "lib" / a).exists() for a in ("libavformat.a", "libavcodec.a")): + _build(prefix, flags, tarball) + return prefix + + +def _build(prefix, flags, tarball): + assert tarball and Path(tarball).exists(), \ + "no FFmpeg tarball at %s (tracked in build/ffmpeg/src) and no MADEIRA_FFMPEG_TARBALL" % tarball + src = Path(str(prefix) + "-src") + configure = src / ("ffmpeg-%s/configure" % VERSION) + if not configure.exists(): + shutil.rmtree(src, ignore_errors=True) + src.mkdir(parents=True) + subprocess.run(["tar", "-xJf", str(tarball), "-C", str(src)], check=True) + # A build directory left by an interrupted run starts again. + bld = Path(str(prefix) + "-build") + shutil.rmtree(bld, ignore_errors=True) + bld.mkdir(parents=True) + print("building host FFmpeg into", prefix, flush=True) + with open(str(bld) + ".log", "w") as log: + for cmd in ([str(configure), "--prefix=" + str(prefix), "--cc=cc"] + list(flags), + ["make", "-j%d" % (os.cpu_count() or 4)], + ["make", "install"]): + subprocess.run(cmd, cwd=bld, check=True, stdout=log, stderr=subprocess.STDOUT) From 0fd0a810a6ca5ca751fb923f5c9f30bcc8059a42 Mon Sep 17 00:00:00 2001 From: allen Date: Sun, 22 Nov 2026 05:56:27 +0800 Subject: [PATCH 8/9] winegstreamer iOS: decode video ahead on a thread of its own Wine's media source asks for every stream's samples on one work-queue thread (a standard work queue has one thread), and so does the WM reader reading the earliest buffer. The parser decoded on the requesting thread, under its lock: each picture of Senren Banka's 1080p WMV (software decode and RGB conversion, about 20 ms) held up the audio request behind it, and the audio renderer ran short for 6 to 17% of each 10 s ("client wrote 8.33 s of audio in 10.01 s"). GStreamer decodes in streaming threads of its own. Here each decoded video stream gets a worker at its first request, which keeps up to three pictures ready in a ring of slots; a request pops one. The worker demuxes under the parser lock like any reader, and decodes and converts without it (mav_heavy_begin), so a request for another stream is answered meanwhile. A seek, a new format or compressed output waits for the picture the worker is on, and it starts no new one until they are done (mav_ahead_quiesce). Disconnect joins the workers and waits for requests waiting on a picture before anything is freed. The worker does not wait on back-pressure for a stream that the thread it reads for would drain. MADEIRA_WG_VIDEO_AHEAD=0 decodes on demand again. tests/host/check-wg-parser.py: with a stub decoder that takes 20 ms a picture and one thread asking for both streams at 30 fps, a video request takes 0.0 ms instead of 21, every picture comes in order, the audio has no gaps, a seek lands exactly, and a disconnect mid-decode is clean; the threaded cases also run under ThreadSanitizer (the harness's read-thread flag is atomic now). tests/host/check-wg-parser-asf.py: every case runs with the worker, and again under ThreadSanitizer; a new back-pressure case (one thread that read the audio, then only the video) stalls 447 ms without the last rule above. Co-Authored-By: Claude Opus 5.5 Signed-off-by: allen --- app/Madeira/ConfigCatalog.generated.swift | 1 + build/ntdll-unix/wg_parser_av_ios.c | 377 ++++++++++++++++++- build/ntdll-unix/winegstreamer_unixlib_ios.c | 12 + build/tools/gen-config-catalog.py | 3 + docs/MEDIA.md | 48 ++- tests/host/check-wg-parser-asf.py | 41 +- tests/host/check-wg-parser.py | 135 ++++++- 7 files changed, 580 insertions(+), 37 deletions(-) diff --git a/app/Madeira/ConfigCatalog.generated.swift b/app/Madeira/ConfigCatalog.generated.swift index bff4e4ce9d..8ac9e69c1d 100644 --- a/app/Madeira/ConfigCatalog.generated.swift +++ b/app/Madeira/ConfigCatalog.generated.swift @@ -404,6 +404,7 @@ extension ConfigCatalog { ConfigOption(key: "env.MADEIRA_WG_PARSER", title: "", kind: .text, defaultValue: "", category: "Media", note: "", choices: [], sources: ["build/ntdll-unix/winegstreamer_unixlib_ios.c"]), ConfigOption(key: "env.MADEIRA_WG_RESAMPLER", title: "Media: audio resampler", kind: .text, defaultValue: "", category: "Media", note: "0 refuses the resampler transform again; by default Media Foundation converts a movie's audio to the device mix format with libswresample.", choices: [], sources: ["build/ntdll-unix/winegstreamer_unixlib_ios.c"]), ConfigOption(key: "env.MADEIRA_WG_VIDEO", title: "Media: MP4 video (32-bit programs)", kind: .text, defaultValue: "", category: "Media", note: "0 limits the media parser to MP3/WAV; by default MP4 with H.264/HEVC video decodes through VideoToolbox.", choices: [], sources: ["build/ntdll-unix/winegstreamer_unixlib_ios.c"]), + ConfigOption(key: "env.MADEIRA_WG_VIDEO_AHEAD", title: "Media: decode video ahead (32-bit programs)", kind: .text, defaultValue: "", category: "Media", note: "0 decodes a movie's video on the thread that asks for it, as before; by default each video stream decodes ahead on a thread of its own, so the audio is not held up behind a picture.", choices: [], sources: ["build/ntdll-unix/winegstreamer_unixlib_ios.c"]), ConfigOption(key: "env.MADEIRA_WG_VIDEO_FORMAT", title: "", kind: .text, defaultValue: "", category: "Media", note: "", choices: [], sources: ["build/ntdll-unix/winegstreamer_unixlib_ios.c"]), ConfigOption(key: "env.MADEIRA_WG_WMV_TRANSFORM", title: "Media: WMV video decoder", kind: .text, defaultValue: "", category: "Media", note: "0 refuses every video transform again, as before: the WMVideo Decoder DMO and MFT cannot be created. By default they decode WMV1/2/3, WMVA and WVC1 with libavcodec. WMA is unaffected.", choices: [], sources: ["build/ntdll-unix/winegstreamer_unixlib_ios.c"]), ConfigOption(key: "env.MADEIRA_WMA_DUMP", title: "", kind: .text, defaultValue: "", category: "Media", note: "", choices: [], sources: ["build/ntdll-unix/winegstreamer_unixlib_ios.c"]), diff --git a/build/ntdll-unix/wg_parser_av_ios.c b/build/ntdll-unix/wg_parser_av_ios.c index 82d8dd569f..0a2798ec57 100644 --- a/build/ntdll-unix/wg_parser_av_ios.c +++ b/build/ntdll-unix/wg_parser_av_ios.c @@ -254,6 +254,8 @@ static void mav_configure( int video_allowed, const struct mav_video_backend *vi const struct mav_audio_backend *audio, enum mav_pixel_format native ); /* 0: a compressed-output parser refuses an ASF too, as before the WM reader's compressed samples */ static void mav_allow_compressed_asf( int allowed ); +/* 0: video is decoded on the thread that asks for a buffer, as before mav_ahead_main */ +static void mav_allow_video_ahead( int allowed ); static struct mav_parser *mav_create( int output_compressed ); static void mav_destroy( struct mav_parser *p ); static int mav_connect( struct mav_parser *p, uint64_t file_size ); @@ -304,6 +306,11 @@ static int mav_seek( struct mav_parser *p, unsigned int stream, int set_start, u /* Pictures held for presentation-order output beyond what the decode-time * rule releases (a stream without decode times, or a broken one). */ #define MAV_REORDER_MAX 16 +/* Decode-ahead (mav_ahead_main): pictures a video stream's worker keeps ready, + * plus the one handed out. A 1080p RGB32 picture is 8 MB. */ +#ifndef MAV_AHEAD_SLOTS +#define MAV_AHEAD_SLOTS 4 +#endif /* Packets queued for a stream nobody is reading from yet. */ #ifndef MAV_QUEUE_MAX_PACKETS /* tests/host/check-wg-parser.py and check-wg-parser-asf.py build with small limits */ #define MAV_QUEUE_MAX_PACKETS 16384 @@ -335,6 +342,7 @@ static const struct mav_video_backend *mav_vbackend; static const struct mav_audio_backend *mav_abackend; static enum mav_pixel_format mav_native_pix = MAV_PIX_NV12; static int mav_compressed_asf = 1; +static int mav_video_ahead = 1; static void mav_configure( int video_allowed, const struct mav_video_backend *video, const struct mav_audio_backend *audio, enum mav_pixel_format native ) @@ -350,6 +358,11 @@ static void mav_allow_compressed_asf( int allowed ) mav_compressed_asf = !!allowed; } +static void mav_allow_video_ahead( int allowed ) +{ + mav_video_ahead = !!allowed; +} + /* ---- the log: bounded, and deduplicated ---- */ static pthread_mutex_t mav_log_lock = PTHREAD_MUTEX_INITIALIZER; static struct { uint32_t hash; uint32_t count; } mav_log_seen[MAV_MAX_LOGS]; @@ -678,6 +691,24 @@ struct mav_stream int enabled, eos, draining, discontinuity; int compressed; /* hands out the demuxer's packets (mav_enable_compressed) */ unsigned int skipped; /* compressed video: delta frames dropped after a seek */ + + /* ---- video decode-ahead (mav_ahead_main), all under the parser lock ---- */ + struct mav_parser *parser; + struct mav_ahead_slot + { + uint8_t *buf; + size_t cap; + struct mav_buffer cur; + } ahead[MAV_AHEAD_SLOTS]; + unsigned int ready[MAV_AHEAD_SLOTS]; /* slots holding pictures, oldest first */ + unsigned int ready_count; + int out_slot; /* the slot get_buffer handed out, -1 = none */ + int ahead_on; /* a worker decodes this stream's pictures */ + int ahead_failed; /* it could not be started: decoded on demand */ + int ahead_eos; /* the worker has no more pictures */ + int ahead_stop; /* the worker leaves */ + int busy; /* the worker decodes or converts without the lock */ + pthread_t ahead_thread; int64_t next_pts; /* 100 ns */ int64_t seek_target; /* 100 ns, -1 = none */ unsigned int decode_errors, errors_logged; @@ -724,6 +755,11 @@ struct mav_parser unsigned int bp_waiters; /* readers inside mav_wait_drain */ unsigned int generation; /* bumped by seek: a waiter re-checks everything */ int closing; /* disconnect: waiters leave, then the streams go */ + + /* ---- decode-ahead (lock) ---- */ + pthread_cond_t ahead_cond; /* a picture is ready, a slot is free, a worker is idle, or closing */ + unsigned int ahead_hold; /* threads that wait for the workers to stop between pictures */ + unsigned int ahead_waiters; /* get_buffer callers waiting for a picture */ }; /*********************************************************************** @@ -866,6 +902,7 @@ static struct mav_parser *mav_create( int output_compressed ) pthread_cond_init( &p->done_cond, NULL ); pthread_mutex_init( &p->lock, NULL ); pthread_cond_init( &p->drain_cond, NULL ); + pthread_cond_init( &p->ahead_cond, NULL ); p->output_compressed = !!output_compressed; p->stop = -1; return p; @@ -892,9 +929,81 @@ static void mav_reorder_clear( struct mav_stream *s ) s->reorder_count = 0; } +/* ---- decode-ahead: the parts the rest of the parser needs ---- */ + +/* A worker produces this stream's pictures; get_buffer hands out its slots. */ +static int mav_ahead_mode( const struct mav_stream *s ) +{ + return s->ahead_on && !s->compressed; +} + +/* The pictures the worker kept, and the one handed out, are dropped (a seek, + * a new format, a disable). */ +static void mav_ahead_reset( struct mav_stream *s ) +{ + s->ready_count = 0; + s->out_slot = -1; + s->ahead_eos = 0; +} + +/* The caller (holding the lock) owns every stream's decoder state once this + * returns: no worker is decoding or converting, and none starts a picture + * until mav_ahead_resume. A worker finishes the picture it is on first. */ +static void mav_ahead_quiesce( struct mav_parser *p ) +{ + unsigned int i; + int busy; + + p->ahead_hold++; + for (;;) + { + for (busy = 0, i = 0; i < p->stream_count; i++) busy |= p->streams[i]->busy; + if (!busy) break; + pthread_cond_wait( &p->ahead_cond, &p->lock ); + } +} + +static void mav_ahead_resume( struct mav_parser *p ) +{ + p->ahead_hold--; + pthread_cond_broadcast( &p->ahead_cond ); +} + +/* Disconnect: every worker leaves and is joined, and every get_buffer caller + * waiting for a picture has left, before the streams are freed. Called with + * the lock and closing set; the lock is dropped while joining. */ +static void mav_ahead_stop_all( struct mav_parser *p ) +{ + unsigned int i; + + while (p->ahead_waiters) + { + pthread_cond_broadcast( &p->ahead_cond ); + pthread_cond_wait( &p->drain_cond, &p->lock ); + } + for (i = 0; i < p->stream_count; i++) + { + struct mav_stream *s = p->streams[i]; + pthread_t thread; + + if (!s->ahead_on) continue; + s->ahead_stop = 1; + thread = s->ahead_thread; + pthread_cond_broadcast( &p->ahead_cond ); + pthread_cond_broadcast( &p->drain_cond ); + pthread_mutex_unlock( &p->lock ); + pthread_join( thread, NULL ); + pthread_mutex_lock( &p->lock ); + s->ahead_on = 0; + } +} + static void mav_stream_free( struct mav_stream *s ) { + unsigned int i; + if (!s) return; + for (i = 0; i < MAV_AHEAD_SLOTS; i++) free( s->ahead[i].buf ); mav_reorder_clear( s ); free( s->reorder ); if (s->vdec && s->vbackend) s->vbackend->close( s->vdec ); @@ -945,7 +1054,9 @@ static void mav_disconnect( struct mav_parser *p ) * under the lock, before this thread gets the lock back. */ p->closing = 1; pthread_cond_broadcast( &p->drain_cond ); + pthread_cond_broadcast( &p->ahead_cond ); while (p->bp_waiters) pthread_cond_wait( &p->drain_cond, &p->lock ); + mav_ahead_stop_all( p ); mav_teardown( p ); p->closing = 0; pthread_mutex_unlock( &p->lock ); @@ -955,6 +1066,7 @@ static void mav_destroy( struct mav_parser *p ) { if (!p) return; mav_disconnect( p ); + pthread_cond_destroy( &p->ahead_cond ); pthread_cond_destroy( &p->drain_cond ); pthread_mutex_destroy( &p->lock ); pthread_cond_destroy( &p->done_cond ); @@ -1179,6 +1291,8 @@ static struct mav_stream *mav_stream_new( struct mav_parser *p, AVStream *st, en s->origin = p->is_mov || p->is_asf ? 0 : (st->start_time != AV_NOPTS_VALUE ? st->start_time : 0); s->last_dts = s->last_vpts = INT64_MIN; s->seek_target = -1; + s->parser = p; + s->out_slot = -1; if (!(s->pkt = av_packet_alloc())) { free( s ); @@ -1679,14 +1793,21 @@ static int mav_enable_video( struct mav_parser *p, unsigned int stream, const st * mav_video_layout knows. The stream stays disabled. */ s->enabled = 0; s->has_buffer = 0; + mav_ahead_reset( s ); status = MAV_E_PARAM; } else { - if (out->fmt != s->vout.fmt || out->height != s->vout.height || s->compressed) s->has_buffer = 0; + mav_ahead_quiesce( p ); + if (out->fmt != s->vout.fmt || out->height != s->vout.height || s->compressed) + { + s->has_buffer = 0; + mav_ahead_reset( s ); + } s->vout = *out; s->compressed = 0; s->enabled = 1; + mav_ahead_resume( p ); } pthread_mutex_unlock( &p->lock ); return status; @@ -1716,6 +1837,7 @@ static int mav_enable_compressed( struct mav_parser *p, unsigned int stream ) /* as a refused decoded format: the stream stays disabled */ s->enabled = 0; s->has_buffer = 0; + mav_ahead_reset( s ); status = MAV_E_PARAM; } else @@ -1723,10 +1845,13 @@ static int mav_enable_compressed( struct mav_parser *p, unsigned int stream ) if (!s->compressed) { /* the held buffer, and what the decoder holds, were decoded output */ + mav_ahead_quiesce( p ); s->has_buffer = 0; + mav_ahead_reset( s ); if (s->pkt_pending) av_packet_unref( s->pkt ); s->pkt_pending = 0; mav_reorder_clear( s ); + mav_ahead_resume( p ); } s->compressed = 1; s->enabled = 1; @@ -1744,9 +1869,11 @@ static void mav_disable( struct mav_parser *p, unsigned int stream ) { s->enabled = 0; s->has_buffer = 0; + mav_ahead_reset( s ); /* its queued packets will not be read */ mav_queue_clear( s ); if (p->bp_waiters) pthread_cond_broadcast( &p->drain_cond ); + pthread_cond_broadcast( &p->ahead_cond ); } pthread_mutex_unlock( &p->lock ); } @@ -1893,9 +2020,12 @@ static int mav_next_packet( struct mav_parser *p, struct mav_stream *s, AVPacket mav_queue_push( owner, copy ); /* Only for an owner another thread reads: one thread serving both * streams (the earliest-buffer mode, or a caller that alternates) - * would wait for itself. */ + * would wait for itself. A decode-ahead worker reads for its + * stream's reader, so an owner that thread reads counts as its own: + * that thread may be waiting for the worker's picture. */ if (mav_queue_over( owner, 1, 1 ) && !owner->unread - && !(owner->has_reader && pthread_equal( owner->reader, pthread_self() ))) + && !(owner->has_reader && (pthread_equal( owner->reader, pthread_self() ) + || (s->has_reader && pthread_equal( owner->reader, s->reader ))))) mav_wait_drain( p, s, owner ); } } @@ -2392,6 +2522,28 @@ static void mav_convert_picture( const struct mav_video_output *vout, int bt709, #undef DST_ROW } +/* The worker decodes and converts without the parser lock, so a request for + * another stream (audio, on the same Media Foundation work queue thread) is + * not held up behind a picture; anyone else keeps the lock. Nothing but the + * worker touches this stream's decoder, reorder queue and s->buf meanwhile: + * whoever would (seek, a new format, disable, disconnect) waits in + * mav_ahead_quiesce. */ +static int mav_heavy_begin( struct mav_parser *p, struct mav_stream *s ) +{ + if (!s->ahead_on || !pthread_equal( s->ahead_thread, pthread_self() )) return 0; + s->busy = 1; + pthread_mutex_unlock( &p->lock ); + return 1; +} + +static void mav_heavy_end( struct mav_parser *p, struct mav_stream *s, int unlocked ) +{ + if (!unlocked) return; + pthread_mutex_lock( &p->lock ); + s->busy = 0; + pthread_cond_broadcast( &p->ahead_cond ); +} + /* One picture out of the reorder queue, into s->buf. Returns 1 if it is * the next buffer, 0 if it was dropped (before the seek target, past the * stop, or unmappable). */ @@ -2401,6 +2553,7 @@ static int mav_video_emit( struct mav_parser *p, struct mav_stream *s, struct ma struct mav_layout l; int64_t pts = mav_to_100ns( s, f->pts ), dur; size_t size; + int unlocked, mapped; dur = f->duration != INT64_MIN && f->duration > 0 ? av_rescale_q( f->duration, s->time_base, (AVRational){ 1, 10000000 } ) : s->frame_duration; @@ -2428,9 +2581,16 @@ static int mav_video_emit( struct mav_parser *p, struct mav_stream *s, struct ma mav_log( "stream %u: cannot hold a %zu-byte picture; ending the stream", s->number, size ); return 0; } - if (s->vbackend->map( f->handle, &planes )) + unlocked = mav_heavy_begin( p, s ); + if ((mapped = !s->vbackend->map( f->handle, &planes ))) + { + mav_convert_picture( &s->vout, s->bt709, &planes, s->buf, &l ); + s->vbackend->unmap( f->handle ); + } + s->vbackend->release( f->handle ); + mav_heavy_end( p, s, unlocked ); + if (!mapped) { - s->vbackend->release( f->handle ); if (s->errors_logged < 3) { s->errors_logged++; @@ -2439,9 +2599,6 @@ static int mav_video_emit( struct mav_parser *p, struct mav_stream *s, struct ma s->discontinuity = 1; return 0; } - mav_convert_picture( &s->vout, s->bt709, &planes, s->buf, &l ); - s->vbackend->unmap( f->handle ); - s->vbackend->release( f->handle ); s->next_pts = pts + dur; s->cur.pts = pts > 0 ? (uint64_t)pts : 0; @@ -2483,14 +2640,23 @@ static int mav_video_next( struct mav_parser *p, struct mav_stream *s ) if (!mav_next_packet( p, s, s->pkt )) { /* libavcodec holds its last pictures until it is drained */ - if (s->vbackend == &mav_lavc_video && !p->closing) mav_lavc_drain( s->vdec, mav_vframe_emit_cb, s ); + if (s->vbackend == &mav_lavc_video && !p->closing) + { + int unlocked = mav_heavy_begin( p, s ); + mav_lavc_drain( s->vdec, mav_vframe_emit_cb, s ); + mav_heavy_end( p, s, unlocked ); + } s->draining = 1; continue; } - err = s->vbackend->decode( s->vdec, s->pkt->data, s->pkt->size, - s->pkt->pts != AV_NOPTS_VALUE ? s->pkt->pts : INT64_MIN, - s->pkt->duration > 0 ? s->pkt->duration : INT64_MIN, - !!(s->pkt->flags & AV_PKT_FLAG_KEY), mav_vframe_emit_cb, s ); + { + int unlocked = mav_heavy_begin( p, s ); + err = s->vbackend->decode( s->vdec, s->pkt->data, s->pkt->size, + s->pkt->pts != AV_NOPTS_VALUE ? s->pkt->pts : INT64_MIN, + s->pkt->duration > 0 ? s->pkt->duration : INT64_MIN, + !!(s->pkt->flags & AV_PKT_FLAG_KEY), mav_vframe_emit_cb, s ); + mav_heavy_end( p, s, unlocked ); + } s->last_dts = s->pkt->dts != AV_NOPTS_VALUE ? s->pkt->dts : INT64_MIN; av_packet_unref( s->pkt ); if (err < 0) @@ -2507,6 +2673,139 @@ static int mav_video_next( struct mav_parser *p, struct mav_stream *s ) } } +/*********************************************************************** + * video decode-ahead + * + * Wine's media source asks for every stream's samples on one work-queue + * thread (a standard work queue has one thread), and so does the WM reader + * reading the earliest buffer. Decoded on demand, each picture of a 1080p + * WMV (software decode and RGB conversion, about 20 ms) held up the audio + * request behind it, and the audio renderer ran short every few seconds + * (Senren Banka's movie). GStreamer decodes in streaming threads of its own; + * here each decoded video stream gets a worker, started at its first request, + * that keeps up to MAV_AHEAD_SLOTS - 1 pictures ready. It demuxes under the + * parser lock like any reader and decodes and converts without it + * (mav_heavy_begin); a request pops a ready picture. MADEIRA_WG_VIDEO_AHEAD=0 + * decodes on demand again. + */ +static int mav_ahead_free_slot( const struct mav_stream *s ) +{ + unsigned int i, j; + + for (i = 0; i < MAV_AHEAD_SLOTS; i++) + { + int used = (int)i == s->out_slot; + for (j = 0; j < s->ready_count && !used; j++) used = s->ready[j] == i; + if (!used) return i; + } + return -1; +} + +static void *mav_ahead_main( void *arg ) +{ + struct mav_stream *s = arg; + struct mav_parser *p = s->parser; + + pthread_mutex_lock( &p->lock ); + for (;;) + { + unsigned int generation; + int status, slot; + + while (!p->closing && !s->ahead_stop + && (p->ahead_hold || !s->enabled || s->compressed || s->ahead_eos || mav_ahead_free_slot( s ) < 0)) + pthread_cond_wait( &p->ahead_cond, &p->lock ); + if (p->closing || s->ahead_stop) break; + + generation = p->generation; + s->has_buffer = 0; + status = mav_video_next( p, s ); + if (p->closing || s->ahead_stop) break; + if (generation != p->generation || !s->enabled || s->compressed) + { + /* a seek, a new format or a disable came while it waited for a + * queue to drain: what it made is not wanted */ + s->has_buffer = 0; + continue; + } + if (status == MAV_OK && s->has_buffer && (slot = mav_ahead_free_slot( s )) >= 0) + { + struct mav_ahead_slot *a = &s->ahead[slot]; + uint8_t *buf = a->buf; + size_t cap = a->cap; + + /* the picture changes hands; its slot's old buffer is the next one made */ + a->buf = s->buf; + a->cap = s->buf_cap; + a->cur = s->cur; + s->buf = buf; + s->buf_cap = cap; + s->ready[s->ready_count++] = slot; + } + else if (status != MAV_OK) + s->ahead_eos = 1; + s->has_buffer = 0; + pthread_cond_broadcast( &p->ahead_cond ); + } + pthread_mutex_unlock( &p->lock ); + return NULL; +} + +/* Called by the first request, with the lock. A worker that cannot be + * started leaves the stream decoded on demand. */ +static void mav_ahead_start( struct mav_parser *p, struct mav_stream *s ) +{ + pthread_attr_t attr; + int err; + + pthread_attr_init( &attr ); + pthread_attr_setstacksize( &attr, 1024 * 1024 ); + s->ahead_stop = 0; + s->ahead_eos = 0; + s->ready_count = 0; + s->out_slot = -1; + /* the worker waits for this lock, so ahead_thread is set before it runs */ + if ((err = pthread_create( &s->ahead_thread, &attr, mav_ahead_main, s ))) + { + s->ahead_failed = 1; + mav_log( "stream %u: no decode-ahead thread (%d); decoding on demand", s->number, err ); + } + else + { + s->ahead_on = 1; + mav_log( "stream %u: decoding ahead on a thread of its own (%u pictures)", s->number, + MAV_AHEAD_SLOTS - 1 ); + } + pthread_attr_destroy( &attr ); +} + +static int mav_ahead_next( struct mav_parser *p, struct mav_stream *s ) +{ + if (s->out_slot >= 0) + { + s->cur = s->ahead[s->out_slot].cur; + return MAV_OK; + } + for (;;) + { + if (p->closing || !s->enabled || s->compressed) return MAV_NO_BUFFER; + if (s->ready_count) + { + s->out_slot = s->ready[0]; + memmove( s->ready, s->ready + 1, (s->ready_count - 1) * sizeof(*s->ready) ); + s->ready_count--; + s->cur = s->ahead[s->out_slot].cur; + pthread_cond_broadcast( &p->ahead_cond ); + return MAV_OK; + } + if (s->ahead_eos || !s->ahead_on) return MAV_NO_BUFFER; + p->ahead_waiters++; + pthread_cond_wait( &p->ahead_cond, &p->lock ); + p->ahead_waiters--; + if (p->closing) pthread_cond_broadcast( &p->drain_cond ); /* mav_ahead_stop_all waits for it */ + } +} + /*********************************************************************** * compressed */ @@ -2587,11 +2886,28 @@ static int mav_compressed_next( struct mav_parser *p, struct mav_stream *s ) static int mav_stream_next( struct mav_parser *p, struct mav_stream *s ) { if (!s->enabled) return MAV_NO_BUFFER; + if (s->compressed) return s->has_buffer ? MAV_OK : mav_compressed_next( p, s ); + if (s->type == MAV_STREAM_VIDEO && mav_video_ahead && !s->ahead_on && !s->ahead_failed && !s->has_buffer) + mav_ahead_start( p, s ); + if (mav_ahead_mode( s )) return mav_ahead_next( p, s ); if (s->has_buffer) return MAV_OK; - if (s->compressed) return mav_compressed_next( p, s ); return s->type == MAV_STREAM_VIDEO ? mav_video_next( p, s ) : mav_audio_next( p, s ); } +/* The buffer get_buffer handed out is no longer the caller's. */ +static void mav_drop_held( struct mav_parser *p, struct mav_stream *s ) +{ + if (mav_ahead_mode( s )) + { + if (s->out_slot >= 0) + { + s->out_slot = -1; + pthread_cond_broadcast( &p->ahead_cond ); + } + } + else s->has_buffer = 0; +} + static int mav_get_buffer( struct mav_parser *p, int stream, struct mav_buffer *buffer ) { struct mav_stream *s = NULL; @@ -2612,7 +2928,7 @@ static int mav_get_buffer( struct mav_parser *p, int stream, struct mav_buffer * /* disabled while this reader slept in mav_wait_drain */ if (status == MAV_OK && !s->enabled) { - s->has_buffer = 0; + mav_drop_held( p, s ); status = MAV_NO_BUFFER; } } @@ -2665,12 +2981,18 @@ static int mav_copy_buffer( struct mav_parser *p, unsigned int stream, void *dst int status = MAV_OK; pthread_mutex_lock( &p->lock ); - if (!(s = mav_get_stream( p, stream )) || !s->has_buffer) + if (!(s = mav_get_stream( p, stream )) || (mav_ahead_mode( s ) ? s->out_slot < 0 : !s->has_buffer)) status = MAV_E_STATE; - else if (offset > s->cur.size || size > s->cur.size - offset || (size && !dst)) - status = MAV_E_PARAM; else - memcpy( dst, s->buf + offset, size ); + { + const struct mav_buffer *cur = mav_ahead_mode( s ) ? &s->ahead[s->out_slot].cur : &s->cur; + const uint8_t *buf = mav_ahead_mode( s ) ? s->ahead[s->out_slot].buf : s->buf; + + if (offset > cur->size || size > cur->size - offset || (size && !dst)) + status = MAV_E_PARAM; + else + memcpy( dst, buf + offset, size ); + } pthread_mutex_unlock( &p->lock ); return status; } @@ -2680,7 +3002,7 @@ static void mav_release_buffer( struct mav_parser *p, unsigned int stream ) struct mav_stream *s; pthread_mutex_lock( &p->lock ); - if ((s = mav_get_stream( p, stream ))) s->has_buffer = 0; + if ((s = mav_get_stream( p, stream ))) mav_drop_held( p, s ); pthread_mutex_unlock( &p->lock ); } @@ -2700,6 +3022,8 @@ static int mav_seek( struct mav_parser *p, unsigned int stream, int set_start, u pthread_mutex_unlock( &p->lock ); return MAV_E_STATE; } + /* the decoders, the demuxer and the decode-ahead pictures are this thread's until the end */ + mav_ahead_quiesce( p ); if (set_stop) { /* wg_parser.c: a stop at the duration means "no stop" */ @@ -2707,6 +3031,17 @@ static int mav_seek( struct mav_parser *p, unsigned int stream, int set_start, u p->stop = -1; else p->stop = stop > INT64_MAX ? -1 : (int64_t)stop; + /* pictures decoded ahead past a new stop are not handed out */ + for (i = 0; i < p->stream_count && p->stop >= 0; i++) + { + struct mav_stream *c = p->streams[i]; + unsigned int j, kept = 0; + + for (j = 0; j < c->ready_count; j++) + if ((int64_t)c->ahead[c->ready[j]].cur.pts < p->stop) c->ready[kept++] = c->ready[j]; + if (kept < c->ready_count) c->ahead_eos = 1; + c->ready_count = kept; + } } if (set_start) { @@ -2749,6 +3084,7 @@ static int mav_seek( struct mav_parser *p, unsigned int stream, int set_start, u mav_queue_clear( c ); c->apts_count = 0; c->has_buffer = 0; + mav_ahead_reset( c ); c->eos = c->draining = 0; c->decode_errors = 0; c->discontinuity = 1; @@ -2761,6 +3097,7 @@ static int mav_seek( struct mav_parser *p, unsigned int stream, int set_start, u if (p->bp_waiters) pthread_cond_broadcast( &p->drain_cond ); } } + mav_ahead_resume( p ); pthread_mutex_unlock( &p->lock ); return status; } diff --git a/build/ntdll-unix/winegstreamer_unixlib_ios.c b/build/ntdll-unix/winegstreamer_unixlib_ios.c index 95030e69c0..c9ba395f6e 100644 --- a/build/ntdll-unix/winegstreamer_unixlib_ios.c +++ b/build/ntdll-unix/winegstreamer_unixlib_ios.c @@ -3822,6 +3822,15 @@ static BOOL wg_video_switch_on(void) return !(v && v[0] == '0' && !v[1]); } +/* Each decoded video stream decodes ahead on a thread of its own, so a request + * for another stream on the same thread is not held up behind a picture + * (mav_ahead_main). 0 decodes on the requesting thread, as before. */ +static BOOL wg_video_ahead_switch_on(void) +{ + const char *v = getenv( "MADEIRA_WG_VIDEO_AHEAD" ); + return !(v && v[0] == '0' && !v[1]); +} + /* The WM reader's compressed samples of an ASF's WMV / WMA streams, for an * application's own decoder (KiriKiri's movie plugin and the decoder DMOs). * 0 refuses them as before: the reader then keeps its decoded streams. */ @@ -3859,6 +3868,9 @@ static void wgp_configure(void) mav_allow_compressed_asf( wg_compressed_switch_on() ); if (!wg_compressed_switch_on()) mav_log( "compressed ASF output disabled by MADEIRA_WG_COMPRESSED=0" ); + mav_allow_video_ahead( wg_video_ahead_switch_on() ); + if (!wg_video_ahead_switch_on()) + mav_log( "video decode-ahead disabled by MADEIRA_WG_VIDEO_AHEAD=0: video decodes on the requesting thread" ); #ifdef __APPLE__ mav_configure( video, &mav_apple_video_backend, &mav_apple_audio_backend, native ); diff --git a/build/tools/gen-config-catalog.py b/build/tools/gen-config-catalog.py index 7cbc1c0c9d..8f1d21fed5 100644 --- a/build/tools/gen-config-catalog.py +++ b/build/tools/gen-config-catalog.py @@ -589,6 +589,9 @@ "created. By default they decode WMV1/2/3, WMVA and WVC1 with libavcodec. WMA is unaffected."}, "env.MADEIRA_WG_VIDEO": {"title": "Media: MP4 video (32-bit programs)", "note": "0 limits the media parser to MP3/WAV; by default MP4 with H.264/HEVC video decodes through VideoToolbox."}, + "env.MADEIRA_WG_VIDEO_AHEAD": {"title": "Media: decode video ahead (32-bit programs)", + "note": "0 decodes a movie's video on the thread that asks for it, as before; by default each video stream " + "decodes ahead on a thread of its own, so the audio is not held up behind a picture."}, "env.MADEIRA_WG_RESAMPLER": {"title": "Media: audio resampler", "note": "0 refuses the resampler transform again; by default Media Foundation converts a movie's audio to the " "device mix format with libswresample."}, diff --git a/docs/MEDIA.md b/docs/MEDIA.md index 6d5cfa259e..8e4527c081 100644 --- a/docs/MEDIA.md +++ b/docs/MEDIA.md @@ -149,9 +149,9 @@ now libswresample: It logs one `[resampler] created ...` line per transform. `MADEIRA_WG_RESAMPLER=0` refuses it again. -**One demuxer, several readers: back-pressure.** Each stream is read on its -own thread by quartz and Media Foundation; a packet read for another stream -is queued for it. A stream whose reader falls behind (a video decoded slower +**One demuxer, several readers: back-pressure.** Quartz reads each stream on +its own thread (Media Foundation's source does not; see decode-ahead below); a +packet read for another stream is queued for it. A stream whose reader falls behind (a video decoded slower than real time) used to lose packets once its queue passed 16,384 packets or 64 MB, which breaks every picture up to the next keyframe. Now, once a queue passes 1,024 packets or 16 MB while another thread reads that stream, the @@ -162,7 +162,25 @@ past the old hard limits, as before) until it is read again; one thread reading both streams (the WM reader's earliest-buffer mode) never waits for itself; a seek, a disable or disconnect wakes a waiting reader. -The PE half of winegstreamer is upstream's and unchanged. Wine's configure +**Decode-ahead.** Wine's media source asks for every stream's samples on one +work-queue thread (a standard work queue has one thread), and so does the WM +reader reading the earliest buffer. Decoded on demand, each picture held that +thread. Senren Banka's 1080p WMV needs about 20 ms a picture in software, so +the audio request behind it was late, and the audio renderer ran short for 6 +to 17% of each 10 s (`[ios_audio] ... client wrote 8.33 s of audio in 10.01 s`). +GStreamer decodes in streaming threads of its own. Here each decoded video +stream gets a worker at its first request: +- it keeps up to three pictures ready, and a request pops one; +- it demuxes under the parser lock like any reader; +- it decodes and converts without that lock, so the audio request is + answered meanwhile; +- a seek, a new format or a disconnect waits for the picture the worker is + on, and it starts no new one until they are done. + +Each such stream logs `decoding ahead on a thread of its own` once. +`MADEIRA_WG_VIDEO_AHEAD=0` decodes on the requesting thread again. + +The PE half of winegstreamer is upstream's but for `wm_reader.c` (above). Wine's configure disables the module when GStreamer is missing, so a PE build tree has to be configured with `--enable-winegstreamer` (`build/wine-pe/build-ntdll.sh` does this for the arm64ec tree) and only the PE target is built. A 32-bit @@ -182,6 +200,7 @@ Environment variables (`env.NAME = value` in `madeira.cfg`): | `MADEIRA_WG_WMV_TRANSFORM` | on | `0`: every video `wg_transform` is refused at create again, so the WMVideo Decoder DMO/MFT cannot be created, as before. Read once per process. WMA is unaffected. | | `MADEIRA_WG_RESAMPLER` | on | `0`: the resampler transform is refused at create, as before. | | `MADEIRA_WG_COMPRESSED` | on | `0`: a compressed-output parser refuses an ASF, as before: the WM reader's compressed samples are not available (see above). | +| `MADEIRA_WG_VIDEO_AHEAD` | on | `0`: video is decoded on the thread that asks for it, as before; a Media Foundation movie's audio then waits behind each picture (see above). | | `MADEIRA_WG_VIDEO_FORMAT` | `rgb32` | Native format a video stream reports: `nv12`, `i420`, `yv12`, `yuy2`, `rgb32`, `argb32` or `abgr32` (see above for why the default is `rgb32`). | | `MADEIRA_WMA_SEARCH` | on | `0`: keep the WMA v1/v2 decoder at the bit rate and flags it opened with; no search over other candidates when a bit-reservoir stream fails. A packet that fails is concealed with silence of its length and the next one is decoded as usual. (An xWMA stream still opens at the rate libavformat's xWMA table normalises to.) | | `MADEIRA_WMA_DUMP` | off | Set: write each WMA decoder's input to `wma-dump-.bin` in the Documents folder, for reproducing a decode failure on a host. | @@ -198,10 +217,16 @@ rate-limited per process (`MADEIRA_DIAG=1` lifts the `[wma]`, `[wmv]` and tables, wow64 thunks, kill switches, FFmpeg configuration and app link; then builds a host FFmpeg from the same tarball and runs the parser core under ASan/UBSan against MP3, MPEG layer II, WAV and synthetic MP4 (stub video and - AAC backends); then, built with small queue limits, the back-pressure cases - (a slow video reader loses nothing, while the same build without - back-pressure drops pictures; an unread stream holds the other reader once; - one thread reading both never waits; disconnect wakes a waiting reader). + AAC backends), every picture format pixel by pixel; then, built with small + queue limits, the back-pressure cases (a slow video reader loses nothing, + while the same build without back-pressure drops pictures; an unread stream + holds the other reader once; one thread reading both never waits; disconnect + wakes a waiting reader). Decode-ahead: with a stub decoder that takes 20 ms + a picture and one thread asking for both streams at 30 fps (the media + source's way), a video request takes 0.0 ms instead of 21. Every picture + still comes in order, the audio has no gaps, a seek lands exactly, and a + disconnect mid-decode is clean. The threaded cases run again under + ThreadSanitizer. - `tests/host/check-wg-parser-asf.py` (Linux): builds a host FFmpeg from the same tarball with the port's demuxers and decoders and test-only WMV/WMA encoders and the asf muxer, synthesises WMV7, WMV8 and MS-MPEG4 v3 files @@ -211,13 +236,16 @@ rate-limited per process (`MADEIRA_DIAG=1` lifts the `[wma]`, `[wmv]` and format it offers after a keyframe seek; a WMV3 stream of garbage; and, with small queue limits, the back-pressure cases (a slow video reader loses nothing, while the same build without back-pressure drops pictures; an - unread stream; one thread reading both; disconnect while a reader waits). + unread stream; one thread reading both, and the worker decoding ahead for + it; disconnect while a reader waits). Compressed output: every packet of WMV7, WMV8, the WMV3 garbage stream and WMA2 against an independent demux of the same file (bytes, keyframe flags, timestamps); compressed video with decoded audio; a seek starting at a keyframe; back to decoded pictures, bit-exact; MS-MPEG4 refused compressed; `MADEIRA_WG_COMPRESSED=0`. Also source checks on Wine's reader (per-stream - compressed reading, no `free_streams` in a failed reinit). + compressed reading, no `free_streams` in a failed reinit). With video + decoded ahead (the default), every case above runs again under + ThreadSanitizer, the back-pressure ones included. WMV9/VC-1 streams themselves are not covered: FFmpeg cannot encode them. - `tests/host/check-wma-decoder.py` (Linux or macOS, needs a configured Wine tree for the generated headers): compiles the production diff --git a/tests/host/check-wg-parser-asf.py b/tests/host/check-wg-parser-asf.py index feb29cf5f2..86b74e7143 100644 --- a/tests/host/check-wg-parser-asf.py +++ b/tests/host/check-wg-parser-asf.py @@ -125,7 +125,7 @@ static void *read_thread( void *arg ) { struct source *s = arg; - while (s->running) + while (__atomic_load_n( &s->running, __ATOMIC_ACQUIRE )) { uint64_t offset; uint32_t size; if (mav_get_next_read_offset( s->p, &offset, &size )) { usleep( 200 ); continue; } @@ -140,7 +140,7 @@ memset( s, 0, sizeof(*s) ); s->data = data; s->size = size; s->p = p; s->running = 1; pthread_create( &s->thread, NULL, read_thread, s ); } -static void src_stop( struct source *s ) { mav_disconnect( s->p ); s->running = 0; pthread_join( s->thread, NULL ); } +static void src_stop( struct source *s ) { mav_disconnect( s->p ); __atomic_store_n( &s->running, 0, __ATOMIC_RELEASE ); pthread_join( s->thread, NULL ); } /* ---- inputs: an ASF made by libavformat's asf muxer in memory ---- */ struct membuf { uint8_t *data; size_t size, cap, pos; }; @@ -575,6 +575,23 @@ } src_stop( &s ); mav_destroy( p ); + /* 5. one thread that read the audio once, then only the video (decoded ahead): the worker + * reads for that thread, so it never waits for the audio that thread would drain */ + p = mav_create( 0 ); src_start( &s, p, asf, size ); + CHECK( mav_connect( p, size ) == MAV_OK, "connect" ); + { + struct mav_buffer b; int n = 0; + CHECK( mav_get_buffer( p, 1, &b ) == MAV_OK, "one audio buffer" ); + mav_release_buffer( p, 1 ); + clock_gettime( CLOCK_MONOTONIC, &t0 ); + while (mav_get_buffer( p, 0, &b ) == MAV_OK) { mav_release_buffer( p, 0 ); n++; } + clock_gettime( CLOCK_MONOTONIC, &t1 ); + CHECK( n == FRAMES && (t1.tv_sec - t0.tv_sec) * 1000 + (t1.tv_nsec - t0.tv_nsec) / 1000000 < MAV_BACKPRESSURE_WAIT_MS, + "video alone after an audio read: %d pictures, %ld ms", n, + (long)((t1.tv_sec - t0.tv_sec) * 1000 + (t1.tv_nsec - t0.tv_nsec) / 1000000) ); + } + src_stop( &s ); mav_destroy( p ); + /* 4. disconnect while a reader waits: it is woken, nothing is freed under it */ p = mav_create( 0 ); src_start( &s, p, asf, size ); CHECK( mav_connect( p, size ) == MAV_OK, "connect" ); @@ -596,8 +613,8 @@ "disconnect woke the waiting reader at once" ); mav_destroy( p ); printf( "PASS: back-pressure (soft %d packets, hard %d): a slow video reader on its own thread gets all %d pictures; " - "an unread stream holds the other reader once (%d ms) and no longer; one thread reading both never waits; " - "disconnect wakes a waiting reader\n", MAV_QUEUE_SOFT_PACKETS, MAV_QUEUE_MAX_PACKETS, FRAMES, + "an unread stream holds the other reader once (%d ms) and no longer; one thread reading both never waits, " + "nor does the worker decoding ahead for it; disconnect wakes a waiting reader\n", MAV_QUEUE_SOFT_PACKETS, MAV_QUEUE_MAX_PACKETS, FRAMES, MAV_BACKPRESSURE_WAIT_MS ); return 0; } @@ -870,5 +887,21 @@ out.stdout + out.stderr[-2000:] print("PASS: without back-pressure the same slow-video case drops packets and loses pictures (%s)" % re.search(r"slow video reader: \d+ pictures of \d+", out.stdout).group(0)) + + # ThreadSanitizer: the decode-ahead worker beside the WM reader's and the back-pressure readers + tsan_flags = [f for f in base if not f.startswith("-fsanitize") and f != "-fno-sanitize-recover=undefined"] + tsan = Path(t) / "asf-tsan" + r = subprocess.run(tsan_flags + ["-fsanitize=thread", "-o", str(tsan)] + libs, capture_output=True, text=True) + tsan_bp = Path(t) / "asf-tsan-bp" + r2 = subprocess.run(tsan_flags + small + ["-fsanitize=thread", "-o", str(tsan_bp)] + libs, capture_output=True, text=True) + if r.returncode or r2.returncode: + print("NOTOOL: no ThreadSanitizer build here") + else: + tenv = {k: v for k, v in env.items() if k != "ASAN_OPTIONS"} + tenv["TSAN_OPTIONS"] = "halt_on_error=1" + for exe_, args_ in [(tsan, []), (tsan_bp, ["bp"])]: + out = subprocess.run([str(exe_)] + args_, env=tenv, capture_output=True, text=True, timeout=900) + assert out.returncode == 0 and "WARNING: ThreadSanitizer" not in out.stderr, out.stdout + out.stderr[-6000:] + print("PASS: ThreadSanitizer clean: every ASF case above, the back-pressure ones included, with video decoded ahead") for l in lines + bp_lines: print(" " + l) diff --git a/tests/host/check-wg-parser.py b/tests/host/check-wg-parser.py index 6561ecb530..a3584a0040 100644 --- a/tests/host/check-wg-parser.py +++ b/tests/host/check-wg-parser.py @@ -160,6 +160,7 @@ def table(name): static uint8_t stub_avcc[] = { 0x01, 0x42, 0xc0, 0x1e, 0xff, 0xe1, 0x00, 0x04, 0x67, 0x42, 0xc0, 0x1e, 0x01, 0x00, 0x02, 0x68, 0xce }; static int stub_vdecodes, stub_vflushes, stub_verrors, stub_vlive, stub_vmapped; +static int stub_vdelay_us; /* a slow decoder: Senren Banka's 1080p WMV takes about 20 ms a picture */ static int ref_y( int idx, int x, int y ) { (void)x; return 16 + (idx + y) % 200; } static int ref_u( int x, int y ) { (void)y; return 64 + (x / 2) % 128; } @@ -189,6 +190,7 @@ def table(name): int x, y; stub_vdecodes++; + if (stub_vdelay_us) usleep( stub_vdelay_us ); if (size != 9 || AV_RB32( data ) != 5 || (data[4] & 0x1f) != (key ? 5 : 1)) { stub_verrors++; return -5; } if (key) d->have_ref = 1; if (!d->have_ref) { stub_verrors++; return -6; } /* a real decoder needs a keyframe after a flush */ @@ -298,7 +300,7 @@ def table(name): static void *read_thread( void *arg ) { struct source *s = arg; - while (s->running) + while (__atomic_load_n( &s->running, __ATOMIC_ACQUIRE )) { uint64_t offset; uint32_t size; if (mav_get_next_read_offset( s->p, &offset, &size )) @@ -330,7 +332,7 @@ def table(name): static void src_stop( struct source *s ) { mav_disconnect( s->p ); - s->running = 0; + __atomic_store_n( &s->running, 0, __ATOMIC_RELEASE ); pthread_join( s->thread, NULL ); } @@ -696,7 +698,7 @@ def table(name): CHECK( t1.tv_sec - t0.tv_sec < 2, "reader was not woken" ); usleep( 1000 ); } - s.running = 0; pthread_join( s.thread, NULL ); + __atomic_store_n( &s.running, 0, __ATOMIC_RELEASE ); pthread_join( s.thread, NULL ); mav_disconnect( p ); /* idempotent, like quartz after a failed connect */ mav_destroy( p ); printf( "PASS: disconnect wakes a read thread blocked in get_next_read_offset\n" ); @@ -1174,6 +1176,105 @@ def table(name): return 0; } +static double ms_since_f( const struct timespec *t0 ) +{ + struct timespec t1; + clock_gettime( CLOCK_MONOTONIC, &t1 ); + return (t1.tv_sec - t0->tv_sec) * 1e3 + (t1.tv_nsec - t0->tv_nsec) / 1e6; +} + +/* Wine's media source asks for both streams on one thread, at the movie's pace. + * With a decoder that takes 20 ms a picture, a video request decoded on + * demand holds that thread (and the audio request after it) for 20 ms; with + * decode-ahead the picture is ready. Every picture still comes, in order; + * a seek lands exactly; a disconnect while the worker decodes neither hangs + * nor frees anything under it. */ +static int test_mp4_ahead( const uint8_t *mp4, size_t size, int frames, int ahead, double *avg_ms, double *max_ms ) +{ + struct mav_parser *p; struct source s; struct mav_stream_info vi, ai; struct drained da; + double total = 0, worst = 0; int n = 0, adone = 0, measured = 0; + + mav_allow_video_ahead( ahead ); + stub_vdelay_us = 20000; + p = mav_create( 0 ); + src_start( &s, p, mp4, size ); + CHECK( mav_connect( p, size ) == MAV_OK && mav_stream_info( p, 0, &vi ) == MAV_OK && mav_stream_info( p, 1, &ai ) == MAV_OK, + "connect" ); + CHECK( mav_enable_video( p, 0, &vi.vnative ) == MAV_OK && mav_enable( p, 1, &ai.native ) == MAV_OK, "enable" ); + CHECK( mav_seek( p, 0, 1, 0, 0, 0 ) == MAV_OK, "seek 0" ); + memset( &da, 0, sizeof(da) ); + for (;;) + { + struct timespec t0, pace; struct mav_buffer b; uint8_t *pic; int r; + + clock_gettime( CLOCK_MONOTONIC, &pace ); + clock_gettime( CLOCK_MONOTONIC, &t0 ); + r = mav_get_buffer( p, 0, &b ); + if (r != MAV_OK) { CHECK( r == MAV_NO_BUFFER, "video get_buffer %d", r ); break; } + if (n >= 4) + { + double ms = ms_since_f( &t0 ); + total += ms; measured++; + if (ms > worst) worst = ms; + } + pic = malloc( b.size ); + CHECK( mav_copy_buffer( p, 0, pic, 0, b.size ) == MAV_OK, "copy picture" ); + CHECK( picture_index( pic, 0, MAV_PIX_NV12 ) == n % 200 && llabs( (long long)b.pts - n * 10000000ll / FPS ) <= 1, + "picture %d: index %d pts %llu", n, picture_index( pic, 0, MAV_PIX_NV12 ), (unsigned long long)b.pts ); + free( pic ); + mav_release_buffer( p, 0 ); + n++; + /* the audio this picture's interval needs */ + while (!adone && (!da.buffers || da.end_pts < (uint64_t)n * 10000000 / FPS)) + if (drain_one( p, 1, &da, &adone )) return 1; + while (ms_since_f( &pace ) < 1000.0 / FPS) usleep( 500 ); + } + while (!adone) if (drain_one( p, 1, &da, &adone )) return 1; + CHECK( n == frames && da.gaps == 0 && da.first_pts == 0, "%d pictures of %d, audio gaps %d", n, frames, da.gaps ); + CHECK( stub_verrors == 0, "stub decoder saw %d bad packets", stub_verrors ); + + if (ahead) + { + /* a seek: the first picture after it is the target's, decoded ahead again */ + struct mav_buffer b; uint8_t *pic; + CHECK( mav_seek( p, 0, 1, 10000000, 0, 0 ) == MAV_OK, "seek to 1 s" ); + CHECK( mav_get_buffer( p, 0, &b ) == MAV_OK && b.pts == 10000000, "picture after the seek at %llu", + (unsigned long long)b.pts ); + pic = malloc( b.size ); + CHECK( mav_copy_buffer( p, 0, pic, 0, b.size ) == MAV_OK && picture_index( pic, 0, MAV_PIX_NV12 ) == FPS, + "the target picture" ); + free( pic ); + mav_release_buffer( p, 0 ); + CHECK( mav_get_buffer( p, 0, &b ) == MAV_OK && llabs( (long long)b.pts - (FPS + 1) * 10000000ll / FPS ) <= 1, "and the next" ); + mav_release_buffer( p, 0 ); + /* disconnect while the worker is decoding */ + usleep( 5000 ); + } + src_stop( &s ); + mav_destroy( p ); + stub_vdelay_us = 0; + CHECK( stub_vmapped == 0 && stub_vlive == 0, "every picture unmapped (%d) and released (%d)", stub_vmapped, stub_vlive ); + free( da.data ); + *avg_ms = measured ? total / measured : 0; + *max_ms = worst; + mav_allow_video_ahead( 1 ); + return 0; +} + +static int test_ahead( const uint8_t *mp4, size_t size, int frames ) +{ + double on_avg, on_max, off_avg, off_max; + + if (test_mp4_ahead( mp4, size, frames, 1, &on_avg, &on_max )) return 1; + if (test_mp4_ahead( mp4, size, frames, 0, &off_avg, &off_max )) return 1; + CHECK( off_avg >= 15, "decoded on demand, a video request should take the decoder's 20 ms: %.1f ms", off_avg ); + CHECK( on_avg < 5, "decoded ahead, a video request took %.1f ms on average (on demand: %.1f ms)", on_avg, off_avg ); + printf( "PASS: decode-ahead: with a 20 ms decoder and one thread asking for both streams at %d fps, a video request " + "takes %.1f ms on average (max %.1f) instead of %.1f (max %.1f); every picture in order, the audio gap-free, " + "an exact seek, a disconnect mid-decode\n", FPS, on_avg, on_max, off_avg, off_max ); + return 0; +} + int main( int argc, char **argv ) { size_t mp2_size, wsize, mp4_size; uint8_t *mp2, *wav, *mp4; @@ -1203,6 +1304,16 @@ def table(name): av_free( mp4 ); return r || failures; } + if (argc > 1 && !strcmp( argv[1], "threads" )) + { + /* the ThreadSanitizer build: the cases where a worker decodes beside the reader */ + mp4 = make_mp4( &mp4_size, AV_CODEC_ID_H264, A_AAC, frames, seconds ); + if (!mp4 || test_mp4_basic( mp4, mp4_size, frames, seconds ) || test_mp4_formats( mp4, mp4_size ) + || test_ahead( mp4, mp4_size, frames )) + return 1; + av_free( mp4 ); + return failures ? 1 : 0; + } mp2 = make_mp2( &mp2_size, 44100, 3.0 ); if (!mp2) { printf( "FAIL: no mp2 encoder in the host build\n" ); return 1; } if (test_wav()) return 1; @@ -1216,6 +1327,7 @@ def table(name): if (test_mp4_basic( mp4, mp4_size, frames, seconds )) return 1; if (test_mp4_formats( mp4, mp4_size )) return 1; if (test_mp4_late_audio( mp4, mp4_size, seconds )) return 1; + if (test_ahead( mp4, mp4_size, frames )) return 1; if (test_mp4_refusals()) return 1; if (argc > 1) { @@ -1273,6 +1385,7 @@ def build(out, defines=()): assert any("connect container=mp4 stream=0 video codec=h264 backend=stub-video 320x240 fps=30/1 out=nv12" in l for l in lines), lines assert any("connect container=mp4 codec=aac layer=0 rate=44100 channels=2 mask=0x3 out=f32" in l and "stream=1 backend=stub-aac" in l for l in lines), lines assert any(l.endswith("stream 0: first picture delivered (nv12 320x240)") for l in lines), lines + assert any(l.endswith("stream 0: decoding ahead on a thread of its own (3 pictures)") for l in lines), lines assert any(l.endswith("stream 1: first audio buffer delivered") for l in lines), lines assert any("connect refused (mov,mp4,m4a,3gp,3g2,mj2, compressed_out=0): container disabled by MADEIRA_WG_VIDEO=0" in l for l in lines), lines assert any("connect refused (mov,mp4,m4a,3gp,3g2,mj2, compressed_out=1): compressed output requested" in l for l in lines), lines @@ -1319,3 +1432,19 @@ def build(out, defines=()): re.search(r"slow video reader: \d+ pictures of \d+", out.stdout).group(0)) for l in bp_lines: print(" " + l) + + # ThreadSanitizer: the decode-ahead worker beside the reader, its seeks and its disconnect + tsan = Path(t) / "wgp-tsan" + r = subprocess.run(["cc", "-std=gnu11", "-O1", "-g", "-Wall", "-Wno-unused-function", "-fsanitize=thread", + "-I" + str(core.parent), "-I" + str(inc), str(c), "-o", str(tsan), + str(lib / "libavformat.a"), str(lib / "libavcodec.a"), str(lib / "libswresample.a"), + str(lib / "libavutil.a"), "-lm", "-lpthread"], capture_output=True, text=True) + if r.returncode: + print("NOTOOL: no ThreadSanitizer build here (%s)" % (r.stderr.strip().splitlines() or ["?"])[-1][:120]) + else: + tenv = {k: v for k, v in env.items() if k != "ASAN_OPTIONS"} + tenv["TSAN_OPTIONS"] = "halt_on_error=1 second_deadlock_stack=1" + out = subprocess.run([str(tsan), "threads"], env=tenv, capture_output=True, text=True, timeout=600) + assert out.returncode == 0 and "WARNING: ThreadSanitizer" not in out.stderr, out.stdout + out.stderr[-6000:] + print("PASS: ThreadSanitizer clean: the interleaved readers, every picture format, and decode-ahead " + "(its seek and its disconnect mid-decode)") From 9976734812ba9c33140af2fb7bc579b6f6ecc9a2 Mon Sep 17 00:00:00 2001 From: allen Date: Sun, 22 Nov 2026 05:57:23 +0800 Subject: [PATCH 9/9] wine: the EVR's DXVA2 render targets and the copier's discard lock (Senren Banka's black movie) Senren Banka's WMV movie (krkrz's MFPlayer, Media Foundation) played its audio over a black video window, its audio running short every few seconds. Two of Wine's choices on the way to the EVR worked only on wined3d, which is lenient where native d3d9 and DXMT are not: - dxva2 (`1f0f5075e94`): CreateSurface() made every surface an offscreen plain surface. The EVR mixer's targets are the size of the video window (1920x1080 into 2360x1328), and DXMT, as native, does not StretchRect into a surface that is not a render target, so the mixer left only its black background. DXVA2_VideoProcessorRenderTarget surfaces are now lockable render targets, and a scaled blit is filtered. - mfplat (`34765056b9e`): the sample copier's ContiguousCopyFrom() locked the EVR's surface without flags, so DXMT read it back and waited for the GPU first, 9 to 12 ms per frame ("[d9-drain] ... avg-us=9300"), on the session thread that also feeds the audio. It now locks with D3DLOCK_DISCARD; a plain write-only lock keeps the contents, as native does. The wine pin moves to the head of willfaust/wine#78, `34765056b9e`, which has these two commits. tests/host/check-mf-video-render.py checks the path from source: DXMT's StretchRect rule and discard lock, the two changes, the allocators that ask for these surfaces, and the one-thread work queue that makes decode-ahead necessary. docs/MEDIA.md says so. Co-Authored-By: Claude Opus 5.5 Signed-off-by: allen --- docs/MEDIA.md | 24 ++++++++ tests/host/check-mf-video-render.py | 94 +++++++++++++++++++++++++++++ wine | 2 +- 3 files changed, 119 insertions(+), 1 deletion(-) create mode 100755 tests/host/check-mf-video-render.py diff --git a/docs/MEDIA.md b/docs/MEDIA.md index 8e4527c081..02170ef612 100644 --- a/docs/MEDIA.md +++ b/docs/MEDIA.md @@ -180,6 +180,23 @@ stream gets a worker at its first request: Each such stream logs `decoding ahead on a thread of its own` once. `MADEIRA_WG_VIDEO_AHEAD=0` decodes on the requesting thread again. +**The video renderer on DXMT.** A Media Foundation movie reaches the EVR +through Wine's sample copier and the EVR mixer, both on Direct3D 9 surfaces +that Wine's DXVA2 creates. Two of Wine's choices only worked on wined3d, which +is lenient where native d3d9 and DXMT are not. Both are fixed in the wine +submodule: +- **A black picture.** `CreateSurface` made every surface an offscreen plain + surface. The mixer's targets are the size of the video window (Senren: + 1920x1080 into 2360x1328), and `StretchRect` does not stretch into a + surface that is not a render target, so the mixer left only its black + background. `DXVA2_VideoProcessorRenderTarget` surfaces are now lockable + render targets, and a scaled blit is filtered (`D3DTEXF_LINEAR`). +- **A GPU wait per frame.** The copier's `ContiguousCopyFrom` locked its + target without flags, so DXMT read the surface back first and waited for + the GPU: 9 to 12 ms per frame (`[d9-drain] ... avg-us=9300`), on the + session thread that also feeds the audio. It now locks with + `D3DLOCK_DISCARD`, since it overwrites every byte. + The PE half of winegstreamer is upstream's but for `wm_reader.c` (above). Wine's configure disables the module when GStreamer is missing, so a PE build tree has to be configured with `--enable-winegstreamer` (`build/wine-pe/build-ntdll.sh` does @@ -247,6 +264,13 @@ rate-limited per process (`MADEIRA_DIAG=1` lifts the `[wma]`, `[wmv]` and decoded ahead (the default), every case above runs again under ThreadSanitizer, the back-pressure ones included. WMV9/VC-1 streams themselves are not covered: FFmpeg cannot encode them. +- `tests/host/check-mf-video-render.py`: source checks on the path a Media + Foundation movie takes to the screen: + - DXMT's StretchRect rule the DXVA2 fix answers, and its discard lock; + - Wine's DXVA2 render targets and filtered scaling; + - mfplat's discard copy; + - the allocators that ask for `DXVA2_VideoProcessorRenderTarget`; + - the one-thread work queue that makes decode-ahead necessary. - `tests/host/check-wma-decoder.py` (Linux or macOS, needs a configured Wine tree for the generated headers): compiles the production `winegstreamer_unixlib_ios.c` under ASan/UBSan against a host FFmpeg built diff --git a/tests/host/check-mf-video-render.py b/tests/host/check-mf-video-render.py new file mode 100755 index 0000000000..8301da1c7c --- /dev/null +++ b/tests/host/check-mf-video-render.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +"""The path a Media Foundation movie takes to the screen on DXMT, from production source; nothing runs. + +Senren Banka's WMV movie (krkrz's MFPlayer) played its audio over a black video window, and the +audio ran short every few seconds. These are the checks that the causes stay fixed: +1. DXMT's d3d9 follows native: StretchRect does not stretch into a destination that is not a + render target, and a D3DLOCK_DISCARD lock of a DEFAULT surface skips the readback that a + plain lock waits for. +2. Wine's DXVA2 (the wine submodule) creates DXVA2_VideoProcessorRenderTarget surfaces as + lockable render targets, so the EVR mixer can stretch the picture into its window-sized + target, and filters a scaled blit. +3. The EVR's and mfplat's sample allocators are what ask for that surface type. +4. mfplat's D3D9 surface buffer overwrites a surface in ContiguousCopyFrom (the sample copier's + path) with D3DLOCK_DISCARD, and keeps the contents for a plain write-only lock. +5. Wine's media source asks for every stream on one work queue, which has one thread: the + reason our parser decodes video ahead on a worker (wg_parser_av_ios.c, MADEIRA_WG_VIDEO_AHEAD). +""" +from pathlib import Path +import re, sys + +root = Path(__file__).resolve().parents[2] +wine = root / "wine" +dxmt = root / "dxmt" +need = [wine / "dlls/dxva2/main.c", dxmt / "src/d3d9/d3d9_stretchrect.hpp"] +for n in need: + if not n.exists(): + sys.exit("SKIP-FAIL: %s is missing (submodules not checked out)" % n) + + +def function(source, start): + a = source.index(start) + b = source.index("{", a) + depth, c = 1, b + 1 + while depth: + depth += (source[c] == "{") - (source[c] == "}") + c += 1 + return source[a:c] + + +# ---- 1. DXMT ------------------------------------------------------------------ +plan = (dxmt / "src/d3d9/d3d9_stretchrect.hpp").read_text() +assert "if (extent_mismatch && !(dst.usage & D3DUSAGE_RENDERTARGET))\n return fail();" in plan, \ + "DXMT no longer refuses a stretch into a non-render-target: recheck what the DXVA2 change answers" +surface = (dxmt / "src/d3d9/d3d9_surface.cpp").read_text() +lock = function(surface, "MTLD3D9Surface::LockRect(") +assert "!(Flags & D3DLOCK_DISCARD)" in lock and "readbackSurfaceMirror" in lock, "a discard lock skips the readback" +print("PASS: DXMT refuses a stretch into a non-render-target and skips the readback for a discard lock") + +# ---- 2. DXVA2 ----------------------------------------------------------------- +dxva2 = (wine / "dlls/dxva2/main.c").read_text() +create = function(dxva2, "static HRESULT WINAPI device_manager_processor_service_CreateSurface(") +assert re.search(r"dxvaType == DXVA2_VideoProcessorRenderTarget && pool == D3DPOOL_DEFAULT\)\s*" + r"hr = IDirect3DDevice9_CreateRenderTarget\(manager->device, width, height, format,\s*" + r"D3DMULTISAMPLE_NONE, 0, TRUE,", create), "processor render targets are lockable render targets" +assert "CreateOffscreenPlainSurface" in create, "other surface types stay offscreen plain" +blit = function(dxva2, "static HRESULT WINAPI video_processor_VideoProcessBlt(") +assert "scaled ? D3DTEXF_LINEAR : D3DTEXF_POINT" in blit, "a scaled blit is filtered" +assert "IDirect3DDevice9_StretchRect(device, samples[i].SrcSurface" in blit +print("PASS: DXVA2 makes video processor render targets render targets (lockable) and filters a scaled blit") + +# ---- 3. the allocators ---------------------------------------------------------- +for f in ["dlls/evr/sample.c", "dlls/mfplat/sample.c"]: + text = (wine / f).read_text() + assert re.search(r"IDirectXVideoProcessorService_CreateSurface\([^;]*DXVA2_VideoProcessorRenderTarget", text, re.S), f +print("PASS: the EVR's and mfplat's sample allocators ask for DXVA2_VideoProcessorRenderTarget surfaces") + +# ---- 4. mfplat -------------------------------------------------------------------- +buf = (wine / "dlls/mfplat/buffer.c").read_text() +copy = function(buf, "static HRESULT WINAPI d3d9_surface_buffer_ContiguousCopyFrom(") +assert "D3DLOCK_DISCARD" in copy and "memory_2d_buffer_ContiguousCopyFrom(iface" in copy, copy[:200] +vtbl = buf[buf.index("static const IMF2DBuffer2Vtbl d3d9_surface_buffer_vtbl ="):] +vtbl = vtbl[:vtbl.index("};")] +assert "d3d9_surface_buffer_ContiguousCopyFrom," in vtbl and "memory_2d_buffer_ContiguousCopyFrom," not in vtbl +plain = function(buf, "static HRESULT d3d9_surface_buffer_lock(") +assert "IDirect3DSurface9_LockRect(buffer->d3d9_surface.surface, &buffer->d3d9_surface.rect, NULL, 0)" in plain, \ + "a plain write-only lock keeps the contents (native, per mfplat's tests)" +sample = function((wine / "dlls/mfplat/sample.c").read_text(), "static HRESULT WINAPI sample_CopyToBuffer(") +assert "IMF2DBuffer_ContiguousCopyFrom(buffer2d" in sample, "the copier's path is ContiguousCopyFrom" +print("PASS: mfplat overwrites a D3D9 surface in ContiguousCopyFrom with D3DLOCK_DISCARD; plain locks keep the contents") + +# ---- 5. why decode-ahead ------------------------------------------------------------ +source = (wine / "dlls/winegstreamer/media_source.c").read_text() +assert "MFAllocateWorkQueue(&object->async_commands_queue)" in source +invoke = function(source, "static HRESULT WINAPI source_async_commands_Invoke(") +assert "wait_on_sample(command->u.request_sample.stream" in invoke, "every stream's request goes through one queue" +queue = (wine / "dlls/rtworkq/queue.c").read_text() +assert re.search(r"max_thread = \(desc->queue_type == RTWQ_STANDARD_WORKQUEUE[^;]*\? 1 : 4;", queue), \ + "a standard work queue has one thread" +core = (root / "build/ntdll-unix/wg_parser_av_ios.c").read_text() +glue = (root / "build/ntdll-unix/winegstreamer_unixlib_ios.c").read_text() +assert "static void *mav_ahead_main( void *arg )" in core and "mav_heavy_begin( p, s )" in core +assert 'getenv( "MADEIRA_WG_VIDEO_AHEAD" )' in glue and "mav_allow_video_ahead(" in glue +print("PASS: the media source asks for every stream on one single-thread queue, and the parser decodes video ahead " + "(MADEIRA_WG_VIDEO_AHEAD)") diff --git a/wine b/wine index b0d33cbd85..34765056b9 160000 --- a/wine +++ b/wine @@ -1 +1 @@ -Subproject commit b0d33cbd85acf4339150507cac9bab137c6021d0 +Subproject commit 34765056b9eec60a8a128c44b9bef8cf5a02a411