Statistics
| Branch: | Revision:

ffmpeg / libavcodec / dv.c @ 2df6e978

History | View | Annotate | Download (43.4 KB)

1
/*
2
 * DV decoder
3
 * Copyright (c) 2002 Fabrice Bellard.
4
 * Copyright (c) 2004 Roman Shaposhnik.
5
 *
6
 * DV encoder
7
 * Copyright (c) 2003 Roman Shaposhnik.
8
 *
9
 * 50 Mbps (DVCPRO50) support
10
 * Copyright (c) 2006 Daniel Maas <dmaas@maasdigital.com>
11
 *
12
 * Many thanks to Dan Dennedy <dan@dennedy.org> for providing wealth
13
 * of DV technical info.
14
 *
15
 * This file is part of FFmpeg.
16
 *
17
 * FFmpeg is free software; you can redistribute it and/or
18
 * modify it under the terms of the GNU Lesser General Public
19
 * License as published by the Free Software Foundation; either
20
 * version 2.1 of the License, or (at your option) any later version.
21
 *
22
 * FFmpeg is distributed in the hope that it will be useful,
23
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
25
 * Lesser General Public License for more details.
26
 *
27
 * You should have received a copy of the GNU Lesser General Public
28
 * License along with FFmpeg; if not, write to the Free Software
29
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30
 */
31

    
32
/**
33
 * @file dv.c
34
 * DV codec.
35
 */
36
#define ALT_BITSTREAM_READER
37
#include "avcodec.h"
38
#include "dsputil.h"
39
#include "mpegvideo.h"
40
#include "simple_idct.h"
41
#include "dvdata.h"
42

    
43
//#undef NDEBUG
44
//#include <assert.h>
45

    
46
typedef struct DVVideoContext {
47
    const DVprofile* sys;
48
    AVFrame picture;
49
    AVCodecContext *avctx;
50
    uint8_t *buf;
51

    
52
    uint8_t dv_zigzag[2][64];
53
    uint8_t dv_idct_shift[2][2][22][64];
54

    
55
    void (*get_pixels)(DCTELEM *block, const uint8_t *pixels, int line_size);
56
    void (*fdct[2])(DCTELEM *block);
57
    void (*idct_put[2])(uint8_t *dest, int line_size, DCTELEM *block);
58
} DVVideoContext;
59

    
60
/* MultiThreading - dv_anchor applies to entire DV codec, not just the avcontext */
61
/* one element is needed for each video segment in a DV frame */
62
/* at most there are 2 DIF channels * 12 DIF sequences * 27 video segments (PAL 50Mbps) */
63
#define DV_ANCHOR_SIZE (2*12*27)
64

    
65
static void* dv_anchor[DV_ANCHOR_SIZE];
66

    
67
#define TEX_VLC_BITS 9
68

    
69
#ifdef DV_CODEC_TINY_TARGET
70
#define DV_VLC_MAP_RUN_SIZE 15
71
#define DV_VLC_MAP_LEV_SIZE 23
72
#else
73
#define DV_VLC_MAP_RUN_SIZE  64
74
#define DV_VLC_MAP_LEV_SIZE 512 //FIXME sign was removed so this should be /2 but needs check
75
#endif
76

    
77
/* XXX: also include quantization */
78
static RL_VLC_ELEM dv_rl_vlc[1184];
79
/* VLC encoding lookup table */
80
static struct dv_vlc_pair {
81
   uint32_t vlc;
82
   uint8_t  size;
83
} (*dv_vlc_map)[DV_VLC_MAP_LEV_SIZE] = NULL;
84

    
85
static void dv_build_unquantize_tables(DVVideoContext *s, uint8_t* perm)
86
{
87
    int i, q, j;
88

    
89
    /* NOTE: max left shift is 6 */
90
    for(q = 0; q < 22; q++) {
91
        /* 88DCT */
92
        for(i = 1; i < 64; i++) {
93
            /* 88 table */
94
            j = perm[i];
95
            s->dv_idct_shift[0][0][q][j] =
96
                dv_quant_shifts[q][dv_88_areas[i]] + 1;
97
            s->dv_idct_shift[1][0][q][j] = s->dv_idct_shift[0][0][q][j] + 1;
98
        }
99

    
100
        /* 248DCT */
101
        for(i = 1; i < 64; i++) {
102
            /* 248 table */
103
            s->dv_idct_shift[0][1][q][i] =
104
                dv_quant_shifts[q][dv_248_areas[i]] + 1;
105
            s->dv_idct_shift[1][1][q][i] = s->dv_idct_shift[0][1][q][i] + 1;
106
        }
107
    }
108
}
109

    
110
static int dvvideo_init(AVCodecContext *avctx)
111
{
112
    DVVideoContext *s = avctx->priv_data;
113
    DSPContext dsp;
114
    static int done=0;
115
    int i, j;
116

    
117
    if (!done) {
118
        VLC dv_vlc;
119
        uint16_t new_dv_vlc_bits[NB_DV_VLC*2];
120
        uint8_t new_dv_vlc_len[NB_DV_VLC*2];
121
        uint8_t new_dv_vlc_run[NB_DV_VLC*2];
122
        int16_t new_dv_vlc_level[NB_DV_VLC*2];
123

    
124
        done = 1;
125

    
126
        dv_vlc_map = av_mallocz_static(DV_VLC_MAP_LEV_SIZE*DV_VLC_MAP_RUN_SIZE*sizeof(struct dv_vlc_pair));
127
        if (!dv_vlc_map)
128
            return AVERROR(ENOMEM);
129

    
130
        /* dv_anchor lets each thread know its Id */
131
        for (i=0; i<DV_ANCHOR_SIZE; i++)
132
            dv_anchor[i] = (void*)(size_t)i;
133

    
134
        /* it's faster to include sign bit in a generic VLC parsing scheme */
135
        for (i=0, j=0; i<NB_DV_VLC; i++, j++) {
136
            new_dv_vlc_bits[j] = dv_vlc_bits[i];
137
            new_dv_vlc_len[j] = dv_vlc_len[i];
138
            new_dv_vlc_run[j] = dv_vlc_run[i];
139
            new_dv_vlc_level[j] = dv_vlc_level[i];
140

    
141
            if (dv_vlc_level[i]) {
142
                new_dv_vlc_bits[j] <<= 1;
143
                new_dv_vlc_len[j]++;
144

    
145
                j++;
146
                new_dv_vlc_bits[j] = (dv_vlc_bits[i] << 1) | 1;
147
                new_dv_vlc_len[j] = dv_vlc_len[i] + 1;
148
                new_dv_vlc_run[j] = dv_vlc_run[i];
149
                new_dv_vlc_level[j] = -dv_vlc_level[i];
150
            }
151
        }
152

    
153
        /* NOTE: as a trick, we use the fact the no codes are unused
154
           to accelerate the parsing of partial codes */
155
        init_vlc(&dv_vlc, TEX_VLC_BITS, j,
156
                 new_dv_vlc_len, 1, 1, new_dv_vlc_bits, 2, 2, 0);
157
        assert(dv_vlc.table_size == 1184);
158

    
159
        for(i = 0; i < dv_vlc.table_size; i++){
160
            int code= dv_vlc.table[i][0];
161
            int len = dv_vlc.table[i][1];
162
            int level, run;
163

    
164
            if(len<0){ //more bits needed
165
                run= 0;
166
                level= code;
167
            } else {
168
                run=   new_dv_vlc_run[code] + 1;
169
                level= new_dv_vlc_level[code];
170
            }
171
            dv_rl_vlc[i].len = len;
172
            dv_rl_vlc[i].level = level;
173
            dv_rl_vlc[i].run = run;
174
        }
175
        free_vlc(&dv_vlc);
176

    
177
        for (i = 0; i < NB_DV_VLC - 1; i++) {
178
           if (dv_vlc_run[i] >= DV_VLC_MAP_RUN_SIZE)
179
               continue;
180
#ifdef DV_CODEC_TINY_TARGET
181
           if (dv_vlc_level[i] >= DV_VLC_MAP_LEV_SIZE)
182
               continue;
183
#endif
184

    
185
           if (dv_vlc_map[dv_vlc_run[i]][dv_vlc_level[i]].size != 0)
186
               continue;
187

    
188
           dv_vlc_map[dv_vlc_run[i]][dv_vlc_level[i]].vlc = dv_vlc_bits[i] <<
189
                                                            (!!dv_vlc_level[i]);
190
           dv_vlc_map[dv_vlc_run[i]][dv_vlc_level[i]].size = dv_vlc_len[i] +
191
                                                             (!!dv_vlc_level[i]);
192
        }
193
        for (i = 0; i < DV_VLC_MAP_RUN_SIZE; i++) {
194
#ifdef DV_CODEC_TINY_TARGET
195
           for (j = 1; j < DV_VLC_MAP_LEV_SIZE; j++) {
196
              if (dv_vlc_map[i][j].size == 0) {
197
                  dv_vlc_map[i][j].vlc = dv_vlc_map[0][j].vlc |
198
                            (dv_vlc_map[i-1][0].vlc << (dv_vlc_map[0][j].size));
199
                  dv_vlc_map[i][j].size = dv_vlc_map[i-1][0].size +
200
                                          dv_vlc_map[0][j].size;
201
              }
202
           }
203
#else
204
           for (j = 1; j < DV_VLC_MAP_LEV_SIZE/2; j++) {
205
              if (dv_vlc_map[i][j].size == 0) {
206
                  dv_vlc_map[i][j].vlc = dv_vlc_map[0][j].vlc |
207
                            (dv_vlc_map[i-1][0].vlc << (dv_vlc_map[0][j].size));
208
                  dv_vlc_map[i][j].size = dv_vlc_map[i-1][0].size +
209
                                          dv_vlc_map[0][j].size;
210
              }
211
              dv_vlc_map[i][((uint16_t)(-j))&0x1ff].vlc =
212
                                            dv_vlc_map[i][j].vlc | 1;
213
              dv_vlc_map[i][((uint16_t)(-j))&0x1ff].size =
214
                                            dv_vlc_map[i][j].size;
215
           }
216
#endif
217
        }
218
    }
219

    
220
    /* Generic DSP setup */
221
    dsputil_init(&dsp, avctx);
222
    s->get_pixels = dsp.get_pixels;
223

    
224
    /* 88DCT setup */
225
    s->fdct[0] = dsp.fdct;
226
    s->idct_put[0] = dsp.idct_put;
227
    for (i=0; i<64; i++)
228
       s->dv_zigzag[0][i] = dsp.idct_permutation[ff_zigzag_direct[i]];
229

    
230
    /* 248DCT setup */
231
    s->fdct[1] = dsp.fdct248;
232
    s->idct_put[1] = simple_idct248_put;  // FIXME: need to add it to DSP
233
    if(avctx->lowres){
234
        for (i=0; i<64; i++){
235
            int j= ff_zigzag248_direct[i];
236
            s->dv_zigzag[1][i] = dsp.idct_permutation[(j&7) + (j&8)*4 + (j&48)/2];
237
        }
238
    }else
239
        memcpy(s->dv_zigzag[1], ff_zigzag248_direct, 64);
240

    
241
    /* XXX: do it only for constant case */
242
    dv_build_unquantize_tables(s, dsp.idct_permutation);
243

    
244
    avctx->coded_frame = &s->picture;
245
    s->avctx= avctx;
246

    
247
    return 0;
248
}
249

    
250
// #define VLC_DEBUG
251
// #define printf(...) av_log(NULL, AV_LOG_ERROR, __VA_ARGS__)
252

    
253
typedef struct BlockInfo {
254
    const uint8_t *shift_table;
255
    const uint8_t *scan_table;
256
    const int *iweight_table;
257
    uint8_t pos; /* position in block */
258
    uint8_t dct_mode;
259
    uint8_t partial_bit_count;
260
    uint16_t partial_bit_buffer;
261
    int shift_offset;
262
} BlockInfo;
263

    
264
/* block size in bits */
265
static const uint16_t block_sizes[6] = {
266
    112, 112, 112, 112, 80, 80
267
};
268
/* bit budget for AC only in 5 MBs */
269
static const int vs_total_ac_bits = (100 * 4 + 68*2) * 5;
270
/* see dv_88_areas and dv_248_areas for details */
271
static const int mb_area_start[5] = { 1, 6, 21, 43, 64 };
272

    
273
static inline int get_bits_left(GetBitContext *s)
274
{
275
    return s->size_in_bits - get_bits_count(s);
276
}
277

    
278
static inline int get_bits_size(GetBitContext *s)
279
{
280
    return s->size_in_bits;
281
}
282

    
283
static inline int put_bits_left(PutBitContext* s)
284
{
285
    return (s->buf_end - s->buf) * 8 - put_bits_count(s);
286
}
287

    
288
/* decode ac coefs */
289
static void dv_decode_ac(GetBitContext *gb, BlockInfo *mb, DCTELEM *block)
290
{
291
    int last_index = get_bits_size(gb);
292
    const uint8_t *scan_table = mb->scan_table;
293
    const uint8_t *shift_table = mb->shift_table;
294
    const int *iweight_table = mb->iweight_table;
295
    int pos = mb->pos;
296
    int partial_bit_count = mb->partial_bit_count;
297
    int level, pos1, run, vlc_len, index;
298

    
299
    OPEN_READER(re, gb);
300
    UPDATE_CACHE(re, gb);
301

    
302
    /* if we must parse a partial vlc, we do it here */
303
    if (partial_bit_count > 0) {
304
        re_cache = ((unsigned)re_cache >> partial_bit_count) |
305
                   (mb->partial_bit_buffer << (sizeof(re_cache)*8 - partial_bit_count));
306
        re_index -= partial_bit_count;
307
        mb->partial_bit_count = 0;
308
    }
309

    
310
    /* get the AC coefficients until last_index is reached */
311
    for(;;) {
312
#ifdef VLC_DEBUG
313
        printf("%2d: bits=%04x index=%d\n", pos, SHOW_UBITS(re, gb, 16), re_index);
314
#endif
315
        /* our own optimized GET_RL_VLC */
316
        index = NEG_USR32(re_cache, TEX_VLC_BITS);
317
        vlc_len = dv_rl_vlc[index].len;
318
        if (vlc_len < 0) {
319
            index = NEG_USR32((unsigned)re_cache << TEX_VLC_BITS, -vlc_len) + dv_rl_vlc[index].level;
320
            vlc_len = TEX_VLC_BITS - vlc_len;
321
        }
322
        level = dv_rl_vlc[index].level;
323
        run = dv_rl_vlc[index].run;
324

    
325
        /* gotta check if we're still within gb boundaries */
326
        if (re_index + vlc_len > last_index) {
327
            /* should be < 16 bits otherwise a codeword could have been parsed */
328
            mb->partial_bit_count = last_index - re_index;
329
            mb->partial_bit_buffer = NEG_USR32(re_cache, mb->partial_bit_count);
330
            re_index = last_index;
331
            break;
332
        }
333
        re_index += vlc_len;
334

    
335
#ifdef VLC_DEBUG
336
        printf("run=%d level=%d\n", run, level);
337
#endif
338
        pos += run;
339
        if (pos >= 64)
340
            break;
341

    
342
        pos1 = scan_table[pos];
343
        level <<= shift_table[pos1];
344

    
345
        /* unweigh, round, and shift down */
346
        level = (level*iweight_table[pos] + (1 << (dv_iweight_bits-1))) >> dv_iweight_bits;
347

    
348
        block[pos1] = level;
349

    
350
        UPDATE_CACHE(re, gb);
351
    }
352
    CLOSE_READER(re, gb);
353
    mb->pos = pos;
354
}
355

    
356
static inline void bit_copy(PutBitContext *pb, GetBitContext *gb)
357
{
358
    int bits_left = get_bits_left(gb);
359
    while (bits_left >= MIN_CACHE_BITS) {
360
        put_bits(pb, MIN_CACHE_BITS, get_bits(gb, MIN_CACHE_BITS));
361
        bits_left -= MIN_CACHE_BITS;
362
    }
363
    if (bits_left > 0) {
364
        put_bits(pb, bits_left, get_bits(gb, bits_left));
365
    }
366
}
367

    
368
/* mb_x and mb_y are in units of 8 pixels */
369
static inline void dv_decode_video_segment(DVVideoContext *s,
370
                                           uint8_t *buf_ptr1,
371
                                           const uint16_t *mb_pos_ptr)
372
{
373
    int quant, dc, dct_mode, class1, j;
374
    int mb_index, mb_x, mb_y, v, last_index;
375
    DCTELEM *block, *block1;
376
    int c_offset;
377
    uint8_t *y_ptr;
378
    void (*idct_put)(uint8_t *dest, int line_size, DCTELEM *block);
379
    uint8_t *buf_ptr;
380
    PutBitContext pb, vs_pb;
381
    GetBitContext gb;
382
    BlockInfo mb_data[5 * 6], *mb, *mb1;
383
    DECLARE_ALIGNED_8(DCTELEM, sblock[5*6][64]);
384
    DECLARE_ALIGNED_8(uint8_t, mb_bit_buffer[80 + 4]); /* allow some slack */
385
    DECLARE_ALIGNED_8(uint8_t, vs_bit_buffer[5 * 80 + 4]); /* allow some slack */
386
    const int log2_blocksize= 3-s->avctx->lowres;
387

    
388
    assert((((int)mb_bit_buffer)&7)==0);
389
    assert((((int)vs_bit_buffer)&7)==0);
390

    
391
    memset(sblock, 0, sizeof(sblock));
392

    
393
    /* pass 1 : read DC and AC coefficients in blocks */
394
    buf_ptr = buf_ptr1;
395
    block1 = &sblock[0][0];
396
    mb1 = mb_data;
397
    init_put_bits(&vs_pb, vs_bit_buffer, 5 * 80);
398
    for(mb_index = 0; mb_index < 5; mb_index++, mb1 += 6, block1 += 6 * 64) {
399
        /* skip header */
400
        quant = buf_ptr[3] & 0x0f;
401
        buf_ptr += 4;
402
        init_put_bits(&pb, mb_bit_buffer, 80);
403
        mb = mb1;
404
        block = block1;
405
        for(j = 0;j < 6; j++) {
406
            last_index = block_sizes[j];
407
            init_get_bits(&gb, buf_ptr, last_index);
408

    
409
            /* get the dc */
410
            dc = get_sbits(&gb, 9);
411
            dct_mode = get_bits1(&gb);
412
            mb->dct_mode = dct_mode;
413
            mb->scan_table = s->dv_zigzag[dct_mode];
414
            mb->iweight_table = dct_mode ? dv_iweight_248 : dv_iweight_88;
415
            class1 = get_bits(&gb, 2);
416
            mb->shift_table = s->dv_idct_shift[class1 == 3][dct_mode]
417
                [quant + dv_quant_offset[class1]];
418
            dc = dc << 2;
419
            /* convert to unsigned because 128 is not added in the
420
               standard IDCT */
421
            dc += 1024;
422
            block[0] = dc;
423
            buf_ptr += last_index >> 3;
424
            mb->pos = 0;
425
            mb->partial_bit_count = 0;
426

    
427
#ifdef VLC_DEBUG
428
            printf("MB block: %d, %d ", mb_index, j);
429
#endif
430
            dv_decode_ac(&gb, mb, block);
431

    
432
            /* write the remaining bits  in a new buffer only if the
433
               block is finished */
434
            if (mb->pos >= 64)
435
                bit_copy(&pb, &gb);
436

    
437
            block += 64;
438
            mb++;
439
        }
440

    
441
        /* pass 2 : we can do it just after */
442
#ifdef VLC_DEBUG
443
        printf("***pass 2 size=%d MB#=%d\n", put_bits_count(&pb), mb_index);
444
#endif
445
        block = block1;
446
        mb = mb1;
447
        init_get_bits(&gb, mb_bit_buffer, put_bits_count(&pb));
448
        flush_put_bits(&pb);
449
        for(j = 0;j < 6; j++, block += 64, mb++) {
450
            if (mb->pos < 64 && get_bits_left(&gb) > 0) {
451
                dv_decode_ac(&gb, mb, block);
452
                /* if still not finished, no need to parse other blocks */
453
                if (mb->pos < 64)
454
                    break;
455
            }
456
        }
457
        /* all blocks are finished, so the extra bytes can be used at
458
           the video segment level */
459
        if (j >= 6)
460
            bit_copy(&vs_pb, &gb);
461
    }
462

    
463
    /* we need a pass other the whole video segment */
464
#ifdef VLC_DEBUG
465
    printf("***pass 3 size=%d\n", put_bits_count(&vs_pb));
466
#endif
467
    block = &sblock[0][0];
468
    mb = mb_data;
469
    init_get_bits(&gb, vs_bit_buffer, put_bits_count(&vs_pb));
470
    flush_put_bits(&vs_pb);
471
    for(mb_index = 0; mb_index < 5; mb_index++) {
472
        for(j = 0;j < 6; j++) {
473
            if (mb->pos < 64) {
474
#ifdef VLC_DEBUG
475
                printf("start %d:%d\n", mb_index, j);
476
#endif
477
                dv_decode_ac(&gb, mb, block);
478
            }
479
            if (mb->pos >= 64 && mb->pos < 127)
480
                av_log(NULL, AV_LOG_ERROR, "AC EOB marker is absent pos=%d\n", mb->pos);
481
            block += 64;
482
            mb++;
483
        }
484
    }
485

    
486
    /* compute idct and place blocks */
487
    block = &sblock[0][0];
488
    mb = mb_data;
489
    for(mb_index = 0; mb_index < 5; mb_index++) {
490
        v = *mb_pos_ptr++;
491
        mb_x = v & 0xff;
492
        mb_y = v >> 8;
493
        if (s->sys->pix_fmt == PIX_FMT_YUV422P) {
494
            y_ptr = s->picture.data[0] + ((mb_y * s->picture.linesize[0] + (mb_x>>1))<<log2_blocksize);
495
            c_offset = ((mb_y * s->picture.linesize[1] + (mb_x >> 2))<<log2_blocksize);
496
        } else { /* 4:1:1 or 4:2:0 */
497
            y_ptr = s->picture.data[0] + ((mb_y * s->picture.linesize[0] + mb_x)<<log2_blocksize);
498
            if (s->sys->pix_fmt == PIX_FMT_YUV411P)
499
                c_offset = ((mb_y * s->picture.linesize[1] + (mb_x >> 2))<<log2_blocksize);
500
            else /* 4:2:0 */
501
                c_offset = (((mb_y >> 1) * s->picture.linesize[1] + (mb_x >> 1))<<log2_blocksize);
502
        }
503
        for(j = 0;j < 6; j++) {
504
            idct_put = s->idct_put[mb->dct_mode && log2_blocksize==3];
505
            if (s->sys->pix_fmt == PIX_FMT_YUV422P) { /* 4:2:2 */
506
                if (j == 0 || j == 2) {
507
                    /* Y0 Y1 */
508
                    idct_put(y_ptr + ((j >> 1)<<log2_blocksize),
509
                             s->picture.linesize[0], block);
510
                } else if(j > 3) {
511
                    /* Cr Cb */
512
                    idct_put(s->picture.data[6 - j] + c_offset,
513
                             s->picture.linesize[6 - j], block);
514
                }
515
                /* note: j=1 and j=3 are "dummy" blocks in 4:2:2 */
516
            } else { /* 4:1:1 or 4:2:0 */
517
                if (j < 4) {
518
                    if (s->sys->pix_fmt == PIX_FMT_YUV411P && mb_x < (704 / 8)) {
519
                        /* NOTE: at end of line, the macroblock is handled as 420 */
520
                        idct_put(y_ptr + (j<<log2_blocksize), s->picture.linesize[0], block);
521
                    } else {
522
                        idct_put(y_ptr + (((j & 1) + (j >> 1) * s->picture.linesize[0])<<log2_blocksize),
523
                                 s->picture.linesize[0], block);
524
                    }
525
                } else {
526
                    if (s->sys->pix_fmt == PIX_FMT_YUV411P && mb_x >= (704 / 8)) {
527
                        uint64_t aligned_pixels[64/8];
528
                        uint8_t *pixels= (uint8_t*)aligned_pixels;
529
                        uint8_t *c_ptr, *c_ptr1, *ptr, *ptr1;
530
                        int x, y, linesize;
531
                        /* NOTE: at end of line, the macroblock is handled as 420 */
532
                        idct_put(pixels, 8, block);
533
                        linesize = s->picture.linesize[6 - j];
534
                        c_ptr = s->picture.data[6 - j] + c_offset;
535
                        ptr = pixels;
536
                        for(y = 0;y < (1<<log2_blocksize); y++) {
537
                            ptr1= ptr + (1<<(log2_blocksize-1));
538
                            c_ptr1 = c_ptr + (linesize<<log2_blocksize);
539
                            for(x=0; x < (1<<(log2_blocksize-1)); x++){
540
                                c_ptr[x]= ptr[x]; c_ptr1[x]= ptr1[x];
541
                            }
542
                            c_ptr += linesize;
543
                            ptr += 8;
544
                        }
545
                    } else {
546
                        /* don't ask me why they inverted Cb and Cr ! */
547
                        idct_put(s->picture.data[6 - j] + c_offset,
548
                                 s->picture.linesize[6 - j], block);
549
                    }
550
                }
551
            }
552
            block += 64;
553
            mb++;
554
        }
555
    }
556
}
557

    
558
#ifdef DV_CODEC_TINY_TARGET
559
/* Converts run and level (where level != 0) pair into vlc, returning bit size */
560
static av_always_inline int dv_rl2vlc(int run, int level, int sign, uint32_t* vlc)
561
{
562
    int size;
563
    if (run < DV_VLC_MAP_RUN_SIZE && level < DV_VLC_MAP_LEV_SIZE) {
564
        *vlc = dv_vlc_map[run][level].vlc | sign;
565
        size = dv_vlc_map[run][level].size;
566
    }
567
    else {
568
        if (level < DV_VLC_MAP_LEV_SIZE) {
569
            *vlc = dv_vlc_map[0][level].vlc | sign;
570
            size = dv_vlc_map[0][level].size;
571
        } else {
572
            *vlc = 0xfe00 | (level << 1) | sign;
573
            size = 16;
574
        }
575
        if (run) {
576
            *vlc |= ((run < 16) ? dv_vlc_map[run-1][0].vlc :
577
                                  (0x1f80 | (run - 1))) << size;
578
            size += (run < 16) ? dv_vlc_map[run-1][0].size : 13;
579
        }
580
    }
581

    
582
    return size;
583
}
584

    
585
static av_always_inline int dv_rl2vlc_size(int run, int level)
586
{
587
    int size;
588

    
589
    if (run < DV_VLC_MAP_RUN_SIZE && level < DV_VLC_MAP_LEV_SIZE) {
590
        size = dv_vlc_map[run][level].size;
591
    }
592
    else {
593
        size = (level < DV_VLC_MAP_LEV_SIZE) ? dv_vlc_map[0][level].size : 16;
594
        if (run) {
595
            size += (run < 16) ? dv_vlc_map[run-1][0].size : 13;
596
        }
597
    }
598
    return size;
599
}
600
#else
601
static av_always_inline int dv_rl2vlc(int run, int l, int sign, uint32_t* vlc)
602
{
603
    *vlc = dv_vlc_map[run][l].vlc | sign;
604
    return dv_vlc_map[run][l].size;
605
}
606

    
607
static av_always_inline int dv_rl2vlc_size(int run, int l)
608
{
609
    return dv_vlc_map[run][l].size;
610
}
611
#endif
612

    
613
typedef struct EncBlockInfo {
614
    int area_q[4];
615
    int bit_size[4];
616
    int prev[5];
617
    int cur_ac;
618
    int cno;
619
    int dct_mode;
620
    DCTELEM mb[64];
621
    uint8_t next[64];
622
    uint8_t sign[64];
623
    uint8_t partial_bit_count;
624
    uint32_t partial_bit_buffer; /* we can't use uint16_t here */
625
} EncBlockInfo;
626

    
627
static av_always_inline PutBitContext* dv_encode_ac(EncBlockInfo* bi, PutBitContext* pb_pool,
628
                                       PutBitContext* pb_end)
629
{
630
    int prev;
631
    int bits_left;
632
    PutBitContext* pb = pb_pool;
633
    int size = bi->partial_bit_count;
634
    uint32_t vlc = bi->partial_bit_buffer;
635

    
636
    bi->partial_bit_count = bi->partial_bit_buffer = 0;
637
    for(;;){
638
       /* Find suitable storage space */
639
       for (; size > (bits_left = put_bits_left(pb)); pb++) {
640
          if (bits_left) {
641
              size -= bits_left;
642
              put_bits(pb, bits_left, vlc >> size);
643
              vlc = vlc & ((1<<size)-1);
644
          }
645
          if (pb + 1 >= pb_end) {
646
              bi->partial_bit_count = size;
647
              bi->partial_bit_buffer = vlc;
648
              return pb;
649
          }
650
       }
651

    
652
       /* Store VLC */
653
       put_bits(pb, size, vlc);
654

    
655
       if(bi->cur_ac>=64)
656
           break;
657

    
658
       /* Construct the next VLC */
659
       prev= bi->cur_ac;
660
       bi->cur_ac = bi->next[prev];
661
       if(bi->cur_ac < 64){
662
           size = dv_rl2vlc(bi->cur_ac - prev - 1, bi->mb[bi->cur_ac], bi->sign[bi->cur_ac], &vlc);
663
       } else {
664
           size = 4; vlc = 6; /* End Of Block stamp */
665
       }
666
    }
667
    return pb;
668
}
669

    
670
static av_always_inline void dv_set_class_number(DCTELEM* blk, EncBlockInfo* bi,
671
                                              const uint8_t* zigzag_scan, const int *weight, int bias)
672
{
673
    int i, area;
674
    /* We offer two different methods for class number assignment: the
675
       method suggested in SMPTE 314M Table 22, and an improved
676
       method. The SMPTE method is very conservative; it assigns class
677
       3 (i.e. severe quantization) to any block where the largest AC
678
       component is greater than 36. ffmpeg's DV encoder tracks AC bit
679
       consumption precisely, so there is no need to bias most blocks
680
       towards strongly lossy compression. Instead, we assign class 2
681
       to most blocks, and use class 3 only when strictly necessary
682
       (for blocks whose largest AC component exceeds 255). */
683

    
684
#if 0 /* SMPTE spec method */
685
    static const int classes[] = {12, 24, 36, 0xffff};
686
#else /* improved ffmpeg method */
687
    static const int classes[] = {-1, -1, 255, 0xffff};
688
#endif
689
    int max=classes[0];
690
    int prev=0;
691

    
692
    bi->mb[0] = blk[0];
693

    
694
    for (area = 0; area < 4; area++) {
695
       bi->prev[area] = prev;
696
       bi->bit_size[area] = 1; // 4 areas 4 bits for EOB :)
697
       for (i=mb_area_start[area]; i<mb_area_start[area+1]; i++) {
698
          int level = blk[zigzag_scan[i]];
699

    
700
          if (level+15 > 30U) {
701
              bi->sign[i] = (level>>31)&1;
702
              /* weigh it and and shift down into range, adding for rounding */
703
              /* the extra division by a factor of 2^4 reverses the 8x expansion of the DCT
704
                 AND the 2x doubling of the weights */
705
              level = (FFABS(level) * weight[i] + (1<<(dv_weight_bits+3))) >> (dv_weight_bits+4);
706
              bi->mb[i] = level;
707
              if(level>max) max= level;
708
              bi->bit_size[area] += dv_rl2vlc_size(i - prev  - 1, level);
709
              bi->next[prev]= i;
710
              prev= i;
711
          }
712
       }
713
    }
714
    bi->next[prev]= i;
715
    for(bi->cno = 0; max > classes[bi->cno]; bi->cno++);
716

    
717
    bi->cno += bias;
718

    
719
    if (bi->cno >= 3) {
720
        bi->cno = 3;
721
        prev=0;
722
        i= bi->next[prev];
723
        for (area = 0; area < 4; area++) {
724
            bi->prev[area] = prev;
725
            bi->bit_size[area] = 1; // 4 areas 4 bits for EOB :)
726
            for (; i<mb_area_start[area+1]; i= bi->next[i]) {
727
                bi->mb[i] >>=1;
728

    
729
                if (bi->mb[i]) {
730
                    bi->bit_size[area] += dv_rl2vlc_size(i - prev - 1, bi->mb[i]);
731
                    bi->next[prev]= i;
732
                    prev= i;
733
                }
734
            }
735
        }
736
        bi->next[prev]= i;
737
    }
738
}
739

    
740
//FIXME replace this by dsputil
741
#define SC(x, y) ((s[x] - s[y]) ^ ((s[x] - s[y]) >> 7))
742
static av_always_inline int dv_guess_dct_mode(DCTELEM *blk) {
743
    DCTELEM *s;
744
    int score88 = 0;
745
    int score248 = 0;
746
    int i;
747

    
748
    /* Compute 8-8 score (small values give a better chance for 8-8 DCT) */
749
    s = blk;
750
    for(i=0; i<7; i++) {
751
        score88 += SC(0,  8) + SC(1, 9) + SC(2, 10) + SC(3, 11) +
752
                   SC(4, 12) + SC(5,13) + SC(6, 14) + SC(7, 15);
753
        s += 8;
754
    }
755
    /* Compute 2-4-8 score (small values give a better chance for 2-4-8 DCT) */
756
    s = blk;
757
    for(i=0; i<6; i++) {
758
        score248 += SC(0, 16) + SC(1,17) + SC(2, 18) + SC(3, 19) +
759
                    SC(4, 20) + SC(5,21) + SC(6, 22) + SC(7, 23);
760
        s += 8;
761
    }
762

    
763
    return (score88 - score248 > -10);
764
}
765

    
766
static inline void dv_guess_qnos(EncBlockInfo* blks, int* qnos)
767
{
768
    int size[5];
769
    int i, j, k, a, prev, a2;
770
    EncBlockInfo* b;
771

    
772
    size[0] = size[1] = size[2] = size[3] = size[4] = 1<<24;
773
    do {
774
       b = blks;
775
       for (i=0; i<5; i++) {
776
          if (!qnos[i])
777
              continue;
778

    
779
          qnos[i]--;
780
          size[i] = 0;
781
          for (j=0; j<6; j++, b++) {
782
             for (a=0; a<4; a++) {
783
                if (b->area_q[a] != dv_quant_shifts[qnos[i] + dv_quant_offset[b->cno]][a]) {
784
                    b->bit_size[a] = 1; // 4 areas 4 bits for EOB :)
785
                    b->area_q[a]++;
786
                    prev= b->prev[a];
787
                    assert(b->next[prev] >= mb_area_start[a+1] || b->mb[prev]);
788
                    for (k= b->next[prev] ; k<mb_area_start[a+1]; k= b->next[k]) {
789
                       b->mb[k] >>= 1;
790
                       if (b->mb[k]) {
791
                           b->bit_size[a] += dv_rl2vlc_size(k - prev - 1, b->mb[k]);
792
                           prev= k;
793
                       } else {
794
                           if(b->next[k] >= mb_area_start[a+1] && b->next[k]<64){
795
                                for(a2=a+1; b->next[k] >= mb_area_start[a2+1]; a2++)
796
                                    b->prev[a2] = prev;
797
                                assert(a2<4);
798
                                assert(b->mb[b->next[k]]);
799
                                b->bit_size[a2] += dv_rl2vlc_size(b->next[k] - prev - 1, b->mb[b->next[k]])
800
                                                  -dv_rl2vlc_size(b->next[k] -    k - 1, b->mb[b->next[k]]);
801
                                assert(b->prev[a2]==k && (a2+1 >= 4 || b->prev[a2+1]!=k));
802
                                b->prev[a2] = prev;
803
                           }
804
                           b->next[prev] = b->next[k];
805
                       }
806
                    }
807
                    b->prev[a+1]= prev;
808
                }
809
                size[i] += b->bit_size[a];
810
             }
811
          }
812
          if(vs_total_ac_bits >= size[0] + size[1] + size[2] + size[3] + size[4])
813
                return;
814
       }
815
    } while (qnos[0]|qnos[1]|qnos[2]|qnos[3]|qnos[4]);
816

    
817

    
818
    for(a=2; a==2 || vs_total_ac_bits < size[0]; a+=a){
819
        b = blks;
820
        size[0] = 5*6*4; //EOB
821
        for (j=0; j<6*5; j++, b++) {
822
            prev= b->prev[0];
823
            for (k= b->next[prev]; k<64; k= b->next[k]) {
824
                if(b->mb[k] < a && b->mb[k] > -a){
825
                    b->next[prev] = b->next[k];
826
                }else{
827
                    size[0] += dv_rl2vlc_size(k - prev - 1, b->mb[k]);
828
                    prev= k;
829
                }
830
            }
831
        }
832
    }
833
}
834

    
835
static inline void dv_encode_video_segment(DVVideoContext *s,
836
                                           uint8_t *dif,
837
                                           const uint16_t *mb_pos_ptr)
838
{
839
    int mb_index, i, j, v;
840
    int mb_x, mb_y, c_offset, linesize;
841
    uint8_t*  y_ptr;
842
    uint8_t*  data;
843
    uint8_t*  ptr;
844
    int       do_edge_wrap;
845
    DECLARE_ALIGNED_8(DCTELEM, block[64]);
846
    EncBlockInfo  enc_blks[5*6];
847
    PutBitContext pbs[5*6];
848
    PutBitContext* pb;
849
    EncBlockInfo* enc_blk;
850
    int       vs_bit_size = 0;
851
    int       qnos[5];
852

    
853
    assert((((int)block) & 7) == 0);
854

    
855
    enc_blk = &enc_blks[0];
856
    pb = &pbs[0];
857
    for(mb_index = 0; mb_index < 5; mb_index++) {
858
        v = *mb_pos_ptr++;
859
        mb_x = v & 0xff;
860
        mb_y = v >> 8;
861
        if (s->sys->pix_fmt == PIX_FMT_YUV422P) {
862
            y_ptr = s->picture.data[0] + (mb_y * s->picture.linesize[0] * 8) + (mb_x * 4);
863
        } else { /* 4:1:1 */
864
            y_ptr = s->picture.data[0] + (mb_y * s->picture.linesize[0] * 8) + (mb_x * 8);
865
        }
866
        if (s->sys->pix_fmt == PIX_FMT_YUV420P) {
867
            c_offset = (((mb_y >> 1) * s->picture.linesize[1] * 8) + ((mb_x >> 1) * 8));
868
        } else { /* 4:2:2 or 4:1:1 */
869
            c_offset = ((mb_y * s->picture.linesize[1] * 8) + ((mb_x >> 2) * 8));
870
        }
871
        do_edge_wrap = 0;
872
        qnos[mb_index] = 15; /* No quantization */
873
        ptr = dif + mb_index*80 + 4;
874
        for(j = 0;j < 6; j++) {
875
            int dummy = 0;
876
            if (s->sys->pix_fmt == PIX_FMT_YUV422P) { /* 4:2:2 */
877
                if (j == 0 || j == 2) {
878
                    /* Y0 Y1 */
879
                    data = y_ptr + ((j>>1) * 8);
880
                    linesize = s->picture.linesize[0];
881
                } else if (j > 3) {
882
                    /* Cr Cb */
883
                    data = s->picture.data[6 - j] + c_offset;
884
                    linesize = s->picture.linesize[6 - j];
885
                } else {
886
                    /* j=1 and j=3 are "dummy" blocks, used for AC data only */
887
                    data = 0;
888
                    linesize = 0;
889
                    dummy = 1;
890
                }
891
            } else { /* 4:1:1 or 4:2:0 */
892
                if (j < 4) {  /* Four Y blocks */
893
                    /* NOTE: at end of line, the macroblock is handled as 420 */
894
                    if (s->sys->pix_fmt == PIX_FMT_YUV411P && mb_x < (704 / 8)) {
895
                        data = y_ptr + (j * 8);
896
                    } else {
897
                        data = y_ptr + ((j & 1) * 8) + ((j >> 1) * 8 * s->picture.linesize[0]);
898
                    }
899
                    linesize = s->picture.linesize[0];
900
                } else {      /* Cr and Cb blocks */
901
                    /* don't ask Fabrice why they inverted Cb and Cr ! */
902
                    data = s->picture.data[6 - j] + c_offset;
903
                    linesize = s->picture.linesize[6 - j];
904
                    if (s->sys->pix_fmt == PIX_FMT_YUV411P && mb_x >= (704 / 8))
905
                        do_edge_wrap = 1;
906
                }
907
            }
908

    
909
            /* Everything is set up -- now just copy data -> DCT block */
910
            if (do_edge_wrap) {  /* Edge wrap copy: 4x16 -> 8x8 */
911
                uint8_t* d;
912
                DCTELEM *b = block;
913
                for (i=0;i<8;i++) {
914
                   d = data + 8 * linesize;
915
                   b[0] = data[0]; b[1] = data[1]; b[2] = data[2]; b[3] = data[3];
916
                   b[4] =    d[0]; b[5] =    d[1]; b[6] =    d[2]; b[7] =    d[3];
917
                   data += linesize;
918
                   b += 8;
919
                }
920
            } else {             /* Simple copy: 8x8 -> 8x8 */
921
                if (!dummy)
922
                    s->get_pixels(block, data, linesize);
923
            }
924

    
925
            if(s->avctx->flags & CODEC_FLAG_INTERLACED_DCT)
926
                enc_blk->dct_mode = dv_guess_dct_mode(block);
927
            else
928
                enc_blk->dct_mode = 0;
929
            enc_blk->area_q[0] = enc_blk->area_q[1] = enc_blk->area_q[2] = enc_blk->area_q[3] = 0;
930
            enc_blk->partial_bit_count = 0;
931
            enc_blk->partial_bit_buffer = 0;
932
            enc_blk->cur_ac = 0;
933

    
934
            if (dummy) {
935
                /* We rely on the fact that encoding all zeros leads to an immediate EOB,
936
                   which is precisely what the spec calls for in the "dummy" blocks. */
937
                memset(block, 0, sizeof(block));
938
            } else {
939
                s->fdct[enc_blk->dct_mode](block);
940
            }
941

    
942
            dv_set_class_number(block, enc_blk,
943
                                enc_blk->dct_mode ? ff_zigzag248_direct : ff_zigzag_direct,
944
                                enc_blk->dct_mode ? dv_weight_248 : dv_weight_88,
945
                                j/4);
946

    
947
            init_put_bits(pb, ptr, block_sizes[j]/8);
948
            put_bits(pb, 9, (uint16_t)(((enc_blk->mb[0] >> 3) - 1024 + 2) >> 2));
949
            put_bits(pb, 1, enc_blk->dct_mode);
950
            put_bits(pb, 2, enc_blk->cno);
951

    
952
            vs_bit_size += enc_blk->bit_size[0] + enc_blk->bit_size[1] +
953
                           enc_blk->bit_size[2] + enc_blk->bit_size[3];
954
            ++enc_blk;
955
            ++pb;
956
            ptr += block_sizes[j]/8;
957
        }
958
    }
959

    
960
    if (vs_total_ac_bits < vs_bit_size)
961
        dv_guess_qnos(&enc_blks[0], &qnos[0]);
962

    
963
    for (i=0; i<5; i++) {
964
       dif[i*80 + 3] = qnos[i];
965
    }
966

    
967
    /* First pass over individual cells only */
968
    for (j=0; j<5*6; j++)
969
       dv_encode_ac(&enc_blks[j], &pbs[j], &pbs[j+1]);
970

    
971
    /* Second pass over each MB space */
972
    for (j=0; j<5*6; j+=6) {
973
        pb= &pbs[j];
974
        for (i=0; i<6; i++) {
975
            if (enc_blks[i+j].partial_bit_count)
976
                pb=dv_encode_ac(&enc_blks[i+j], pb, &pbs[j+6]);
977
        }
978
    }
979

    
980
    /* Third and final pass over the whole vides segment space */
981
    pb= &pbs[0];
982
    for (j=0; j<5*6; j++) {
983
       if (enc_blks[j].partial_bit_count)
984
           pb=dv_encode_ac(&enc_blks[j], pb, &pbs[6*5]);
985
       if (enc_blks[j].partial_bit_count)
986
            av_log(NULL, AV_LOG_ERROR, "ac bitstream overflow\n");
987
    }
988

    
989
    for (j=0; j<5*6; j++)
990
       flush_put_bits(&pbs[j]);
991
}
992

    
993
static int dv_decode_mt(AVCodecContext *avctx, void* sl)
994
{
995
    DVVideoContext *s = avctx->priv_data;
996
    int slice = (size_t)sl;
997

    
998
    /* which DIF channel is this? */
999
    int chan = slice / (s->sys->difseg_size * 27);
1000

    
1001
    /* slice within the DIF channel */
1002
    int chan_slice = slice % (s->sys->difseg_size * 27);
1003

    
1004
    /* byte offset of this channel's data */
1005
    int chan_offset = chan * s->sys->difseg_size * 150 * 80;
1006

    
1007
    dv_decode_video_segment(s, &s->buf[((chan_slice/27)*6+(chan_slice/3)+chan_slice*5+7)*80 + chan_offset],
1008
                            &s->sys->video_place[slice*5]);
1009
    return 0;
1010
}
1011

    
1012
#ifdef CONFIG_ENCODERS
1013
static int dv_encode_mt(AVCodecContext *avctx, void* sl)
1014
{
1015
    DVVideoContext *s = avctx->priv_data;
1016
    int slice = (size_t)sl;
1017

    
1018
    /* which DIF channel is this? */
1019
    int chan = slice / (s->sys->difseg_size * 27);
1020

    
1021
    /* slice within the DIF channel */
1022
    int chan_slice = slice % (s->sys->difseg_size * 27);
1023

    
1024
    /* byte offset of this channel's data */
1025
    int chan_offset = chan * s->sys->difseg_size * 150 * 80;
1026

    
1027
    dv_encode_video_segment(s, &s->buf[((chan_slice/27)*6+(chan_slice/3)+chan_slice*5+7)*80 + chan_offset],
1028
                            &s->sys->video_place[slice*5]);
1029
    return 0;
1030
}
1031
#endif
1032

    
1033
#ifdef CONFIG_DECODERS
1034
/* NOTE: exactly one frame must be given (120000 bytes for NTSC,
1035
   144000 bytes for PAL - or twice those for 50Mbps) */
1036
static int dvvideo_decode_frame(AVCodecContext *avctx,
1037
                                 void *data, int *data_size,
1038
                                 uint8_t *buf, int buf_size)
1039
{
1040
    DVVideoContext *s = avctx->priv_data;
1041

    
1042
    s->sys = dv_frame_profile(buf);
1043
    if (!s->sys || buf_size < s->sys->frame_size)
1044
        return -1; /* NOTE: we only accept several full frames */
1045

    
1046
    if(s->picture.data[0])
1047
        avctx->release_buffer(avctx, &s->picture);
1048

    
1049
    s->picture.reference = 0;
1050
    s->picture.key_frame = 1;
1051
    s->picture.pict_type = FF_I_TYPE;
1052
    avctx->pix_fmt = s->sys->pix_fmt;
1053
    avcodec_set_dimensions(avctx, s->sys->width, s->sys->height);
1054
    if(avctx->get_buffer(avctx, &s->picture) < 0) {
1055
        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1056
        return -1;
1057
    }
1058
    s->picture.interlaced_frame = 1;
1059
    s->picture.top_field_first = 0;
1060

    
1061
    s->buf = buf;
1062
    avctx->execute(avctx, dv_decode_mt, (void**)&dv_anchor[0], NULL,
1063
                   s->sys->n_difchan * s->sys->difseg_size * 27);
1064

    
1065
    emms_c();
1066

    
1067
    /* return image */
1068
    *data_size = sizeof(AVFrame);
1069
    *(AVFrame*)data= s->picture;
1070

    
1071
    return s->sys->frame_size;
1072
}
1073
#endif
1074

    
1075

    
1076
static inline int dv_write_pack(enum dv_pack_type pack_id, DVVideoContext *c, uint8_t* buf)
1077
{
1078
    /*
1079
     * Here's what SMPTE314M says about these two:
1080
     *    (page 6) APTn, AP1n, AP2n, AP3n: These data shall be identical
1081
     *             as track application IDs (APTn = 001, AP1n =
1082
     *             001, AP2n = 001, AP3n = 001), if the source signal
1083
     *             comes from a digital VCR. If the signal source is
1084
     *             unknown, all bits for these data shall be set to 1.
1085
     *    (page 12) STYPE: STYPE defines a signal type of video signal
1086
     *                     00000b = 4:1:1 compression
1087
     *                     00100b = 4:2:2 compression
1088
     *                     XXXXXX = Reserved
1089
     * Now, I've got two problems with these statements:
1090
     *   1. it looks like APT == 111b should be a safe bet, but it isn't.
1091
     *      It seems that for PAL as defined in IEC 61834 we have to set
1092
     *      APT to 000 and for SMPTE314M to 001.
1093
     *   2. It is not at all clear what STYPE is used for 4:2:0 PAL
1094
     *      compression scheme (if any).
1095
     */
1096
    int apt = (c->sys->pix_fmt == PIX_FMT_YUV420P ? 0 : 1);
1097
    int stype = (c->sys->pix_fmt == PIX_FMT_YUV422P ? 4 : 0);
1098

    
1099
    uint8_t aspect = 0;
1100
    if((int)(av_q2d(c->avctx->sample_aspect_ratio) * c->avctx->width / c->avctx->height * 10) == 17) /* 16:9 */
1101
        aspect = 0x02;
1102

    
1103
    buf[0] = (uint8_t)pack_id;
1104
    switch (pack_id) {
1105
    case dv_header525: /* I can't imagine why these two weren't defined as real */
1106
    case dv_header625: /* packs in SMPTE314M -- they definitely look like ones */
1107
          buf[1] = 0xf8 |               /* reserved -- always 1 */
1108
                   (apt & 0x07);        /* APT: Track application ID */
1109
          buf[2] = (0 << 7)    | /* TF1: audio data is 0 - valid; 1 - invalid */
1110
                   (0x0f << 3) | /* reserved -- always 1 */
1111
                   (apt & 0x07); /* AP1: Audio application ID */
1112
          buf[3] = (0 << 7)    | /* TF2: video data is 0 - valid; 1 - invalid */
1113
                   (0x0f << 3) | /* reserved -- always 1 */
1114
                   (apt & 0x07); /* AP2: Video application ID */
1115
          buf[4] = (0 << 7)    | /* TF3: subcode(SSYB) is 0 - valid; 1 - invalid */
1116
                   (0x0f << 3) | /* reserved -- always 1 */
1117
                   (apt & 0x07); /* AP3: Subcode application ID */
1118
          break;
1119
    case dv_video_source:
1120
          buf[1] = 0xff; /* reserved -- always 1 */
1121
          buf[2] = (1 << 7) | /* B/W: 0 - b/w, 1 - color */
1122
                   (1 << 6) | /* following CLF is valid - 0, invalid - 1 */
1123
                   (3 << 4) | /* CLF: color frames id (see ITU-R BT.470-4) */
1124
                   0xf; /* reserved -- always 1 */
1125
          buf[3] = (3 << 6) | /* reserved -- always 1 */
1126
                   (c->sys->dsf << 5) | /*  system: 60fields/50fields */
1127
                   stype; /* signal type video compression */
1128
          buf[4] = 0xff; /* VISC: 0xff -- no information */
1129
          break;
1130
    case dv_video_control:
1131
          buf[1] = (0 << 6) | /* Copy generation management (CGMS) 0 -- free */
1132
                   0x3f; /* reserved -- always 1 */
1133
          buf[2] = 0xc8 | /* reserved -- always b11001xxx */
1134
                   aspect;
1135
          buf[3] = (1 << 7) | /* Frame/field flag 1 -- frame, 0 -- field */
1136
                   (1 << 6) | /* First/second field flag 0 -- field 2, 1 -- field 1 */
1137
                   (1 << 5) | /* Frame change flag 0 -- same picture as before, 1 -- different */
1138
                   (1 << 4) | /* 1 - interlaced, 0 - noninterlaced */
1139
                   0xc; /* reserved -- always b1100 */
1140
          buf[4] = 0xff; /* reserved -- always 1 */
1141
          break;
1142
    default:
1143
          buf[1] = buf[2] = buf[3] = buf[4] = 0xff;
1144
    }
1145
    return 5;
1146
}
1147

    
1148
static void dv_format_frame(DVVideoContext* c, uint8_t* buf)
1149
{
1150
    int chan, i, j, k;
1151

    
1152
    for (chan = 0; chan < c->sys->n_difchan; chan++) {
1153
        for (i = 0; i < c->sys->difseg_size; i++) {
1154
            memset(buf, 0xff, 80 * 6); /* First 6 DIF blocks are for control data */
1155

    
1156
            /* DV header: 1DIF */
1157
            buf += dv_write_dif_id(dv_sect_header, chan, i, 0, buf);
1158
            buf += dv_write_pack((c->sys->dsf ? dv_header625 : dv_header525), c, buf);
1159
            buf += 72; /* unused bytes */
1160

    
1161
            /* DV subcode: 2DIFs */
1162
            for (j = 0; j < 2; j++) {
1163
                buf += dv_write_dif_id(dv_sect_subcode, chan, i, j, buf);
1164
                for (k = 0; k < 6; k++)
1165
                     buf += dv_write_ssyb_id(k, (i < c->sys->difseg_size/2), buf) + 5;
1166
                buf += 29; /* unused bytes */
1167
            }
1168

    
1169
            /* DV VAUX: 3DIFS */
1170
            for (j = 0; j < 3; j++) {
1171
                buf += dv_write_dif_id(dv_sect_vaux, chan, i, j, buf);
1172
                buf += dv_write_pack(dv_video_source,  c, buf);
1173
                buf += dv_write_pack(dv_video_control, c, buf);
1174
                buf += 7*5;
1175
                buf += dv_write_pack(dv_video_source,  c, buf);
1176
                buf += dv_write_pack(dv_video_control, c, buf);
1177
                buf += 4*5 + 2; /* unused bytes */
1178
            }
1179

    
1180
            /* DV Audio/Video: 135 Video DIFs + 9 Audio DIFs */
1181
            for (j = 0; j < 135; j++) {
1182
                if (j%15 == 0) {
1183
                    memset(buf, 0xff, 80);
1184
                    buf += dv_write_dif_id(dv_sect_audio, chan, i, j/15, buf);
1185
                    buf += 77; /* audio control & shuffled PCM audio */
1186
                }
1187
                buf += dv_write_dif_id(dv_sect_video, chan, i, j, buf);
1188
                buf += 77; /* 1 video macro block: 1 bytes control
1189
                              4 * 14 bytes Y 8x8 data
1190
                              10 bytes Cr 8x8 data
1191
                              10 bytes Cb 8x8 data */
1192
            }
1193
        }
1194
    }
1195
}
1196

    
1197

    
1198
#ifdef CONFIG_ENCODERS
1199
static int dvvideo_encode_frame(AVCodecContext *c, uint8_t *buf, int buf_size,
1200
                                void *data)
1201
{
1202
    DVVideoContext *s = c->priv_data;
1203

    
1204
    s->sys = dv_codec_profile(c);
1205
    if (!s->sys)
1206
        return -1;
1207
    if(buf_size < s->sys->frame_size)
1208
        return -1;
1209

    
1210
    c->pix_fmt = s->sys->pix_fmt;
1211
    s->picture = *((AVFrame *)data);
1212
    s->picture.key_frame = 1;
1213
    s->picture.pict_type = FF_I_TYPE;
1214

    
1215
    s->buf = buf;
1216
    c->execute(c, dv_encode_mt, (void**)&dv_anchor[0], NULL,
1217
               s->sys->n_difchan * s->sys->difseg_size * 27);
1218

    
1219
    emms_c();
1220

    
1221
    dv_format_frame(s, buf);
1222

    
1223
    return s->sys->frame_size;
1224
}
1225
#endif
1226

    
1227
static int dvvideo_close(AVCodecContext *c)
1228
{
1229
    DVVideoContext *s = c->priv_data;
1230

    
1231
    if(s->picture.data[0])
1232
        c->release_buffer(c, &s->picture);
1233

    
1234
    return 0;
1235
}
1236

    
1237

    
1238
#ifdef CONFIG_DVVIDEO_ENCODER
1239
AVCodec dvvideo_encoder = {
1240
    "dvvideo",
1241
    CODEC_TYPE_VIDEO,
1242
    CODEC_ID_DVVIDEO,
1243
    sizeof(DVVideoContext),
1244
    dvvideo_init,
1245
    dvvideo_encode_frame,
1246
    .pix_fmts = (enum PixelFormat[]) {PIX_FMT_YUV411P, PIX_FMT_YUV422P, PIX_FMT_YUV420P, -1},
1247
};
1248
#endif // CONFIG_DVVIDEO_ENCODER
1249

    
1250
#ifdef CONFIG_DVVIDEO_DECODER
1251
AVCodec dvvideo_decoder = {
1252
    "dvvideo",
1253
    CODEC_TYPE_VIDEO,
1254
    CODEC_ID_DVVIDEO,
1255
    sizeof(DVVideoContext),
1256
    dvvideo_init,
1257
    NULL,
1258
    dvvideo_close,
1259
    dvvideo_decode_frame,
1260
    CODEC_CAP_DR1,
1261
    NULL
1262
};
1263
#endif