vpxenc

00001 /*
00002  *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
00003  *
00004  *  Use of this source code is governed by a BSD-style license
00005  *  that can be found in the LICENSE file in the root of the source
00006  *  tree. An additional intellectual property rights grant can be found
00007  *  in the file PATENTS.  All contributing project authors may
00008  *  be found in the AUTHORS file in the root of the source tree.
00009  */
00010 
00011 
00012 /* This is a simple program that encodes YV12 files and generates ivf
00013  * files using the new interface.
00014  */
00015 #if defined(_WIN32)
00016 #define USE_POSIX_MMAP 0
00017 #else
00018 #define USE_POSIX_MMAP 1
00019 #endif
00020 
00021 #include <stdio.h>
00022 #include <stdlib.h>
00023 #include <stdarg.h>
00024 #include <string.h>
00025 #include <limits.h>
00026 #include "vpx/vpx_encoder.h"
00027 #if USE_POSIX_MMAP
00028 #include <sys/types.h>
00029 #include <sys/stat.h>
00030 #include <sys/mman.h>
00031 #include <fcntl.h>
00032 #include <unistd.h>
00033 #endif
00034 #include "vpx_version.h"
00035 #include "vpx/vp8cx.h"
00036 #include "vpx_ports/mem_ops.h"
00037 #include "vpx_ports/vpx_timer.h"
00038 #include "y4minput.h"
00039 #include "libmkv/EbmlWriter.h"
00040 #include "libmkv/EbmlIDs.h"
00041 
00042 /* Need special handling of these functions on Windows */
00043 #if defined(_MSC_VER)
00044 /* MSVS doesn't define off_t, and uses _f{seek,tell}i64 */
00045 typedef __int64 off_t;
00046 #define fseeko _fseeki64
00047 #define ftello _ftelli64
00048 #elif defined(_WIN32)
00049 /* MinGW defines off_t, and uses f{seek,tell}o64 */
00050 #define fseeko fseeko64
00051 #define ftello ftello64
00052 #endif
00053 
00054 #if defined(_MSC_VER)
00055 #define LITERALU64(n) n
00056 #else
00057 #define LITERALU64(n) n##LLU
00058 #endif
00059 
00060 static const char *exec_name;
00061 
00062 static const struct codec_item
00063 {
00064     char const              *name;
00065     const vpx_codec_iface_t *iface;
00066     unsigned int             fourcc;
00067 } codecs[] =
00068 {
00069 #if CONFIG_VP8_ENCODER
00070     {"vp8",  &vpx_codec_vp8_cx_algo, 0x30385056},
00071 #endif
00072 };
00073 
00074 static void usage_exit();
00075 
00076 void die(const char *fmt, ...)
00077 {
00078     va_list ap;
00079     va_start(ap, fmt);
00080     vfprintf(stderr, fmt, ap);
00081     fprintf(stderr, "\n");
00082     usage_exit();
00083 }
00084 
00085 static void ctx_exit_on_error(vpx_codec_ctx_t *ctx, const char *s)
00086 {
00087     if (ctx->err)
00088     {
00089         const char *detail = vpx_codec_error_detail(ctx);
00090 
00091         fprintf(stderr, "%s: %s\n", s, vpx_codec_error(ctx));
00092 
00093         if (detail)
00094             fprintf(stderr, "    %s\n", detail);
00095 
00096         exit(EXIT_FAILURE);
00097     }
00098 }
00099 
00100 /* This structure is used to abstract the different ways of handling
00101  * first pass statistics.
00102  */
00103 typedef struct
00104 {
00105     vpx_fixed_buf_t buf;
00106     int             pass;
00107     FILE           *file;
00108     char           *buf_ptr;
00109     size_t          buf_alloc_sz;
00110 } stats_io_t;
00111 
00112 int stats_open_file(stats_io_t *stats, const char *fpf, int pass)
00113 {
00114     int res;
00115 
00116     stats->pass = pass;
00117 
00118     if (pass == 0)
00119     {
00120         stats->file = fopen(fpf, "wb");
00121         stats->buf.sz = 0;
00122         stats->buf.buf = NULL,
00123                    res = (stats->file != NULL);
00124     }
00125     else
00126     {
00127 #if 0
00128 #elif USE_POSIX_MMAP
00129         struct stat stat_buf;
00130         int fd;
00131 
00132         fd = open(fpf, O_RDONLY);
00133         stats->file = fdopen(fd, "rb");
00134         fstat(fd, &stat_buf);
00135         stats->buf.sz = stat_buf.st_size;
00136         stats->buf.buf = mmap(NULL, stats->buf.sz, PROT_READ, MAP_PRIVATE,
00137                               fd, 0);
00138         res = (stats->buf.buf != NULL);
00139 #else
00140         size_t nbytes;
00141 
00142         stats->file = fopen(fpf, "rb");
00143 
00144         if (fseek(stats->file, 0, SEEK_END))
00145         {
00146             fprintf(stderr, "First-pass stats file must be seekable!\n");
00147             exit(EXIT_FAILURE);
00148         }
00149 
00150         stats->buf.sz = stats->buf_alloc_sz = ftell(stats->file);
00151         rewind(stats->file);
00152 
00153         stats->buf.buf = malloc(stats->buf_alloc_sz);
00154 
00155         if (!stats->buf.buf)
00156         {
00157             fprintf(stderr, "Failed to allocate first-pass stats buffer (%d bytes)\n",
00158                     stats->buf_alloc_sz);
00159             exit(EXIT_FAILURE);
00160         }
00161 
00162         nbytes = fread(stats->buf.buf, 1, stats->buf.sz, stats->file);
00163         res = (nbytes == stats->buf.sz);
00164 #endif
00165     }
00166 
00167     return res;
00168 }
00169 
00170 int stats_open_mem(stats_io_t *stats, int pass)
00171 {
00172     int res;
00173     stats->pass = pass;
00174 
00175     if (!pass)
00176     {
00177         stats->buf.sz = 0;
00178         stats->buf_alloc_sz = 64 * 1024;
00179         stats->buf.buf = malloc(stats->buf_alloc_sz);
00180     }
00181 
00182     stats->buf_ptr = stats->buf.buf;
00183     res = (stats->buf.buf != NULL);
00184     return res;
00185 }
00186 
00187 
00188 void stats_close(stats_io_t *stats)
00189 {
00190     if (stats->file)
00191     {
00192         if (stats->pass == 1)
00193         {
00194 #if 0
00195 #elif USE_POSIX_MMAP
00196             munmap(stats->buf.buf, stats->buf.sz);
00197 #else
00198             free(stats->buf.buf);
00199 #endif
00200         }
00201 
00202         fclose(stats->file);
00203         stats->file = NULL;
00204     }
00205     else
00206     {
00207         if (stats->pass == 1)
00208             free(stats->buf.buf);
00209     }
00210 }
00211 
00212 void stats_write(stats_io_t *stats, const void *pkt, size_t len)
00213 {
00214     if (stats->file)
00215     {
00216         if(fwrite(pkt, 1, len, stats->file));
00217     }
00218     else
00219     {
00220         if (stats->buf.sz + len > stats->buf_alloc_sz)
00221         {
00222             size_t  new_sz = stats->buf_alloc_sz + 64 * 1024;
00223             char   *new_ptr = realloc(stats->buf.buf, new_sz);
00224 
00225             if (new_ptr)
00226             {
00227                 stats->buf_ptr = new_ptr + (stats->buf_ptr - (char *)stats->buf.buf);
00228                 stats->buf.buf = new_ptr;
00229                 stats->buf_alloc_sz = new_sz;
00230             } /* else ... */
00231         }
00232 
00233         memcpy(stats->buf_ptr, pkt, len);
00234         stats->buf.sz += len;
00235         stats->buf_ptr += len;
00236     }
00237 }
00238 
00239 vpx_fixed_buf_t stats_get(stats_io_t *stats)
00240 {
00241     return stats->buf;
00242 }
00243 
00244 enum video_file_type
00245 {
00246     FILE_TYPE_RAW,
00247     FILE_TYPE_IVF,
00248     FILE_TYPE_Y4M
00249 };
00250 
00251 struct detect_buffer {
00252     char buf[4];
00253     int  valid;
00254 };
00255 
00256 
00257 #define IVF_FRAME_HDR_SZ (4+8) /* 4 byte size + 8 byte timestamp */
00258 static int read_frame(FILE *f, vpx_image_t *img, unsigned int file_type,
00259                       y4m_input *y4m, struct detect_buffer *detect)
00260 {
00261     int plane = 0;
00262     int shortread = 0;
00263 
00264     if (file_type == FILE_TYPE_Y4M)
00265     {
00266         if (y4m_input_fetch_frame(y4m, f, img) < 1)
00267            return 0;
00268     }
00269     else
00270     {
00271         if (file_type == FILE_TYPE_IVF)
00272         {
00273             char junk[IVF_FRAME_HDR_SZ];
00274 
00275             /* Skip the frame header. We know how big the frame should be. See
00276              * write_ivf_frame_header() for documentation on the frame header
00277              * layout.
00278              */
00279             if(fread(junk, 1, IVF_FRAME_HDR_SZ, f));
00280         }
00281 
00282         for (plane = 0; plane < 3; plane++)
00283         {
00284             unsigned char *ptr;
00285             int w = (plane ? (1 + img->d_w) / 2 : img->d_w);
00286             int h = (plane ? (1 + img->d_h) / 2 : img->d_h);
00287             int r;
00288 
00289             /* Determine the correct plane based on the image format. The for-loop
00290              * always counts in Y,U,V order, but this may not match the order of
00291              * the data on disk.
00292              */
00293             switch (plane)
00294             {
00295             case 1:
00296                 ptr = img->planes[img->fmt==VPX_IMG_FMT_YV12? VPX_PLANE_V : VPX_PLANE_U];
00297                 break;
00298             case 2:
00299                 ptr = img->planes[img->fmt==VPX_IMG_FMT_YV12?VPX_PLANE_U : VPX_PLANE_V];
00300                 break;
00301             default:
00302                 ptr = img->planes[plane];
00303             }
00304 
00305             for (r = 0; r < h; r++)
00306             {
00307                 if (detect->valid)
00308                 {
00309                     memcpy(ptr, detect->buf, 4);
00310                     shortread |= fread(ptr+4, 1, w-4, f) < w-4;
00311                     detect->valid = 0;
00312                 }
00313                 else
00314                     shortread |= fread(ptr, 1, w, f) < w;
00315 
00316                 ptr += img->stride[plane];
00317             }
00318         }
00319     }
00320 
00321     return !shortread;
00322 }
00323 
00324 
00325 unsigned int file_is_y4m(FILE      *infile,
00326                          y4m_input *y4m,
00327                          char       detect[4])
00328 {
00329     if(memcmp(detect, "YUV4", 4) == 0)
00330     {
00331         return 1;
00332     }
00333     return 0;
00334 }
00335 
00336 #define IVF_FILE_HDR_SZ (32)
00337 unsigned int file_is_ivf(FILE *infile,
00338                          unsigned int *fourcc,
00339                          unsigned int *width,
00340                          unsigned int *height,
00341                          char          detect[4])
00342 {
00343     char raw_hdr[IVF_FILE_HDR_SZ];
00344     int is_ivf = 0;
00345 
00346     if(memcmp(detect, "DKIF", 4) != 0)
00347         return 0;
00348 
00349     /* See write_ivf_file_header() for more documentation on the file header
00350      * layout.
00351      */
00352     if (fread(raw_hdr + 4, 1, IVF_FILE_HDR_SZ - 4, infile)
00353         == IVF_FILE_HDR_SZ - 4)
00354     {
00355         {
00356             is_ivf = 1;
00357 
00358             if (mem_get_le16(raw_hdr + 4) != 0)
00359                 fprintf(stderr, "Error: Unrecognized IVF version! This file may not"
00360                         " decode properly.");
00361 
00362             *fourcc = mem_get_le32(raw_hdr + 8);
00363         }
00364     }
00365 
00366     if (is_ivf)
00367     {
00368         *width = mem_get_le16(raw_hdr + 12);
00369         *height = mem_get_le16(raw_hdr + 14);
00370     }
00371 
00372     return is_ivf;
00373 }
00374 
00375 
00376 static void write_ivf_file_header(FILE *outfile,
00377                                   const vpx_codec_enc_cfg_t *cfg,
00378                                   unsigned int fourcc,
00379                                   int frame_cnt)
00380 {
00381     char header[32];
00382 
00383     if (cfg->g_pass != VPX_RC_ONE_PASS && cfg->g_pass != VPX_RC_LAST_PASS)
00384         return;
00385 
00386     header[0] = 'D';
00387     header[1] = 'K';
00388     header[2] = 'I';
00389     header[3] = 'F';
00390     mem_put_le16(header + 4,  0);                 /* version */
00391     mem_put_le16(header + 6,  32);                /* headersize */
00392     mem_put_le32(header + 8,  fourcc);            /* headersize */
00393     mem_put_le16(header + 12, cfg->g_w);          /* width */
00394     mem_put_le16(header + 14, cfg->g_h);          /* height */
00395     mem_put_le32(header + 16, cfg->g_timebase.den); /* rate */
00396     mem_put_le32(header + 20, cfg->g_timebase.num); /* scale */
00397     mem_put_le32(header + 24, frame_cnt);         /* length */
00398     mem_put_le32(header + 28, 0);                 /* unused */
00399 
00400     if(fwrite(header, 1, 32, outfile));
00401 }
00402 
00403 
00404 static void write_ivf_frame_header(FILE *outfile,
00405                                    const vpx_codec_cx_pkt_t *pkt)
00406 {
00407     char             header[12];
00408     vpx_codec_pts_t  pts;
00409 
00410     if (pkt->kind != VPX_CODEC_CX_FRAME_PKT)
00411         return;
00412 
00413     pts = pkt->data.frame.pts;
00414     mem_put_le32(header, pkt->data.frame.sz);
00415     mem_put_le32(header + 4, pts & 0xFFFFFFFF);
00416     mem_put_le32(header + 8, pts >> 32);
00417 
00418     if(fwrite(header, 1, 12, outfile));
00419 }
00420 
00421 
00422 typedef off_t EbmlLoc;
00423 
00424 
00425 struct cue_entry
00426 {
00427     unsigned int time;
00428     uint64_t     loc;
00429 };
00430 
00431 
00432 struct EbmlGlobal
00433 {
00434     int debug;
00435 
00436     FILE    *stream;
00437     uint64_t last_pts_ms;
00438     vpx_rational_t  framerate;
00439 
00440     /* These pointers are to the start of an element */
00441     off_t    position_reference;
00442     off_t    seek_info_pos;
00443     off_t    segment_info_pos;
00444     off_t    track_pos;
00445     off_t    cue_pos;
00446     off_t    cluster_pos;
00447 
00448     /* This pointer is to a specific element to be serialized */
00449     off_t    track_id_pos;
00450 
00451     /* These pointers are to the size field of the element */
00452     EbmlLoc  startSegment;
00453     EbmlLoc  startCluster;
00454 
00455     uint32_t cluster_timecode;
00456     int      cluster_open;
00457 
00458     struct cue_entry *cue_list;
00459     unsigned int      cues;
00460 
00461 };
00462 
00463 
00464 void Ebml_Write(EbmlGlobal *glob, const void *buffer_in, unsigned long len)
00465 {
00466     if(fwrite(buffer_in, 1, len, glob->stream));
00467 }
00468 
00469 
00470 void Ebml_Serialize(EbmlGlobal *glob, const void *buffer_in, unsigned long len)
00471 {
00472     const unsigned char *q = (const unsigned char *)buffer_in + len - 1;
00473 
00474     for(; len; len--)
00475         Ebml_Write(glob, q--, 1);
00476 }
00477 
00478 
00479 /* Need a fixed size serializer for the track ID. libmkv provdes a 64 bit
00480  * one, but not a 32 bit one.
00481  */
00482 static void Ebml_SerializeUnsigned32(EbmlGlobal *glob, unsigned long class_id, uint64_t ui)
00483 {
00484     unsigned char sizeSerialized = 4 | 0x80;
00485     Ebml_WriteID(glob, class_id);
00486     Ebml_Serialize(glob, &sizeSerialized, 1);
00487     Ebml_Serialize(glob, &ui, 4);
00488 }
00489 
00490 
00491 static void
00492 Ebml_StartSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc,
00493                           unsigned long class_id)
00494 {
00495     //todo this is always taking 8 bytes, this may need later optimization
00496     //this is a key that says lenght unknown
00497     unsigned long long unknownLen =  LITERALU64(0x01FFFFFFFFFFFFFF);
00498 
00499     Ebml_WriteID(glob, class_id);
00500     *ebmlLoc = ftello(glob->stream);
00501     Ebml_Serialize(glob, &unknownLen, 8);
00502 }
00503 
00504 static void
00505 Ebml_EndSubElement(EbmlGlobal *glob, EbmlLoc *ebmlLoc)
00506 {
00507     off_t pos;
00508     uint64_t size;
00509 
00510     /* Save the current stream pointer */
00511     pos = ftello(glob->stream);
00512 
00513     /* Calculate the size of this element */
00514     size = pos - *ebmlLoc - 8;
00515     size |=  LITERALU64(0x0100000000000000);
00516 
00517     /* Seek back to the beginning of the element and write the new size */
00518     fseeko(glob->stream, *ebmlLoc, SEEK_SET);
00519     Ebml_Serialize(glob, &size, 8);
00520 
00521     /* Reset the stream pointer */
00522     fseeko(glob->stream, pos, SEEK_SET);
00523 }
00524 
00525 
00526 static void
00527 write_webm_seek_element(EbmlGlobal *ebml, unsigned long id, off_t pos)
00528 {
00529     uint64_t offset = pos - ebml->position_reference;
00530     EbmlLoc start;
00531     Ebml_StartSubElement(ebml, &start, Seek);
00532     Ebml_SerializeBinary(ebml, SeekID, id);
00533     Ebml_SerializeUnsigned64(ebml, SeekPosition, offset);
00534     Ebml_EndSubElement(ebml, &start);
00535 }
00536 
00537 
00538 static void
00539 write_webm_seek_info(EbmlGlobal *ebml)
00540 {
00541 
00542     off_t pos;
00543 
00544     /* Save the current stream pointer */
00545     pos = ftello(ebml->stream);
00546 
00547     if(ebml->seek_info_pos)
00548         fseeko(ebml->stream, ebml->seek_info_pos, SEEK_SET);
00549     else
00550         ebml->seek_info_pos = pos;
00551 
00552     {
00553         EbmlLoc start;
00554 
00555         Ebml_StartSubElement(ebml, &start, SeekHead);
00556         write_webm_seek_element(ebml, Tracks, ebml->track_pos);
00557         write_webm_seek_element(ebml, Cues,   ebml->cue_pos);
00558         write_webm_seek_element(ebml, Info,   ebml->segment_info_pos);
00559         Ebml_EndSubElement(ebml, &start);
00560     }
00561     {
00562         //segment info
00563         EbmlLoc startInfo;
00564         uint64_t frame_time;
00565 
00566         frame_time = (uint64_t)1000 * ebml->framerate.den
00567                      / ebml->framerate.num;
00568         ebml->segment_info_pos = ftello(ebml->stream);
00569         Ebml_StartSubElement(ebml, &startInfo, Info);
00570         Ebml_SerializeUnsigned(ebml, TimecodeScale, 1000000);
00571         Ebml_SerializeFloat(ebml, Segment_Duration,
00572                             ebml->last_pts_ms + frame_time);
00573         Ebml_SerializeString(ebml, 0x4D80,
00574             ebml->debug ? "vpxenc" : "vpxenc" VERSION_STRING);
00575         Ebml_SerializeString(ebml, 0x5741,
00576             ebml->debug ? "vpxenc" : "vpxenc" VERSION_STRING);
00577         Ebml_EndSubElement(ebml, &startInfo);
00578     }
00579 }
00580 
00581 
00582 static void
00583 write_webm_file_header(EbmlGlobal                *glob,
00584                        const vpx_codec_enc_cfg_t *cfg,
00585                        const struct vpx_rational *fps)
00586 {
00587     {
00588         EbmlLoc start;
00589         Ebml_StartSubElement(glob, &start, EBML);
00590         Ebml_SerializeUnsigned(glob, EBMLVersion, 1);
00591         Ebml_SerializeUnsigned(glob, EBMLReadVersion, 1); //EBML Read Version
00592         Ebml_SerializeUnsigned(glob, EBMLMaxIDLength, 4); //EBML Max ID Length
00593         Ebml_SerializeUnsigned(glob, EBMLMaxSizeLength, 8); //EBML Max Size Length
00594         Ebml_SerializeString(glob, DocType, "webm"); //Doc Type
00595         Ebml_SerializeUnsigned(glob, DocTypeVersion, 2); //Doc Type Version
00596         Ebml_SerializeUnsigned(glob, DocTypeReadVersion, 2); //Doc Type Read Version
00597         Ebml_EndSubElement(glob, &start);
00598     }
00599     {
00600         Ebml_StartSubElement(glob, &glob->startSegment, Segment); //segment
00601         glob->position_reference = ftello(glob->stream);
00602         glob->framerate = *fps;
00603         write_webm_seek_info(glob);
00604 
00605         {
00606             EbmlLoc trackStart;
00607             glob->track_pos = ftello(glob->stream);
00608             Ebml_StartSubElement(glob, &trackStart, Tracks);
00609             {
00610                 unsigned int trackNumber = 1;
00611                 uint64_t     trackID = 0;
00612 
00613                 EbmlLoc start;
00614                 Ebml_StartSubElement(glob, &start, TrackEntry);
00615                 Ebml_SerializeUnsigned(glob, TrackNumber, trackNumber);
00616                 glob->track_id_pos = ftello(glob->stream);
00617                 Ebml_SerializeUnsigned32(glob, TrackUID, trackID);
00618                 Ebml_SerializeUnsigned(glob, TrackType, 1); //video is always 1
00619                 Ebml_SerializeString(glob, CodecID, "V_VP8");
00620                 {
00621                     unsigned int pixelWidth = cfg->g_w;
00622                     unsigned int pixelHeight = cfg->g_h;
00623                     float        frameRate   = (float)fps->num/(float)fps->den;
00624 
00625                     EbmlLoc videoStart;
00626                     Ebml_StartSubElement(glob, &videoStart, Video);
00627                     Ebml_SerializeUnsigned(glob, PixelWidth, pixelWidth);
00628                     Ebml_SerializeUnsigned(glob, PixelHeight, pixelHeight);
00629                     Ebml_SerializeFloat(glob, FrameRate, frameRate);
00630                     Ebml_EndSubElement(glob, &videoStart); //Video
00631                 }
00632                 Ebml_EndSubElement(glob, &start); //Track Entry
00633             }
00634             Ebml_EndSubElement(glob, &trackStart);
00635         }
00636         // segment element is open
00637     }
00638 }
00639 
00640 
00641 static void
00642 write_webm_block(EbmlGlobal                *glob,
00643                  const vpx_codec_enc_cfg_t *cfg,
00644                  const vpx_codec_cx_pkt_t  *pkt)
00645 {
00646     unsigned long  block_length;
00647     unsigned char  track_number;
00648     unsigned short block_timecode = 0;
00649     unsigned char  flags;
00650     uint64_t       pts_ms;
00651     int            start_cluster = 0, is_keyframe;
00652 
00653     /* Calculate the PTS of this frame in milliseconds */
00654     pts_ms = pkt->data.frame.pts * 1000
00655              * (uint64_t)cfg->g_timebase.num / (uint64_t)cfg->g_timebase.den;
00656     if(pts_ms <= glob->last_pts_ms)
00657         pts_ms = glob->last_pts_ms + 1;
00658     glob->last_pts_ms = pts_ms;
00659 
00660     /* Calculate the relative time of this block */
00661     if(pts_ms - glob->cluster_timecode > SHRT_MAX)
00662         start_cluster = 1;
00663     else
00664         block_timecode = pts_ms - glob->cluster_timecode;
00665 
00666     is_keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY);
00667     if(start_cluster || is_keyframe)
00668     {
00669         if(glob->cluster_open)
00670             Ebml_EndSubElement(glob, &glob->startCluster);
00671 
00672         /* Open the new cluster */
00673         block_timecode = 0;
00674         glob->cluster_open = 1;
00675         glob->cluster_timecode = pts_ms;
00676         glob->cluster_pos = ftello(glob->stream);
00677         Ebml_StartSubElement(glob, &glob->startCluster, Cluster); //cluster
00678         Ebml_SerializeUnsigned(glob, Timecode, glob->cluster_timecode);
00679 
00680         /* Save a cue point if this is a keyframe. */
00681         if(is_keyframe)
00682         {
00683             struct cue_entry *cue;
00684 
00685             glob->cue_list = realloc(glob->cue_list,
00686                                      (glob->cues+1) * sizeof(struct cue_entry));
00687             cue = &glob->cue_list[glob->cues];
00688             cue->time = glob->cluster_timecode;
00689             cue->loc = glob->cluster_pos;
00690             glob->cues++;
00691         }
00692     }
00693 
00694     /* Write the Simple Block */
00695     Ebml_WriteID(glob, SimpleBlock);
00696 
00697     block_length = pkt->data.frame.sz + 4;
00698     block_length |= 0x10000000;
00699     Ebml_Serialize(glob, &block_length, 4);
00700 
00701     track_number = 1;
00702     track_number |= 0x80;
00703     Ebml_Write(glob, &track_number, 1);
00704 
00705     Ebml_Serialize(glob, &block_timecode, 2);
00706 
00707     flags = 0;
00708     if(is_keyframe)
00709         flags |= 0x80;
00710     if(pkt->data.frame.flags & VPX_FRAME_IS_INVISIBLE)
00711         flags |= 0x08;
00712     Ebml_Write(glob, &flags, 1);
00713 
00714     Ebml_Write(glob, pkt->data.frame.buf, pkt->data.frame.sz);
00715 }
00716 
00717 
00718 static void
00719 write_webm_file_footer(EbmlGlobal *glob, long hash)
00720 {
00721 
00722     if(glob->cluster_open)
00723         Ebml_EndSubElement(glob, &glob->startCluster);
00724 
00725     {
00726         EbmlLoc start;
00727         int i;
00728 
00729         glob->cue_pos = ftello(glob->stream);
00730         Ebml_StartSubElement(glob, &start, Cues);
00731         for(i=0; i<glob->cues; i++)
00732         {
00733             struct cue_entry *cue = &glob->cue_list[i];
00734             EbmlLoc start;
00735 
00736             Ebml_StartSubElement(glob, &start, CuePoint);
00737             {
00738                 EbmlLoc start;
00739 
00740                 Ebml_SerializeUnsigned(glob, CueTime, cue->time);
00741 
00742                 Ebml_StartSubElement(glob, &start, CueTrackPositions);
00743                 Ebml_SerializeUnsigned(glob, CueTrack, 1);
00744                 Ebml_SerializeUnsigned64(glob, CueClusterPosition,
00745                                          cue->loc - glob->position_reference);
00746                 //Ebml_SerializeUnsigned(glob, CueBlockNumber, cue->blockNumber);
00747                 Ebml_EndSubElement(glob, &start);
00748             }
00749             Ebml_EndSubElement(glob, &start);
00750         }
00751         Ebml_EndSubElement(glob, &start);
00752     }
00753 
00754     Ebml_EndSubElement(glob, &glob->startSegment);
00755 
00756     /* Patch up the seek info block */
00757     write_webm_seek_info(glob);
00758 
00759     /* Patch up the track id */
00760     fseeko(glob->stream, glob->track_id_pos, SEEK_SET);
00761     Ebml_SerializeUnsigned32(glob, TrackUID, glob->debug ? 0xDEADBEEF : hash);
00762 
00763     fseeko(glob->stream, 0, SEEK_END);
00764 }
00765 
00766 
00767 /* Murmur hash derived from public domain reference implementation at
00768  *   http://sites.google.com/site/murmurhash/
00769  */
00770 static unsigned int murmur ( const void * key, int len, unsigned int seed )
00771 {
00772     const unsigned int m = 0x5bd1e995;
00773     const int r = 24;
00774 
00775     unsigned int h = seed ^ len;
00776 
00777     const unsigned char * data = (const unsigned char *)key;
00778 
00779     while(len >= 4)
00780     {
00781         unsigned int k;
00782 
00783         k  = data[0];
00784         k |= data[1] << 8;
00785         k |= data[2] << 16;
00786         k |= data[3] << 24;
00787 
00788         k *= m;
00789         k ^= k >> r;
00790         k *= m;
00791 
00792         h *= m;
00793         h ^= k;
00794 
00795         data += 4;
00796         len -= 4;
00797     }
00798 
00799     switch(len)
00800     {
00801     case 3: h ^= data[2] << 16;
00802     case 2: h ^= data[1] << 8;
00803     case 1: h ^= data[0];
00804             h *= m;
00805     };
00806 
00807     h ^= h >> 13;
00808     h *= m;
00809     h ^= h >> 15;
00810 
00811     return h;
00812 }
00813 
00814 #include "math.h"
00815 
00816 static double vp8_mse2psnr(double Samples, double Peak, double Mse)
00817 {
00818     double psnr;
00819 
00820     if ((double)Mse > 0.0)
00821         psnr = 10.0 * log10(Peak * Peak * Samples / Mse);
00822     else
00823         psnr = 60;      // Limit to prevent / 0
00824 
00825     if (psnr > 60)
00826         psnr = 60;
00827 
00828     return psnr;
00829 }
00830 
00831 
00832 #include "args.h"
00833 
00834 static const arg_def_t debugmode = ARG_DEF("D", "debug", 0,
00835         "Debug mode (makes output deterministic)");
00836 static const arg_def_t outputfile = ARG_DEF("o", "output", 1,
00837         "Output filename");
00838 static const arg_def_t use_yv12 = ARG_DEF(NULL, "yv12", 0,
00839                                   "Input file is YV12 ");
00840 static const arg_def_t use_i420 = ARG_DEF(NULL, "i420", 0,
00841                                   "Input file is I420 (default)");
00842 static const arg_def_t codecarg = ARG_DEF(NULL, "codec", 1,
00843                                   "Codec to use");
00844 static const arg_def_t passes           = ARG_DEF("p", "passes", 1,
00845         "Number of passes (1/2)");
00846 static const arg_def_t pass_arg         = ARG_DEF(NULL, "pass", 1,
00847         "Pass to execute (1/2)");
00848 static const arg_def_t fpf_name         = ARG_DEF(NULL, "fpf", 1,
00849         "First pass statistics file name");
00850 static const arg_def_t limit = ARG_DEF(NULL, "limit", 1,
00851                                        "Stop encoding after n input frames");
00852 static const arg_def_t deadline         = ARG_DEF("d", "deadline", 1,
00853         "Deadline per frame (usec)");
00854 static const arg_def_t best_dl          = ARG_DEF(NULL, "best", 0,
00855         "Use Best Quality Deadline");
00856 static const arg_def_t good_dl          = ARG_DEF(NULL, "good", 0,
00857         "Use Good Quality Deadline");
00858 static const arg_def_t rt_dl            = ARG_DEF(NULL, "rt", 0,
00859         "Use Realtime Quality Deadline");
00860 static const arg_def_t verbosearg       = ARG_DEF("v", "verbose", 0,
00861         "Show encoder parameters");
00862 static const arg_def_t psnrarg          = ARG_DEF(NULL, "psnr", 0,
00863         "Show PSNR in status line");
00864 static const arg_def_t framerate        = ARG_DEF(NULL, "fps", 1,
00865         "Stream frame rate (rate/scale)");
00866 static const arg_def_t use_ivf          = ARG_DEF(NULL, "ivf", 0,
00867         "Output IVF (default is WebM)");
00868 static const arg_def_t *main_args[] =
00869 {
00870     &debugmode,
00871     &outputfile, &codecarg, &passes, &pass_arg, &fpf_name, &limit, &deadline,
00872     &best_dl, &good_dl, &rt_dl,
00873     &verbosearg, &psnrarg, &use_ivf, &framerate,
00874     NULL
00875 };
00876 
00877 static const arg_def_t usage            = ARG_DEF("u", "usage", 1,
00878         "Usage profile number to use");
00879 static const arg_def_t threads          = ARG_DEF("t", "threads", 1,
00880         "Max number of threads to use");
00881 static const arg_def_t profile          = ARG_DEF(NULL, "profile", 1,
00882         "Bitstream profile number to use");
00883 static const arg_def_t width            = ARG_DEF("w", "width", 1,
00884         "Frame width");
00885 static const arg_def_t height           = ARG_DEF("h", "height", 1,
00886         "Frame height");
00887 static const arg_def_t timebase         = ARG_DEF(NULL, "timebase", 1,
00888         "Stream timebase (frame duration)");
00889 static const arg_def_t error_resilient  = ARG_DEF(NULL, "error-resilient", 1,
00890         "Enable error resiliency features");
00891 static const arg_def_t lag_in_frames    = ARG_DEF(NULL, "lag-in-frames", 1,
00892         "Max number of frames to lag");
00893 
00894 static const arg_def_t *global_args[] =
00895 {
00896     &use_yv12, &use_i420, &usage, &threads, &profile,
00897     &width, &height, &timebase, &framerate, &error_resilient,
00898     &lag_in_frames, NULL
00899 };
00900 
00901 static const arg_def_t dropframe_thresh   = ARG_DEF(NULL, "drop-frame", 1,
00902         "Temporal resampling threshold (buf %)");
00903 static const arg_def_t resize_allowed     = ARG_DEF(NULL, "resize-allowed", 1,
00904         "Spatial resampling enabled (bool)");
00905 static const arg_def_t resize_up_thresh   = ARG_DEF(NULL, "resize-up", 1,
00906         "Upscale threshold (buf %)");
00907 static const arg_def_t resize_down_thresh = ARG_DEF(NULL, "resize-down", 1,
00908         "Downscale threshold (buf %)");
00909 static const arg_def_t end_usage          = ARG_DEF(NULL, "end-usage", 1,
00910         "VBR=0 | CBR=1");
00911 static const arg_def_t target_bitrate     = ARG_DEF(NULL, "target-bitrate", 1,
00912         "Bitrate (kbps)");
00913 static const arg_def_t min_quantizer      = ARG_DEF(NULL, "min-q", 1,
00914         "Minimum (best) quantizer");
00915 static const arg_def_t max_quantizer      = ARG_DEF(NULL, "max-q", 1,
00916         "Maximum (worst) quantizer");
00917 static const arg_def_t undershoot_pct     = ARG_DEF(NULL, "undershoot-pct", 1,
00918         "Datarate undershoot (min) target (%)");
00919 static const arg_def_t overshoot_pct      = ARG_DEF(NULL, "overshoot-pct", 1,
00920         "Datarate overshoot (max) target (%)");
00921 static const arg_def_t buf_sz             = ARG_DEF(NULL, "buf-sz", 1,
00922         "Client buffer size (ms)");
00923 static const arg_def_t buf_initial_sz     = ARG_DEF(NULL, "buf-initial-sz", 1,
00924         "Client initial buffer size (ms)");
00925 static const arg_def_t buf_optimal_sz     = ARG_DEF(NULL, "buf-optimal-sz", 1,
00926         "Client optimal buffer size (ms)");
00927 static const arg_def_t *rc_args[] =
00928 {
00929     &dropframe_thresh, &resize_allowed, &resize_up_thresh, &resize_down_thresh,
00930     &end_usage, &target_bitrate, &min_quantizer, &max_quantizer,
00931     &undershoot_pct, &overshoot_pct, &buf_sz, &buf_initial_sz, &buf_optimal_sz,
00932     NULL
00933 };
00934 
00935 
00936 static const arg_def_t bias_pct = ARG_DEF(NULL, "bias-pct", 1,
00937                                   "CBR/VBR bias (0=CBR, 100=VBR)");
00938 static const arg_def_t minsection_pct = ARG_DEF(NULL, "minsection-pct", 1,
00939                                         "GOP min bitrate (% of target)");
00940 static const arg_def_t maxsection_pct = ARG_DEF(NULL, "maxsection-pct", 1,
00941                                         "GOP max bitrate (% of target)");
00942 static const arg_def_t *rc_twopass_args[] =
00943 {
00944     &bias_pct, &minsection_pct, &maxsection_pct, NULL
00945 };
00946 
00947 
00948 static const arg_def_t kf_min_dist = ARG_DEF(NULL, "kf-min-dist", 1,
00949                                      "Minimum keyframe interval (frames)");
00950 static const arg_def_t kf_max_dist = ARG_DEF(NULL, "kf-max-dist", 1,
00951                                      "Maximum keyframe interval (frames)");
00952 static const arg_def_t kf_disabled = ARG_DEF(NULL, "disable-kf", 0,
00953                                      "Disable keyframe placement");
00954 static const arg_def_t *kf_args[] =
00955 {
00956     &kf_min_dist, &kf_max_dist, &kf_disabled, NULL
00957 };
00958 
00959 
00960 #if CONFIG_VP8_ENCODER
00961 static const arg_def_t noise_sens = ARG_DEF(NULL, "noise-sensitivity", 1,
00962                                     "Noise sensitivity (frames to blur)");
00963 static const arg_def_t sharpness = ARG_DEF(NULL, "sharpness", 1,
00964                                    "Filter sharpness (0-7)");
00965 static const arg_def_t static_thresh = ARG_DEF(NULL, "static-thresh", 1,
00966                                        "Motion detection threshold");
00967 #endif
00968 
00969 #if CONFIG_VP8_ENCODER
00970 static const arg_def_t cpu_used = ARG_DEF(NULL, "cpu-used", 1,
00971                                   "CPU Used (-16..16)");
00972 #endif
00973 
00974 
00975 #if CONFIG_VP8_ENCODER
00976 static const arg_def_t token_parts = ARG_DEF(NULL, "token-parts", 1,
00977                                      "Number of token partitions to use, log2");
00978 static const arg_def_t auto_altref = ARG_DEF(NULL, "auto-alt-ref", 1,
00979                                      "Enable automatic alt reference frames");
00980 static const arg_def_t arnr_maxframes = ARG_DEF(NULL, "arnr-maxframes", 1,
00981                                         "alt_ref Max Frames");
00982 static const arg_def_t arnr_strength = ARG_DEF(NULL, "arnr-strength", 1,
00983                                        "alt_ref Strength");
00984 static const arg_def_t arnr_type = ARG_DEF(NULL, "arnr-type", 1,
00985                                    "alt_ref Type");
00986 
00987 static const arg_def_t *vp8_args[] =
00988 {
00989     &cpu_used, &auto_altref, &noise_sens, &sharpness, &static_thresh,
00990     &token_parts, &arnr_maxframes, &arnr_strength, &arnr_type, NULL
00991 };
00992 static const int vp8_arg_ctrl_map[] =
00993 {
00994     VP8E_SET_CPUUSED, VP8E_SET_ENABLEAUTOALTREF,
00995     VP8E_SET_NOISE_SENSITIVITY, VP8E_SET_SHARPNESS, VP8E_SET_STATIC_THRESHOLD,
00996     VP8E_SET_TOKEN_PARTITIONS,
00997     VP8E_SET_ARNR_MAXFRAMES, VP8E_SET_ARNR_STRENGTH , VP8E_SET_ARNR_TYPE, 0
00998 };
00999 #endif
01000 
01001 static const arg_def_t *no_args[] = { NULL };
01002 
01003 static void usage_exit()
01004 {
01005     int i;
01006 
01007     fprintf(stderr, "Usage: %s <options> -o dst_filename src_filename \n",
01008             exec_name);
01009 
01010     fprintf(stderr, "\nOptions:\n");
01011     arg_show_usage(stdout, main_args);
01012     fprintf(stderr, "\nEncoder Global Options:\n");
01013     arg_show_usage(stdout, global_args);
01014     fprintf(stderr, "\nRate Control Options:\n");
01015     arg_show_usage(stdout, rc_args);
01016     fprintf(stderr, "\nTwopass Rate Control Options:\n");
01017     arg_show_usage(stdout, rc_twopass_args);
01018     fprintf(stderr, "\nKeyframe Placement Options:\n");
01019     arg_show_usage(stdout, kf_args);
01020 #if CONFIG_VP8_ENCODER
01021     fprintf(stderr, "\nVP8 Specific Options:\n");
01022     arg_show_usage(stdout, vp8_args);
01023 #endif
01024     fprintf(stderr, "\n"
01025            "Included encoders:\n"
01026            "\n");
01027 
01028     for (i = 0; i < sizeof(codecs) / sizeof(codecs[0]); i++)
01029         fprintf(stderr, "    %-6s - %s\n",
01030                codecs[i].name,
01031                vpx_codec_iface_name(codecs[i].iface));
01032 
01033     exit(EXIT_FAILURE);
01034 }
01035 
01036 #define ARG_CTRL_CNT_MAX 10
01037 
01038 
01039 int main(int argc, const char **argv_)
01040 {
01041     vpx_codec_ctx_t        encoder;
01042     const char                  *in_fn = NULL, *out_fn = NULL, *stats_fn = NULL;
01043     int                    i;
01044     FILE                  *infile, *outfile;
01045     vpx_codec_enc_cfg_t    cfg;
01046     vpx_codec_err_t        res;
01047     int                    pass, one_pass_only = 0;
01048     stats_io_t             stats;
01049     vpx_image_t            raw;
01050     const struct codec_item  *codec = codecs;
01051     int                    frame_avail, got_data;
01052 
01053     struct arg               arg;
01054     char                   **argv, **argi, **argj;
01055     int                      arg_usage = 0, arg_passes = 1, arg_deadline = 0;
01056     int                      arg_ctrls[ARG_CTRL_CNT_MAX][2], arg_ctrl_cnt = 0;
01057     int                      arg_limit = 0;
01058     static const arg_def_t **ctrl_args = no_args;
01059     static const int        *ctrl_args_map = NULL;
01060     int                      verbose = 0, show_psnr = 0;
01061     int                      arg_use_i420 = 1;
01062     unsigned long            cx_time = 0;
01063     unsigned int             file_type, fourcc;
01064     y4m_input                y4m;
01065     struct vpx_rational      arg_framerate = {30, 1};
01066     int                      arg_have_framerate = 0;
01067     int                      write_webm = 1;
01068     EbmlGlobal               ebml = {0};
01069     uint32_t                 hash = 0;
01070     uint64_t                 psnr_sse_total = 0;
01071     uint64_t                 psnr_samples_total = 0;
01072     double                   psnr_totals[4] = {0, 0, 0, 0};
01073     int                      psnr_count = 0;
01074 
01075     exec_name = argv_[0];
01076 
01077     if (argc < 3)
01078         usage_exit();
01079 
01080 
01081     /* First parse the codec and usage values, because we want to apply other
01082      * parameters on top of the default configuration provided by the codec.
01083      */
01084     argv = argv_dup(argc - 1, argv_ + 1);
01085 
01086     for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
01087     {
01088         arg.argv_step = 1;
01089 
01090         if (arg_match(&arg, &codecarg, argi))
01091         {
01092             int j, k = -1;
01093 
01094             for (j = 0; j < sizeof(codecs) / sizeof(codecs[0]); j++)
01095                 if (!strcmp(codecs[j].name, arg.val))
01096                     k = j;
01097 
01098             if (k >= 0)
01099                 codec = codecs + k;
01100             else
01101                 die("Error: Unrecognized argument (%s) to --codec\n",
01102                     arg.val);
01103 
01104         }
01105         else if (arg_match(&arg, &passes, argi))
01106         {
01107             arg_passes = arg_parse_uint(&arg);
01108 
01109             if (arg_passes < 1 || arg_passes > 2)
01110                 die("Error: Invalid number of passes (%d)\n", arg_passes);
01111         }
01112         else if (arg_match(&arg, &pass_arg, argi))
01113         {
01114             one_pass_only = arg_parse_uint(&arg);
01115 
01116             if (one_pass_only < 1 || one_pass_only > 2)
01117                 die("Error: Invalid pass selected (%d)\n", one_pass_only);
01118         }
01119         else if (arg_match(&arg, &fpf_name, argi))
01120             stats_fn = arg.val;
01121         else if (arg_match(&arg, &usage, argi))
01122             arg_usage = arg_parse_uint(&arg);
01123         else if (arg_match(&arg, &deadline, argi))
01124             arg_deadline = arg_parse_uint(&arg);
01125         else if (arg_match(&arg, &best_dl, argi))
01126             arg_deadline = VPX_DL_BEST_QUALITY;
01127         else if (arg_match(&arg, &good_dl, argi))
01128             arg_deadline = VPX_DL_GOOD_QUALITY;
01129         else if (arg_match(&arg, &rt_dl, argi))
01130             arg_deadline = VPX_DL_REALTIME;
01131         else if (arg_match(&arg, &use_yv12, argi))
01132         {
01133             arg_use_i420 = 0;
01134         }
01135         else if (arg_match(&arg, &use_i420, argi))
01136         {
01137             arg_use_i420 = 1;
01138         }
01139         else if (arg_match(&arg, &verbosearg, argi))
01140             verbose = 1;
01141         else if (arg_match(&arg, &limit, argi))
01142             arg_limit = arg_parse_uint(&arg);
01143         else if (arg_match(&arg, &psnrarg, argi))
01144             show_psnr = 1;
01145         else if (arg_match(&arg, &framerate, argi))
01146         {
01147             arg_framerate = arg_parse_rational(&arg);
01148             arg_have_framerate = 1;
01149         }
01150         else if (arg_match(&arg, &use_ivf, argi))
01151             write_webm = 0;
01152         else if (arg_match(&arg, &outputfile, argi))
01153             out_fn = arg.val;
01154         else if (arg_match(&arg, &debugmode, argi))
01155             ebml.debug = 1;
01156         else
01157             argj++;
01158     }
01159 
01160     /* Ensure that --passes and --pass are consistent. If --pass is set and --passes=2,
01161      * ensure --fpf was set.
01162      */
01163     if (one_pass_only)
01164     {
01165         /* DWIM: Assume the user meant passes=2 if pass=2 is specified */
01166         if (one_pass_only > arg_passes)
01167         {
01168             fprintf(stderr, "Warning: Assuming --pass=%d implies --passes=%d\n",
01169                    one_pass_only, one_pass_only);
01170             arg_passes = one_pass_only;
01171         }
01172 
01173         if (arg_passes == 2 && !stats_fn)
01174             die("Must specify --fpf when --pass=%d and --passes=2\n", one_pass_only);
01175     }
01176 
01177     /* Populate encoder configuration */
01178     res = vpx_codec_enc_config_default(codec->iface, &cfg, arg_usage);
01179 
01180     if (res)
01181     {
01182         fprintf(stderr, "Failed to get config: %s\n",
01183                 vpx_codec_err_to_string(res));
01184         return EXIT_FAILURE;
01185     }
01186 
01187     /* Change the default timebase to a high enough value so that the encoder
01188      * will always create strictly increasing timestamps.
01189      */
01190     cfg.g_timebase.den = 1000;
01191 
01192     /* Now parse the remainder of the parameters. */
01193     for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
01194     {
01195         arg.argv_step = 1;
01196 
01197         if (0);
01198         else if (arg_match(&arg, &threads, argi))
01199             cfg.g_threads = arg_parse_uint(&arg);
01200         else if (arg_match(&arg, &profile, argi))
01201             cfg.g_profile = arg_parse_uint(&arg);
01202         else if (arg_match(&arg, &width, argi))
01203             cfg.g_w = arg_parse_uint(&arg);
01204         else if (arg_match(&arg, &height, argi))
01205             cfg.g_h = arg_parse_uint(&arg);
01206         else if (arg_match(&arg, &timebase, argi))
01207             cfg.g_timebase = arg_parse_rational(&arg);
01208         else if (arg_match(&arg, &error_resilient, argi))
01209             cfg.g_error_resilient = arg_parse_uint(&arg);
01210         else if (arg_match(&arg, &lag_in_frames, argi))
01211             cfg.g_lag_in_frames = arg_parse_uint(&arg);
01212         else if (arg_match(&arg, &dropframe_thresh, argi))
01213             cfg.rc_dropframe_thresh = arg_parse_uint(&arg);
01214         else if (arg_match(&arg, &resize_allowed, argi))
01215             cfg.rc_resize_allowed = arg_parse_uint(&arg);
01216         else if (arg_match(&arg, &resize_up_thresh, argi))
01217             cfg.rc_resize_up_thresh = arg_parse_uint(&arg);
01218         else if (arg_match(&arg, &resize_down_thresh, argi))
01219             cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
01220         else if (arg_match(&arg, &resize_down_thresh, argi))
01221             cfg.rc_resize_down_thresh = arg_parse_uint(&arg);
01222         else if (arg_match(&arg, &end_usage, argi))
01223             cfg.rc_end_usage = arg_parse_uint(&arg);
01224         else if (arg_match(&arg, &target_bitrate, argi))
01225             cfg.rc_target_bitrate = arg_parse_uint(&arg);
01226         else if (arg_match(&arg, &min_quantizer, argi))
01227             cfg.rc_min_quantizer = arg_parse_uint(&arg);
01228         else if (arg_match(&arg, &max_quantizer, argi))
01229             cfg.rc_max_quantizer = arg_parse_uint(&arg);
01230         else if (arg_match(&arg, &undershoot_pct, argi))
01231             cfg.rc_undershoot_pct = arg_parse_uint(&arg);
01232         else if (arg_match(&arg, &overshoot_pct, argi))
01233             cfg.rc_overshoot_pct = arg_parse_uint(&arg);
01234         else if (arg_match(&arg, &buf_sz, argi))
01235             cfg.rc_buf_sz = arg_parse_uint(&arg);
01236         else if (arg_match(&arg, &buf_initial_sz, argi))
01237             cfg.rc_buf_initial_sz = arg_parse_uint(&arg);
01238         else if (arg_match(&arg, &buf_optimal_sz, argi))
01239             cfg.rc_buf_optimal_sz = arg_parse_uint(&arg);
01240         else if (arg_match(&arg, &bias_pct, argi))
01241         {
01242             cfg.rc_2pass_vbr_bias_pct = arg_parse_uint(&arg);
01243 
01244             if (arg_passes < 2)
01245                 fprintf(stderr,
01246                         "Warning: option %s ignored in one-pass mode.\n",
01247                         arg.name);
01248         }
01249         else if (arg_match(&arg, &minsection_pct, argi))
01250         {
01251             cfg.rc_2pass_vbr_minsection_pct = arg_parse_uint(&arg);
01252 
01253             if (arg_passes < 2)
01254                 fprintf(stderr,
01255                         "Warning: option %s ignored in one-pass mode.\n",
01256                         arg.name);
01257         }
01258         else if (arg_match(&arg, &maxsection_pct, argi))
01259         {
01260             cfg.rc_2pass_vbr_maxsection_pct = arg_parse_uint(&arg);
01261 
01262             if (arg_passes < 2)
01263                 fprintf(stderr,
01264                         "Warning: option %s ignored in one-pass mode.\n",
01265                         arg.name);
01266         }
01267         else if (arg_match(&arg, &kf_min_dist, argi))
01268             cfg.kf_min_dist = arg_parse_uint(&arg);
01269         else if (arg_match(&arg, &kf_max_dist, argi))
01270             cfg.kf_max_dist = arg_parse_uint(&arg);
01271         else if (arg_match(&arg, &kf_disabled, argi))
01272             cfg.kf_mode = VPX_KF_DISABLED;
01273         else
01274             argj++;
01275     }
01276 
01277     /* Handle codec specific options */
01278 #if CONFIG_VP8_ENCODER
01279 
01280     if (codec->iface == &vpx_codec_vp8_cx_algo)
01281     {
01282         ctrl_args = vp8_args;
01283         ctrl_args_map = vp8_arg_ctrl_map;
01284     }
01285 
01286 #endif
01287 
01288     for (argi = argj = argv; (*argj = *argi); argi += arg.argv_step)
01289     {
01290         int match = 0;
01291 
01292         arg.argv_step = 1;
01293 
01294         for (i = 0; ctrl_args[i]; i++)
01295         {
01296             if (arg_match(&arg, ctrl_args[i], argi))
01297             {
01298                 match = 1;
01299 
01300                 if (arg_ctrl_cnt < ARG_CTRL_CNT_MAX)
01301                 {
01302                     arg_ctrls[arg_ctrl_cnt][0] = ctrl_args_map[i];
01303                     arg_ctrls[arg_ctrl_cnt][1] = arg_parse_int(&arg);
01304                     arg_ctrl_cnt++;
01305                 }
01306             }
01307         }
01308 
01309         if (!match)
01310             argj++;
01311     }
01312 
01313     /* Check for unrecognized options */
01314     for (argi = argv; *argi; argi++)
01315         if (argi[0][0] == '-' && argi[0][1])
01316             die("Error: Unrecognized option %s\n", *argi);
01317 
01318     /* Handle non-option arguments */
01319     in_fn = argv[0];
01320 
01321     if (!in_fn)
01322         usage_exit();
01323 
01324     if(!out_fn)
01325         die("Error: Output file is required (specify with -o)\n");
01326 
01327     memset(&stats, 0, sizeof(stats));
01328 
01329     for (pass = one_pass_only ? one_pass_only - 1 : 0; pass < arg_passes; pass++)
01330     {
01331         int frames_in = 0, frames_out = 0;
01332         unsigned long nbytes = 0;
01333         size_t detect_bytes;
01334         struct detect_buffer detect;
01335 
01336         /* Parse certain options from the input file, if possible */
01337         infile = strcmp(in_fn, "-") ? fopen(in_fn, "rb") : stdin;
01338 
01339         if (!infile)
01340         {
01341             fprintf(stderr, "Failed to open input file\n");
01342             return EXIT_FAILURE;
01343         }
01344 
01345         /* For RAW input sources, these bytes will applied on the first frame
01346          *  in read_frame().
01347          * We can always read 4 bytes because the minimum supported frame size
01348          *  is 2x2.
01349          */
01350         detect_bytes = fread(detect.buf, 1, 4, infile);
01351         detect.valid = 0;
01352 
01353         if (detect_bytes == 4 && file_is_y4m(infile, &y4m, detect.buf))
01354         {
01355             if (y4m_input_open(&y4m, infile, detect.buf, 4) >= 0)
01356             {
01357                 file_type = FILE_TYPE_Y4M;
01358                 cfg.g_w = y4m.pic_w;
01359                 cfg.g_h = y4m.pic_h;
01360 
01361                 /* Use the frame rate from the file only if none was specified
01362                  * on the command-line.
01363                  */
01364                 if (!arg_have_framerate)
01365                 {
01366                     arg_framerate.num = y4m.fps_n;
01367                     arg_framerate.den = y4m.fps_d;
01368                 }
01369 
01370                 arg_use_i420 = 0;
01371             }
01372             else
01373             {
01374                 fprintf(stderr, "Unsupported Y4M stream.\n");
01375                 return EXIT_FAILURE;
01376             }
01377         }
01378         else if (detect_bytes == 4 &&
01379                  file_is_ivf(infile, &fourcc, &cfg.g_w, &cfg.g_h, detect.buf))
01380         {
01381             file_type = FILE_TYPE_IVF;
01382             switch (fourcc)
01383             {
01384             case 0x32315659:
01385                 arg_use_i420 = 0;
01386                 break;
01387             case 0x30323449:
01388                 arg_use_i420 = 1;
01389                 break;
01390             default:
01391                 fprintf(stderr, "Unsupported fourcc (%08x) in IVF\n", fourcc);
01392                 return EXIT_FAILURE;
01393             }
01394         }
01395         else
01396         {
01397             file_type = FILE_TYPE_RAW;
01398             detect.valid = 1;
01399         }
01400 #define SHOW(field) fprintf(stderr, "    %-28s = %d\n", #field, cfg.field)
01401 
01402         if (verbose && pass == 0)
01403         {
01404             fprintf(stderr, "Codec: %s\n", vpx_codec_iface_name(codec->iface));
01405             fprintf(stderr, "Source file: %s Format: %s\n", in_fn,
01406                     arg_use_i420 ? "I420" : "YV12");
01407             fprintf(stderr, "Destination file: %s\n", out_fn);
01408             fprintf(stderr, "Encoder parameters:\n");
01409 
01410             SHOW(g_usage);
01411             SHOW(g_threads);
01412             SHOW(g_profile);
01413             SHOW(g_w);
01414             SHOW(g_h);
01415             SHOW(g_timebase.num);
01416             SHOW(g_timebase.den);
01417             SHOW(g_error_resilient);
01418             SHOW(g_pass);
01419             SHOW(g_lag_in_frames);
01420             SHOW(rc_dropframe_thresh);
01421             SHOW(rc_resize_allowed);
01422             SHOW(rc_resize_up_thresh);
01423             SHOW(rc_resize_down_thresh);
01424             SHOW(rc_end_usage);
01425             SHOW(rc_target_bitrate);
01426             SHOW(rc_min_quantizer);
01427             SHOW(rc_max_quantizer);
01428             SHOW(rc_undershoot_pct);
01429             SHOW(rc_overshoot_pct);
01430             SHOW(rc_buf_sz);
01431             SHOW(rc_buf_initial_sz);
01432             SHOW(rc_buf_optimal_sz);
01433             SHOW(rc_2pass_vbr_bias_pct);
01434             SHOW(rc_2pass_vbr_minsection_pct);
01435             SHOW(rc_2pass_vbr_maxsection_pct);
01436             SHOW(kf_mode);
01437             SHOW(kf_min_dist);
01438             SHOW(kf_max_dist);
01439         }
01440 
01441         if(pass == (one_pass_only ? one_pass_only - 1 : 0)) {
01442             if (file_type == FILE_TYPE_Y4M)
01443                 /*The Y4M reader does its own allocation.
01444                   Just initialize this here to avoid problems if we never read any
01445                    frames.*/
01446                 memset(&raw, 0, sizeof(raw));
01447             else
01448                 vpx_img_alloc(&raw, arg_use_i420 ? VPX_IMG_FMT_I420 : VPX_IMG_FMT_YV12,
01449                               cfg.g_w, cfg.g_h, 1);
01450         }
01451 
01452         outfile = strcmp(out_fn, "-") ? fopen(out_fn, "wb") : stdout;
01453 
01454         if (!outfile)
01455         {
01456             fprintf(stderr, "Failed to open output file\n");
01457             return EXIT_FAILURE;
01458         }
01459 
01460         if(write_webm && fseek(outfile, 0, SEEK_CUR))
01461         {
01462             fprintf(stderr, "WebM output to pipes not supported.\n");
01463             return EXIT_FAILURE;
01464         }
01465 
01466         if (stats_fn)
01467         {
01468             if (!stats_open_file(&stats, stats_fn, pass))
01469             {
01470                 fprintf(stderr, "Failed to open statistics store\n");
01471                 return EXIT_FAILURE;
01472             }
01473         }
01474         else
01475         {
01476             if (!stats_open_mem(&stats, pass))
01477             {
01478                 fprintf(stderr, "Failed to open statistics store\n");
01479                 return EXIT_FAILURE;
01480             }
01481         }
01482 
01483         cfg.g_pass = arg_passes == 2
01484                      ? pass ? VPX_RC_LAST_PASS : VPX_RC_FIRST_PASS
01485                  : VPX_RC_ONE_PASS;
01486 #if VPX_ENCODER_ABI_VERSION > (1 + VPX_CODEC_ABI_VERSION)
01487 
01488         if (pass)
01489         {
01490             cfg.rc_twopass_stats_in = stats_get(&stats);
01491         }
01492 
01493 #endif
01494 
01495         if(write_webm)
01496         {
01497             ebml.stream = outfile;
01498             write_webm_file_header(&ebml, &cfg, &arg_framerate);
01499         }
01500         else
01501             write_ivf_file_header(outfile, &cfg, codec->fourcc, 0);
01502 
01503 
01504         /* Construct Encoder Context */
01505         vpx_codec_enc_init(&encoder, codec->iface, &cfg,
01506                            show_psnr ? VPX_CODEC_USE_PSNR : 0);
01507         ctx_exit_on_error(&encoder, "Failed to initialize encoder");
01508 
01509         /* Note that we bypass the vpx_codec_control wrapper macro because
01510          * we're being clever to store the control IDs in an array. Real
01511          * applications will want to make use of the enumerations directly
01512          */
01513         for (i = 0; i < arg_ctrl_cnt; i++)
01514         {
01515             if (vpx_codec_control_(&encoder, arg_ctrls[i][0], arg_ctrls[i][1]))
01516                 fprintf(stderr, "Error: Tried to set control %d = %d\n",
01517                         arg_ctrls[i][0], arg_ctrls[i][1]);
01518 
01519             ctx_exit_on_error(&encoder, "Failed to control codec");
01520         }
01521 
01522         frame_avail = 1;
01523         got_data = 0;
01524 
01525         while (frame_avail || got_data)
01526         {
01527             vpx_codec_iter_t iter = NULL;
01528             const vpx_codec_cx_pkt_t *pkt;
01529             struct vpx_usec_timer timer;
01530             int64_t frame_start;
01531 
01532             if (!arg_limit || frames_in < arg_limit)
01533             {
01534                 frame_avail = read_frame(infile, &raw, file_type, &y4m,
01535                                          &detect);
01536 
01537                 if (frame_avail)
01538                     frames_in++;
01539 
01540                 fprintf(stderr,
01541                         "\rPass %d/%d frame %4d/%-4d %7ldB \033[K", pass + 1,
01542                         arg_passes, frames_in, frames_out, nbytes);
01543             }
01544             else
01545                 frame_avail = 0;
01546 
01547             vpx_usec_timer_start(&timer);
01548 
01549             frame_start = (cfg.g_timebase.den * (int64_t)(frames_in - 1)
01550                           * arg_framerate.den) / cfg.g_timebase.num / arg_framerate.num;
01551             vpx_codec_encode(&encoder, frame_avail ? &raw : NULL, frame_start,
01552                              cfg.g_timebase.den * arg_framerate.den
01553                              / cfg.g_timebase.num / arg_framerate.num,
01554                              0, arg_deadline);
01555             vpx_usec_timer_mark(&timer);
01556             cx_time += vpx_usec_timer_elapsed(&timer);
01557             ctx_exit_on_error(&encoder, "Failed to encode frame");
01558             got_data = 0;
01559 
01560             while ((pkt = vpx_codec_get_cx_data(&encoder, &iter)))
01561             {
01562                 got_data = 1;
01563 
01564                 switch (pkt->kind)
01565                 {
01566                 case VPX_CODEC_CX_FRAME_PKT:
01567                     frames_out++;
01568                     fprintf(stderr, " %6luF",
01569                             (unsigned long)pkt->data.frame.sz);
01570 
01571                     if(write_webm)
01572                     {
01573                         /* Update the hash */
01574                         if(!ebml.debug)
01575                             hash = murmur(pkt->data.frame.buf,
01576                                           pkt->data.frame.sz, hash);
01577 
01578                         write_webm_block(&ebml, &cfg, pkt);
01579                     }
01580                     else
01581                     {
01582                         write_ivf_frame_header(outfile, pkt);
01583                         if(fwrite(pkt->data.frame.buf, 1,
01584                                   pkt->data.frame.sz, outfile));
01585                     }
01586                     nbytes += pkt->data.raw.sz;
01587                     break;
01588                 case VPX_CODEC_STATS_PKT:
01589                     frames_out++;
01590                     fprintf(stderr, " %6luS",
01591                            (unsigned long)pkt->data.twopass_stats.sz);
01592                     stats_write(&stats,
01593                                 pkt->data.twopass_stats.buf,
01594                                 pkt->data.twopass_stats.sz);
01595                     nbytes += pkt->data.raw.sz;
01596                     break;
01597                 case VPX_CODEC_PSNR_PKT:
01598 
01599                     if (show_psnr)
01600                     {
01601                         int i;
01602 
01603                         psnr_sse_total += pkt->data.psnr.sse[0];
01604                         psnr_samples_total += pkt->data.psnr.samples[0];
01605                         for (i = 0; i < 4; i++)
01606                         {
01607                             fprintf(stderr, "%.3lf ", pkt->data.psnr.psnr[i]);
01608                             psnr_totals[i] += pkt->data.psnr.psnr[i];
01609                         }
01610                         psnr_count++;
01611                     }
01612 
01613                     break;
01614                 default:
01615                     break;
01616                 }
01617             }
01618 
01619             fflush(stdout);
01620         }
01621 
01622         fprintf(stderr,
01623                "\rPass %d/%d frame %4d/%-4d %7ldB %7ldb/f %7"PRId64"b/s"
01624                " %7lu %s (%.2f fps)\033[K", pass + 1,
01625                arg_passes, frames_in, frames_out, nbytes, nbytes * 8 / frames_in,
01626                nbytes * 8 *(int64_t)arg_framerate.num / arg_framerate.den / frames_in,
01627                cx_time > 9999999 ? cx_time / 1000 : cx_time,
01628                cx_time > 9999999 ? "ms" : "us",
01629                (float)frames_in * 1000000.0 / (float)cx_time);
01630 
01631         if ( (show_psnr) && (psnr_count>0) )
01632         {
01633             int i;
01634             double ovpsnr = vp8_mse2psnr(psnr_samples_total, 255.0,
01635                                          psnr_sse_total);
01636 
01637             fprintf(stderr, "\nPSNR (Overall/Avg/Y/U/V)");
01638 
01639             fprintf(stderr, " %.3lf", ovpsnr);
01640             for (i = 0; i < 4; i++)
01641             {
01642                 fprintf(stderr, " %.3lf", psnr_totals[i]/psnr_count);
01643             }
01644         }
01645 
01646         vpx_codec_destroy(&encoder);
01647 
01648         fclose(infile);
01649 
01650         if(write_webm)
01651         {
01652             write_webm_file_footer(&ebml, hash);
01653         }
01654         else
01655         {
01656             if (!fseek(outfile, 0, SEEK_SET))
01657                 write_ivf_file_header(outfile, &cfg, codec->fourcc, frames_out);
01658         }
01659 
01660         fclose(outfile);
01661         stats_close(&stats);
01662         fprintf(stderr, "\n");
01663 
01664         if (one_pass_only)
01665             break;
01666     }
01667 
01668     vpx_img_free(&raw);
01669     free(argv);
01670     return EXIT_SUCCESS;
01671 }
Generated on Thu Dec 16 16:04:36 2010 for WebM VP8 Codec SDK by  doxygen 1.6.3